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-2025, 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/prepared_statement.hxx"
38#include "pqxx/result.hxx"
39#include "pqxx/row.hxx"
40#include "pqxx/util.hxx"
41
42namespace pqxx::internal::gate
43{
44class transaction_subtransaction;
45class transaction_sql_cursor;
46class transaction_stream_to;
47class transaction_transaction_focus;
48} // namespace pqxx::internal::gate
49
50
51namespace pqxx
52{
53using namespace std::literals;
54
55
56class transaction_focus;
57
58
145
150class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
151{
152public:
153 transaction_base() = delete;
154 transaction_base(transaction_base const &) = delete;
155 transaction_base(transaction_base &&) = delete;
156 transaction_base &operator=(transaction_base const &) = delete;
157 transaction_base &operator=(transaction_base &&) = delete;
158
159 virtual ~transaction_base() = 0;
160
162
175 void commit();
176
178
181 void abort();
182
194 template<typename... ARGS> [[nodiscard]] auto esc(ARGS &&...args) const
195 {
196 return conn().esc(std::forward<ARGS>(args)...);
197 }
198
200
211 template<typename... ARGS> [[nodiscard]] auto esc_raw(ARGS &&...args) const
212 {
213 return conn().esc_raw(std::forward<ARGS>(args)...);
214 }
215
217
220 [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
221 unesc_raw(zview text) const
222 {
223#include "pqxx/internal/ignore-deprecated-pre.hxx"
224 return conn().unesc_raw(text);
225#include "pqxx/internal/ignore-deprecated-post.hxx"
226 }
227
229
232 [[nodiscard]] bytes unesc_bin(zview text) { return conn().unesc_bin(text); }
233
235
238 [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
239 unesc_raw(char const *text) const
240 {
241#include "pqxx/internal/ignore-deprecated-pre.hxx"
242 return conn().unesc_raw(text);
243#include "pqxx/internal/ignore-deprecated-post.hxx"
244 }
245
247
250 [[nodiscard]] bytes unesc_bin(char const text[])
251 {
252 return conn().unesc_bin(text);
253 }
254
256
257 template<typename T> [[nodiscard]] std::string quote(T const &t) const
258 {
259 return conn().quote(t);
260 }
261
262 [[deprecated("Use bytes instead of binarystring.")]] std::string
263 quote(binarystring const &t) const
264 {
265 return conn().quote(t.bytes_view());
266 }
267
269 [[deprecated("Use quote(pqxx::bytes_view).")]] std::string
270 quote_raw(unsigned char const bin[], std::size_t len) const
271 {
272 return quote(binary_cast(bin, len));
273 }
274
276 [[deprecated("Use quote(pqxx::bytes_view).")]] std::string
277 quote_raw(zview bin) const;
278
279#if defined(PQXX_HAVE_CONCEPTS)
281
282 template<binary DATA>
283 [[nodiscard]] std::string quote_raw(DATA const &data) const
284 {
285 return conn().quote_raw(data);
286 }
287#endif
288
290 [[nodiscard]] std::string quote_name(std::string_view identifier) const
291 {
292 return conn().quote_name(identifier);
293 }
294
296 [[nodiscard]] std::string
297 esc_like(std::string_view bin, char escape_char = '\\') const
298 {
299 return conn().esc_like(bin, escape_char);
300 }
302
338
340
345 [[deprecated("The desc parameter is going away.")]]
346 result exec(std::string_view query, std::string_view desc);
347
348 // TODO: Wrap PQdescribePrepared().
349
350 result exec(std::string_view query, params parms)
351 {
352 return internal_exec_params(query, parms.make_c_params());
353 }
354
356
360 result exec(std::string_view query)
361 {
362#include "pqxx/internal/ignore-deprecated-pre.hxx"
363 return exec(query, std::string_view{});
364#include "pqxx/internal/ignore-deprecated-post.hxx"
365 }
366
368
373 [[deprecated(
374 "Pass your query as a std::string_view, not stringstream.")]] result
375 exec(std::stringstream const &query, std::string_view desc)
376 {
377#include "pqxx/internal/ignore-deprecated-pre.hxx"
378 return exec(query.str(), desc);
379#include "pqxx/internal/ignore-deprecated-post.hxx"
380 }
381
383
388 [[deprecated("Use exec(string_view) and call no_rows() on the result.")]]
389 result exec0(zview query, std::string_view desc)
390 {
391#include "pqxx/internal/ignore-deprecated-pre.hxx"
392 return exec(query, desc).no_rows();
393#include "pqxx/internal/ignore-deprecated-post.hxx"
394 }
395
397
402 [[deprecated("Use exec() and call no_rows() on the result.")]]
403 result exec0(zview query)
404 {
405 return exec(query).no_rows();
406 }
407
409
415 [[deprecated("Use exec(string_view), and call one_row() on the result.")]]
416 row exec1(zview query, std::string_view desc)
417 {
418#include "pqxx/internal/ignore-deprecated-pre.hxx"
419 return exec(query, desc).one_row();
420#include "pqxx/internal/ignore-deprecated-post.hxx"
421 }
422
424
430 [[deprecated("Use exec() instead, and call one_row() on the result.")]]
431 row exec1(zview query)
432 {
433 return exec(query).one_row();
434 }
435
437
442 [[deprecated("Use exec() instead, and call expect_rows() on the result.")]]
443 result exec_n(result::size_type rows, zview query, std::string_view desc);
444
446
451 [[deprecated("Use exec() instead, and call expect_rows() on the result.")]]
452 result exec_n(result::size_type rows, zview query)
453 {
454#include "pqxx/internal/ignore-deprecated-pre.hxx"
455 return exec(query, std::string_view{}).expect_rows(rows);
456#include "pqxx/internal/ignore-deprecated-post.hxx"
457 }
458
460
463 template<typename TYPE>
464 [[deprecated("The desc parameter is going away.")]]
465 TYPE query_value(zview query, std::string_view desc)
466 {
467#include "pqxx/internal/ignore-deprecated-pre.hxx"
468 return exec(query, desc).one_field().as<TYPE>();
469#include "pqxx/internal/ignore-deprecated-post.hxx"
470 }
471
473
479 template<typename TYPE> TYPE query_value(zview query)
480 {
481 return exec(query).one_field().as<TYPE>();
482 }
483
485
492 template<typename... TYPE>
493 [[nodiscard]] std::tuple<TYPE...> query1(zview query)
494 {
495 return exec(query).expect_columns(sizeof...(TYPE)).one_row().as<TYPE...>();
496 }
497
499
506 template<typename... TYPE>
507 [[nodiscard]] std::optional<std::tuple<TYPE...>> query01(zview query)
508 {
509 std::optional<row> const r{exec(query).opt_row()};
510 if (r)
511 return {r->as<TYPE...>()};
512 else
513 return {};
514 }
515
517
568 template<typename... TYPE>
569 [[nodiscard]] auto stream(std::string_view query) &
570 {
571 return pqxx::internal::stream_query<TYPE...>{*this, query};
572 }
573
575
577 template<typename... TYPE>
578 [[nodiscard]] auto stream(std::string_view query, params parms) &
579 {
580 return pqxx::internal::stream_query<TYPE...>{*this, query, parms};
581 }
582
583 // C++20: Concept like std::invocable, but without specifying param types.
585
613 template<typename CALLABLE>
614 auto for_stream(std::string_view query, CALLABLE &&func)
615 {
616 using param_types =
618 param_types const *const sample{nullptr};
619 auto data_stream{stream_like(query, sample)};
620 for (auto const &fields : data_stream) std::apply(func, fields);
621 }
622
623 template<typename CALLABLE>
624 [[deprecated(
625 "pqxx::transaction_base::for_each is now called for_stream.")]] auto
626 for_each(std::string_view query, CALLABLE &&func)
627 {
628 return for_stream(query, std::forward<CALLABLE>(func));
629 }
630
632
663 template<typename... TYPE> auto query(zview query)
664 {
665 return exec(query).iter<TYPE...>();
666 }
667
669 template<typename... TYPE>
670 [[deprecated("Use query() instead, and call expect_rows() on the result.")]]
671 auto query_n(result::size_type rows, zview query)
672 {
673 return exec(query).expect_rows(rows).iter<TYPE...>();
674 }
675
676 // C++20: Concept like std::invocable, but without specifying param types.
678
686 template<typename CALLABLE> void for_query(zview query, CALLABLE &&func)
687 {
688 exec(query).for_each(std::forward<CALLABLE>(func));
689 }
690
720
722
726 template<typename... Args>
727 [[deprecated("Use exec(zview, params) instead.")]]
728 result exec_params(std::string_view query, Args &&...args)
729 {
730 return exec(query, params{args...});
731 }
732
733 // Execute parameterised statement, expect a single-row result.
736 template<typename... Args>
737 [[deprecated("Use exec() instead, and call one_row() on the result.")]]
738 row exec_params1(zview query, Args &&...args)
739 {
740 return exec(query, params{args...}).one_row();
741 }
742
743 // Execute parameterised statement, expect a result with zero rows.
746 template<typename... Args>
747 [[deprecated(
748 "Use exec(string_view, params) and call no_rows() on the result.")]]
749 result exec_params0(zview query, Args &&...args)
750 {
751 return exec(query, params{args...}).no_rows();
752 }
753
754 // Execute parameterised statement, expect exactly a given number of rows.
757 template<typename... Args>
758 [[deprecated("Use exec(), and call expect_rows() on the result.")]]
759 result exec_params_n(std::size_t rows, zview query, Args &&...args)
760 {
761 return exec(query, params{args...})
762 .expect_rows(check_cast<result_size_type>(rows, "number of rows"));
763 }
764
765 // Execute parameterised statement, expect exactly a given number of rows.
768 template<typename... Args>
769 [[deprecated("Use exec(), and call expect_rows() on the result.")]]
770 result exec_params_n(result::size_type rows, zview query, Args &&...args)
771 {
772 return exec(query, params{args...}).expect_rows(rows);
773 }
774
776
809 template<typename... TYPE> auto query(zview query, params const &parms)
810 {
811 return exec(query, parms).iter<TYPE...>();
812 }
813
816
824 template<typename... TYPE>
825 [[deprecated("Use exec(), and call expect_rows() & iter() on the result.")]]
826 auto query_n(result::size_type rows, zview query, params const &parms)
827 {
828 return exec(query, parms).expect_rows(rows).iter<TYPE...>();
829 }
830
832
838 template<typename TYPE> TYPE query_value(zview query, params const &parms)
839 {
840 return exec(query, parms).expect_columns(1).one_field().as<TYPE>();
841 }
842
844
851 template<typename... TYPE>
852 [[nodiscard]]
853 std::tuple<TYPE...> query1(zview query, params const &parms)
854 {
855 return exec(query, parms).one_row().as<TYPE...>();
856 }
857
859
866 template<typename... TYPE>
867 [[nodiscard]] std::optional<std::tuple<TYPE...>>
868 query01(zview query, params const &parms)
869 {
870 std::optional<row> r{exec(query, parms).opt_row()};
871 if (r)
872 return {r->as<TYPE...>()};
873 else
874 return {};
875 }
876
877 // C++20: Concept like std::invocable, but without specifying param types.
879
890 template<typename CALLABLE>
891 void for_query(zview query, CALLABLE &&func, params const &parms)
892 {
893 exec(query, parms).for_each(std::forward<CALLABLE>(func));
894 }
895
897
912 void notify(std::string_view channel, std::string_view payload = {});
914
916 template<typename... Args>
917 [[deprecated("Use exec(prepped, params) instead.")]]
918 result exec_prepared(zview statement, Args &&...args)
919 {
920 return exec(prepped{statement}, params{args...});
921 }
922
924 result exec(prepped statement)
925 {
926 params pp;
927 return internal_exec_prepared(statement, pp.make_c_params());
928 }
929
931
936 template<typename... TYPE>
937 auto query(prepped statement, params const &parms = {})
938 {
939 return exec(statement, parms).iter<TYPE...>();
940 }
941
943
946 template<typename TYPE>
947 TYPE query_value(prepped statement, params const &parms = {})
948 {
949 return exec(statement, parms).expect_columns(1).one_field().as<TYPE>();
950 }
951
952 // C++20: Concept like std::invocable, but without specifying param types.
954
956 template<typename CALLABLE>
957 void for_query(prepped statement, CALLABLE &&func, params const &parms = {})
958 {
959 exec(statement, parms).for_each(std::forward<CALLABLE>(func));
960 }
961
962 // TODO: stream() with prepped.
963 // TODO: stream_like() with prepped.
964
966 result exec(prepped statement, params const &parms)
967 {
968 return internal_exec_prepared(statement, parms.make_c_params());
969 }
970
972
974 template<typename... Args>
975 [[deprecated(
976 "Use exec(string_view, params) and call one_row() on the result.")]]
977 row exec_prepared1(zview statement, Args &&...args)
978 {
979 return exec(prepped{statement}, params{args...}).one_row();
980 }
981
983
985 template<typename... Args>
986 [[deprecated(
987 "Use exec(prepped, params), and call no_rows() on the result.")]]
988 result exec_prepared0(zview statement, Args &&...args)
989 {
990 return exec(prepped{statement}, params{args...}).no_rows();
991 }
992
994
997 template<typename... Args>
998 [[deprecated(
999 "Use exec(prepped, params), and call expect_rows() on the result.")]]
1000 result
1001 exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
1002 {
1003 return exec(pqxx::prepped{statement}, params{args...}).expect_rows(rows);
1004 }
1005
1011 void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
1013 void process_notice(zview msg) const { m_conn.process_notice(msg); }
1015
1017 [[nodiscard]] constexpr connection &conn() const noexcept { return m_conn; }
1018
1020
1035 [[deprecated("Set transaction-local variables using SQL SET statements.")]]
1036 void set_variable(std::string_view var, std::string_view value);
1037
1039
1042 [[deprecated("Read variables using SQL SHOW statements.")]]
1043 std::string get_variable(std::string_view);
1044
1045 // C++20: constexpr.
1047 [[nodiscard]] std::string_view name() const & noexcept { return m_name; }
1048
1049protected:
1051
1054 transaction_base(
1055 connection &cx, std::string_view tname,
1056 std::shared_ptr<std::string> rollback_cmd) :
1057 m_conn{cx}, m_name{tname}, m_rollback_cmd{rollback_cmd}
1058 {}
1059
1061
1066 transaction_base(connection &cx, std::string_view tname);
1067
1069 explicit transaction_base(connection &cx);
1070
1072 void register_transaction();
1073
1075 void close() noexcept;
1076
1078 virtual void do_commit() = 0;
1079
1081
1084 virtual void do_abort();
1085
1087 void set_rollback_cmd(std::shared_ptr<std::string> cmd)
1088 {
1089 m_rollback_cmd = cmd;
1090 }
1091
1093 result direct_exec(std::string_view, std::string_view desc = ""sv);
1094 result
1095 direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
1096
1097private:
1098 enum class status
1099 {
1100 active,
1101 aborted,
1102 committed,
1103 in_doubt
1104 };
1105
1106 PQXX_PRIVATE void check_pending_error();
1107
1108 result internal_exec_prepared(
1109 std::string_view statement, internal::c_params const &args);
1110
1111 result
1112 internal_exec_params(std::string_view query, internal::c_params const &args);
1113
1115 [[nodiscard]] std::string description() const;
1116
1117 friend class pqxx::internal::gate::transaction_transaction_focus;
1118 PQXX_PRIVATE void register_focus(transaction_focus *);
1119 PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
1120 PQXX_PRIVATE void register_pending_error(zview) noexcept;
1121 PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
1122
1124 template<typename... ARGS>
1125 auto stream_like(std::string_view query, std::tuple<ARGS...> const *)
1126 {
1127 return stream<ARGS...>(query);
1128 }
1129
1130 connection &m_conn;
1131
1133
1136 transaction_focus const *m_focus = nullptr;
1137
1138 status m_status = status::active;
1139 bool m_registered = false;
1140 std::string m_name;
1141 std::string m_pending_error;
1142
1144 std::shared_ptr<std::string> m_rollback_cmd;
1145
1146 static constexpr std::string_view s_type_name{"transaction"sv};
1147};
1148
1149
1150// C++20: Can borrowed_range help?
1152template<>
1153std::string_view transaction_base::query_value<std::string_view>(
1154 zview query, std::string_view desc) = delete;
1156template<>
1157zview transaction_base::query_value<zview>(
1158 zview query, std::string_view desc) = delete;
1159
1160} // namespace pqxx
1161
1162
1163namespace pqxx::internal
1164{
1166template<pqxx::isolation_level isolation, pqxx::write_policy rw>
1167extern const zview begin_cmd;
1168
1169// These are not static members, so "constexpr" does not imply "inline".
1170template<>
1171inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
1172 "BEGIN"_zv};
1173template<>
1174inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
1175 "BEGIN READ ONLY"_zv};
1176template<>
1177inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
1178 "BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
1179template<>
1180inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
1181 "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
1182template<>
1183inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
1184 "BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
1185template<>
1186inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
1187 "BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
1188} // namespace pqxx::internal
1189
1190#include "pqxx/internal/stream_query_impl.hxx"
1191#endif
Stream query results from the database. Used by transaction_base::stream.
Definition stream_query.hxx:80
A string that is the name of a prepared statement.
Definition prepared_statement.hxx:70
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)
Cast binary data to a type that libpqxx will recognise as binary.
Definition util.hxx:409