libpqxx  7.8.0
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-2023, 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/internal/stream_query.hxx"
36 #include "pqxx/isolation.hxx"
37 #include "pqxx/result.hxx"
38 #include "pqxx/row.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 
82 
87 class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
88 {
89 public:
90  transaction_base() = delete;
95 
96  virtual ~transaction_base() = 0;
97 
99 
112  void commit();
113 
115 
118  void abort();
119 
131  template<typename... ARGS> [[nodiscard]] auto esc(ARGS &&...args) const
132  {
133  return conn().esc(std::forward<ARGS>(args)...);
134  }
135 
137 
148  template<typename... ARGS> [[nodiscard]] auto esc_raw(ARGS &&...args) const
149  {
150  return conn().esc_raw(std::forward<ARGS>(args)...);
151  }
152 
154 
157  [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
158  unesc_raw(zview text) const
159  {
160 #include "pqxx/internal/ignore-deprecated-pre.hxx"
161  return conn().unesc_raw(text);
162 #include "pqxx/internal/ignore-deprecated-post.hxx"
163  }
164 
166 
169  [[nodiscard]] std::basic_string<std::byte> unesc_bin(zview text)
170  {
171  return conn().unesc_bin(text);
172  }
173 
175 
178  [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
179  unesc_raw(char const *text) const
180  {
181 #include "pqxx/internal/ignore-deprecated-pre.hxx"
182  return conn().unesc_raw(text);
183 #include "pqxx/internal/ignore-deprecated-post.hxx"
184  }
185 
187 
190  [[nodiscard]] std::basic_string<std::byte> unesc_bin(char const text[])
191  {
192  return conn().unesc_bin(text);
193  }
194 
196 
197  template<typename T> [[nodiscard]] std::string quote(T const &t) const
198  {
199  return conn().quote(t);
200  }
201 
202  [[deprecated(
203  "Use std::basic_string<std::byte> instead of binarystring.")]] std::string
204  quote(binarystring const &t) const
205  {
206  return conn().quote(t.bytes_view());
207  }
208 
210  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
211  quote_raw(unsigned char const bin[], std::size_t len) const
212  {
213  return quote(binary_cast(bin, len));
214  }
215 
217  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
218  quote_raw(zview bin) const;
219 
220 #if defined(PQXX_HAVE_CONCEPTS)
222 
223  template<binary DATA>
224  [[nodiscard]] std::string quote_raw(DATA const &data) const
225  {
226  return conn().quote_raw(data);
227  }
228 #endif
229 
231  [[nodiscard]] std::string quote_name(std::string_view identifier) const
232  {
233  return conn().quote_name(identifier);
234  }
235 
237  [[nodiscard]] std::string
238  esc_like(std::string_view bin, char escape_char = '\\') const
239  {
240  return conn().esc_like(bin, escape_char);
241  }
243 
285 
287 
292  [[deprecated("The desc parameter is going away.")]] result
293  exec(std::string_view query, std::string_view desc);
294 
296 
300  result exec(std::string_view query)
301  {
302 #include "pqxx/internal/ignore-deprecated-pre.hxx"
303  return exec(query, std::string_view{});
304 #include "pqxx/internal/ignore-deprecated-post.hxx"
305  }
306 
308 
313  [[deprecated(
314  "Pass your query as a std::string_view, not stringstream.")]] result
315  exec(std::stringstream const &query, std::string_view desc)
316  {
317 #include "pqxx/internal/ignore-deprecated-pre.hxx"
318  return exec(query.str(), desc);
319 #include "pqxx/internal/ignore-deprecated-post.hxx"
320  }
321 
323 
328  [[deprecated("The desc parameter is going away.")]] result
329  exec0(zview query, std::string_view desc)
330  {
331 #include "pqxx/internal/ignore-deprecated-pre.hxx"
332  return exec_n(0, query, desc);
333 #include "pqxx/internal/ignore-deprecated-post.hxx"
334  }
335 
337 
343  {
344  return exec_n(0, query);
345  }
346 
348 
354  [[deprecated("The desc parameter is going away.")]] row
355  exec1(zview query, std::string_view desc)
356  {
357 #include "pqxx/internal/ignore-deprecated-pre.hxx"
358  return exec_n(1, query, desc).front();
359 #include "pqxx/internal/ignore-deprecated-post.hxx"
360  }
361 
363 
369  row exec1(zview query)
370  {
371  return exec_n(1, query).front();
372  }
373 
375 
380  [[deprecated("The desc parameter is going away.")]] result
381  exec_n(result::size_type rows, zview query, std::string_view desc);
382 
384 
390  {
391 #include "pqxx/internal/ignore-deprecated-pre.hxx"
392  return exec_n(rows, query, std::string_view{});
393 #include "pqxx/internal/ignore-deprecated-post.hxx"
394  }
395 
397 
400  template<typename TYPE>
401  [[deprecated("The desc parameter is going away.")]] TYPE
402  query_value(zview query, std::string_view desc)
403  {
404 #include "pqxx/internal/ignore-deprecated-pre.hxx"
405  row const r{exec1(query, desc)};
406 #include "pqxx/internal/ignore-deprecated-post.hxx"
407  if (std::size(r) != 1)
408  throw usage_error{internal::concat(
409  "Queried single value from result with ", std::size(r), " columns.")};
410  return r[0].as<TYPE>();
411  }
412 
414 
420  template<typename TYPE> TYPE query_value(zview query)
421  {
422  row const r{exec1(query)};
423  if (std::size(r) != 1)
424  throw usage_error{internal::concat(
425  "Queried single value from result with ", std::size(r), " columns.")};
426  return r[0].as<TYPE>();
427  }
428 
430 
437  template<typename... TYPE>
438  [[nodiscard]] std::tuple<TYPE...> query1(zview query)
439  {
440  return exec1(query).as<TYPE...>();
441  }
442 
444 
451  template<typename... TYPE>
452  [[nodiscard]] std::optional<std::tuple<TYPE...>> query01(zview query)
453  {
454  result res{exec(query)};
455  auto const rows{std::size(res)};
456  switch (rows)
457  {
458  case 0: return {};
459  case 1: return {res[0].as<TYPE...>()};
460  default:
461  throw unexpected_rows{internal::concat(
462  "Expected at most one row of data, got "sv, rows, "."sv)};
463  }
464  }
465 
467 
511  template<typename... TYPE>
512  [[nodiscard]] auto stream(std::string_view query) &
513  {
514  return pqxx::internal::stream_query<TYPE...>{*this, query};
515  }
516 
517  // C++20: Concept like std::invocable, but without specifying param types.
519 
543  template<typename CALLABLE>
544  auto for_stream(std::string_view query, CALLABLE &&func)
545  {
546  using param_types =
548  param_types const *const sample{nullptr};
549  auto data_stream{stream_like(query, sample)};
550  for (auto const &fields : data_stream) std::apply(func, fields);
551  }
552 
553  template<typename CALLABLE>
554  [[deprecated(
555  "pqxx::transaction_base::for_each is now called for_stream.")]] auto
556  for_each(std::string_view query, CALLABLE &&func)
557  {
558  return for_stream(query, std::forward<CALLABLE>(func));
559  }
560 
562 
593  template<typename... TYPE> auto query(zview query)
594  {
595  return exec(query).iter<TYPE...>();
596  }
597 
599 
607  template<typename... TYPE> auto query_n(result::size_type rows, zview query)
608  {
609  return exec_n(rows, query).iter<TYPE...>();
610  }
611 
612  // C++20: Concept like std::invocable, but without specifying param types.
614 
622  template<typename CALLABLE> void for_query(zview query, CALLABLE &&func)
623  {
624  exec(query).for_each(std::forward<CALLABLE>(func));
625  }
626 
657  template<typename... Args> result exec_params(zview query, Args &&...args)
658  {
659  params pp(args...);
660  return internal_exec_params(query, pp.make_c_params());
661  }
662 
663  // Execute parameterised statement, expect a single-row result.
666  template<typename... Args> row exec_params1(zview query, Args &&...args)
667  {
668  return exec_params_n(1, query, std::forward<Args>(args)...).front();
669  }
670 
671  // Execute parameterised statement, expect a result with zero rows.
674  template<typename... Args> result exec_params0(zview query, Args &&...args)
675  {
676  return exec_params_n(0, query, std::forward<Args>(args)...);
677  }
678 
679  // Execute parameterised statement, expect exactly a given number of rows.
682  template<typename... Args>
683  result exec_params_n(std::size_t rows, zview query, Args &&...args)
684  {
685  auto const r{exec_params(query, std::forward<Args>(args)...)};
686  check_rowcount_params(rows, std::size(r));
687  return r;
688  }
690 
733 
735  template<typename... Args>
736  result exec_prepared(zview statement, Args &&...args)
737  {
738  params pp(args...);
739  return internal_exec_prepared(statement, pp.make_c_params());
740  }
741 
743 
745  template<typename... Args>
746  row exec_prepared1(zview statement, Args &&...args)
747  {
748  return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
749  }
750 
752 
754  template<typename... Args>
755  result exec_prepared0(zview statement, Args &&...args)
756  {
757  return exec_prepared_n(0, statement, std::forward<Args>(args)...);
758  }
759 
761 
764  template<typename... Args>
765  result
766  exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
767  {
768  auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
769  check_rowcount_prepared(statement, rows, std::size(r));
770  return r;
771  }
772 
774 
780  void process_notice(char const msg[]) const
781  {
782  m_conn.process_notice(msg);
783  }
785  void process_notice(zview msg) const
786  {
787  m_conn.process_notice(msg);
788  }
790 
792  [[nodiscard]] constexpr connection &conn() const noexcept
793  {
794  return m_conn;
795  }
796 
798 
813  [[deprecated(
814  "Set transaction-local variables using SQL SET statements.")]] void
815  set_variable(std::string_view var, std::string_view value);
816 
818 
821  [[deprecated("Read variables using SQL SHOW statements.")]] std::string
822  get_variable(std::string_view);
823 
824  // C++20: constexpr.
826  [[nodiscard]] std::string_view name() const &noexcept
827  {
828  return m_name;
829  }
830 
831 protected:
833 
837  connection &c, std::string_view tname,
838  std::shared_ptr<std::string> rollback_cmd) :
839  m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
840  {}
841 
843 
848  transaction_base(connection &c, std::string_view tname);
849 
851  explicit transaction_base(connection &c);
852 
854  void register_transaction();
855 
857  void close() noexcept;
858 
860  virtual void do_commit() = 0;
861 
863 
866  virtual void do_abort();
867 
869  void set_rollback_cmd(std::shared_ptr<std::string> cmd)
870  {
871  m_rollback_cmd = cmd;
872  }
873 
875  result direct_exec(std::string_view, std::string_view desc = ""sv);
876  result
877  direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
878 
879 private:
880  enum class status
881  {
882  active,
883  aborted,
884  committed,
885  in_doubt
886  };
887 
888  PQXX_PRIVATE void check_pending_error();
889 
890  result
891  internal_exec_prepared(zview statement, internal::c_params const &args);
892 
893  result internal_exec_params(zview query, internal::c_params const &args);
894 
896  void check_rowcount_prepared(
897  zview statement, result::size_type expected_rows,
898  result::size_type actual_rows);
899 
901  void
902  check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
903 
905  [[nodiscard]] std::string description() const;
906 
907  friend class pqxx::internal::gate::transaction_transaction_focus;
908  PQXX_PRIVATE void register_focus(transaction_focus *);
909  PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
910  PQXX_PRIVATE void register_pending_error(zview) noexcept;
911  PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
912 
914  template<typename... ARGS>
915  auto stream_like(std::string_view query, std::tuple<ARGS...> const *)
916  {
917  return stream<ARGS...>(query);
918  }
919 
920  connection &m_conn;
921 
923 
926  transaction_focus const *m_focus = nullptr;
927 
928  status m_status = status::active;
929  bool m_registered = false;
930  std::string m_name;
931  std::string m_pending_error;
932 
934  std::shared_ptr<std::string> m_rollback_cmd;
935 
936  static constexpr std::string_view s_type_name{"transaction"sv};
937 };
938 
939 
940 // C++20: Can borrowed_range help?
942 template<>
943 std::string_view transaction_base::query_value<std::string_view>(
944  zview query, std::string_view desc) = delete;
946 template<>
947 zview transaction_base::query_value<zview>(
948  zview query, std::string_view desc) = delete;
949 
950 } // namespace pqxx
951 
952 
953 namespace pqxx::internal
954 {
956 template<pqxx::isolation_level isolation, pqxx::write_policy rw>
957 extern const zview begin_cmd;
958 
959 // These are not static members, so "constexpr" does not imply "inline".
960 template<>
961 inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
962  "BEGIN"_zv};
963 template<>
964 inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
965  "BEGIN READ ONLY"_zv};
966 template<>
967 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
968  "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
969 template<>
970 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
971  "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
972 template<>
973 inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
974  "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
975 template<>
976 inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
977  "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
978 } // namespace pqxx::internal
979 
980 #include "pqxx/internal/stream_query_impl.hxx"
981 #endif
auto esc(ARGS &&...args) const
Escape string for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:131
The home of all libpqxx classes, functions, templates, etc.
Definition: array.hxx:33
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:303
Internal items for libpqxx' own use. Do not use these yourself.
Definition: composite.hxx:84
const zview begin_cmd
The SQL command for starting a given type of transaction.
decltype(strip_types(std::declval< TYPES... >())) strip_types_t
Take a tuple type and apply strip_t to its component types.
Definition: util.hxx:527
Definition: connection.hxx:109
Binary data corresponding to PostgreSQL's "BYTEA" binary-string type.
Definition: binarystring.hxx:59
std::basic_string_view< std::byte > bytes_view() const
Read data as a std::basic_string_view<std::byte>.
Definition: binarystring.hxx:178
Connection to a database.
Definition: connection.hxx:250
Error in usage of libpqxx library, similar to std::logic_error.
Definition: except.hxx:238
Query returned an unexpected number of rows.
Definition: except.hxx:320
Build a parameter list for a parameterised or prepared statement.
Definition: params.hxx:220
pqxx::internal::c_params make_c_params() const
For internal use: Generate a params object for use in calls.
Definition: params.cxx:96
Result set containing data returned by a query or command.
Definition: result.hxx:73
result_size_type size_type
Definition: result.hxx:75
Reference to one row in a result.
Definition: row.hxx:47
reference front() const noexcept
Definition: row.cxx:60
Interface definition (and common code) for "transaction" classes.
Definition: transaction_base.hxx:88
result exec_prepared(zview statement, Args &&...args)
Execute a prepared statement, with optional arguments.
Definition: transaction_base.hxx:736
result exec0(zview query, std::string_view desc)
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:329
auto for_each(std::string_view query, CALLABLE &&func)
Definition: transaction_base.hxx:556
auto query(zview query)
Execute query, read full results, then iterate rows of data.
Definition: transaction_base.hxx:593
void process_notice(zview msg) const
Have connection process a warning message.
Definition: transaction_base.hxx:785
result exec0(zview query)
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:342
auto query_n(result::size_type rows, zview query)
Perform query, expect given number of rows, iterate results.
Definition: transaction_base.hxx:607
std::string unesc_raw(char const *text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:179
transaction_base & operator=(transaction_base &&)=delete
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:402
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:766
transaction_base(transaction_base const &)=delete
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:836
std::string quote(T const &t) const
Represent object as SQL string, including quoting & escaping.
Definition: transaction_base.hxx:197
row exec_params1(zview query, Args &&...args)
Definition: transaction_base.hxx:666
TYPE query_value(zview query)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition: transaction_base.hxx:420
auto esc_raw(ARGS &&...args) const
Escape binary data for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:148
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:190
result exec(std::stringstream const &query, std::string_view desc)
Execute a command.
Definition: transaction_base.hxx:315
std::string quote(binarystring const &t) const
Definition: transaction_base.hxx:204
row exec1(zview query)
Execute command returning a single row of data.
Definition: transaction_base.hxx:369
row exec1(zview query, std::string_view desc)
Execute command returning a single row of data.
Definition: transaction_base.hxx:355
transaction_base(transaction_base &&)=delete
std::tuple< TYPE... > query1(zview query)
Perform query returning exactly one row, and convert its fields.
Definition: transaction_base.hxx:438
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:452
result exec_params(zview query, Args &&...args)
Execute an SQL statement with parameters.
Definition: transaction_base.hxx:657
result exec_params0(zview query, Args &&...args)
Definition: transaction_base.hxx:674
auto for_stream(std::string_view query, CALLABLE &&func)
Perform a streaming query, and for each result row, call func.
Definition: transaction_base.hxx:544
std::string unesc_raw(zview text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:158
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition: transaction_base.hxx:755
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition: transaction_base.hxx:238
result exec_n(result::size_type rows, zview query)
Execute command, expect given number of rows.
Definition: transaction_base.hxx:389
result exec(std::string_view query)
Execute a command.
Definition: transaction_base.hxx:300
row exec_prepared1(zview statement, Args &&...args)
Execute a prepared statement, and expect a single-row result.
Definition: transaction_base.hxx:746
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition: transaction_base.hxx:231
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:211
std::string_view name() const &noexcept
Transaction name, if you passed one to the constructor; or empty string.
Definition: transaction_base.hxx:826
constexpr connection & conn() const noexcept
The connection in which this transaction lives.
Definition: transaction_base.hxx:792
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:169
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition: transaction_base.hxx:683
auto stream(std::string_view query) &
Execute a query, and loop over the results row by row.
Definition: transaction_base.hxx:512
void for_query(zview query, CALLABLE &&func)
Execute a query, load the full result, and perform func for each row.
Definition: transaction_base.hxx:622
transaction_base & operator=(transaction_base const &)=delete
void process_notice(char const msg[]) const
Have connection process a warning message.
Definition: transaction_base.hxx:780
Base class for things that monopolise a transaction's attention.
Definition: transaction_focus.hxx:29
Marker-type wrapper: zero-terminated std::string_view.
Definition: zview.hxx:38