libpqxx
The C++ client library for PostgreSQL
Loading...
Searching...
No Matches
connection.hxx
1/* Definition of the connection class.
2 *
3 * pqxx::connection encapsulates a connection to a database.
4 *
5 * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/connection instead.
6 *
7 * Copyright (c) 2000-2025, Jeroen T. Vermeulen.
8 *
9 * See COPYING for copyright license. If you did not receive a file called
10 * COPYING with this source code, please notify the distributor of this
11 * mistake, or contact the author.
12 */
13#ifndef PQXX_H_CONNECTION
14#define PQXX_H_CONNECTION
15
16#if !defined(PQXX_HEADER_PRE)
17# error "Include libpqxx headers as <pqxx/header>, not <pqxx/header.hxx>."
18#endif
19
20#include <cstddef>
21#include <ctime>
22#include <functional>
23#include <initializer_list>
24#include <list>
25#include <map>
26#include <memory>
27#include <string_view>
28#include <tuple>
29#include <utility>
30
31// Double-check in order to suppress an overzealous Visual C++ warning (#418).
32#if defined(PQXX_HAVE_CONCEPTS) && __has_include(<ranges>)
33# include <ranges>
34#endif
35
36#include "pqxx/errorhandler.hxx"
37#include "pqxx/except.hxx"
38#include "pqxx/internal/concat.hxx"
39#include "pqxx/params.hxx"
40#include "pqxx/separated_list.hxx"
41#include "pqxx/strconv.hxx"
42#include "pqxx/types.hxx"
43#include "pqxx/util.hxx"
44#include "pqxx/zview.hxx"
45
46
79namespace pqxx::internal
80{
81class sql_cursor;
82
83#if defined(PQXX_HAVE_CONCEPTS)
85template<typename T>
86concept ZKey_ZValues = std::ranges::input_range<T> and requires(T t) {
87 { std::cbegin(t) };
88 { std::get<0>(*std::cbegin(t)) } -> ZString;
89 { std::get<1>(*std::cbegin(t)) } -> ZString;
90} and std::tuple_size_v<typename std::ranges::iterator_t<T>::value_type> == 2;
91#endif // PQXX_HAVE_CONCEPTS
92
93
95
102void PQXX_COLD PQXX_LIBEXPORT skip_init_ssl(int skips) noexcept;
103} // namespace pqxx::internal
104
105
106namespace pqxx::internal::gate
107{
108class connection_dbtransaction;
109class connection_errorhandler;
110class connection_largeobject;
111class connection_notification_receiver;
112class connection_pipeline;
113class connection_sql_cursor;
114struct connection_stream_from;
115class connection_stream_to;
116class connection_transaction;
117class const_connection_largeobject;
118} // namespace pqxx::internal::gate
119
120
121namespace pqxx
122{
124
136{
138
143 connection &conn;
144
146
150
152
155
157
168};
169
170
172
179enum skip_init : int
180{
183
186
189};
190
191
193
216template<skip_init... SKIP> inline void skip_init_ssl() noexcept
217{
218 // (Normalise skip flags to one per.)
219 pqxx::internal::skip_init_ssl(((1 << SKIP) | ...));
220}
221
222
224
231using table_path = std::initializer_list<std::string_view>;
232
233
235enum class error_verbosity : int
236{
237 // These values must match those in libpq's PGVerbosity enum.
238 terse = 0,
239 normal = 1,
240 verbose = 2
241};
242
243
245
278class PQXX_LIBEXPORT connection
279{
280public:
281 connection() : connection{""} {}
282
284 explicit connection(char const options[])
285 {
287 init(options);
288 }
289
291 explicit connection(zview options) : connection{options.c_str()}
292 {
293 // (Delegates to other constructor which calls check_version for us.)
294 }
295
297
302 connection(connection &&rhs);
303
304#if defined(PQXX_HAVE_CONCEPTS)
306
321 template<internal::ZKey_ZValues MAPPING>
322 inline connection(MAPPING const &params);
323#endif // PQXX_HAVE_CONCEPTS
324
325 ~connection()
326 {
327 try
328 {
329 close();
330 }
331 catch (std::exception const &)
332 {}
333 }
334
335 // TODO: Once we drop notification_receiver/errorhandler, move is easier.
337
340 connection &operator=(connection &&rhs);
341
342 connection(connection const &) = delete;
343 connection &operator=(connection const &) = delete;
344
346
351 [[nodiscard]] bool PQXX_PURE is_open() const noexcept;
352
354 void process_notice(char const[]) noexcept;
356
359 void process_notice(zview) noexcept;
360
362 void trace(std::FILE *) noexcept;
363
375
376 [[nodiscard]] char const *dbname() const;
377
379
380 [[nodiscard]] char const *username() const;
381
383
386 [[nodiscard]] char const *hostname() const;
387
389 [[nodiscard]] char const *port() const;
390
392 [[nodiscard]] int PQXX_PURE backendpid() const & noexcept;
393
395
405 [[nodiscard]] int PQXX_PURE sock() const & noexcept;
406
408
411 [[nodiscard]] int PQXX_PURE protocol_version() const noexcept;
412
414
426 [[nodiscard]] int PQXX_PURE server_version() const noexcept;
428
430
451 [[nodiscard]] std::string get_client_encoding() const;
452
454
457 void set_client_encoding(zview encoding) &
458 {
459 set_client_encoding(encoding.c_str());
460 }
461
463
466 void set_client_encoding(char const encoding[]) &;
467
469 [[nodiscard]] int encoding_id() const;
470
472
474
495 template<typename TYPE>
496 void set_session_var(std::string_view var, TYPE const &value) &
497 {
498 if constexpr (nullness<TYPE>::has_null)
499 {
500 if (nullness<TYPE>::is_null(value))
501 throw variable_set_to_null{
502 internal::concat("Attempted to set variable ", var, " to null.")};
503 }
504 exec(internal::concat("SET ", quote_name(var), "=", quote(value)));
505 }
506
508
514 std::string get_var(std::string_view var);
515
517
523 template<typename TYPE> TYPE get_var_as(std::string_view var)
524 {
525 return from_string<TYPE>(get_var(var));
526 }
527
619
636 int get_notifs();
637
639
653 int await_notification();
654
656
672 int await_notification(std::time_t seconds, long microseconds = 0);
673
675
682 using notification_handler = std::function<void(notification)>;
683
685
712 void listen(std::string_view channel, notification_handler handler = {});
713
715
747 [[nodiscard]] std::string
748 encrypt_password(zview user, zview password, zview algorithm)
749 {
750 return encrypt_password(user.c_str(), password.c_str(), algorithm.c_str());
751 }
753 [[nodiscard]] std::string encrypt_password(
754 char const user[], char const password[], char const *algorithm = nullptr);
756
799
801
805 void prepare(zview name, zview definition) &
806 {
807 prepare(name.c_str(), definition.c_str());
808 }
809
814 void prepare(char const name[], char const definition[]) &;
815
817
824 void prepare(char const definition[]) &;
825 void prepare(zview definition) & { return prepare(definition.c_str()); }
826
828 void unprepare(std::string_view name);
829
831
832 // C++20: constexpr. Breaks ABI.
834
837 [[nodiscard]] std::string adorn_name(std::string_view);
838
843
845 [[nodiscard]] std::string esc(char const text[]) const
846 {
847 return esc(std::string_view{text});
848 }
849
850#if defined(PQXX_HAVE_SPAN)
852
863 [[nodiscard]] std::string_view
864 esc(std::string_view text, std::span<char> buffer)
865 {
866 auto const size{std::size(text)}, space{std::size(buffer)};
867 auto const needed{2 * size + 1};
868 if (space < needed)
869 throw range_error{internal::concat(
870 "Not enough room to escape string of ", size, " byte(s): need ",
871 needed, " bytes of buffer space, but buffer size is ", space, ".")};
872 auto const data{buffer.data()};
873 return {data, esc_to_buf(text, data)};
874 }
875#endif
876
878
881 [[nodiscard]] std::string esc(std::string_view text) const;
882
883#if defined(PQXX_HAVE_CONCEPTS)
885
886 template<binary DATA> [[nodiscard]] std::string esc(DATA const &data) const
887 {
888 return esc_raw(data);
889 }
890#endif
891
892#if defined(PQXX_HAVE_CONCEPTS) && defined(PQXX_HAVE_SPAN)
894
905 template<binary DATA>
906 [[nodiscard]] zview esc(DATA const &data, std::span<char> buffer) const
907 {
908 auto const size{std::size(data)}, space{std::size(buffer)};
909 auto const needed{internal::size_esc_bin(std::size(data))};
910 if (space < needed)
911 throw range_error{internal::concat(
912 "Not enough room to escape binary string of ", size, " byte(s): need ",
913 needed, " bytes of buffer space, but buffer size is ", space, ".")};
914
915 bytes_view view{std::data(data), std::size(data)};
916 auto const out{std::data(buffer)};
917 // Actually, in the modern format, we know beforehand exactly how many
918 // bytes we're going to fill. Just leave out the trailing zero.
919 internal::esc_bin(view, out);
920 return zview{out, needed - 1};
921 }
922#endif
923
925 [[deprecated("Use std::byte for binary data.")]] std::string
926 esc_raw(unsigned char const bin[], std::size_t len) const;
927
929
930 [[nodiscard]] std::string esc_raw(bytes_view) const;
931
932#if defined(PQXX_HAVE_SPAN)
934
935 [[nodiscard]] std::string esc_raw(bytes_view, std::span<char> buffer) const;
936#endif
937
938#if defined(PQXX_HAVE_CONCEPTS)
940
941 template<binary DATA>
942 [[nodiscard]] std::string esc_raw(DATA const &data) const
943 {
944 return esc_raw(bytes_view{std::data(data), std::size(data)});
945 }
946#endif
947
948#if defined(PQXX_HAVE_CONCEPTS) && defined(PQXX_HAVE_SPAN)
950 template<binary DATA>
951 [[nodiscard]] zview esc_raw(DATA const &data, std::span<char> buffer) const
952 {
953 return this->esc(binary_cast(data), buffer);
954 }
955#endif
956
957 // TODO: Make "into buffer" variant to eliminate a string allocation.
959
966 [[nodiscard]] bytes unesc_bin(std::string_view text) const
967 {
968 bytes buf;
969 buf.resize(pqxx::internal::size_unesc_bin(std::size(text)));
970 pqxx::internal::unesc_bin(text, buf.data());
971 return buf;
972 }
973
975 std::string quote_raw(bytes_view) const;
976
977#if defined(PQXX_HAVE_CONCEPTS)
979
980 template<binary DATA>
981 [[nodiscard]] std::string quote_raw(DATA const &data) const
982 {
983 return quote_raw(bytes_view{std::data(data), std::size(data)});
984 }
985#endif
986
987 // TODO: Make "into buffer" variant to eliminate a string allocation.
989 [[nodiscard]] std::string quote_name(std::string_view identifier) const;
990
991 // TODO: Make "into buffer" variant to eliminate a string allocation.
993
996 [[nodiscard]] std::string quote_table(std::string_view name) const;
997
998 // TODO: Make "into buffer" variant to eliminate a string allocation.
1000
1008 [[nodiscard]] std::string quote_table(table_path) const;
1009
1010 // TODO: Make "into buffer" variant to eliminate a string allocation.
1012
1019 template<PQXX_CHAR_STRINGS_ARG STRINGS>
1020 inline std::string quote_columns(STRINGS const &columns) const;
1021
1022 // TODO: Make "into buffer" variant to eliminate a string allocation.
1024
1027 template<typename T>
1028 [[nodiscard]] inline std::string quote(T const &t) const;
1029
1030 [[deprecated("Use std::byte for binary data.")]] std::string
1031 quote(binarystring const &) const;
1032
1033 // TODO: Make "into buffer" variant to eliminate a string allocation.
1035 [[nodiscard]] std::string quote(bytes_view bytes) const;
1036
1037 // TODO: Make "into buffer" variant to eliminate a string allocation.
1039
1064 [[nodiscard]] std::string
1065 esc_like(std::string_view text, char escape_char = '\\') const;
1066
1068
1072 [[deprecated("Use std::string_view or pqxx:zview.")]] std::string
1073 esc(char const text[], std::size_t maxlen) const
1074 {
1075 return esc(std::string_view{text, maxlen});
1076 }
1077
1079
1082 [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
1083 unesc_raw(zview text) const
1084 {
1085#include "pqxx/internal/ignore-deprecated-pre.hxx"
1086 return unesc_raw(text.c_str());
1087#include "pqxx/internal/ignore-deprecated-post.hxx"
1088 }
1089
1091
1094 [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
1095 unesc_raw(char const text[]) const;
1096
1098 [[deprecated("Use quote(bytes_view).")]] std::string
1099 quote_raw(unsigned char const bin[], std::size_t len) const;
1101
1103
1107 void cancel_query();
1108
1109#if defined(_WIN32) || __has_include(<fcntl.h>)
1111
1115 void set_blocking(bool block) &;
1116#endif // defined(_WIN32) || __has_include(<fcntl.h>)
1117
1119
1131 void set_verbosity(error_verbosity verbosity) & noexcept;
1132
1133 // C++20: Use std::callable.
1134
1136
1148 void set_notice_handler(std::function<void(zview)> handler)
1149 {
1150 m_notice_waiters->notice_handler = std::move(handler);
1151 }
1152
1154
1159 [[nodiscard, deprecated("Use a notice handler instead.")]]
1160 std::vector<errorhandler *> get_errorhandlers() const;
1161
1163
1169 [[nodiscard]] std::string connection_string() const;
1170
1172
1180 void close();
1181
1183
1189 static connection seize_raw_connection(internal::pq::PGconn *raw_conn)
1190 {
1191 return connection{raw_conn};
1192 }
1193
1195
1200 internal::pq::PGconn *release_raw_connection() &&
1201 {
1202 return std::exchange(m_conn, nullptr);
1203 }
1204
1206
1219 [[deprecated("To set session variables, use set_session_var.")]] void
1220 set_variable(std::string_view var, std::string_view value) &;
1221
1223
1226 [[deprecated("Use get_var instead.")]] std::string
1227 get_variable(std::string_view);
1228
1229private:
1230 friend class connecting;
1231 enum connect_mode
1232 {
1233 connect_nonblocking
1234 };
1235 connection(connect_mode, zview connection_string);
1236
1238 explicit connection(internal::pq::PGconn *raw_conn);
1239
1241
1246 std::pair<bool, bool> poll_connect();
1247
1248 // Initialise based on connection string.
1249 void init(char const options[]);
1250 // Initialise based on parameter names and values.
1251 void init(char const *params[], char const *values[]);
1252 void set_up_notice_handlers();
1253 void complete_init();
1254
1255 result make_result(
1256 internal::pq::PGresult *pgr, std::shared_ptr<std::string> const &query,
1257 std::string_view desc = ""sv);
1258
1259 void PQXX_PRIVATE set_up_state();
1260
1261 int PQXX_PRIVATE PQXX_PURE status() const noexcept;
1262
1264
1268 std::size_t esc_to_buf(std::string_view text, char *buf) const;
1269
1270 friend class internal::gate::const_connection_largeobject;
1271 char const *PQXX_PURE err_msg() const noexcept;
1272
1273 result exec_prepared(std::string_view statement, internal::c_params const &);
1274
1276 void check_movable() const;
1278 void check_overwritable() const;
1279
1280 friend class internal::gate::connection_errorhandler;
1281 void PQXX_PRIVATE register_errorhandler(errorhandler *);
1282 void PQXX_PRIVATE unregister_errorhandler(errorhandler *) noexcept;
1283
1284 friend class internal::gate::connection_transaction;
1285 result exec(std::string_view, std::string_view = ""sv);
1286 result PQXX_PRIVATE
1287 exec(std::shared_ptr<std::string> const &, std::string_view = ""sv);
1288 void PQXX_PRIVATE register_transaction(transaction_base *);
1289 void PQXX_PRIVATE unregister_transaction(transaction_base *) noexcept;
1290
1291 friend struct internal::gate::connection_stream_from;
1293
1298 std::pair<std::unique_ptr<char, void (*)(void const *)>, std::size_t>
1299 read_copy_line();
1300
1301 friend class internal::gate::connection_stream_to;
1302 void PQXX_PRIVATE write_copy_line(std::string_view);
1303 void PQXX_PRIVATE end_copy_write();
1304
1305 friend class internal::gate::connection_largeobject;
1306 internal::pq::PGconn *raw_connection() const { return m_conn; }
1307
1308 friend class internal::gate::connection_notification_receiver;
1309 void add_receiver(notification_receiver *);
1310 void remove_receiver(notification_receiver *) noexcept;
1311
1312 friend class internal::gate::connection_pipeline;
1313 void PQXX_PRIVATE start_exec(char const query[]);
1314 bool PQXX_PRIVATE consume_input() noexcept;
1315 bool PQXX_PRIVATE is_busy() const noexcept;
1316 internal::pq::PGresult *get_result();
1317
1318 friend class internal::gate::connection_dbtransaction;
1319 friend class internal::gate::connection_sql_cursor;
1320
1321 result exec_params(std::string_view query, internal::c_params const &args);
1322
1324 internal::pq::PGconn *m_conn = nullptr;
1325
1327
1334 transaction_base const *m_trans = nullptr;
1335
1337 std::shared_ptr<pqxx::internal::notice_waiters> m_notice_waiters;
1338
1339 // TODO: Remove these when we retire notification_receiver.
1340 // TODO: Can we make these movable?
1341 using receiver_list =
1342 std::multimap<std::string, pqxx::notification_receiver *>;
1344 receiver_list m_receivers;
1345
1347
1354 std::map<std::string, notification_handler> m_notification_handlers;
1355
1357 int m_unique_id = 0;
1358};
1359
1360
1362using connection_base = connection;
1363
1364
1366
1409class PQXX_LIBEXPORT connecting
1410{
1411public:
1413 connecting(zview connection_string = ""_zv);
1414
1415 connecting(connecting const &) = delete;
1416 connecting(connecting &&) = default;
1417 connecting &operator=(connecting const &) = delete;
1418 connecting &operator=(connecting &&) = default;
1419
1421 [[nodiscard]] int sock() const & noexcept { return m_conn.sock(); }
1422
1424 [[nodiscard]] constexpr bool wait_to_read() const & noexcept
1425 {
1426 return m_reading;
1427 }
1428
1430 [[nodiscard]] constexpr bool wait_to_write() const & noexcept
1431 {
1432 return m_writing;
1433 }
1434
1436 void process() &;
1437
1439 [[nodiscard]] constexpr bool done() const & noexcept
1440 {
1441 return not m_reading and not m_writing;
1442 }
1443
1445
1453 [[nodiscard]] connection produce() &&;
1454
1455private:
1456 connection m_conn;
1457 bool m_reading{false};
1458 bool m_writing{true};
1459};
1460
1461
1462template<typename T> inline std::string connection::quote(T const &t) const
1463{
1464 if constexpr (nullness<T>::always_null)
1465 {
1466 return "NULL";
1467 }
1468 else
1469 {
1470 if (is_null(t))
1471 return "NULL";
1472 auto const text{to_string(t)};
1473
1474 // Okay, there's an easy way to do this and there's a hard way. The easy
1475 // way was "quote, esc(to_string(t)), quote". I'm going with the hard way
1476 // because it's going to save some string manipulation that will probably
1477 // incur some unnecessary memory allocations and deallocations.
1478 std::string buf{'\''};
1479 buf.resize(2 + 2 * std::size(text) + 1);
1480 auto const content_bytes{esc_to_buf(text, buf.data() + 1)};
1481 auto const closing_quote{1 + content_bytes};
1482 buf[closing_quote] = '\'';
1483 auto const end{closing_quote + 1};
1484 buf.resize(end);
1485 return buf;
1486 }
1487}
1488
1489
1490template<PQXX_CHAR_STRINGS_ARG STRINGS>
1491inline std::string connection::quote_columns(STRINGS const &columns) const
1492{
1493 return separated_list(
1494 ","sv, std::cbegin(columns), std::cend(columns),
1495 [this](auto col) { return this->quote_name(*col); });
1496}
1497
1498
1499#if defined(PQXX_HAVE_CONCEPTS)
1500template<internal::ZKey_ZValues MAPPING>
1501inline connection::connection(MAPPING const &params)
1502{
1503 check_version();
1504
1505 std::vector<char const *> keys, values;
1506 if constexpr (std::ranges::sized_range<MAPPING>)
1507 {
1508 auto const size{std::ranges::size(params) + 1};
1509 keys.reserve(size);
1510 values.reserve(size);
1511 }
1512 for (auto const &[key, value] : params)
1513 {
1514 keys.push_back(internal::as_c_string(key));
1515 values.push_back(internal::as_c_string(value));
1516 }
1517 keys.push_back(nullptr);
1518 values.push_back(nullptr);
1519 init(std::data(keys), std::data(values));
1520}
1521#endif // PQXX_HAVE_CONCEPTS
1522
1523
1525[[nodiscard,
1526 deprecated("Use connection::encrypt_password instead.")]] std::string
1527 PQXX_LIBEXPORT
1528 encrypt_password(char const user[], char const password[]);
1529
1531[[nodiscard,
1532 deprecated("Use connection::encrypt_password instead.")]] inline std::string
1534{
1535#include "pqxx/internal/ignore-deprecated-pre.hxx"
1536 return encrypt_password(user.c_str(), password.c_str());
1537#include "pqxx/internal/ignore-deprecated-post.hxx"
1538}
1539} // namespace pqxx
1540#endif
Marker-type wrapper: zero-terminated std::string_view.
Definition zview.hxx:38
constexpr char const * c_str() const &noexcept
Either a null pointer, or a zero-terminated text buffer.
Definition zview.hxx:96
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
constexpr std::size_t size_unesc_bin(std::size_t escaped_bytes) noexcept
Compute binary size from the size of its escaped version.
Definition util.hxx:525
The home of all libpqxx classes, functions, templates, etc.
Definition array.cxx:27
std::string encrypt_password(zview user, zview password)
Encrypt password.
Definition connection.hxx:1533
std::string separated_list(std::string_view sep, ITER begin, ITER end, ACCESS access)
Represent sequence of values as a string, joined by a given separator.
Definition separated_list.hxx:46
PQXX_PRIVATE void check_version() noexcept
Definition util.hxx:236
std::conditional< has_generic_bytes_char_traits, std::basic_string_view< std::byte >, std::basic_string_view< std::byte, byte_char_traits > >::type bytes_view
Type alias for a view of bytes.
Definition util.hxx:383
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
void skip_init_ssl() noexcept
Control initialisation of OpenSSL and libcrypto libraries.
Definition connection.hxx:216
bytes_view binary_cast(TYPE const &data)
End a code block started by "ignore-deprecated-pre.hxx".
Definition util.hxx:409
std::initializer_list< std::string_view > table_path
Representation of a PostgreSQL table path.
Definition connection.hxx:231
connection & conn
The connection which received the notification.
Definition connection.hxx:143
constexpr bool is_null(TYPE const &value) noexcept
Is value null?
Definition strconv.hxx:515
int backend_pid
Process ID of the backend that sent the notification.
Definition connection.hxx:167
skip_init
Flags for skipping initialisation of SSL-related libraries.
Definition connection.hxx:180
@ crypto
Skip initialisation of libcrypto.
Definition connection.hxx:188
@ openssl
Skip initialisation of OpenSSL library.
Definition connection.hxx:185
@ nothing
A do-nothing flag that does not affect anything.
Definition connection.hxx:182
zview channel
Channel name.
Definition connection.hxx:149
connection connection_base
Definition connection.hxx:1362
zview payload
Optional payload text.
Definition connection.hxx:154
error_verbosity
Error verbosity levels.
Definition connection.hxx:236
An incoming notification.
Definition connection.hxx:136