libpqxx  7.7.4
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 
23 /* End-user programs need not include this file, unless they define their own
24  * transaction classes. This is not something the typical program should want
25  * to do.
26  *
27  * However, reading this file is worthwhile because it defines the public
28  * interface for the available transaction classes such as transaction and
29  * nontransaction.
30  */
31 
32 #include "pqxx/connection.hxx"
33 #include "pqxx/internal/concat.hxx"
34 #include "pqxx/internal/encoding_group.hxx"
35 #include "pqxx/isolation.hxx"
36 #include "pqxx/result.hxx"
37 #include "pqxx/row.hxx"
38 #include "pqxx/stream_from.hxx"
39 #include "pqxx/util.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 
273 
275 
280  [[deprecated("The desc parameter is going away.")]] result
281  exec(std::string_view query, std::string_view desc);
282 
284 
288  result exec(std::string_view query)
289  {
290 #include "pqxx/internal/ignore-deprecated-pre.hxx"
291  return exec(query, std::string_view{});
292 #include "pqxx/internal/ignore-deprecated-post.hxx"
293  }
294 
296 
301  [[deprecated(
302  "Pass your query as a std::string_view, not stringstream.")]] result
303  exec(std::stringstream const &query, std::string_view desc)
304  {
305 #include "pqxx/internal/ignore-deprecated-pre.hxx"
306  return exec(query.str(), desc);
307 #include "pqxx/internal/ignore-deprecated-post.hxx"
308  }
309 
311 
316  [[deprecated("The desc parameter is going away.")]] result
317  exec0(zview query, std::string_view desc)
318  {
319 #include "pqxx/internal/ignore-deprecated-pre.hxx"
320  return exec_n(0, query, desc);
321 #include "pqxx/internal/ignore-deprecated-post.hxx"
322  }
323 
325 
331  {
332  return exec_n(0, query);
333  }
334 
336 
342  [[deprecated("The desc parameter is going away.")]] row
343  exec1(zview query, std::string_view desc)
344  {
345 #include "pqxx/internal/ignore-deprecated-pre.hxx"
346  return exec_n(1, query, desc).front();
347 #include "pqxx/internal/ignore-deprecated-post.hxx"
348  }
349 
351 
357  row exec1(zview query)
358  {
359  return exec_n(1, query).front();
360  }
361 
363 
368  [[deprecated("The desc parameter is going away.")]] result
369  exec_n(result::size_type rows, zview query, std::string_view desc);
370 
372 
378  {
379 #include "pqxx/internal/ignore-deprecated-pre.hxx"
380  return exec_n(rows, query, std::string_view{});
381 #include "pqxx/internal/ignore-deprecated-post.hxx"
382  }
383 
385 
388  template<typename TYPE>
389  [[deprecated("The desc parameter is going away.")]] TYPE
390  query_value(zview query, std::string_view desc)
391  {
392 #include "pqxx/internal/ignore-deprecated-pre.hxx"
393  row const r{exec1(query, desc)};
394 #include "pqxx/internal/ignore-deprecated-post.hxx"
395  if (std::size(r) != 1)
396  throw usage_error{internal::concat(
397  "Queried single value from result with ", std::size(r), " columns.")};
398  return r[0].as<TYPE>();
399  }
400 
402 
408  template<typename TYPE> TYPE query_value(zview query)
409  {
410  row const r{exec1(query)};
411  if (std::size(r) != 1)
412  throw usage_error{internal::concat(
413  "Queried single value from result with ", std::size(r), " columns.")};
414  return r[0].as<TYPE>();
415  }
416 
418 
425  template<typename... TYPE>
426  [[nodiscard]] std::tuple<TYPE...> query1(zview query)
427  {
428  return exec1(query).as<TYPE...>();
429  }
430 
432 
439  template<typename... TYPE>
440  [[nodiscard]] std::optional<std::tuple<TYPE...>> query01(zview query)
441  {
442  result res{exec(query)};
443  auto const rows{std::size(res)};
444  switch (rows)
445  {
446  case 0: return {};
447  case 1: return {res[0].as<TYPE...>()};
448  default:
449  throw unexpected_rows{internal::concat(
450  "Expected at most one row of data, got "sv, rows, "."sv)};
451  }
452  }
453 
455 
501  template<typename... TYPE>
502  [[nodiscard]] auto stream(std::string_view query) &
503  {
504  // Tricky: std::make_unique() supports constructors but not RVO functions.
505  return pqxx::internal::owning_stream_input_iteration<TYPE...>{
506  std::unique_ptr<stream_from>{
507  new stream_from{stream_from::query(*this, query)}}};
508  }
509 
510  // C++20: Concept like std::invocable, but without specifying param types.
512 
531  template<typename CALLABLE>
532  auto for_stream(std::string_view query, CALLABLE &&func)
533  {
534  using param_types =
536  param_types const *const sample{nullptr};
537  auto data_stream{stream_like(query, sample)};
538  for (auto const &fields : data_stream) std::apply(func, fields);
539  }
540 
541  template<typename CALLABLE>
542  [[deprecated(
543  "pqxx::transaction_base::for_each is now called for_stream.")]] auto
544  for_each(std::string_view query, CALLABLE &&func)
545  {
546  return for_stream(query, std::forward<CALLABLE>(func));
547  }
548 
550 
581  template<typename... TYPE> auto query(zview query)
582  {
583  return exec(query).iter<TYPE...>();
584  }
585 
587 
595  template<typename... TYPE> auto query_n(result::size_type rows, zview query)
596  {
597  return exec_n(rows, query).iter<TYPE...>();
598  }
599 
600  // C++20: Concept like std::invocable, but without specifying param types.
602 
610  template<typename CALLABLE> void for_query(zview query, CALLABLE &&func)
611  {
612  exec(query).for_each(std::forward<CALLABLE>(func));
613  }
614 
644  template<typename... Args> result exec_params(zview query, Args &&...args)
646  {
647  params pp(args...);
648  return internal_exec_params(query, pp.make_c_params());
649  }
650 
651  // Execute parameterised statement, expect a single-row result.
654  template<typename... Args> row exec_params1(zview query, Args &&...args)
655  {
656  return exec_params_n(1, query, std::forward<Args>(args)...).front();
657  }
658 
659  // Execute parameterised statement, expect a result with zero rows.
662  template<typename... Args> result exec_params0(zview query, Args &&...args)
663  {
664  return exec_params_n(0, query, std::forward<Args>(args)...);
665  }
666 
667  // Execute parameterised statement, expect exactly a given number of rows.
670  template<typename... Args>
671  result exec_params_n(std::size_t rows, zview query, Args &&...args)
672  {
673  auto const r{exec_params(query, std::forward<Args>(args)...)};
674  check_rowcount_params(rows, std::size(r));
675  return r;
676  }
678 
710 
712  template<typename... Args>
713  result exec_prepared(zview statement, Args &&...args)
714  {
715  params pp(args...);
716  return internal_exec_prepared(statement, pp.make_c_params());
717  }
718 
720 
722  template<typename... Args>
723  row exec_prepared1(zview statement, Args &&...args)
724  {
725  return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
726  }
727 
729 
731  template<typename... Args>
732  result exec_prepared0(zview statement, Args &&...args)
733  {
734  return exec_prepared_n(0, statement, std::forward<Args>(args)...);
735  }
736 
738 
741  template<typename... Args>
742  result
743  exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
744  {
745  auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
746  check_rowcount_prepared(statement, rows, std::size(r));
747  return r;
748  }
749 
751 
756  void process_notice(char const msg[]) const
758  {
759  m_conn.process_notice(msg);
760  }
762  void process_notice(zview msg) const
763  {
764  m_conn.process_notice(msg);
765  }
767 
769  [[nodiscard]] constexpr connection &conn() const noexcept
770  {
771  return m_conn;
772  }
773 
775 
790  [[deprecated(
791  "Set transaction-local variables using SQL SET statements.")]] void
792  set_variable(std::string_view var, std::string_view value);
793 
795 
798  [[deprecated("Read variables using SQL SHOW statements.")]] std::string
799  get_variable(std::string_view);
800 
801  // C++20: constexpr.
803  [[nodiscard]] std::string_view name() const &noexcept
804  {
805  return m_name;
806  }
807 
808 protected:
810 
814  connection &c, std::string_view tname,
815  std::shared_ptr<std::string> rollback_cmd) :
816  m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
817  {}
818 
820 
825  transaction_base(connection &c, std::string_view tname);
826 
828  explicit transaction_base(connection &c);
829 
831  void register_transaction();
832 
834  void close() noexcept;
835 
837  virtual void do_commit() = 0;
838 
840 
843  virtual void do_abort();
844 
846  void set_rollback_cmd(std::shared_ptr<std::string> cmd)
847  {
848  m_rollback_cmd = cmd;
849  }
850 
852  result direct_exec(std::string_view, std::string_view desc = ""sv);
853  result
854  direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
855 
856 private:
857  enum class status
858  {
859  active,
860  aborted,
861  committed,
862  in_doubt
863  };
864 
865  PQXX_PRIVATE void check_pending_error();
866 
867  result
868  internal_exec_prepared(zview statement, internal::c_params const &args);
869 
870  result internal_exec_params(zview query, internal::c_params const &args);
871 
873  void check_rowcount_prepared(
874  zview statement, result::size_type expected_rows,
875  result::size_type actual_rows);
876 
878  void
879  check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
880 
882  [[nodiscard]] std::string description() const;
883 
884  friend class pqxx::internal::gate::transaction_transaction_focus;
885  PQXX_PRIVATE void register_focus(transaction_focus *);
886  PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
887  PQXX_PRIVATE void register_pending_error(zview) noexcept;
888  PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
889 
891  template<typename... ARGS>
892  auto stream_like(std::string_view query, std::tuple<ARGS...> const *)
893  {
894  return stream<ARGS...>(query);
895  }
896 
897  connection &m_conn;
898 
900 
903  transaction_focus const *m_focus = nullptr;
904 
905  status m_status = status::active;
906  bool m_registered = false;
907  std::string m_name;
908  std::string m_pending_error;
909 
911  std::shared_ptr<std::string> m_rollback_cmd;
912 
913  static constexpr std::string_view s_type_name{"transaction"sv};
914 };
915 
916 
917 // C++20: Can borrowed_range help?
919 template<>
920 std::string_view transaction_base::query_value<std::string_view>(
921  zview query, std::string_view desc) = delete;
923 template<>
924 zview transaction_base::query_value<zview>(
925  zview query, std::string_view desc) = delete;
926 
927 } // namespace pqxx
928 
929 
930 namespace pqxx::internal
931 {
933 template<pqxx::isolation_level isolation, pqxx::write_policy rw>
934 extern const zview begin_cmd;
935 
936 // These are not static members, so "constexpr" does not imply "inline".
937 template<>
938 inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
939  "BEGIN"_zv};
940 template<>
941 inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
942  "BEGIN READ ONLY"_zv};
943 template<>
944 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
945  "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
946 template<>
947 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
948  "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
949 template<>
950 inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
951  "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
952 template<>
953 inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
954  "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
955 } // namespace pqxx::internal
956 #endif
Stream data from the database.
Definition: stream_from.hxx:77
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:723
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
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:93
Connection to a database.
Definition: connection.hxx:184
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
result exec0(zview query)
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:330
pqxx::internal::c_params make_c_params() const
For internal use: Generate a params object for use in calls.
Definition: params.cxx:96
row exec_params1(zview query, Args &&...args)
Definition: transaction_base.hxx:654
std::tuple< TYPE... > query1(zview query)
Perform query returning exactly one row, and convert its fields.
Definition: transaction_base.hxx:426
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition: transaction_base.hxx:220
TYPE query_value(zview query)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition: transaction_base.hxx:408
std::string quote(binarystring const &t) const
Definition: transaction_base.hxx:193
auto query(zview query)
Execute query, read full results, then iterate rows of data.
Definition: transaction_base.hxx:581
STL namespace.
row exec1(zview query, std::string_view desc)
Execute command returning a single row of data.
Definition: transaction_base.hxx:343
const zview begin_cmd
The SQL command for starting a given type of transaction.
auto query_n(result::size_type rows, zview query)
Perform query, expect given number of rows, iterate results.
Definition: transaction_base.hxx:595
result exec_prepared(zview statement, Args &&...args)
Execute a prepared statement, with optional arguments.
Definition: transaction_base.hxx:713
void process_notice(zview msg) const
Have connection process a warning message.
Definition: transaction_base.hxx:762
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition: transaction_base.hxx:671
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition: transaction_base.hxx:227
void for_query(zview query, CALLABLE &&func)
Execute a query, load the full result, and perform func for each row.
Definition: transaction_base.hxx:610
result exec0(zview query, std::string_view desc)
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:317
Definition: connection.hxx:98
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:743
void for_each(CALLABLE &&func) const
Run func on each row, passing the row&#39;s fields as parameters.
auto iter() const
Iterate rows, reading them directly into a tuple of "TYPE...".
TYPE query_value(zview query, std::string_view desc)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition: transaction_base.hxx:390
result_size_type size_type
Definition: result.hxx:76
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
auto for_each(std::string_view query, CALLABLE &&func)
Definition: transaction_base.hxx:544
decltype(strip_types(std::declval< TYPES... >())) strip_types_t
Take a tuple type and apply strip_t to its component types.
Definition: util.hxx:529
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
auto for_stream(std::string_view query, CALLABLE &&func)
Perform a streaming query, and for each result row, call func.
Definition: transaction_base.hxx:532
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:813
Result set containing data returned by a query or command.
Definition: result.hxx:73
Query returned an unexpected number of rows.
Definition: except.hxx:208
std::optional< std::tuple< TYPE... > > query01(zview query)
Query at most one row of data, and if there is one, convert it.
Definition: transaction_base.hxx:440
result exec(std::stringstream const &query, std::string_view desc)
Execute a command.
Definition: transaction_base.hxx:303
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:803
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:846
result exec(std::string_view query)
Execute a command.
Definition: transaction_base.hxx:288
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition: transaction_base.hxx:732
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
result exec_n(result::size_type rows, zview query)
Execute command, expect given number of rows.
Definition: transaction_base.hxx:377
constexpr connection & conn() const noexcept
The connection in which this transaction lives.
Definition: transaction_base.hxx:769
row exec1(zview query)
Execute command returning a single row of data.
Definition: transaction_base.hxx:357
auto stream(std::string_view query) &
Execute a query, and loop over the results row by row.
Definition: transaction_base.hxx:502
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:306
result exec_params0(zview query, Args &&...args)
Definition: transaction_base.hxx:662
Build a parameter list for a parameterised or prepared statement.
Definition: params.hxx:219