libpqxx
The C++ client library for PostgreSQL
Loading...
Searching...
No Matches
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
41namespace pqxx::internal::gate
42{
43class transaction_subtransaction;
44class transaction_sql_cursor;
45class transaction_stream_to;
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
144
149class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
150{
151public:
152 transaction_base() = delete;
153 transaction_base(transaction_base const &) = delete;
154 transaction_base(transaction_base &&) = delete;
155 transaction_base &operator=(transaction_base const &) = delete;
156 transaction_base &operator=(transaction_base &&) = delete;
157
158 virtual ~transaction_base() = 0;
159
161
174 void commit();
175
177
180 void abort();
181
193 template<typename... ARGS> [[nodiscard]] auto esc(ARGS &&...args) const
194 {
195 return conn().esc(std::forward<ARGS>(args)...);
196 }
197
199
210 template<typename... ARGS> [[nodiscard]] auto esc_raw(ARGS &&...args) const
211 {
212 return conn().esc_raw(std::forward<ARGS>(args)...);
213 }
214
216
219 [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
220 unesc_raw(zview text) const
221 {
222#include "pqxx/internal/ignore-deprecated-pre.hxx"
223 return conn().unesc_raw(text);
224#include "pqxx/internal/ignore-deprecated-post.hxx"
225 }
226
228
231 [[nodiscard]] bytes unesc_bin(zview text) { return conn().unesc_bin(text); }
232
234
237 [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
238 unesc_raw(char const *text) const
239 {
240#include "pqxx/internal/ignore-deprecated-pre.hxx"
241 return conn().unesc_raw(text);
242#include "pqxx/internal/ignore-deprecated-post.hxx"
243 }
244
246
249 [[nodiscard]] bytes unesc_bin(char const text[])
250 {
251 return conn().unesc_bin(text);
252 }
253
255
256 template<typename T> [[nodiscard]] std::string quote(T const &t) const
257 {
258 return conn().quote(t);
259 }
260
261 [[deprecated("Use bytes instead of binarystring.")]] std::string
262 quote(binarystring const &t) const
263 {
264 return conn().quote(t.bytes_view());
265 }
266
268 [[deprecated("Use quote(pqxx::bytes_view).")]] std::string
269 quote_raw(unsigned char const bin[], std::size_t len) const
270 {
271 return quote(binary_cast(bin, len));
272 }
273
275 [[deprecated("Use quote(pqxx::bytes_view).")]] std::string
276 quote_raw(zview bin) const;
277
278#if defined(PQXX_HAVE_CONCEPTS)
280
281 template<binary DATA>
282 [[nodiscard]] std::string quote_raw(DATA const &data) const
283 {
284 return conn().quote_raw(data);
285 }
286#endif
287
289 [[nodiscard]] std::string quote_name(std::string_view identifier) const
290 {
291 return conn().quote_name(identifier);
292 }
293
295 [[nodiscard]] std::string
296 esc_like(std::string_view bin, char escape_char = '\\') const
297 {
298 return conn().esc_like(bin, escape_char);
299 }
301
343
345
350 [[deprecated("The desc parameter is going away.")]] result
351 exec(std::string_view query, std::string_view desc);
352
354
358 result exec(std::string_view query)
359 {
360#include "pqxx/internal/ignore-deprecated-pre.hxx"
361 return exec(query, std::string_view{});
362#include "pqxx/internal/ignore-deprecated-post.hxx"
363 }
364
366
371 [[deprecated(
372 "Pass your query as a std::string_view, not stringstream.")]] result
373 exec(std::stringstream const &query, std::string_view desc)
374 {
375#include "pqxx/internal/ignore-deprecated-pre.hxx"
376 return exec(query.str(), desc);
377#include "pqxx/internal/ignore-deprecated-post.hxx"
378 }
379
381
386 [[deprecated("The desc parameter is going away.")]] result
387 exec0(zview query, std::string_view desc)
388 {
389#include "pqxx/internal/ignore-deprecated-pre.hxx"
390 return exec_n(0, query, desc);
391#include "pqxx/internal/ignore-deprecated-post.hxx"
392 }
393
395
400 result exec0(zview query) { return exec_n(0, query); }
401
403
409 [[deprecated("The desc parameter is going away.")]] row
410 exec1(zview query, std::string_view desc)
411 {
412#include "pqxx/internal/ignore-deprecated-pre.hxx"
413 return exec_n(1, query, desc).front();
414#include "pqxx/internal/ignore-deprecated-post.hxx"
415 }
416
418
424 row exec1(zview query) { return exec_n(1, query).front(); }
425
427
432 [[deprecated("The desc parameter is going away.")]] result
433 exec_n(result::size_type rows, zview query, std::string_view desc);
434
436
441 result exec_n(result::size_type rows, zview query)
442 {
443#include "pqxx/internal/ignore-deprecated-pre.hxx"
444 return exec_n(rows, query, std::string_view{});
445#include "pqxx/internal/ignore-deprecated-post.hxx"
446 }
447
449
452 template<typename TYPE>
453 [[deprecated("The desc parameter is going away.")]] TYPE
454 query_value(zview query, std::string_view desc)
455 {
456#include "pqxx/internal/ignore-deprecated-pre.hxx"
457 row const r{exec1(query, desc)};
458#include "pqxx/internal/ignore-deprecated-post.hxx"
459 if (std::size(r) != 1)
460 throw usage_error{internal::concat(
461 "Queried single value from result with ", std::size(r), " columns.")};
462 return r[0].as<TYPE>();
463 }
464
466
472 template<typename TYPE> TYPE query_value(zview query)
473 {
474 row const r{exec1(query)};
475 if (std::size(r) != 1)
476 throw usage_error{internal::concat(
477 "Queried single value from result with ", std::size(r), " columns.")};
478 return r[0].as<TYPE>();
479 }
480
482
489 template<typename... TYPE>
490 [[nodiscard]] std::tuple<TYPE...> query1(zview query)
491 {
492 return exec1(query).as<TYPE...>();
493 }
494
496
503 template<typename... TYPE>
504 [[nodiscard]] std::optional<std::tuple<TYPE...>> query01(zview query)
505 {
506 result res{exec(query)};
507 auto const rows{std::size(res)};
508 switch (rows)
509 {
510 case 0: return {};
511 case 1: return {res[0].as<TYPE...>()};
512 default:
513 throw unexpected_rows{internal::concat(
514 "Expected at most one row of data, got "sv, rows, "."sv)};
515 }
516 }
517
519
570 template<typename... TYPE>
571 [[nodiscard]] auto stream(std::string_view query) &
572 {
573 return pqxx::internal::stream_query<TYPE...>{*this, query};
574 }
575
576 // C++20: Concept like std::invocable, but without specifying param types.
578
606 template<typename CALLABLE>
607 auto for_stream(std::string_view query, CALLABLE &&func)
608 {
609 using param_types =
611 param_types const *const sample{nullptr};
612 auto data_stream{stream_like(query, sample)};
613 for (auto const &fields : data_stream) std::apply(func, fields);
614 }
615
616 template<typename CALLABLE>
617 [[deprecated(
618 "pqxx::transaction_base::for_each is now called for_stream.")]] auto
619 for_each(std::string_view query, CALLABLE &&func)
620 {
621 return for_stream(query, std::forward<CALLABLE>(func));
622 }
623
625
656 template<typename... TYPE> auto query(zview query)
657 {
658 return exec(query).iter<TYPE...>();
659 }
660
662
670 template<typename... TYPE> auto query_n(result::size_type rows, zview query)
671 {
672 return exec_n(rows, query).iter<TYPE...>();
673 }
674
675 // C++20: Concept like std::invocable, but without specifying param types.
677
685 template<typename CALLABLE> void for_query(zview query, CALLABLE &&func)
686 {
687 exec(query).for_each(std::forward<CALLABLE>(func));
688 }
689
719
721
725 template<typename... Args> result exec_params(zview query, Args &&...args)
726 {
727 params pp{args...};
728 return internal_exec_params(query, pp.make_c_params());
729 }
730
731 // Execute parameterised statement, expect a single-row result.
734 template<typename... Args> row exec_params1(zview query, Args &&...args)
735 {
736 return exec_params_n(1, query, std::forward<Args>(args)...).front();
737 }
738
739 // Execute parameterised statement, expect a result with zero rows.
742 template<typename... Args> result exec_params0(zview query, Args &&...args)
743 {
744 return exec_params_n(0, query, std::forward<Args>(args)...);
745 }
746
747 // Execute parameterised statement, expect exactly a given number of rows.
750 template<typename... Args>
751 result exec_params_n(std::size_t rows, zview query, Args &&...args)
752 {
753 auto const r{exec_params(query, std::forward<Args>(args)...)};
754 // The cast isn't to get the type of the right width. Automatic promotion
755 // will take care of that. But we do need it unsigned first.
756 check_rowcount_params(rows, static_cast<unsigned>(std::size(r)));
757 return r;
758 }
759
760 // Execute parameterised statement, expect exactly a given number of rows.
763 template<typename... Args>
764 result exec_params_n(result::size_type rows, zview query, Args &&...args)
765 {
766 auto const r{exec_params(query, std::forward<Args>(args)...)};
767 // The casts aren't to get the type of the right width. Automatic
768 // promotion will take care of that. But we do need these unsigned first.
769 check_rowcount_params(
770 static_cast<unsigned>(rows), static_cast<unsigned>(std::size(r)));
771 return r;
772 }
773
775
808 template<typename... TYPE> auto query(zview query, params const &parms)
809 {
810 return exec_params(query, parms).iter<TYPE...>();
811 }
812
815
823 template<typename... TYPE>
824 auto query_n(result::size_type rows, zview query, params const &parms)
825 {
826 return exec_params_n(rows, query, parms).iter<TYPE...>();
827 }
828
830
836 template<typename TYPE> TYPE query_value(zview query, params const &parms)
837 {
838 row const r{exec_params1(query, parms)};
839 if (std::size(r) != 1)
840 throw usage_error{internal::concat(
841 "Queried single value from result with ", std::size(r), " columns.")};
842 return r[0].as<TYPE>();
843 }
844
846
853 template<typename... TYPE>
854 [[nodiscard]] std::tuple<TYPE...> query1(zview query, params const &parms)
855 {
856 result const r{exec_params_n(1, query, parms)};
857 return r[0].as<TYPE...>();
858 }
859
861
868 template<typename... TYPE>
869 [[nodiscard]] std::optional<std::tuple<TYPE...>>
870 query01(zview query, params const &parms)
871 {
872 result res{exec_params(query, parms)};
873 auto const rows{std::size(res)};
874 switch (rows)
875 {
876 case 0: return {};
877 case 1: return {res[0].as<TYPE...>()};
878 default:
879 throw unexpected_rows{internal::concat(
880 "Expected at most one row of data, got "sv, rows, "."sv)};
881 }
882 }
883
884 // C++20: Concept like std::invocable, but without specifying param types.
886
897 template<typename CALLABLE>
898 void for_query(zview query, CALLABLE &&func, params const &parms)
899 {
900 exec_params(query, parms).for_each(std::forward<CALLABLE>(func));
901 }
903
945
947 template<typename... Args>
948 result exec_prepared(zview statement, Args &&...args)
949 {
950 params pp(args...);
951 return internal_exec_prepared(statement, pp.make_c_params());
952 }
953
955
957 template<typename... Args>
958 row exec_prepared1(zview statement, Args &&...args)
959 {
960 return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
961 }
962
964
966 template<typename... Args>
967 result exec_prepared0(zview statement, Args &&...args)
968 {
969 return exec_prepared_n(0, statement, std::forward<Args>(args)...);
970 }
971
973
976 template<typename... Args>
977 result
978 exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
979 {
980 auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
981 check_rowcount_prepared(statement, rows, std::size(r));
982 return r;
983 }
984
986
992 void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
994 void process_notice(zview msg) const { m_conn.process_notice(msg); }
996
998 [[nodiscard]] constexpr connection &conn() const noexcept { return m_conn; }
999
1001
1016 [[deprecated(
1017 "Set transaction-local variables using SQL SET statements.")]] void
1018 set_variable(std::string_view var, std::string_view value);
1019
1021
1024 [[deprecated("Read variables using SQL SHOW statements.")]] std::string
1025 get_variable(std::string_view);
1026
1027 // C++20: constexpr.
1029 [[nodiscard]] std::string_view name() const & noexcept { return m_name; }
1030
1031protected:
1033
1036 transaction_base(
1037 connection &c, std::string_view tname,
1038 std::shared_ptr<std::string> rollback_cmd) :
1039 m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
1040 {}
1041
1043
1048 transaction_base(connection &c, std::string_view tname);
1049
1051 explicit transaction_base(connection &c);
1052
1054 void register_transaction();
1055
1057 void close() noexcept;
1058
1060 virtual void do_commit() = 0;
1061
1063
1066 virtual void do_abort();
1067
1069 void set_rollback_cmd(std::shared_ptr<std::string> cmd)
1070 {
1071 m_rollback_cmd = cmd;
1072 }
1073
1075 result direct_exec(std::string_view, std::string_view desc = ""sv);
1076 result
1077 direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
1078
1079private:
1080 enum class status
1081 {
1082 active,
1083 aborted,
1084 committed,
1085 in_doubt
1086 };
1087
1088 PQXX_PRIVATE void check_pending_error();
1089
1090 result
1091 internal_exec_prepared(zview statement, internal::c_params const &args);
1092
1093 result internal_exec_params(zview query, internal::c_params const &args);
1094
1096 void check_rowcount_prepared(
1097 zview statement, result::size_type expected_rows,
1098 result::size_type actual_rows);
1099
1101 void
1102 check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
1103
1105 [[nodiscard]] std::string description() const;
1106
1107 friend class pqxx::internal::gate::transaction_transaction_focus;
1108 PQXX_PRIVATE void register_focus(transaction_focus *);
1109 PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
1110 PQXX_PRIVATE void register_pending_error(zview) noexcept;
1111 PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
1112
1114 template<typename... ARGS>
1115 auto stream_like(std::string_view query, std::tuple<ARGS...> const *)
1116 {
1117 return stream<ARGS...>(query);
1118 }
1119
1120 connection &m_conn;
1121
1123
1126 transaction_focus const *m_focus = nullptr;
1127
1128 status m_status = status::active;
1129 bool m_registered = false;
1130 std::string m_name;
1131 std::string m_pending_error;
1132
1134 std::shared_ptr<std::string> m_rollback_cmd;
1135
1136 static constexpr std::string_view s_type_name{"transaction"sv};
1137};
1138
1139
1140// C++20: Can borrowed_range help?
1142template<>
1143std::string_view transaction_base::query_value<std::string_view>(
1144 zview query, std::string_view desc) = delete;
1146template<>
1147zview transaction_base::query_value<zview>(
1148 zview query, std::string_view desc) = delete;
1149
1150} // namespace pqxx
1151
1152
1153namespace pqxx::internal
1154{
1156template<pqxx::isolation_level isolation, pqxx::write_policy rw>
1157extern const zview begin_cmd;
1158
1159// These are not static members, so "constexpr" does not imply "inline".
1160template<>
1162 "BEGIN"_zv};
1163template<>
1165 "BEGIN READ ONLY"_zv};
1166template<>
1168 "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
1169template<>
1171 "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
1172template<>
1174 "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
1175template<>
1177 "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
1178} // namespace pqxx::internal
1179
1180#include "pqxx/internal/stream_query_impl.hxx"
1181#endif
Stream query results from the database. Used by transaction_base::stream.
Definition stream_query.hxx:80
Marker-type wrapper: zero-terminated std::string_view.
Definition zview.hxx:38
Internal items for libpqxx' own use. Do not use these yourself.
Definition encodings.cxx:33
void PQXX_LIBEXPORT unesc_bin(std::string_view escaped_data, std::byte buffer[])
Reconstitute binary data from its escaped version.
Definition util.cxx:165
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:629
The home of all libpqxx classes, functions, templates, etc.
Definition array.cxx:27
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:373
bytes_view binary_cast(TYPE const &data)
End a code block started by "ignore-deprecated-pre.hxx".
Definition util.hxx:409