libpqxx 7.9.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-2024, 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
42{
46class transaction_transaction_focus;
47} // namespace pqxx::internal::gate
48
49
50namespace pqxx
51{
52using namespace std::literals;
53
54
55class transaction_focus;
56
57
82
88{
89public:
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
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]] bytes unesc_bin(zview text) { return conn().unesc_bin(text); }
170
172
175 [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
176 unesc_raw(char const *text) const
177 {
178#include "pqxx/internal/ignore-deprecated-pre.hxx"
179 return conn().unesc_raw(text);
180#include "pqxx/internal/ignore-deprecated-post.hxx"
181 }
182
184
187 [[nodiscard]] bytes unesc_bin(char const text[])
188 {
189 return conn().unesc_bin(text);
190 }
191
193
194 template<typename T> [[nodiscard]] std::string quote(T const &t) const
195 {
196 return conn().quote(t);
197 }
198
199 [[deprecated("Use bytes instead of binarystring.")]] std::string
200 quote(binarystring const &t) const
201 {
202 return conn().quote(t.bytes_view());
203 }
204
206 [[deprecated("Use quote(pqxx::bytes_view).")]] std::string
207 quote_raw(unsigned char const bin[], std::size_t len) const
208 {
209 return quote(binary_cast(bin, len));
210 }
211
213 [[deprecated("Use quote(pqxx::bytes_view).")]] std::string
214 quote_raw(zview bin) const;
215
216#if defined(PQXX_HAVE_CONCEPTS)
218
219 template<binary DATA>
220 [[nodiscard]] std::string quote_raw(DATA const &data) const
221 {
222 return conn().quote_raw(data);
223 }
224#endif
225
227 [[nodiscard]] std::string quote_name(std::string_view identifier) const
228 {
229 return conn().quote_name(identifier);
230 }
231
233 [[nodiscard]] std::string
234 esc_like(std::string_view bin, char escape_char = '\\') const
235 {
236 return conn().esc_like(bin, escape_char);
237 }
239
281
283
288 [[deprecated("The desc parameter is going away.")]] result
289 exec(std::string_view query, std::string_view desc);
290
292
296 result exec(std::string_view query)
297 {
298#include "pqxx/internal/ignore-deprecated-pre.hxx"
299 return exec(query, std::string_view{});
300#include "pqxx/internal/ignore-deprecated-post.hxx"
301 }
302
304
309 [[deprecated(
310 "Pass your query as a std::string_view, not stringstream.")]] result
311 exec(std::stringstream const &query, std::string_view desc)
312 {
313#include "pqxx/internal/ignore-deprecated-pre.hxx"
314 return exec(query.str(), desc);
315#include "pqxx/internal/ignore-deprecated-post.hxx"
316 }
317
319
324 [[deprecated("The desc parameter is going away.")]] result
325 exec0(zview query, std::string_view desc)
326 {
327#include "pqxx/internal/ignore-deprecated-pre.hxx"
328 return exec_n(0, query, desc);
329#include "pqxx/internal/ignore-deprecated-post.hxx"
330 }
331
333
338 result exec0(zview query) { return exec_n(0, query); }
339
341
347 [[deprecated("The desc parameter is going away.")]] row
348 exec1(zview query, std::string_view desc)
349 {
350#include "pqxx/internal/ignore-deprecated-pre.hxx"
351 return exec_n(1, query, desc).front();
352#include "pqxx/internal/ignore-deprecated-post.hxx"
353 }
354
356
362 row exec1(zview query) { return exec_n(1, query).front(); }
363
365
370 [[deprecated("The desc parameter is going away.")]] result
371 exec_n(result::size_type rows, zview query, std::string_view desc);
372
374
380 {
381#include "pqxx/internal/ignore-deprecated-pre.hxx"
382 return exec_n(rows, query, std::string_view{});
383#include "pqxx/internal/ignore-deprecated-post.hxx"
384 }
385
387
390 template<typename TYPE>
391 [[deprecated("The desc parameter is going away.")]] TYPE
392 query_value(zview query, std::string_view desc)
393 {
394#include "pqxx/internal/ignore-deprecated-pre.hxx"
395 row const r{exec1(query, desc)};
396#include "pqxx/internal/ignore-deprecated-post.hxx"
397 if (std::size(r) != 1)
398 throw usage_error{internal::concat(
399 "Queried single value from result with ", std::size(r), " columns.")};
400 return r[0].as<TYPE>();
401 }
402
404
410 template<typename TYPE> TYPE query_value(zview query)
411 {
412 row const r{exec1(query)};
413 if (std::size(r) != 1)
414 throw usage_error{internal::concat(
415 "Queried single value from result with ", std::size(r), " columns.")};
416 return r[0].as<TYPE>();
417 }
418
420
427 template<typename... TYPE>
428 [[nodiscard]] std::tuple<TYPE...> query1(zview query)
429 {
430 return exec1(query).as<TYPE...>();
431 }
432
434
441 template<typename... TYPE>
442 [[nodiscard]] std::optional<std::tuple<TYPE...>> query01(zview query)
443 {
444 result res{exec(query)};
445 auto const rows{std::size(res)};
446 switch (rows)
447 {
448 case 0: return {};
449 case 1: return {res[0].as<TYPE...>()};
450 default:
451 throw unexpected_rows{internal::concat(
452 "Expected at most one row of data, got "sv, rows, "."sv)};
453 }
454 }
455
457
508 template<typename... TYPE>
509 [[nodiscard]] auto stream(std::string_view query) &
510 {
511 return pqxx::internal::stream_query<TYPE...>{*this, query};
512 }
513
514 // C++20: Concept like std::invocable, but without specifying param types.
516
544 template<typename CALLABLE>
545 auto for_stream(std::string_view query, CALLABLE &&func)
546 {
547 using param_types =
549 param_types const *const sample{nullptr};
550 auto data_stream{stream_like(query, sample)};
551 for (auto const &fields : data_stream) std::apply(func, fields);
552 }
553
554 template<typename CALLABLE>
555 [[deprecated(
556 "pqxx::transaction_base::for_each is now called for_stream.")]] auto
557 for_each(std::string_view query, CALLABLE &&func)
558 {
559 return for_stream(query, std::forward<CALLABLE>(func));
560 }
561
563
594 template<typename... TYPE> auto query(zview query)
595 {
596 return exec(query).iter<TYPE...>();
597 }
598
600
608 template<typename... TYPE> auto query_n(result::size_type rows, zview query)
609 {
610 return exec_n(rows, query).iter<TYPE...>();
611 }
612
613 // C++20: Concept like std::invocable, but without specifying param types.
615
623 template<typename CALLABLE> void for_query(zview query, CALLABLE &&func)
624 {
625 exec(query).for_each(std::forward<CALLABLE>(func));
626 }
627
657
659
663 template<typename... Args> result exec_params(zview query, Args &&...args)
664 {
665 params pp{args...};
666 return internal_exec_params(query, pp.make_c_params());
667 }
668
669 // Execute parameterised statement, expect a single-row result.
672 template<typename... Args> row exec_params1(zview query, Args &&...args)
673 {
674 return exec_params_n(1, query, std::forward<Args>(args)...).front();
675 }
676
677 // Execute parameterised statement, expect a result with zero rows.
680 template<typename... Args> result exec_params0(zview query, Args &&...args)
681 {
682 return exec_params_n(0, query, std::forward<Args>(args)...);
683 }
684
685 // Execute parameterised statement, expect exactly a given number of rows.
688 template<typename... Args>
689 result exec_params_n(std::size_t rows, zview query, Args &&...args)
690 {
691 auto const r{exec_params(query, std::forward<Args>(args)...)};
692 // The cast isn't to get the type of the right width. Automatic promotion
693 // will take care of that. But we do need it unsigned first.
694 check_rowcount_params(rows, static_cast<unsigned>(std::size(r)));
695 return r;
696 }
697
698 // Execute parameterised statement, expect exactly a given number of rows.
701 template<typename... Args>
703 {
704 auto const r{exec_params(query, std::forward<Args>(args)...)};
705 // The casts aren't to get the type of the right width. Automatic
706 // promotion will take care of that. But we do need these unsigned first.
707 check_rowcount_params(
708 static_cast<unsigned>(rows), static_cast<unsigned>(std::size(r)));
709 return r;
710 }
711
713
746 template<typename... TYPE> auto query(zview query, params const &parms)
747 {
748 return exec_params(query, parms).iter<TYPE...>();
749 }
750
753
761 template<typename... TYPE>
763 {
764 return exec_params_n(rows, query, parms).iter<TYPE...>();
765 }
766
768
774 template<typename TYPE> TYPE query_value(zview query, params const &parms)
775 {
776 row const r{exec_params1(query, parms)};
777 if (std::size(r) != 1)
778 throw usage_error{internal::concat(
779 "Queried single value from result with ", std::size(r), " columns.")};
780 return r[0].as<TYPE>();
781 }
782
784
791 template<typename... TYPE>
792 [[nodiscard]] std::tuple<TYPE...> query1(zview query, params const &parms)
793 {
794 result const r{exec_params_n(1, query, parms)};
795 return r[0].as<TYPE...>();
796 }
797
799
806 template<typename... TYPE>
807 [[nodiscard]] std::optional<std::tuple<TYPE...>>
808 query01(zview query, params const &parms)
809 {
810 result res{exec_params(query, parms)};
811 auto const rows{std::size(res)};
812 switch (rows)
813 {
814 case 0: return {};
815 case 1: return {res[0].as<TYPE...>()};
816 default:
817 throw unexpected_rows{internal::concat(
818 "Expected at most one row of data, got "sv, rows, "."sv)};
819 }
820 }
821
822 // C++20: Concept like std::invocable, but without specifying param types.
824
835 template<typename CALLABLE>
836 void for_query(zview query, CALLABLE &&func, params const &parms)
837 {
838 exec_params(query, parms).for_each(std::forward<CALLABLE>(func));
839 }
841
883
885 template<typename... Args>
887 {
888 params pp(args...);
889 return internal_exec_prepared(statement, pp.make_c_params());
890 }
891
893
895 template<typename... Args>
897 {
898 return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
899 }
900
902
904 template<typename... Args>
906 {
907 return exec_prepared_n(0, statement, std::forward<Args>(args)...);
908 }
909
911
914 template<typename... Args>
915 result
917 {
918 auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
919 check_rowcount_prepared(statement, rows, std::size(r));
920 return r;
921 }
922
924
930 void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
932 void process_notice(zview msg) const { m_conn.process_notice(msg); }
934
936 [[nodiscard]] constexpr connection &conn() const noexcept { return m_conn; }
937
939
954 [[deprecated(
955 "Set transaction-local variables using SQL SET statements.")]] void
956 set_variable(std::string_view var, std::string_view value);
957
959
962 [[deprecated("Read variables using SQL SHOW statements.")]] std::string
963 get_variable(std::string_view);
964
965 // C++20: constexpr.
967 [[nodiscard]] std::string_view name() const & noexcept { return m_name; }
968
969protected:
971
975 connection &c, std::string_view tname,
976 std::shared_ptr<std::string> rollback_cmd) :
977 m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
978 {}
979
981
986 transaction_base(connection &c, std::string_view tname);
987
989 explicit transaction_base(connection &c);
990
992 void register_transaction();
993
995 void close() noexcept;
996
998 virtual void do_commit() = 0;
999
1001
1004 virtual void do_abort();
1005
1007 void set_rollback_cmd(std::shared_ptr<std::string> cmd)
1008 {
1009 m_rollback_cmd = cmd;
1010 }
1011
1013 result direct_exec(std::string_view, std::string_view desc = ""sv);
1014 result
1015 direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
1016
1017private:
1018 enum class status
1019 {
1020 active,
1021 aborted,
1022 committed,
1023 in_doubt
1024 };
1025
1026 PQXX_PRIVATE void check_pending_error();
1027
1028 result
1029 internal_exec_prepared(zview statement, internal::c_params const &args);
1030
1031 result internal_exec_params(zview query, internal::c_params const &args);
1032
1034 void check_rowcount_prepared(
1037
1039 void
1040 check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
1041
1043 [[nodiscard]] std::string description() const;
1044
1045 friend class pqxx::internal::gate::transaction_transaction_focus;
1046 PQXX_PRIVATE void register_focus(transaction_focus *);
1047 PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
1048 PQXX_PRIVATE void register_pending_error(zview) noexcept;
1049 PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
1050
1053 auto stream_like(std::string_view query, std::tuple<ARGS...> const *)
1054 {
1055 return stream<ARGS...>(query);
1056 }
1057
1058 connection &m_conn;
1059
1061
1064 transaction_focus const *m_focus = nullptr;
1065
1066 status m_status = status::active;
1067 bool m_registered = false;
1068 std::string m_name;
1069 std::string m_pending_error;
1070
1072 std::shared_ptr<std::string> m_rollback_cmd;
1073
1074 static constexpr std::string_view s_type_name{"transaction"sv};
1075};
1076
1077
1078// C++20: Can borrowed_range help?
1080template<>
1081std::string_view transaction_base::query_value<std::string_view>(
1082 zview query, std::string_view desc) = delete;
1084template<>
1085zview transaction_base::query_value<zview>(
1086 zview query, std::string_view desc) = delete;
1087
1088} // namespace pqxx
1089
1090
1091namespace pqxx::internal
1092{
1094template<pqxx::isolation_level isolation, pqxx::write_policy rw>
1095extern const zview begin_cmd;
1096
1097// These are not static members, so "constexpr" does not imply "inline".
1098template<>
1100 "BEGIN"_zv};
1101template<>
1103 "BEGIN READ ONLY"_zv};
1104template<>
1106 "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
1107template<>
1109 "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
1110template<>
1112 "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
1113template<>
1115 "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
1116} // namespace pqxx::internal
1117
1118#include "pqxx/internal/stream_query_impl.hxx"
1119#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
constexpr char array_separator
Element separator between SQL array elements of this type.
Definition strconv.hxx:557
std::conditional< has_generic_bytes_char_traits, std::basic_string< std::byte >, std::basic_string< std::byte, byte_char_traits > >::type bytes
Type alias for a container containing bytes.
Definition util.hxx:371
bytes_view binary_cast(TYPE const &data)
Cast binary data to a type that libpqxx will recognise as binary.
Definition util.hxx:407
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:627
Definition connection.hxx:109
Binary data corresponding to PostgreSQL's "BYTEA" binary-string type.
Definition binarystring.hxx:58
Connection to a database.
Definition connection.hxx:233
Error in usage of libpqxx library, similar to std::logic_error.
Definition except.hxx:249
Query returned an unexpected number of rows.
Definition except.hxx:343
Build a parameter list for a parameterised or prepared statement.
Definition params.hxx:46
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:886
result exec_params_n(result::size_type rows, zview query, Args &&...args)
Definition transaction_base.hxx:702
result exec0(zview query, std::string_view desc)
Execute command, which should return zero rows of data.
Definition transaction_base.hxx:325
bytes unesc_bin(char const text[])
Unescape binary data, e.g. from a table field or notification payload.
Definition transaction_base.hxx:187
constexpr connection & conn() const noexcept
The connection in which this transaction lives.
Definition transaction_base.hxx:936
auto for_each(std::string_view query, CALLABLE &&func)
Definition transaction_base.hxx:557
void for_query(zview query, CALLABLE &&func, params const &parms)
Execute a query, load the full result, and perform func for each row.
Definition transaction_base.hxx:836
auto query(zview query)
Execute query, read full results, then iterate rows of data.
Definition transaction_base.hxx:594
bytes unesc_bin(zview text)
Unescape binary data, e.g. from a table field or notification payload.
Definition transaction_base.hxx:169
TYPE query_value(zview query, params const &parms)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition transaction_base.hxx:774
void process_notice(zview msg) const
Have connection process a warning message.
Definition transaction_base.hxx:932
result exec0(zview query)
Execute command, which should return zero rows of data.
Definition transaction_base.hxx:338
auto query_n(result::size_type rows, zview query)
Perform query, expect given number of rows, iterate results.
Definition transaction_base.hxx:608
std::optional< std::tuple< TYPE... > > query01(zview query, params const &parms)
Query at most one row of data, and if there is one, convert it.
Definition transaction_base.hxx:808
std::string unesc_raw(char const *text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition transaction_base.hxx:176
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:392
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:916
transaction_base(transaction_base const &)=delete
std::tuple< TYPE... > query1(zview query, params const &parms)
Perform query returning exactly one row, and convert its fields.
Definition transaction_base.hxx:792
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:974
std::string quote(T const &t) const
Represent object as SQL string, including quoting & escaping.
Definition transaction_base.hxx:194
row exec_params1(zview query, Args &&...args)
Definition transaction_base.hxx:672
TYPE query_value(zview query)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition transaction_base.hxx:410
transaction_base & operator=(transaction_base const &)=delete
auto esc_raw(ARGS &&...args) const
Escape binary data for use as SQL string literal in this transaction.
Definition transaction_base.hxx:148
result exec(std::stringstream const &query, std::string_view desc)
Execute a command.
Definition transaction_base.hxx:311
std::string quote(binarystring const &t) const
Definition transaction_base.hxx:200
row exec1(zview query)
Execute command returning a single row of data.
Definition transaction_base.hxx:362
row exec1(zview query, std::string_view desc)
Execute command returning a single row of data.
Definition transaction_base.hxx:348
transaction_base(transaction_base &&)=delete
result exec_params(zview query, Args &&...args)
Execute an SQL statement with parameters.
Definition transaction_base.hxx:663
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:442
result exec_params0(zview query, Args &&...args)
Definition transaction_base.hxx:680
auto for_stream(std::string_view query, CALLABLE &&func)
Perform a streaming query, and for each result row, call func.
Definition transaction_base.hxx:545
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:905
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition transaction_base.hxx:234
transaction_base & operator=(transaction_base &&)=delete
result exec_n(result::size_type rows, zview query)
Execute command, expect given number of rows.
Definition transaction_base.hxx:379
auto query_n(result::size_type rows, zview query, params const &parms)
Definition transaction_base.hxx:762
std::tuple< TYPE... > query1(zview query)
Perform query returning exactly one row, and convert its fields.
Definition transaction_base.hxx:428
result exec(std::string_view query)
Execute a command.
Definition transaction_base.hxx:296
auto query(zview query, params const &parms)
Execute parameterised query, read full results, iterate rows of data.
Definition transaction_base.hxx:746
row exec_prepared1(zview statement, Args &&...args)
Execute a prepared statement, and expect a single-row result.
Definition transaction_base.hxx:896
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition transaction_base.hxx:227
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:207
std::string_view name() const &noexcept
Transaction name, if you passed one to the constructor; or empty string.
Definition transaction_base.hxx:967
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition transaction_base.hxx:689
auto stream(std::string_view query) &
Execute a query, in streaming fashion; loop over the results row by row.
Definition transaction_base.hxx:509
void for_query(zview query, CALLABLE &&func)
Execute a query, load the full result, and perform func for each row.
Definition transaction_base.hxx:623
void process_notice(char const msg[]) const
Have connection process a warning message.
Definition transaction_base.hxx:930
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