libpqxx  7.5.2
transaction_base.hxx
1 /* Common code and definitions for the transaction classes.
2  *
3  * pqxx::transaction_base defines the interface for any abstract class that
4  * represents a database transaction.
5  *
6  * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/transaction_base instead.
7  *
8  * Copyright (c) 2000-2021, Jeroen T. Vermeulen.
9  *
10  * See COPYING for copyright license. If you did not receive a file called
11  * COPYING with this source code, please notify the distributor of this
12  * mistake, or contact the author.
13  */
14 #ifndef PQXX_H_TRANSACTION_BASE
15 #define PQXX_H_TRANSACTION_BASE
16 
17 #include "pqxx/compiler-public.hxx"
18 #include "pqxx/internal/compiler-internal-pre.hxx"
19 
20 #include <string_view>
21 
22 /* End-user programs need not include this file, unless they define their own
23  * transaction classes. This is not something the typical program should want
24  * to do.
25  *
26  * However, reading this file is worthwhile because it defines the public
27  * interface for the available transaction classes such as transaction and
28  * nontransaction.
29  */
30 
31 #include "pqxx/connection.hxx"
32 #include "pqxx/internal/concat.hxx"
33 #include "pqxx/internal/encoding_group.hxx"
34 #include "pqxx/isolation.hxx"
35 #include "pqxx/result.hxx"
36 #include "pqxx/row.hxx"
37 #include "pqxx/stream_from.hxx"
38 
39 namespace pqxx::internal::gate
40 {
41 class transaction_subtransaction;
42 class transaction_sql_cursor;
43 class transaction_stream_to;
44 class transaction_transaction_focus;
45 } // namespace pqxx::internal::gate
46 
47 
48 namespace pqxx
49 {
50 using namespace std::literals;
51 
52 
53 class transaction_focus;
54 
55 
69 
74 class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
75 {
76 public:
77  transaction_base() = delete;
82 
83  virtual ~transaction_base() = 0;
84 
86 
98  void commit();
99 
101 
104  void abort();
105 
111  [[nodiscard]] std::string esc(char const text[]) const
112  {
113  return conn().esc(text);
114  }
116  [[nodiscard]] std::string esc(char const text[], std::size_t maxlen) const
117  {
118  return conn().esc(text, maxlen);
119  }
121  [[nodiscard]] std::string esc(std::string_view text) const
122  {
123  return conn().esc(text);
124  }
125 
127 
138  [[nodiscard]] std::string
139  esc_raw(unsigned char const data[], std::size_t len) const
140  {
141  return to_string(std::basic_string_view<std::byte>{
142  reinterpret_cast<std::byte const *>(data), len});
143  }
145  [[nodiscard]] std::string esc_raw(zview) const;
146 
148 
151  [[nodiscard]] std::string unesc_raw(zview text) const
152  {
153  return conn().unesc_raw(text);
154  }
155 
157 
160  [[nodiscard]] std::string unesc_raw(char const *text) const
161  {
162  return conn().unesc_raw(text);
163  }
164 
166 
167  template<typename T> [[nodiscard]] std::string quote(T const &t) const
168  {
169  return conn().quote(t);
170  }
171 
172  [[deprecated(
173  "Use std::basic_string<std::byte> instead of binarystring.")]] std::string
174  quote(binarystring const &t) const
175  {
176  return conn().quote(t.bytes_view());
177  }
178 
180  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
181  quote_raw(unsigned char const bin[], std::size_t len) const
182  {
183  return quote(std::basic_string_view<std::byte>{
184  reinterpret_cast<std::byte const *>(bin), len});
185  }
186 
188  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
189  quote_raw(zview bin) const;
190 
192  [[nodiscard]] std::string quote_name(std::string_view identifier) const
193  {
194  return conn().quote_name(identifier);
195  }
196 
198  [[nodiscard]] std::string
199  esc_like(std::string_view bin, char escape_char = '\\') const
200  {
201  return conn().esc_like(bin, escape_char);
202  }
204 
224 
226 
231  result
232  exec(std::string_view query, std::string_view desc = std::string_view{});
233 
235 
241  std::stringstream const &query, std::string_view desc = std::string_view{})
242  {
243  return exec(query.str(), desc);
244  }
245 
247 
252  result exec0(zview query, std::string_view desc = std::string_view{})
253  {
254  return exec_n(0, query, desc);
255  }
256 
258 
264  row exec1(zview query, std::string_view desc = std::string_view{})
265  {
266  return exec_n(1, query, desc).front();
267  }
268 
270 
275  result exec_n(
276  result::size_type rows, zview query,
277  std::string_view desc = std::string_view{});
278 
280 
283  template<typename TYPE>
284  TYPE query_value(zview query, std::string_view desc = std::string_view{})
285  {
286  row const r{exec1(query, desc)};
287  if (std::size(r) != 1)
288  throw usage_error{internal::concat(
289  "Queried single value from result with ", std::size(r), " columns.")};
290  return r[0].as<TYPE>();
291  }
292 
294 
342  template<typename... TYPE> [[nodiscard]] auto stream(std::string_view query)
343  {
344  // Tricky: std::make_unique() supports constructors but not RVO functions.
345  return pqxx::internal::owning_stream_input_iteration<TYPE...>{
346  std::unique_ptr<stream_from>{
347  new stream_from{stream_from::query(*this, query)}}};
348  }
349 
380  template<typename... Args> result exec_params(zview query, Args &&...args)
381  {
382  params pp(args...);
383  return internal_exec_params(query, pp.make_c_params());
384  }
385 
386  // Execute parameterised statement, expect a single-row result.
389  template<typename... Args> row exec_params1(zview query, Args &&...args)
390  {
391  return exec_params_n(1, query, std::forward<Args>(args)...).front();
392  }
393 
394  // Execute parameterised statement, expect a result with zero rows.
397  template<typename... Args> result exec_params0(zview query, Args &&...args)
398  {
399  return exec_params_n(0, query, std::forward<Args>(args)...);
400  }
401 
402  // Execute parameterised statement, expect exactly a given number of rows.
405  template<typename... Args>
406  result exec_params_n(std::size_t rows, zview query, Args &&...args)
407  {
408  auto const r{exec_params(query, std::forward<Args>(args)...)};
409  check_rowcount_params(rows, std::size(r));
410  return r;
411  }
413 
442 
444  template<typename... Args>
445  result exec_prepared(zview statement, Args &&...args)
446  {
447  params pp(args...);
448  return internal_exec_prepared(statement, pp.make_c_params());
449  }
450 
452 
454  template<typename... Args>
455  row exec_prepared1(zview statement, Args &&...args)
456  {
457  return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
458  }
459 
461 
463  template<typename... Args>
464  result exec_prepared0(zview statement, Args &&...args)
465  {
466  return exec_prepared_n(0, statement, std::forward<Args>(args)...);
467  }
468 
470 
473  template<typename... Args>
474  result
475  exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
476  {
477  auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
478  check_rowcount_prepared(statement, rows, std::size(r));
479  return r;
480  }
481 
483 
489  void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
491  void process_notice(zview msg) const { m_conn.process_notice(msg); }
493 
495  [[nodiscard]] connection &conn() const { return m_conn; }
496 
498 
508  void set_variable(std::string_view var, std::string_view value);
509 
511 
514  std::string get_variable(std::string_view);
515 
517  [[nodiscard]] std::string_view name() const noexcept { return m_name; }
518 
519 protected:
521 
525  connection &c, std::string_view tname,
526  std::shared_ptr<std::string> rollback_cmd) :
527  m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
528  {}
529 
531 
536  transaction_base(connection &c, std::string_view tname);
537 
539  explicit transaction_base(connection &c);
540 
542  void register_transaction();
543 
545  void close() noexcept;
546 
548  virtual void do_commit() = 0;
549 
551 
554  virtual void do_abort();
555 
557  void set_rollback_cmd(std::shared_ptr<std::string> cmd)
558  {
559  m_rollback_cmd = cmd;
560  }
561 
563  result direct_exec(std::string_view, std::string_view desc = ""sv);
564  result
565  direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
566 
567 private:
568  enum class status
569  {
570  active,
571  aborted,
572  committed,
573  in_doubt
574  };
575 
576  PQXX_PRIVATE void check_pending_error();
577 
578  template<typename T> bool parm_is_null(T *p) const noexcept
579  {
580  return p == nullptr;
581  }
582  template<typename T> bool parm_is_null(T) const noexcept { return false; }
583 
584  result
585  internal_exec_prepared(zview statement, internal::c_params const &args);
586 
587  result internal_exec_params(zview query, internal::c_params const &args);
588 
590  void check_rowcount_prepared(
591  zview statement, result::size_type expected_rows,
592  result::size_type actual_rows);
593 
595  void
596  check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
597 
599  [[nodiscard]] std::string description() const;
600 
601  friend class pqxx::internal::gate::transaction_transaction_focus;
602  PQXX_PRIVATE void register_focus(transaction_focus *);
603  PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
604  PQXX_PRIVATE void register_pending_error(zview) noexcept;
605  PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
606 
607  connection &m_conn;
608 
610 
613  transaction_focus const *m_focus = nullptr;
614 
615  status m_status = status::active;
616  bool m_registered = false;
617  std::string m_name;
618  std::string m_pending_error;
619 
621  std::shared_ptr<std::string> m_rollback_cmd;
622 
623  constexpr static std::string_view s_type_name{"transaction"sv};
624 };
625 
626 
627 // TODO: C++20 "Conversion remains valid after underlying result dies" concept?
629 template<>
630 std::string_view transaction_base::query_value<std::string_view>(
631  zview query, std::string_view desc) = delete;
633 template<>
634 zview transaction_base::query_value<zview>(
635  zview query, std::string_view desc) = delete;
636 
637 } // namespace pqxx
638 
639 
640 namespace pqxx::internal
641 {
643 template<pqxx::isolation_level isolation, pqxx::write_policy rw>
644 extern const zview begin_cmd;
645 
646 // These are not static members, so "constexpr" does not imply "inline".
647 template<>
648 inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
649  "BEGIN"_zv};
650 template<>
651 inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
652  "BEGIN READ ONLY"_zv};
653 template<>
654 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
655  "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
656 template<>
657 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
658  "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
659 template<>
660 inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
661  "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
662 template<>
663 inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
664  "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
665 } // namespace pqxx::internal
666 
667 #include "pqxx/internal/compiler-internal-post.hxx"
668 #endif
std::string esc(char const text[]) const
Escape string for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:111
The home of all libpqxx classes, functions, templates, etc.
Definition: array.hxx:26
std::string to_string(field const &value)
Convert a field to a string.
Definition: result.cxx:503
Internal items for libpqxx' own use. Do not use these yourself.
Definition: composite.hxx:74
const zview begin_cmd
The SQL command for starting a given type of transaction.
Definition: connection.hxx:98
Binary data corresponding to PostgreSQL's "BYTEA" binary-string type.
Definition: binarystring.hxx:57
std::basic_string_view< std::byte > bytes_view() const
Read data as a std::basic_string_view<std::byte>.
Definition: binarystring.hxx:176
Connection to a database.
Definition: connection.hxx:184
Build a parameter list for a parameterised or prepared statement.
Definition: prepared_statement.hxx:122
pqxx::internal::c_params make_c_params() const
For internal use: Generate a params object for use in calls.
Definition: params.cxx:92
Result set containing data returned by a query or command.
Definition: result.hxx:71
result_size_type size_type
Definition: result.hxx:73
Reference to one row in a result.
Definition: row.hxx:46
reference front() const noexcept
Definition: row.cxx:54
std::tuple< TYPE... > as() const
Definition: row.hxx:184
Stream data from the database.
Definition: stream_from.hxx:73
Use std::string_view query
Definition: stream_from.hxx:139
Interface definition (and common code) for "transaction" classes.
Definition: transaction_base.hxx:75
result exec_prepared(zview statement, Args &&...args)
Execute a prepared statement, with optional arguments.
Definition: transaction_base.hxx:445
row exec1(zview query, std::string_view desc=std::string_view{})
Execute command returning a single row of data.
Definition: transaction_base.hxx:264
void process_notice(zview msg) const
Have connection process a warning message.
Definition: transaction_base.hxx:491
std::string unesc_raw(char const *text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:160
transaction_base & operator=(transaction_base &&)=delete
result exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
Execute a prepared statement, expect a result with given number of rows.
Definition: transaction_base.hxx:475
transaction_base(transaction_base const &)=delete
TYPE query_value(zview query, std::string_view desc=std::string_view{})
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition: transaction_base.hxx:284
transaction_base(connection &c, std::string_view tname, std::shared_ptr< std::string > rollback_cmd)
Create a transaction (to be called by implementation classes only).
Definition: transaction_base.hxx:524
std::string quote(T const &t) const
Represent object as SQL string, including quoting & escaping.
Definition: transaction_base.hxx:167
row exec_params1(zview query, Args &&...args)
Definition: transaction_base.hxx:389
std::string esc(char const text[], std::size_t maxlen) const
Escape string for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:116
std::string quote(binarystring const &t) const
Definition: transaction_base.hxx:174
std::string esc(std::string_view text) const
Escape string for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:121
auto stream(std::string_view query)
Execute a query, and loop over the results row by row.
Definition: transaction_base.hxx:342
transaction_base(transaction_base &&)=delete
result exec_params(zview query, Args &&...args)
Execute an SQL statement with parameters.
Definition: transaction_base.hxx:380
std::string_view name() const noexcept
Transaction name, if you passed one to the constructor; or empty string.
Definition: transaction_base.hxx:517
result exec_params0(zview query, Args &&...args)
Definition: transaction_base.hxx:397
std::string unesc_raw(zview text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:151
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition: transaction_base.hxx:464
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition: transaction_base.hxx:199
connection & conn() const
The connection in which this transaction lives.
Definition: transaction_base.hxx:495
result exec0(zview query, std::string_view desc=std::string_view{})
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:252
result exec(std::stringstream const &query, std::string_view desc=std::string_view{})
Execute a command.
Definition: transaction_base.hxx:240
row exec_prepared1(zview statement, Args &&...args)
Execute a prepared statement, and expect a single-row result.
Definition: transaction_base.hxx:455
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition: transaction_base.hxx:192
std::string quote_raw(unsigned char const bin[], std::size_t len) const
Binary-escape and quote a binary string for use as an SQL constant.
Definition: transaction_base.hxx:181
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition: transaction_base.hxx:406
std::string esc_raw(unsigned char const data[], std::size_t len) const
Escape binary data for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:139
transaction_base & operator=(transaction_base const &)=delete
void process_notice(char const msg[]) const
Have connection process a warning message.
Definition: transaction_base.hxx:489
Base class for things that monopolise a transaction's attention.
Definition: transaction_focus.hxx:28
Marker-type wrapper: zero-terminated std::string_view.
Definition: zview.hxx:38