libpqxx  7.7.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-2022, 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 #if !defined(PQXX_HEADER_PRE)
18 # error "Include libpqxx headers as <pqxx/header>, not <pqxx/header.hxx>."
19 #endif
20 
21 #include <string_view>
22 #include <utility>
23 
24 /* End-user programs need not include this file, unless they define their own
25  * transaction classes. This is not something the typical program should want
26  * to do.
27  *
28  * However, reading this file is worthwhile because it defines the public
29  * interface for the available transaction classes such as transaction and
30  * nontransaction.
31  */
32 
33 #include "pqxx/connection.hxx"
34 #include "pqxx/internal/concat.hxx"
35 #include "pqxx/internal/encoding_group.hxx"
36 #include "pqxx/isolation.hxx"
37 #include "pqxx/result.hxx"
38 #include "pqxx/row.hxx"
39 #include "pqxx/stream_from.hxx"
40 
41 namespace pqxx::internal::gate
42 {
43 class transaction_subtransaction;
44 class transaction_sql_cursor;
45 class transaction_stream_to;
46 class transaction_transaction_focus;
47 } // namespace pqxx::internal::gate
48 
49 
50 namespace pqxx
51 {
52 using namespace std::literals;
53 
54 
55 class transaction_focus;
56 
57 
70 
76 class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
77 {
78 public:
79  transaction_base() = delete;
80  transaction_base(transaction_base const &) = delete;
82  transaction_base &operator=(transaction_base const &) = delete;
83  transaction_base &operator=(transaction_base &&) = delete;
84 
85  virtual ~transaction_base() = 0;
86 
88 
101  void commit();
102 
104 
107  void abort();
108 
119  template<typename... ARGS> [[nodiscard]] auto esc(ARGS &&...args) const
121  {
122  return conn().esc(std::forward<ARGS>(args)...);
123  }
124 
126 
137  template<typename... ARGS> [[nodiscard]] auto esc_raw(ARGS &&...args) const
138  {
139  return conn().esc_raw(std::forward<ARGS>(args)...);
140  }
141 
143 
146  [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
147  unesc_raw(zview text) const
148  {
149 #include "pqxx/internal/ignore-deprecated-pre.hxx"
150  return conn().unesc_raw(text);
151 #include "pqxx/internal/ignore-deprecated-post.hxx"
152  }
153 
155 
158  [[nodiscard]] std::basic_string<std::byte> unesc_bin(zview text)
159  {
160  return conn().unesc_bin(text);
161  }
162 
164 
167  [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
168  unesc_raw(char const *text) const
169  {
170 #include "pqxx/internal/ignore-deprecated-pre.hxx"
171  return conn().unesc_raw(text);
172 #include "pqxx/internal/ignore-deprecated-post.hxx"
173  }
174 
176 
179  [[nodiscard]] std::basic_string<std::byte> unesc_bin(char const text[])
180  {
181  return conn().unesc_bin(text);
182  }
183 
185 
186  template<typename T> [[nodiscard]] std::string quote(T const &t) const
187  {
188  return conn().quote(t);
189  }
190 
191  [[deprecated(
192  "Use std::basic_string<std::byte> instead of binarystring.")]] std::string
193  quote(binarystring const &t) const
194  {
195  return conn().quote(t.bytes_view());
196  }
197 
199  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
200  quote_raw(unsigned char const bin[], std::size_t len) const
201  {
202  return quote(binary_cast(bin, len));
203  }
204 
206  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
207  quote_raw(zview bin) const;
208 
209 #if defined(PQXX_HAVE_CONCEPTS)
210 
212  template<binary DATA>
213  [[nodiscard]] std::string quote_raw(DATA const &data) const
214  {
215  return conn().quote_raw(data);
216  }
217 #endif
218 
220  [[nodiscard]] std::string quote_name(std::string_view identifier) const
221  {
222  return conn().quote_name(identifier);
223  }
224 
226  [[nodiscard]] std::string
227  esc_like(std::string_view bin, char escape_char = '\\') const
228  {
229  return conn().esc_like(bin, escape_char);
230  }
232 
252 
254 
259  result
260  exec(std::string_view query, std::string_view desc = std::string_view{});
261 
263 
269  std::stringstream const &query, std::string_view desc = std::string_view{})
270  {
271  return exec(query.str(), desc);
272  }
273 
275 
280  result exec0(zview query, std::string_view desc = std::string_view{})
281  {
282  return exec_n(0, query, desc);
283  }
284 
286 
292  row exec1(zview query, std::string_view desc = std::string_view{})
293  {
294  return exec_n(1, query, desc).front();
295  }
296 
298 
303  result exec_n(
304  result::size_type rows, zview query,
305  std::string_view desc = std::string_view{});
306 
308 
311  template<typename TYPE>
312  TYPE query_value(zview query, std::string_view desc = std::string_view{})
313  {
314  row const r{exec1(query, desc)};
315  if (std::size(r) != 1)
316  throw usage_error{internal::concat(
317  "Queried single value from result with ", std::size(r), " columns.")};
318  return r[0].as<TYPE>();
319  }
320 
322 
370  template<typename... TYPE>
371  [[nodiscard]] auto stream(std::string_view query) &
372  {
373  // Tricky: std::make_unique() supports constructors but not RVO functions.
374  return pqxx::internal::owning_stream_input_iteration<TYPE...>{
375  std::unique_ptr<stream_from>{
376  new stream_from{stream_from::query(*this, query)}}};
377  }
378 
408  template<typename... Args> result exec_params(zview query, Args &&...args)
410  {
411  params pp(args...);
412  return internal_exec_params(query, pp.make_c_params());
413  }
414 
415  // Execute parameterised statement, expect a single-row result.
418  template<typename... Args> row exec_params1(zview query, Args &&...args)
419  {
420  return exec_params_n(1, query, std::forward<Args>(args)...).front();
421  }
422 
423  // Execute parameterised statement, expect a result with zero rows.
426  template<typename... Args> result exec_params0(zview query, Args &&...args)
427  {
428  return exec_params_n(0, query, std::forward<Args>(args)...);
429  }
430 
431  // Execute parameterised statement, expect exactly a given number of rows.
434  template<typename... Args>
435  result exec_params_n(std::size_t rows, zview query, Args &&...args)
436  {
437  auto const r{exec_params(query, std::forward<Args>(args)...)};
438  check_rowcount_params(rows, std::size(r));
439  return r;
440  }
442 
474 
476  template<typename... Args>
477  result exec_prepared(zview statement, Args &&...args)
478  {
479  params pp(args...);
480  return internal_exec_prepared(statement, pp.make_c_params());
481  }
482 
484 
486  template<typename... Args>
487  row exec_prepared1(zview statement, Args &&...args)
488  {
489  return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
490  }
491 
493 
495  template<typename... Args>
496  result exec_prepared0(zview statement, Args &&...args)
497  {
498  return exec_prepared_n(0, statement, std::forward<Args>(args)...);
499  }
500 
502 
505  template<typename... Args>
506  result
507  exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
508  {
509  auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
510  check_rowcount_prepared(statement, rows, std::size(r));
511  return r;
512  }
513 
515 
520  void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
523  void process_notice(zview msg) const { m_conn.process_notice(msg); }
525 
527  [[nodiscard]] constexpr connection &conn() const noexcept { return m_conn; }
528 
530 
545  [[deprecated(
546  "Set transaction-local variables using SQL SET statements.")]] void
547  set_variable(std::string_view var, std::string_view value);
548 
550 
553  [[deprecated("Read variables using SQL SHOW statements.")]] std::string
554  get_variable(std::string_view);
555 
556  // C++20: constexpr.
558  [[nodiscard]] std::string_view name() const &noexcept { return m_name; }
559 
560 protected:
562 
566  connection &c, std::string_view tname,
567  std::shared_ptr<std::string> rollback_cmd) :
568  m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
569  {}
570 
572 
577  transaction_base(connection &c, std::string_view tname);
578 
580  explicit transaction_base(connection &c);
581 
583  void register_transaction();
584 
586  void close() noexcept;
587 
589  virtual void do_commit() = 0;
590 
592 
595  virtual void do_abort();
596 
598  void set_rollback_cmd(std::shared_ptr<std::string> cmd)
599  {
600  m_rollback_cmd = cmd;
601  }
602 
604  result direct_exec(std::string_view, std::string_view desc = ""sv);
605  result
606  direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
607 
608 private:
609  enum class status
610  {
611  active,
612  aborted,
613  committed,
614  in_doubt
615  };
616 
617  PQXX_PRIVATE void check_pending_error();
618 
619  result
620  internal_exec_prepared(zview statement, internal::c_params const &args);
621 
622  result internal_exec_params(zview query, internal::c_params const &args);
623 
625  void check_rowcount_prepared(
626  zview statement, result::size_type expected_rows,
627  result::size_type actual_rows);
628 
630  void
631  check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
632 
634  [[nodiscard]] std::string description() const;
635 
636  friend class pqxx::internal::gate::transaction_transaction_focus;
637  PQXX_PRIVATE void register_focus(transaction_focus *);
638  PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
639  PQXX_PRIVATE void register_pending_error(zview) noexcept;
640  PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
641 
642  connection &m_conn;
643 
645 
648  transaction_focus const *m_focus = nullptr;
649 
650  status m_status = status::active;
651  bool m_registered = false;
652  std::string m_name;
653  std::string m_pending_error;
654 
656  std::shared_ptr<std::string> m_rollback_cmd;
657 
658  static constexpr std::string_view s_type_name{"transaction"sv};
659 };
660 
661 
662 // C++20: Can borrowed_range help?
664 template<>
665 std::string_view transaction_base::query_value<std::string_view>(
666  zview query, std::string_view desc) = delete;
668 template<>
669 zview transaction_base::query_value<zview>(
670  zview query, std::string_view desc) = delete;
671 
672 } // namespace pqxx
673 
674 
675 namespace pqxx::internal
676 {
678 template<pqxx::isolation_level isolation, pqxx::write_policy rw>
679 extern const zview begin_cmd;
680 
681 // These are not static members, so "constexpr" does not imply "inline".
682 template<>
683 inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
684  "BEGIN"_zv};
685 template<>
686 inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
687  "BEGIN READ ONLY"_zv};
688 template<>
689 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
690  "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
691 template<>
692 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
693  "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
694 template<>
695 inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
696  "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
697 template<>
698 inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
699  "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
700 } // namespace pqxx::internal
701 #endif
Stream data from the database.
Definition: stream_from.hxx:73
std::basic_string_view< std::byte > bytes_view() const
Read data as a std::basic_string_view<std::byte>.
Definition: binarystring.hxx:178
Base class for things that monopolise a transaction&#39;s attention.
Definition: transaction_focus.hxx:28
row exec_prepared1(zview statement, Args &&...args)
Execute a prepared statement, and expect a single-row result.
Definition: transaction_base.hxx:487
auto esc_raw(ARGS &&...args) const
Escape binary data for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:137
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:200
The home of all libpqxx classes, functions, templates, etc.
Definition: array.hxx:26
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:312
Reference to one row in a result.
Definition: row.hxx:46
static stream_from query(transaction_base &tx, std::string_view q)
Factory: Execute query, and stream the results.
Definition: stream_from.hxx:89
Connection to a database.
Definition: connection.hxx:185
std::string unesc_raw(zview text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:147
std::basic_string< std::byte > unesc_bin(zview text)
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:158
pqxx::internal::c_params make_c_params() const
For internal use: Generate a params object for use in calls.
Definition: params.cxx:94
row exec_params1(zview query, Args &&...args)
Definition: transaction_base.hxx:418
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition: transaction_base.hxx:220
std::string quote(binarystring const &t) const
Definition: transaction_base.hxx:193
row exec1(zview query, std::string_view desc=std::string_view{})
Execute command returning a single row of data.
Definition: transaction_base.hxx:292
STL namespace.
const zview begin_cmd
The SQL command for starting a given type of transaction.
result exec_prepared(zview statement, Args &&...args)
Execute a prepared statement, with optional arguments.
Definition: transaction_base.hxx:477
void process_notice(zview msg) const
Have connection process a warning message.
Definition: transaction_base.hxx:523
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition: transaction_base.hxx:435
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition: transaction_base.hxx:227
Definition: connection.hxx:99
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:507
result_size_type size_type
Definition: result.hxx:75
Error in usage of libpqxx library, similar to std::logic_error.
Definition: except.hxx:173
std::string quote(T const &t) const
Represent object as SQL string, including quoting & escaping.
Definition: transaction_base.hxx:186
Interface definition (and common code) for "transaction" classes.
Definition: transaction_base.hxx:76
std::basic_string< std::byte > unesc_bin(char const text[])
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:179
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:565
Result set containing data returned by a query or command.
Definition: result.hxx:72
result exec0(zview query, std::string_view desc=std::string_view{})
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:280
Marker-type wrapper: zero-terminated std::string_view.
Definition: zview.hxx:37
Internal items for libpqxx&#39; own use. Do not use these yourself.
Definition: composite.hxx:82
std::string_view name() const &noexcept
Transaction name, if you passed one to the constructor; or empty string.
Definition: transaction_base.hxx:558
reference front() const noexcept
Definition: row.cxx:60
void set_rollback_cmd(std::shared_ptr< std::string > cmd)
Set the rollback command.
Definition: transaction_base.hxx:598
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition: transaction_base.hxx:496
std::string unesc_raw(char const *text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:168
constexpr connection & conn() const noexcept
The connection in which this transaction lives.
Definition: transaction_base.hxx:527
auto stream(std::string_view query) &
Execute a query, and loop over the results row by row.
Definition: transaction_base.hxx:371
Binary data corresponding to PostgreSQL&#39;s "BYTEA" binary-string type.
Definition: binarystring.hxx:58
std::basic_string_view< std::byte > binary_cast(TYPE const &data)
Cast binary data to a type that libpqxx will recognise as binary.
Definition: util.hxx:297
result exec_params0(zview query, Args &&...args)
Definition: transaction_base.hxx:426
result exec(std::stringstream const &query, std::string_view desc=std::string_view{})
Execute a command.
Definition: transaction_base.hxx:268
Build a parameter list for a parameterised or prepared statement.
Definition: params.hxx:219