libpqxx  7.5.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-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 
22 /* End-user programs need not include this file, unless they define their own
23  * transaction classes. This is not something the typical program should want
24  * to do.
25  *
26  * However, reading this file is worthwhile because it defines the public
27  * interface for the available transaction classes such as transaction and
28  * nontransaction.
29  */
30 
31 #include "pqxx/connection.hxx"
32 #include "pqxx/internal/concat.hxx"
33 #include "pqxx/internal/encoding_group.hxx"
34 #include "pqxx/isolation.hxx"
35 #include "pqxx/result.hxx"
36 #include "pqxx/row.hxx"
37 #include "pqxx/stream_from.hxx"
38 
39 namespace pqxx::internal::gate
40 {
41 class transaction_subtransaction;
42 class transaction_sql_cursor;
43 class transaction_stream_to;
44 class transaction_transaction_focus;
45 } // namespace pqxx::internal::gate
46 
47 
48 namespace pqxx
49 {
50 using namespace std::literals;
51 
52 
53 class transaction_focus;
54 
55 
68 
74 class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
75 {
76 public:
77  transaction_base() = delete;
78  transaction_base(transaction_base const &) = delete;
80  transaction_base &operator=(transaction_base const &) = delete;
81  transaction_base &operator=(transaction_base &&) = delete;
82 
83  virtual ~transaction_base() = 0;
84 
86 
98  void commit();
99 
101 
104  void abort();
105 
110  [[nodiscard]] std::string esc(char const text[]) const
112  {
113  return conn().esc(text);
114  }
116  [[nodiscard]] std::string esc(char const text[], std::size_t maxlen) const
117  {
118  return conn().esc(text, maxlen);
119  }
121  [[nodiscard]] std::string esc(std::string_view text) const
122  {
123  return conn().esc(text);
124  }
125 
127 
138  [[nodiscard]] std::string
139  esc_raw(unsigned char const data[], std::size_t len) const
140  {
141  return to_string(std::basic_string_view<std::byte>{
142  reinterpret_cast<std::byte const *>(data), len});
143  }
145  [[nodiscard]] std::string esc_raw(zview) const;
146 
148 
151  [[nodiscard]] std::string unesc_raw(zview text) const
152  {
153  return conn().unesc_raw(text);
154  }
155 
157 
160  [[nodiscard]] std::string unesc_raw(char const *text) const
161  {
162  return conn().unesc_raw(text);
163  }
164 
166 
167  template<typename T> [[nodiscard]] std::string quote(T const &t) const
168  {
169  return conn().quote(t);
170  }
171 
172  [[deprecated("Use std::basic_string<std::byte> instead of binarystring.")]]
173  std::string quote(binarystring const &t) const
174  {
175  return conn().quote(t.bytes_view());
176  }
177 
179  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]]
180  std::string
181  quote_raw(unsigned char const bin[], std::size_t len) const
182  {
183  return quote(std::basic_string_view<std::byte>{reinterpret_cast<std::byte const *>(bin), len});
184  }
185 
187  [[deprecated("Use quote(std::basic_string_view<std::byte>).")]]
188  std::string quote_raw(zview bin) const;
189 
191  [[nodiscard]] std::string quote_name(std::string_view identifier) const
192  {
193  return conn().quote_name(identifier);
194  }
195 
197  [[nodiscard]] std::string
198  esc_like(std::string_view bin, char escape_char = '\\') const
199  {
200  return conn().esc_like(bin, escape_char);
201  }
203 
223 
225 
230  result
231  exec(std::string_view query, std::string_view desc = std::string_view{});
232 
234 
240  std::stringstream const &query, std::string_view desc = std::string_view{})
241  {
242  return exec(query.str(), desc);
243  }
244 
246 
251  result exec0(zview query, std::string_view desc = std::string_view{})
252  {
253  return exec_n(0, query, desc);
254  }
255 
257 
263  row exec1(zview query, std::string_view desc = std::string_view{})
264  {
265  return exec_n(1, query, desc).front();
266  }
267 
269 
274  result exec_n(
275  result::size_type rows, zview query,
276  std::string_view desc = std::string_view{});
277 
279 
282  template<typename TYPE>
283  TYPE query_value(zview query, std::string_view desc = std::string_view{})
284  {
285  row const r{exec1(query, desc)};
286  if (std::size(r) != 1)
287  throw usage_error{internal::concat(
288  "Queried single value from result with ", std::size(r), " columns.")};
289  return r[0].as<TYPE>();
290  }
291 
293 
341  template<typename... TYPE> [[nodiscard]] auto stream(std::string_view query)
342  {
343  // Tricky: std::make_unique() supports constructors but not RVO functions.
344  return pqxx::internal::owning_stream_input_iteration<TYPE...>{
345  std::unique_ptr<stream_from>{
346  new stream_from{stream_from::query(*this, query)}}};
347  }
348 
378  template<typename... Args> result exec_params(zview query, Args &&...args)
380  {
381  params pp(args...);
382  return internal_exec_params(query, pp.make_c_params());
383  }
384 
385  // Execute parameterised statement, expect a single-row result.
388  template<typename... Args> row exec_params1(zview query, Args &&...args)
389  {
390  return exec_params_n(1, query, std::forward<Args>(args)...).front();
391  }
392 
393  // Execute parameterised statement, expect a result with zero rows.
396  template<typename... Args> result exec_params0(zview query, Args &&...args)
397  {
398  return exec_params_n(0, query, std::forward<Args>(args)...);
399  }
400 
401  // Execute parameterised statement, expect exactly a given number of rows.
404  template<typename... Args>
405  result exec_params_n(std::size_t rows, zview query, Args &&...args)
406  {
407  auto const r{exec_params(query, std::forward<Args>(args)...)};
408  check_rowcount_params(rows, std::size(r));
409  return r;
410  }
412 
441 
443  template<typename... Args>
444  result exec_prepared(zview statement, Args &&...args)
445  {
446  params pp(args...);
447  return internal_exec_prepared(statement, pp.make_c_params());
448  }
449 
451 
453  template<typename... Args>
454  row exec_prepared1(zview statement, Args &&...args)
455  {
456  return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
457  }
458 
460 
462  template<typename... Args>
463  result exec_prepared0(zview statement, Args &&...args)
464  {
465  return exec_prepared_n(0, statement, std::forward<Args>(args)...);
466  }
467 
469 
472  template<typename... Args>
473  result
474  exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
475  {
476  auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
477  check_rowcount_prepared(statement, rows, std::size(r));
478  return r;
479  }
480 
482 
487  void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
490  void process_notice(zview msg) const { m_conn.process_notice(msg); }
492 
494  [[nodiscard]] connection &conn() const { return m_conn; }
495 
497 
507  void set_variable(std::string_view var, std::string_view value);
508 
510 
513  std::string get_variable(std::string_view);
514 
516  [[nodiscard]] std::string_view name() const noexcept { return m_name; }
517 
518 protected:
520 
524  connection &c, std::string_view tname,
525  std::shared_ptr<std::string> rollback_cmd) :
526  m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
527  {}
528 
530 
535  transaction_base(connection &c, std::string_view tname);
536 
538  explicit transaction_base(connection &c);
539 
541  void register_transaction();
542 
544  void close() noexcept;
545 
547  virtual void do_commit() = 0;
548 
550 
553  virtual void do_abort();
554 
556  void set_rollback_cmd(std::shared_ptr<std::string> cmd)
557  {
558  m_rollback_cmd = cmd;
559  }
560 
562  result direct_exec(std::string_view, std::string_view desc = ""sv);
563  result
564  direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
565 
566 private:
567  enum class status
568  {
569  active,
570  aborted,
571  committed,
572  in_doubt
573  };
574 
575  PQXX_PRIVATE void check_pending_error();
576 
577  template<typename T> bool parm_is_null(T *p) const noexcept
578  {
579  return p == nullptr;
580  }
581  template<typename T> bool parm_is_null(T) const noexcept { return false; }
582 
583  result
584  internal_exec_prepared(zview statement, internal::c_params const &args);
585 
586  result internal_exec_params(zview query, internal::c_params const &args);
587 
589  void check_rowcount_prepared(
590  zview statement, result::size_type expected_rows,
591  result::size_type actual_rows);
592 
594  void
595  check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
596 
598  [[nodiscard]] std::string description() const;
599 
600  friend class pqxx::internal::gate::transaction_transaction_focus;
601  PQXX_PRIVATE void register_focus(transaction_focus *);
602  PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
603  PQXX_PRIVATE void register_pending_error(zview) noexcept;
604  PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
605 
606  connection &m_conn;
607 
609 
612  transaction_focus const *m_focus = nullptr;
613 
614  status m_status = status::active;
615  bool m_registered = false;
616  std::string m_name;
617  std::string m_pending_error;
618 
620  std::shared_ptr<std::string> m_rollback_cmd;
621 
622  constexpr static std::string_view s_type_name{"transaction"sv};
623 };
624 
625 
626 // TODO: C++20 "Conversion remains valid after underlying result dies" concept?
628 template<>
629 std::string_view transaction_base::query_value<std::string_view>(
630  zview query, std::string_view desc) = delete;
632 template<>
633 zview transaction_base::query_value<zview>(
634  zview query, std::string_view desc) = delete;
635 
636 } // namespace pqxx
637 
638 
639 namespace pqxx::internal
640 {
642 template<pqxx::isolation_level isolation, pqxx::write_policy rw>
643 extern const zview begin_cmd;
644 
645 // These are not static members, so "constexpr" does not imply "inline".
646 template<>
647 inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
648  "BEGIN"_zv};
649 template<>
650 inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
651  "BEGIN READ ONLY"_zv};
652 template<>
653 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
654  "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
655 template<>
656 inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
657  "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
658 template<>
659 inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
660  "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
661 template<>
662 inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
663  "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
664 } // namespace pqxx::internal
665 
666 #include "pqxx/internal/compiler-internal-post.hxx"
667 #endif
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:181
row exec_params1(zview query, Args &&...args)
Definition: transaction_base.hxx:388
pqxx::internal::c_params make_c_params() const
For internal use: Generate a params object for use in calls.
Definition: params.cxx:92
std::string unesc_raw(char const *text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:160
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:474
Internal items for libpqxx&#39; own use. Do not use these yourself.
Definition: composite.hxx:73
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition: transaction_base.hxx:191
std::string_view name() const noexcept
Transaction name, if you passed one to the constructor; or empty string.
Definition: transaction_base.hxx:516
std::string to_string(field const &value)
Convert a field to a string.
Definition: result.cxx:503
Base class for things that monopolise a transaction&#39;s attention.
Definition: transaction_focus.hxx:27
std::string esc(char const text[], std::size_t maxlen) const
Escape string for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:116
result exec_params0(zview query, Args &&...args)
Definition: transaction_base.hxx:396
reference front() const noexcept
Definition: row.cxx:54
Error in usage of libpqxx library, similar to std::logic_error.
Definition: except.hxx:164
Result set containing data returned by a query or command.
Definition: result.hxx:70
Definition: connection.hxx:97
const zview begin_cmd
The SQL command for starting a given type of transaction.
Use std::string_view query
Definition: stream_from.hxx:139
The home of all libpqxx classes, functions, templates, etc.
Definition: array.hxx:25
std::string esc_raw(unsigned char const data[], std::size_t len) const
Escape binary data for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:139
result exec_prepared(zview statement, Args &&...args)
Execute a prepared statement, with optional arguments.
Definition: transaction_base.hxx:444
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:523
Binary data corresponding to PostgreSQL&#39;s "BYTEA" binary-string type.
Definition: binarystring.hxx:56
void process_notice(zview msg) const
Have connection process a warning message.
Definition: transaction_base.hxx:490
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition: transaction_base.hxx:405
std::string quote(T const &t) const
Represent object as SQL string, including quoting & escaping.
Definition: transaction_base.hxx:167
Reference to one row in a result.
Definition: row.hxx:45
std::string quote(binarystring const &t) const
Definition: transaction_base.hxx:173
auto stream(std::string_view query)
Execute a query, and loop over the results row by row.
Definition: transaction_base.hxx:341
row exec1(zview query, std::string_view desc=std::string_view{})
Execute command returning a single row of data.
Definition: transaction_base.hxx:263
STL namespace.
connection & conn() const
The connection in which this transaction lives.
Definition: transaction_base.hxx:494
Stream data from the database.
Definition: stream_from.hxx:72
row exec_prepared1(zview statement, Args &&...args)
Execute a prepared statement, and expect a single-row result.
Definition: transaction_base.hxx:454
result_size_type size_type
Definition: result.hxx:73
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition: transaction_base.hxx:198
Interface definition (and common code) for "transaction" classes.
Definition: transaction_base.hxx:74
void set_rollback_cmd(std::shared_ptr< std::string > cmd)
Set the rollback command.
Definition: transaction_base.hxx:556
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition: transaction_base.hxx:463
std::basic_string_view< std::byte > bytes_view() const
Read data as a std::basic_string_view<std::byte>.
Definition: binarystring.hxx:174
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:283
Connection to a database.
Definition: connection.hxx:183
Build a parameter list for a parameterised or prepared statement.
Definition: prepared_statement.hxx:121
Marker-type wrapper: zero-terminated std::string_view.
Definition: zview.hxx:37
result exec0(zview query, std::string_view desc=std::string_view{})
Execute command, which should return zero rows of data.
Definition: transaction_base.hxx:251
std::string unesc_raw(zview text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition: transaction_base.hxx:151
result exec(std::stringstream const &query, std::string_view desc=std::string_view{})
Execute a command.
Definition: transaction_base.hxx:239
std::string esc(std::string_view text) const
Escape string for use as SQL string literal in this transaction.
Definition: transaction_base.hxx:121