libpqxx  7.7.3
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 #include "pqxx/util.hxx"
41 
42 namespace pqxx::internal::gate
43 {
44 class transaction_subtransaction;
45 class transaction_sql_cursor;
46 class transaction_stream_to;
47 class transaction_transaction_focus;
48 } // namespace pqxx::internal::gate
49 
50 
51 namespace pqxx
52 {
53 using namespace std::literals;
54 
55 
56 class transaction_focus;
57 
58 
71 
77 class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
78 {
79 public:
80  transaction_base() = delete;
81  transaction_base(transaction_base const &) = delete;
83  transaction_base &operator=(transaction_base const &) = delete;
84  transaction_base &operator=(transaction_base &&) = delete;
85 
86  virtual ~transaction_base() = 0;
87 
89 
102  void commit();
103 
105 
108  void abort();
109 
120  template<typename... ARGS> [[nodiscard]] auto esc(ARGS &&...args) const
122  {
123  return conn().esc(std::forward<ARGS>(args)...);
124  }
125 
127 
138  template<typename... ARGS> [[nodiscard]] auto esc_raw(ARGS &&...args) const
139  {
140  return conn().esc_raw(std::forward<ARGS>(args)...);
141  }
142 
144 
147  [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
148  unesc_raw(zview text) const
149  {
150 #include "pqxx/internal/ignore-deprecated-pre.hxx"
151  return conn().unesc_raw(text);
152 #include "pqxx/internal/ignore-deprecated-post.hxx"
153  }
154 
156 
159  [[nodiscard]] std::basic_string<std::byte> unesc_bin(zview text)
160  {
161  return conn().unesc_bin(text);
162  }
163 
165 
168  [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
169  unesc_raw(char const *text) const
170  {
171 #include "pqxx/internal/ignore-deprecated-pre.hxx"
172  return conn().unesc_raw(text);
173 #include "pqxx/internal/ignore-deprecated-post.hxx"
174  }
175 
177 
180  [[nodiscard]] std::basic_string<std::byte> unesc_bin(char const text[])
181  {
182  return conn().unesc_bin(text);
183  }
184 
186 
187  template<typename T> [[nodiscard]] std::string quote(T const &t) const
188  {
189  return conn().quote(t);
190  }
191 
192  [[deprecated(
193  "Use std::basic_string<std::byte> instead of binarystring.")]] std::string
194  quote(binarystring const &t) const
195  {
196  return conn().quote(t.bytes_view());
197  }
198 
200  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
201  quote_raw(unsigned char const bin[], std::size_t len) const
202  {
203  return quote(binary_cast(bin, len));
204  }
205 
207  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
208  quote_raw(zview bin) const;
209 
210 #if defined(PQXX_HAVE_CONCEPTS)
211 
213  template<binary DATA>
214  [[nodiscard]] std::string quote_raw(DATA const &data) const
215  {
216  return conn().quote_raw(data);
217  }
218 #endif
219 
221  [[nodiscard]] std::string quote_name(std::string_view identifier) const
222  {
223  return conn().quote_name(identifier);
224  }
225 
227  [[nodiscard]] std::string
228  esc_like(std::string_view bin, char escape_char = '\\') const
229  {
230  return conn().esc_like(bin, escape_char);
231  }
233 
258 
260 
265  [[deprecated("The desc parameter is going away.")]] result
266  exec(std::string_view query, std::string_view desc);
267 
269 
273  result exec(std::string_view query)
274  {
275 #include "pqxx/internal/ignore-deprecated-pre.hxx"
276  return exec(query, std::string_view{});
277 #include "pqxx/internal/ignore-deprecated-post.hxx"
278  }
279 
281 
286  [[deprecated(
287  "Pass your query as a std::string_view, not stringstream.")]] result
288  exec(std::stringstream const &query, std::string_view desc)
289  {
290 #include "pqxx/internal/ignore-deprecated-pre.hxx"
291  return exec(query.str(), desc);
292 #include "pqxx/internal/ignore-deprecated-post.hxx"
293  }
294 
296 
301  [[deprecated("The desc parameter is going away.")]] result
302  exec0(zview query, std::string_view desc)
303  {
304 #include "pqxx/internal/ignore-deprecated-pre.hxx"
305  return exec_n(0, query, desc);
306 #include "pqxx/internal/ignore-deprecated-post.hxx"
307  }
308 
310 
315  result exec0(zview query) { return exec_n(0, query); }
316 
318 
324  [[deprecated("The desc parameter is going away.")]] row
325  exec1(zview query, std::string_view desc)
326  {
327 #include "pqxx/internal/ignore-deprecated-pre.hxx"
328  return exec_n(1, query, desc).front();
329 #include "pqxx/internal/ignore-deprecated-post.hxx"
330  }
331 
333 
339  row exec1(zview query) { return exec_n(1, query).front(); }
340 
342 
347  [[deprecated("The desc parameter is going away.")]] result
348  exec_n(result::size_type rows, zview query, std::string_view desc);
349 
351 
357  {
358 #include "pqxx/internal/ignore-deprecated-pre.hxx"
359  return exec_n(rows, query, std::string_view{});
360 #include "pqxx/internal/ignore-deprecated-post.hxx"
361  }
362 
364 
367  template<typename TYPE>
368  [[deprecated("The desc parameter is going away.")]] TYPE
369  query_value(zview query, std::string_view desc)
370  {
371 #include "pqxx/internal/ignore-deprecated-pre.hxx"
372  row const r{exec1(query, desc)};
373 #include "pqxx/internal/ignore-deprecated-post.hxx"
374  if (std::size(r) != 1)
375  throw usage_error{internal::concat(
376  "Queried single value from result with ", std::size(r), " columns.")};
377  return r[0].as<TYPE>();
378  }
379 
381 
384  template<typename TYPE> TYPE query_value(zview query)
385  {
386  row const r{exec1(query)};
387  if (std::size(r) != 1)
388  throw usage_error{internal::concat(
389  "Queried single value from result with ", std::size(r), " columns.")};
390  return r[0].as<TYPE>();
391  }
392 
394 
441  template<typename... TYPE>
442  [[nodiscard]] auto stream(std::string_view query) &
443  {
444  // Tricky: std::make_unique() supports constructors but not RVO functions.
445  return pqxx::internal::owning_stream_input_iteration<TYPE...>{
446  std::unique_ptr<stream_from>{
447  new stream_from{stream_from::query(*this, query)}}};
448  }
449 
450  // C++20: Concept like std::invocable, but without specifying param types.
452 
471  template<typename CALLABLE>
472  inline auto for_each(std::string_view query, CALLABLE &&func)
473  {
474  using param_types =
476  param_types const *const sample{nullptr};
477  auto data_stream{stream_like(query, sample)};
478  for (auto const &fields : data_stream) std::apply(func, fields);
479  }
480 
510  template<typename... Args> result exec_params(zview query, Args &&...args)
512  {
513  params pp(args...);
514  return internal_exec_params(query, pp.make_c_params());
515  }
516 
517  // Execute parameterised statement, expect a single-row result.
520  template<typename... Args> row exec_params1(zview query, Args &&...args)
521  {
522  return exec_params_n(1, query, std::forward<Args>(args)...).front();
523  }
524 
525  // Execute parameterised statement, expect a result with zero rows.
528  template<typename... Args> result exec_params0(zview query, Args &&...args)
529  {
530  return exec_params_n(0, query, std::forward<Args>(args)...);
531  }
532 
533  // Execute parameterised statement, expect exactly a given number of rows.
536  template<typename... Args>
537  result exec_params_n(std::size_t rows, zview query, Args &&...args)
538  {
539  auto const r{exec_params(query, std::forward<Args>(args)...)};
540  check_rowcount_params(rows, std::size(r));
541  return r;
542  }
544 
576 
578  template<typename... Args>
579  result exec_prepared(zview statement, Args &&...args)
580  {
581  params pp(args...);
582  return internal_exec_prepared(statement, pp.make_c_params());
583  }
584 
586 
588  template<typename... Args>
589  row exec_prepared1(zview statement, Args &&...args)
590  {
591  return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
592  }
593 
595 
597  template<typename... Args>
598  result exec_prepared0(zview statement, Args &&...args)
599  {
600  return exec_prepared_n(0, statement, std::forward<Args>(args)...);
601  }
602 
604 
607  template<typename... Args>
608  result
609  exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
610  {
611  auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
612  check_rowcount_prepared(statement, rows, std::size(r));
613  return r;
614  }
615 
617 
622  void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
625  void process_notice(zview msg) const { m_conn.process_notice(msg); }
627 
629  [[nodiscard]] constexpr connection &conn() const noexcept { return m_conn; }
630 
632 
647  [[deprecated(
648  "Set transaction-local variables using SQL SET statements.")]] void
649  set_variable(std::string_view var, std::string_view value);
650 
652 
655  [[deprecated("Read variables using SQL SHOW statements.")]] std::string
656  get_variable(std::string_view);
657 
658  // C++20: constexpr.
660  [[nodiscard]] std::string_view name() const &noexcept { return m_name; }
661 
662 protected:
664 
668  connection &c, std::string_view tname,
669  std::shared_ptr<std::string> rollback_cmd) :
670  m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
671  {}
672 
674 
679  transaction_base(connection &c, std::string_view tname);
680 
682  explicit transaction_base(connection &c);
683 
685  void register_transaction();
686 
688  void close() noexcept;
689 
691  virtual void do_commit() = 0;
692 
694 
697  virtual void do_abort();
698 
700  void set_rollback_cmd(std::shared_ptr<std::string> cmd)
701  {
702  m_rollback_cmd = cmd;
703  }
704 
706  result direct_exec(std::string_view, std::string_view desc = ""sv);
707  result
708  direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
709 
710 private:
711  enum class status
712  {
713  active,
714  aborted,
715  committed,
716  in_doubt
717  };
718 
719  PQXX_PRIVATE void check_pending_error();
720 
721  result
722  internal_exec_prepared(zview statement, internal::c_params const &args);
723 
724  result internal_exec_params(zview query, internal::c_params const &args);
725 
727  void check_rowcount_prepared(
728  zview statement, result::size_type expected_rows,
729  result::size_type actual_rows);
730 
732  void
733  check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
734 
736  [[nodiscard]] std::string description() const;
737 
738  friend class pqxx::internal::gate::transaction_transaction_focus;
739  PQXX_PRIVATE void register_focus(transaction_focus *);
740  PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
741  PQXX_PRIVATE void register_pending_error(zview) noexcept;
742  PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
743 
745  template<typename... ARGS>
746  auto stream_like(std::string_view query, std::tuple<ARGS...> const *)
747  {
748  return stream<ARGS...>(query);
749  }
750 
751  connection &m_conn;
752 
754 
757  transaction_focus const *m_focus = nullptr;
758 
759  status m_status = status::active;
760  bool m_registered = false;
761  std::string m_name;
762  std::string m_pending_error;
763 
765  std::shared_ptr<std::string> m_rollback_cmd;
766 
767  static constexpr std::string_view s_type_name{"transaction"sv};
768 };
769 
770 
771 // C++20: Can borrowed_range help?
773 template<>
774 std::string_view transaction_base::query_value<std::string_view>(
775  zview query, std::string_view desc) = delete;
777 template<>
778 zview transaction_base::query_value<zview>(
779  zview query, std::string_view desc) = delete;
780 
781 } // namespace pqxx
782 
783 
784 namespace pqxx::internal
785 {
787 template<pqxx::isolation_level isolation, pqxx::write_policy rw>
788 extern const zview begin_cmd;
789 
790 // These are not static members, so "constexpr" does not imply "inline".
791 template<>
792 inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
793  "BEGIN"_zv};
794 template<>
795 inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
796  "BEGIN READ ONLY"_zv};
797 template<>
798 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
799  "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
800 template<>
801 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
802  "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
803 template<>
804 inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
805  "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
806 template<>
807 inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
808  "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
809 } // namespace pqxx::internal
810 #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:589
auto esc_raw(ARGS &&...args) const
Escape binary data for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:138
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:201
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:185
std::string unesc_raw(zview text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:148
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:159
result exec0(zview query)
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:315
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:520
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition: transaction_base.hxx:221
TYPE query_value(zview query)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition: transaction_base.hxx:384
std::string quote(binarystring const &t) const
Definition: transaction_base.hxx:194
STL namespace.
row exec1(zview query, std::string_view desc)
Execute command returning a single row of data.
Definition: transaction_base.hxx:325
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:579
void process_notice(zview msg) const
Have connection process a warning message.
Definition: transaction_base.hxx:625
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition: transaction_base.hxx:537
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition: transaction_base.hxx:228
result exec0(zview query, std::string_view desc)
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:302
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:609
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:369
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:187
Interface definition (and common code) for "transaction" classes.
Definition: transaction_base.hxx:77
auto for_each(std::string_view query, CALLABLE &&func)
Perform a streaming query, and for each result row, call func.
Definition: transaction_base.hxx:472
decltype(strip_types(std::declval< TYPES... >())) strip_types_t
Take a tuple type and apply strip_t to its component types.
Definition: util.hxx:519
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:180
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:667
Result set containing data returned by a query or command.
Definition: result.hxx:73
result exec(std::stringstream const &query, std::string_view desc)
Execute a command.
Definition: transaction_base.hxx:288
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:660
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:700
result exec(std::string_view query)
Execute a command.
Definition: transaction_base.hxx:273
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition: transaction_base.hxx:598
std::string unesc_raw(char const *text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:169
result exec_n(result::size_type rows, zview query)
Execute command, expect given number of rows.
Definition: transaction_base.hxx:356
constexpr connection & conn() const noexcept
The connection in which this transaction lives.
Definition: transaction_base.hxx:629
row exec1(zview query)
Execute command returning a single row of data.
Definition: transaction_base.hxx:339
auto stream(std::string_view query) &
Execute a query, and loop over the results row by row.
Definition: transaction_base.hxx:442
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:296
result exec_params0(zview query, Args &&...args)
Definition: transaction_base.hxx:528
Build a parameter list for a parameterised or prepared statement.
Definition: params.hxx:219