libpqxx  7.8.1
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 
81 
87 class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
88 {
89 public:
90  transaction_base() = delete;
91  transaction_base(transaction_base const &) = delete;
93  transaction_base &operator=(transaction_base const &) = delete;
94  transaction_base &operator=(transaction_base &&) = delete;
95 
96  virtual ~transaction_base() = 0;
97 
99 
112  void commit();
113 
115 
118  void abort();
119 
130  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
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)
221 
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 
342  result exec0(zview query) { return exec_n(0, query); }
343 
345 
351  [[deprecated("The desc parameter is going away.")]] row
352  exec1(zview query, std::string_view desc)
353  {
354 #include "pqxx/internal/ignore-deprecated-pre.hxx"
355  return exec_n(1, query, desc).front();
356 #include "pqxx/internal/ignore-deprecated-post.hxx"
357  }
358 
360 
366  row exec1(zview query) { return exec_n(1, query).front(); }
367 
369 
374  [[deprecated("The desc parameter is going away.")]] result
375  exec_n(result::size_type rows, zview query, std::string_view desc);
376 
378 
384  {
385 #include "pqxx/internal/ignore-deprecated-pre.hxx"
386  return exec_n(rows, query, std::string_view{});
387 #include "pqxx/internal/ignore-deprecated-post.hxx"
388  }
389 
391 
394  template<typename TYPE>
395  [[deprecated("The desc parameter is going away.")]] TYPE
396  query_value(zview query, std::string_view desc)
397  {
398 #include "pqxx/internal/ignore-deprecated-pre.hxx"
399  row const r{exec1(query, desc)};
400 #include "pqxx/internal/ignore-deprecated-post.hxx"
401  if (std::size(r) != 1)
402  throw usage_error{internal::concat(
403  "Queried single value from result with ", std::size(r), " columns.")};
404  return r[0].as<TYPE>();
405  }
406 
408 
414  template<typename TYPE> TYPE query_value(zview query)
415  {
416  row const r{exec1(query)};
417  if (std::size(r) != 1)
418  throw usage_error{internal::concat(
419  "Queried single value from result with ", std::size(r), " columns.")};
420  return r[0].as<TYPE>();
421  }
422 
424 
431  template<typename... TYPE>
432  [[nodiscard]] std::tuple<TYPE...> query1(zview query)
433  {
434  return exec1(query).as<TYPE...>();
435  }
436 
438 
445  template<typename... TYPE>
446  [[nodiscard]] std::optional<std::tuple<TYPE...>> query01(zview query)
447  {
448  result res{exec(query)};
449  auto const rows{std::size(res)};
450  switch (rows)
451  {
452  case 0: return {};
453  case 1: return {res[0].as<TYPE...>()};
454  default:
455  throw unexpected_rows{internal::concat(
456  "Expected at most one row of data, got "sv, rows, "."sv)};
457  }
458  }
459 
461 
505  template<typename... TYPE>
506  [[nodiscard]] auto stream(std::string_view query) &
507  {
508  return pqxx::internal::stream_query<TYPE...>{*this, query};
509  }
510 
511  // C++20: Concept like std::invocable, but without specifying param types.
513 
537  template<typename CALLABLE>
538  auto for_stream(std::string_view query, CALLABLE &&func)
539  {
540  using param_types =
542  param_types const *const sample{nullptr};
543  auto data_stream{stream_like(query, sample)};
544  for (auto const &fields : data_stream) std::apply(func, fields);
545  }
546 
547  template<typename CALLABLE>
548  [[deprecated(
549  "pqxx::transaction_base::for_each is now called for_stream.")]] auto
550  for_each(std::string_view query, CALLABLE &&func)
551  {
552  return for_stream(query, std::forward<CALLABLE>(func));
553  }
554 
556 
587  template<typename... TYPE> auto query(zview query)
588  {
589  return exec(query).iter<TYPE...>();
590  }
591 
593 
601  template<typename... TYPE> auto query_n(result::size_type rows, zview query)
602  {
603  return exec_n(rows, query).iter<TYPE...>();
604  }
605 
606  // C++20: Concept like std::invocable, but without specifying param types.
608 
616  template<typename CALLABLE> void for_query(zview query, CALLABLE &&func)
617  {
618  exec(query).for_each(std::forward<CALLABLE>(func));
619  }
620 
650  template<typename... Args> result exec_params(zview query, Args &&...args)
652  {
653  params pp(args...);
654  return internal_exec_params(query, pp.make_c_params());
655  }
656 
657  // Execute parameterised statement, expect a single-row result.
660  template<typename... Args> row exec_params1(zview query, Args &&...args)
661  {
662  return exec_params_n(1, query, std::forward<Args>(args)...).front();
663  }
664 
665  // Execute parameterised statement, expect a result with zero rows.
668  template<typename... Args> result exec_params0(zview query, Args &&...args)
669  {
670  return exec_params_n(0, query, std::forward<Args>(args)...);
671  }
672 
673  // Execute parameterised statement, expect exactly a given number of rows.
676  template<typename... Args>
677  result exec_params_n(std::size_t rows, zview query, Args &&...args)
678  {
679  auto const r{exec_params(query, std::forward<Args>(args)...)};
680  check_rowcount_params(rows, std::size(r));
681  return r;
682  }
684 
727 
729  template<typename... Args>
730  result exec_prepared(zview statement, Args &&...args)
731  {
732  params pp(args...);
733  return internal_exec_prepared(statement, pp.make_c_params());
734  }
735 
737 
739  template<typename... Args>
740  row exec_prepared1(zview statement, Args &&...args)
741  {
742  return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
743  }
744 
746 
748  template<typename... Args>
749  result exec_prepared0(zview statement, Args &&...args)
750  {
751  return exec_prepared_n(0, statement, std::forward<Args>(args)...);
752  }
753 
755 
758  template<typename... Args>
759  result
760  exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
761  {
762  auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
763  check_rowcount_prepared(statement, rows, std::size(r));
764  return r;
765  }
766 
768 
773  void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
776  void process_notice(zview msg) const { m_conn.process_notice(msg); }
778 
780  [[nodiscard]] constexpr connection &conn() const noexcept { return m_conn; }
781 
783 
798  [[deprecated(
799  "Set transaction-local variables using SQL SET statements.")]] void
800  set_variable(std::string_view var, std::string_view value);
801 
803 
806  [[deprecated("Read variables using SQL SHOW statements.")]] std::string
807  get_variable(std::string_view);
808 
809  // C++20: constexpr.
811  [[nodiscard]] std::string_view name() const &noexcept { return m_name; }
812 
813 protected:
815 
819  connection &c, std::string_view tname,
820  std::shared_ptr<std::string> rollback_cmd) :
821  m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
822  {}
823 
825 
830  transaction_base(connection &c, std::string_view tname);
831 
833  explicit transaction_base(connection &c);
834 
836  void register_transaction();
837 
839  void close() noexcept;
840 
842  virtual void do_commit() = 0;
843 
845 
848  virtual void do_abort();
849 
851  void set_rollback_cmd(std::shared_ptr<std::string> cmd)
852  {
853  m_rollback_cmd = cmd;
854  }
855 
857  result direct_exec(std::string_view, std::string_view desc = ""sv);
858  result
859  direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
860 
861 private:
862  enum class status
863  {
864  active,
865  aborted,
866  committed,
867  in_doubt
868  };
869 
870  PQXX_PRIVATE void check_pending_error();
871 
872  result
873  internal_exec_prepared(zview statement, internal::c_params const &args);
874 
875  result internal_exec_params(zview query, internal::c_params const &args);
876 
878  void check_rowcount_prepared(
879  zview statement, result::size_type expected_rows,
880  result::size_type actual_rows);
881 
883  void
884  check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
885 
887  [[nodiscard]] std::string description() const;
888 
889  friend class pqxx::internal::gate::transaction_transaction_focus;
890  PQXX_PRIVATE void register_focus(transaction_focus *);
891  PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
892  PQXX_PRIVATE void register_pending_error(zview) noexcept;
893  PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
894 
896  template<typename... ARGS>
897  auto stream_like(std::string_view query, std::tuple<ARGS...> const *)
898  {
899  return stream<ARGS...>(query);
900  }
901 
902  connection &m_conn;
903 
905 
908  transaction_focus const *m_focus = nullptr;
909 
910  status m_status = status::active;
911  bool m_registered = false;
912  std::string m_name;
913  std::string m_pending_error;
914 
916  std::shared_ptr<std::string> m_rollback_cmd;
917 
918  static constexpr std::string_view s_type_name{"transaction"sv};
919 };
920 
921 
922 // C++20: Can borrowed_range help?
924 template<>
925 std::string_view transaction_base::query_value<std::string_view>(
926  zview query, std::string_view desc) = delete;
928 template<>
929 zview transaction_base::query_value<zview>(
930  zview query, std::string_view desc) = delete;
931 
932 } // namespace pqxx
933 
934 
935 namespace pqxx::internal
936 {
938 template<pqxx::isolation_level isolation, pqxx::write_policy rw>
939 extern const zview begin_cmd;
940 
941 // These are not static members, so "constexpr" does not imply "inline".
942 template<>
943 inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
944  "BEGIN"_zv};
945 template<>
946 inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
947  "BEGIN READ ONLY"_zv};
948 template<>
949 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
950  "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
951 template<>
952 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
953  "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
954 template<>
955 inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
956  "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
957 template<>
958 inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
959  "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
960 } // namespace pqxx::internal
961 
962 #include "pqxx/internal/stream_query_impl.hxx"
963 #endif
Definition: connection.hxx:111
void for_query(zview query, CALLABLE &&func)
Execute a query, load the full result, and perform func for each row.
Definition: transaction_base.hxx:616
Error in usage of libpqxx library, similar to std::logic_error.
Definition: except.hxx:248
Query returned an unexpected number of rows.
Definition: except.hxx:342
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:760
Result set containing data returned by a query or command.
Definition: result.hxx:72
auto query_n(result::size_type rows, zview query)
Perform query, expect given number of rows, iterate results.
Definition: transaction_base.hxx:601
result exec0(zview query, std::string_view desc)
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:329
Interface definition (and common code) for "transaction" classes.
Definition: transaction_base.hxx:87
Binary data corresponding to PostgreSQL's "BYTEA" binary-string type.
Definition: binarystring.hxx:58
auto for_each(std::string_view query, CALLABLE &&func)
Definition: transaction_base.hxx:550
result_size_type size_type
Definition: result.hxx:75
std::string quote(binarystring const &t) const
Definition: transaction_base.hxx:204
TYPE query_value(zview query)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition: transaction_base.hxx:414
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
Connection to a database.
Definition: connection.hxx:252
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_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
Internal items for libpqxx' own use. Do not use these yourself.
Definition: composite.hxx:83
row exec_params1(zview query, Args &&...args)
Definition: transaction_base.hxx:660
Reference to one row in a result.
Definition: row.hxx:46
auto stream(std::string_view query)&
Execute a query, and loop over the results row by row.
Definition: transaction_base.hxx:506
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition: transaction_base.hxx:749
The home of all libpqxx classes, functions, templates, etc.
Definition: array.hxx:32
std::string quote(T const &t) const
Represent object as SQL string, including quoting & escaping.
Definition: transaction_base.hxx:197
row exec1(zview query)
Execute command returning a single row of data.
Definition: transaction_base.hxx:366
result exec_prepared(zview statement, Args &&...args)
Execute a prepared statement, with optional arguments.
Definition: transaction_base.hxx:730
std::string esc_like(std::string_view bin, char escape_char= '\\') const
Escape string for literal LIKE match.
Definition: transaction_base.hxx:238
auto for_stream(std::string_view query, CALLABLE &&func)
Perform a streaming query, and for each result row, call func.
Definition: transaction_base.hxx:538
STL namespace.
Marker-type wrapper: zero-terminated std::string_view.
Definition: zview.hxx:37
reference front() const noexcept
Definition: row.cxx:60
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition: transaction_base.hxx:231
row exec_prepared1(zview statement, Args &&...args)
Execute a prepared statement, and expect a single-row result.
Definition: transaction_base.hxx:740
auto esc_raw(ARGS &&...args) const
Escape binary data for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:148
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
std::basic_string_view< std::byte > bytes_view() const
Read data as a std::basic_string_view.
Definition: binarystring.hxx:178
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:396
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
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
result exec(std::string_view query)
Execute a command.
Definition: transaction_base.hxx:300
const zview begin_cmd
The SQL command for starting a given type of transaction.
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:818
std::string_view name() const &noexcept
Transaction name, if you passed one to the constructor; or empty string.
Definition: transaction_base.hxx:811
constexpr connection & conn() const noexcept
The connection in which this transaction lives.
Definition: transaction_base.hxx:780
result exec_n(result::size_type rows, zview query)
Execute command, expect given number of rows.
Definition: transaction_base.hxx:383
std::tuple< TYPE... > query1(zview query)
Perform query returning exactly one row, and convert its fields.
Definition: transaction_base.hxx:432
Build a parameter list for a parameterised or prepared statement.
Definition: params.hxx:219
Base class for things that monopolise a transaction's attention.
Definition: transaction_focus.hxx:28
pqxx::internal::c_params make_c_params() const
For internal use: Generate a params object for use in calls.
Definition: params.cxx:96
result exec0(zview query)
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:342
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_params0(zview query, Args &&...args)
Definition: transaction_base.hxx:668
auto query(zview query)
Execute query, read full results, then iterate rows of data.
Definition: transaction_base.hxx:587
void process_notice(zview msg) const
Have connection process a warning message.
Definition: transaction_base.hxx:776
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition: transaction_base.hxx:677
row exec1(zview query, std::string_view desc)
Execute command returning a single row of data.
Definition: transaction_base.hxx:352
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:446