libpqxx  7.6.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-2021, 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 #include "pqxx/compiler-public.hxx"
18 #include "pqxx/internal/compiler-internal-pre.hxx"
19 
20 #include <string_view>
21 #include <utility>
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 
40 namespace pqxx::internal::gate
41 {
42 class transaction_subtransaction;
43 class transaction_sql_cursor;
44 class transaction_stream_to;
45 class transaction_transaction_focus;
46 } // namespace pqxx::internal::gate
47 
48 
49 namespace pqxx
50 {
51 using namespace std::literals;
52 
53 
54 class transaction_focus;
55 
56 
69 
75 class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
76 {
77 public:
78  transaction_base() = delete;
79  transaction_base(transaction_base const &) = delete;
81  transaction_base &operator=(transaction_base const &) = delete;
82  transaction_base &operator=(transaction_base &&) = delete;
83 
84  virtual ~transaction_base() = 0;
85 
87 
99  void commit();
100 
102 
105  void abort();
106 
117  template<typename... ARGS> [[nodiscard]] auto esc(ARGS &&...args) const
119  {
120  return conn().esc(std::forward<ARGS>(args)...);
121  }
122 
124 
135  template<typename... ARGS> [[nodiscard]] auto esc_raw(ARGS &&...args) const
136  {
137  return conn().esc_raw(std::forward<ARGS>(args)...);
138  }
139 
141 
144  [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
145  unesc_raw(zview text) const
146  {
147 #include "pqxx/internal/ignore-deprecated-pre.hxx"
148  return conn().unesc_raw(text);
149 #include "pqxx/internal/ignore-deprecated-post.hxx"
150  }
151 
153 
156  [[nodiscard]] std::basic_string<std::byte> unesc_bin(zview text)
157  {
158  return conn().unesc_bin(text);
159  }
160 
162 
165  [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
166  unesc_raw(char const *text) const
167  {
168 #include "pqxx/internal/ignore-deprecated-pre.hxx"
169  return conn().unesc_raw(text);
170 #include "pqxx/internal/ignore-deprecated-post.hxx"
171  }
172 
174 
177  [[nodiscard]] std::basic_string<std::byte> unesc_bin(char const text[])
178  {
179  return conn().unesc_bin(text);
180  }
181 
183 
184  template<typename T> [[nodiscard]] std::string quote(T const &t) const
185  {
186  return conn().quote(t);
187  }
188 
189  [[deprecated(
190  "Use std::basic_string<std::byte> instead of binarystring.")]] std::string
191  quote(binarystring const &t) const
192  {
193  return conn().quote(t.bytes_view());
194  }
195 
197  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
198  quote_raw(unsigned char const bin[], std::size_t len) const
199  {
200  return quote(binary_cast(bin, len));
201  }
202 
204  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
205  quote_raw(zview bin) const;
206 
207 #if defined(PQXX_HAVE_CONCEPTS)
208 
210  template<binary DATA>
211  [[nodiscard]] std::string quote_raw(DATA const &data) const
212  {
213  return conn().quote_raw(data);
214  }
215 #endif
216 
218  [[nodiscard]] std::string quote_name(std::string_view identifier) const
219  {
220  return conn().quote_name(identifier);
221  }
222 
224  [[nodiscard]] std::string
225  esc_like(std::string_view bin, char escape_char = '\\') const
226  {
227  return conn().esc_like(bin, escape_char);
228  }
230 
250 
252 
257  result
258  exec(std::string_view query, std::string_view desc = std::string_view{});
259 
261 
267  std::stringstream const &query, std::string_view desc = std::string_view{})
268  {
269  return exec(query.str(), desc);
270  }
271 
273 
278  result exec0(zview query, std::string_view desc = std::string_view{})
279  {
280  return exec_n(0, query, desc);
281  }
282 
284 
290  row exec1(zview query, std::string_view desc = std::string_view{})
291  {
292  return exec_n(1, query, desc).front();
293  }
294 
296 
301  result exec_n(
302  result::size_type rows, zview query,
303  std::string_view desc = std::string_view{});
304 
306 
309  template<typename TYPE>
310  TYPE query_value(zview query, std::string_view desc = std::string_view{})
311  {
312  row const r{exec1(query, desc)};
313  if (std::size(r) != 1)
314  throw usage_error{internal::concat(
315  "Queried single value from result with ", std::size(r), " columns.")};
316  return r[0].as<TYPE>();
317  }
318 
320 
368  template<typename... TYPE> [[nodiscard]] auto stream(std::string_view query)
369  {
370  // Tricky: std::make_unique() supports constructors but not RVO functions.
371  return pqxx::internal::owning_stream_input_iteration<TYPE...>{
372  std::unique_ptr<stream_from>{
373  new stream_from{stream_from::query(*this, query)}}};
374  }
375 
405  template<typename... Args> result exec_params(zview query, Args &&...args)
407  {
408  params pp(args...);
409  return internal_exec_params(query, pp.make_c_params());
410  }
411 
412  // Execute parameterised statement, expect a single-row result.
415  template<typename... Args> row exec_params1(zview query, Args &&...args)
416  {
417  return exec_params_n(1, query, std::forward<Args>(args)...).front();
418  }
419 
420  // Execute parameterised statement, expect a result with zero rows.
423  template<typename... Args> result exec_params0(zview query, Args &&...args)
424  {
425  return exec_params_n(0, query, std::forward<Args>(args)...);
426  }
427 
428  // Execute parameterised statement, expect exactly a given number of rows.
431  template<typename... Args>
432  result exec_params_n(std::size_t rows, zview query, Args &&...args)
433  {
434  auto const r{exec_params(query, std::forward<Args>(args)...)};
435  check_rowcount_params(rows, std::size(r));
436  return r;
437  }
439 
471 
473  template<typename... Args>
474  result exec_prepared(zview statement, Args &&...args)
475  {
476  params pp(args...);
477  return internal_exec_prepared(statement, pp.make_c_params());
478  }
479 
481 
483  template<typename... Args>
484  row exec_prepared1(zview statement, Args &&...args)
485  {
486  return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
487  }
488 
490 
492  template<typename... Args>
493  result exec_prepared0(zview statement, Args &&...args)
494  {
495  return exec_prepared_n(0, statement, std::forward<Args>(args)...);
496  }
497 
499 
502  template<typename... Args>
503  result
504  exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
505  {
506  auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
507  check_rowcount_prepared(statement, rows, std::size(r));
508  return r;
509  }
510 
512 
517  void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
520  void process_notice(zview msg) const { m_conn.process_notice(msg); }
522 
524  [[nodiscard]] connection &conn() const { return m_conn; }
525 
527 
537  void set_variable(std::string_view var, std::string_view value);
538 
540 
543  std::string get_variable(std::string_view);
544 
546  [[nodiscard]] std::string_view name() const noexcept { return m_name; }
547 
548 protected:
550 
554  connection &c, std::string_view tname,
555  std::shared_ptr<std::string> rollback_cmd) :
556  m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
557  {}
558 
560 
565  transaction_base(connection &c, std::string_view tname);
566 
568  explicit transaction_base(connection &c);
569 
571  void register_transaction();
572 
574  void close() noexcept;
575 
577  virtual void do_commit() = 0;
578 
580 
583  virtual void do_abort();
584 
586  void set_rollback_cmd(std::shared_ptr<std::string> cmd)
587  {
588  m_rollback_cmd = cmd;
589  }
590 
592  result direct_exec(std::string_view, std::string_view desc = ""sv);
593  result
594  direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
595 
596 private:
597  enum class status
598  {
599  active,
600  aborted,
601  committed,
602  in_doubt
603  };
604 
605  PQXX_PRIVATE void check_pending_error();
606 
607  template<typename T> bool parm_is_null(T *p) const noexcept
608  {
609  return p == nullptr;
610  }
611  template<typename T> bool parm_is_null(T) const noexcept { return false; }
612 
613  result
614  internal_exec_prepared(zview statement, internal::c_params const &args);
615 
616  result internal_exec_params(zview query, internal::c_params const &args);
617 
619  void check_rowcount_prepared(
620  zview statement, result::size_type expected_rows,
621  result::size_type actual_rows);
622 
624  void
625  check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
626 
628  [[nodiscard]] std::string description() const;
629 
630  friend class pqxx::internal::gate::transaction_transaction_focus;
631  PQXX_PRIVATE void register_focus(transaction_focus *);
632  PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
633  PQXX_PRIVATE void register_pending_error(zview) noexcept;
634  PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
635 
636  connection &m_conn;
637 
639 
642  transaction_focus const *m_focus = nullptr;
643 
644  status m_status = status::active;
645  bool m_registered = false;
646  std::string m_name;
647  std::string m_pending_error;
648 
650  std::shared_ptr<std::string> m_rollback_cmd;
651 
652  static constexpr std::string_view s_type_name{"transaction"sv};
653 };
654 
655 
656 // TODO: Can C++20's borrowed_range help?
658 template<>
659 std::string_view transaction_base::query_value<std::string_view>(
660  zview query, std::string_view desc) = delete;
662 template<>
663 zview transaction_base::query_value<zview>(
664  zview query, std::string_view desc) = delete;
665 
666 } // namespace pqxx
667 
668 
669 namespace pqxx::internal
670 {
672 template<pqxx::isolation_level isolation, pqxx::write_policy rw>
673 extern const zview begin_cmd;
674 
675 // These are not static members, so "constexpr" does not imply "inline".
676 template<>
677 inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
678  "BEGIN"_zv};
679 template<>
680 inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
681  "BEGIN READ ONLY"_zv};
682 template<>
683 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
684  "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
685 template<>
686 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
687  "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
688 template<>
689 inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
690  "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
691 template<>
692 inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
693  "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
694 } // namespace pqxx::internal
695 
696 #include "pqxx/internal/compiler-internal-post.hxx"
697 #endif
Marker-type wrapper: zero-terminated std::string_view.
Definition: zview.hxx:39
auto stream(std::string_view query)
Execute a query, and loop over the results row by row.
Definition: transaction_base.hxx:368
std::string quote(T const &t) const
Represent object as SQL string, including quoting & escaping.
Definition: transaction_base.hxx:184
result exec_prepared(zview statement, Args &&...args)
Execute a prepared statement, with optional arguments.
Definition: transaction_base.hxx:474
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:177
static stream_from query(transaction_base &tx, std::string_view q)
Factory: Execute query, and stream the results.
Definition: stream_from.hxx:88
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition: transaction_base.hxx:493
row exec_prepared1(zview statement, Args &&...args)
Execute a prepared statement, and expect a single-row result.
Definition: transaction_base.hxx:484
The home of all libpqxx classes, functions, templates, etc.
Definition: array.hxx:25
Binary data corresponding to PostgreSQL&#39;s "BYTEA" binary-string type.
Definition: binarystring.hxx:57
std::basic_string_view< std::byte > bytes_view() const
Read data as a std::basic_string_view<std::byte>.
Definition: binarystring.hxx:177
result exec0(zview query, std::string_view desc=std::string_view{})
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:278
void set_rollback_cmd(std::shared_ptr< std::string > cmd)
Set the rollback command.
Definition: transaction_base.hxx:586
std::string unesc_raw(char const *text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:166
auto esc_raw(ARGS &&...args) const
Escape binary data for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:135
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:553
pqxx::internal::c_params make_c_params() const
For internal use: Generate a params object for use in calls.
Definition: params.cxx:92
const zview begin_cmd
The SQL command for starting a given type of transaction.
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:504
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:230
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:310
result exec(std::stringstream const &query, std::string_view desc=std::string_view{})
Execute a command.
Definition: transaction_base.hxx:266
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:198
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition: transaction_base.hxx:432
Error in usage of libpqxx library, similar to std::logic_error.
Definition: except.hxx:164
std::string quote(binarystring const &t) const
Definition: transaction_base.hxx:191
reference front() const noexcept
Definition: row.cxx:54
std::string unesc_raw(zview text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:145
STL namespace.
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:156
Connection to a database.
Definition: connection.hxx:180
connection & conn() const
The connection in which this transaction lives.
Definition: transaction_base.hxx:524
Definition: connection.hxx:94
row exec1(zview query, std::string_view desc=std::string_view{})
Execute command returning a single row of data.
Definition: transaction_base.hxx:290
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition: transaction_base.hxx:218
row exec_params1(zview query, Args &&...args)
Definition: transaction_base.hxx:415
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition: transaction_base.hxx:225
Reference to one row in a result.
Definition: row.hxx:45
void process_notice(zview msg) const
Have connection process a warning message.
Definition: transaction_base.hxx:520
Base class for things that monopolise a transaction&#39;s attention.
Definition: transaction_focus.hxx:27
Stream data from the database.
Definition: stream_from.hxx:72
Internal items for libpqxx&#39; own use. Do not use these yourself.
Definition: composite.hxx:73
Result set containing data returned by a query or command.
Definition: result.hxx:70
std::string_view name() const noexcept
Transaction name, if you passed one to the constructor; or empty string.
Definition: transaction_base.hxx:546
result exec_params0(zview query, Args &&...args)
Definition: transaction_base.hxx:423
Build a parameter list for a parameterised or prepared statement.
Definition: params.hxx:213
result_size_type size_type
Definition: result.hxx:73
Interface definition (and common code) for "transaction" classes.
Definition: transaction_base.hxx:75