connection.hxx 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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-2022, 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. #if !defined(PQXX_HEADER_PRE)
  16. # error "Include libpqxx headers as <pqxx/header>, not <pqxx/header.hxx>."
  17. #endif
  18. #include <cstddef>
  19. #include <ctime>
  20. #include <functional>
  21. #include <initializer_list>
  22. #include <list>
  23. #include <map>
  24. #include <memory>
  25. #include <string_view>
  26. #include <tuple>
  27. #include <utility>
  28. // Double-check in order to suppress an overzealous Visual C++ warning (#418).
  29. #if defined(PQXX_HAVE_CONCEPTS) && __has_include(<ranges>)
  30. # include <ranges>
  31. #endif
  32. #include "pqxx/errorhandler.hxx"
  33. #include "pqxx/except.hxx"
  34. #include "pqxx/internal/concat.hxx"
  35. #include "pqxx/params.hxx"
  36. #include "pqxx/separated_list.hxx"
  37. #include "pqxx/strconv.hxx"
  38. #include "pqxx/types.hxx"
  39. #include "pqxx/util.hxx"
  40. #include "pqxx/zview.hxx"
  41. /**
  42. * @addtogroup connections
  43. *
  44. * Use of the libpqxx library starts here.
  45. *
  46. * Everything that can be done with a database through libpqxx must go through
  47. * a @ref pqxx::connection object. It connects to a database when you create
  48. * it, and it terminates that communication during destruction.
  49. *
  50. * Many things come together in this class. Handling of error and warning
  51. * messages, for example, is defined by @ref pqxx::errorhandler objects in the
  52. * context of a connection. Prepared statements are also defined here.
  53. *
  54. * When you connect to a database, you pass a connection string containing any
  55. * parameters and options, such as the server address and the database name.
  56. *
  57. * These are identical to the ones in libpq, the C language binding upon which
  58. * libpqxx itself is built:
  59. *
  60. * https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
  61. *
  62. * There are also environment variables you can set to provide defaults, again
  63. * as defined by libpq:
  64. *
  65. * https://www.postgresql.org/docs/current/libpq-envars.html
  66. *
  67. * You can also create a database connection _asynchronously_ using an
  68. * intermediate @ref pqxx::connecting object.
  69. */
  70. namespace pqxx::internal
  71. {
  72. class sql_cursor;
  73. #if defined(PQXX_HAVE_CONCEPTS)
  74. /// Concept: T is a range of pairs of zero-terminated strings.
  75. template<typename T>
  76. concept ZKey_ZValues = std::ranges::input_range<T> and requires(T t)
  77. {
  78. {std::cbegin(t)};
  79. {
  80. std::get<0>(*std::cbegin(t))
  81. } -> ZString;
  82. {
  83. std::get<1>(*std::cbegin(t))
  84. } -> ZString;
  85. } and std::tuple_size_v<typename std::ranges::iterator_t<T>::value_type>
  86. == 2;
  87. #endif // PQXX_HAVE_CONCEPTS
  88. } // namespace pqxx::internal
  89. namespace pqxx::internal::gate
  90. {
  91. class connection_dbtransaction;
  92. class connection_errorhandler;
  93. class connection_largeobject;
  94. class connection_notification_receiver;
  95. class connection_pipeline;
  96. class connection_sql_cursor;
  97. class connection_stream_from;
  98. class connection_stream_to;
  99. class connection_transaction;
  100. class const_connection_largeobject;
  101. } // namespace pqxx::internal::gate
  102. namespace pqxx
  103. {
  104. /// Representation of a PostgreSQL table path.
  105. /** A "table path" consists of a table name, optionally prefixed by a schema
  106. * name, which in turn is optionally prefixed by a database name.
  107. *
  108. * A minimal example of a table path would be `{mytable}`. But a table path
  109. * may also take the forms `{myschema,mytable}` or
  110. * `{mydb,myschema,mytable}`.
  111. */
  112. using table_path = std::initializer_list<std::string_view>;
  113. /// Encrypt a password. @deprecated Use connection::encrypt_password instead.
  114. [[nodiscard,
  115. deprecated("Use connection::encrypt_password instead.")]] std::string
  116. PQXX_LIBEXPORT
  117. encrypt_password(char const user[], char const password[]);
  118. /// Encrypt password. @deprecated Use connection::encrypt_password instead.
  119. [[nodiscard,
  120. deprecated("Use connection::encrypt_password instead.")]] inline std::string
  121. encrypt_password(zview user, zview password)
  122. {
  123. #include "pqxx/internal/ignore-deprecated-pre.hxx"
  124. return encrypt_password(user.c_str(), password.c_str());
  125. #include "pqxx/internal/ignore-deprecated-post.hxx"
  126. }
  127. /// Error verbosity levels.
  128. enum class error_verbosity : int
  129. {
  130. // These values must match those in libpq's PGVerbosity enum.
  131. terse = 0,
  132. normal = 1,
  133. verbose = 2
  134. };
  135. /// Connection to a database.
  136. /** This is the first class to look at when you wish to work with a database
  137. * through libpqxx. The connection opens during construction, and closes upon
  138. * destruction.
  139. *
  140. * When creating a connection, you can pass a connection URI or a postgres
  141. * connection string, to specify the database server's address, a login
  142. * username, and so on. If you don't, the connection will try to obtain them
  143. * from certain environment variables. If those are not set either, the
  144. * default is to try and connect to the local system's port 5432.
  145. *
  146. * Find more about connection strings here:
  147. *
  148. * https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
  149. *
  150. * The variables are documented here:
  151. *
  152. * https://www.postgresql.org/docs/current/libpq-envars.html
  153. *
  154. * To query or manipulate the database once connected, use one of the
  155. * transaction classes (see pqxx/transaction_base.hxx) and perhaps also the
  156. * transactor framework (see pqxx/transactor.hxx).
  157. *
  158. * When a connection breaks, you will typically get a @ref broken_connection
  159. * exception. This can happen at almost any point.
  160. *
  161. * @warning On Unix-like systems, including GNU and BSD systems, your program
  162. * may receive the SIGPIPE signal when the connection to the backend breaks. By
  163. * default this signal will abort your program. Use "signal(SIGPIPE, SIG_IGN)"
  164. * if you want your program to continue running after a connection fails.
  165. */
  166. class PQXX_LIBEXPORT connection
  167. {
  168. public:
  169. connection() : connection{""} {}
  170. /// Connect to a database, using `options` string.
  171. explicit connection(char const options[])
  172. {
  173. check_version();
  174. init(options);
  175. }
  176. /// Connect to a database, using `options` string.
  177. explicit connection(zview options) : connection{options.c_str()}
  178. {
  179. // (Delegates to other constructor which calls check_version for us.)
  180. }
  181. /// Move constructor.
  182. /** Moving a connection is not allowed if it has an open transaction, or has
  183. * error handlers or notification receivers registered on it. In those
  184. * situations, other objects may hold references to the old object which
  185. * would become invalid and might produce hard-to-diagnose bugs.
  186. */
  187. connection(connection &&rhs);
  188. #if defined(PQXX_HAVE_CONCEPTS)
  189. /// Connect to a database, passing options as a range of key/value pairs.
  190. /** @warning Experimental. Requires C++20 "concepts" support. Define
  191. * `PQXX_HAVE_CONCEPTS` to enable it.
  192. *
  193. * There's no need to escape the parameter values.
  194. *
  195. * See the PostgreSQL libpq documentation for the full list of possible
  196. * options:
  197. *
  198. * https://postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
  199. *
  200. * The options can be anything that can be iterated as a series of pairs of
  201. * zero-terminated strings: `std::pair<std::string, std::string>`, or
  202. * `std::tuple<pqxx::zview, char const *>`, or
  203. * `std::map<std::string, pqxx::zview>`, and so on.
  204. */
  205. template<internal::ZKey_ZValues MAPPING>
  206. inline connection(MAPPING const &params);
  207. #endif // PQXX_HAVE_CONCEPTS
  208. ~connection()
  209. {
  210. try
  211. {
  212. close();
  213. }
  214. catch (std::exception const &)
  215. {}
  216. }
  217. /// Move assignment.
  218. /** Neither connection can have an open transaction, registered error
  219. * handlers, or registered notification receivers.
  220. */
  221. connection &operator=(connection &&rhs);
  222. connection(connection const &) = delete;
  223. connection &operator=(connection const &) = delete;
  224. /// Is this connection open at the moment?
  225. /** @warning This function is **not** needed in most code. Resist the
  226. * temptation to check it after opening a connection. The `connection`
  227. * constructor will throw a @ref broken_connection exception if can't connect
  228. * to the database.
  229. */
  230. [[nodiscard]] bool PQXX_PURE is_open() const noexcept;
  231. /// Invoke notice processor function. The message should end in newline.
  232. void process_notice(char const[]) noexcept;
  233. /// Invoke notice processor function. Newline at end is recommended.
  234. /** The zview variant, with a message ending in newline, is the most
  235. * efficient way to call process_notice.
  236. */
  237. void process_notice(zview) noexcept;
  238. /// Enable tracing to a given output stream, or nullptr to disable.
  239. void trace(std::FILE *) noexcept;
  240. /**
  241. * @name Connection properties
  242. *
  243. * These are probably not of great interest, since most are derived from
  244. * information supplied by the client program itself, but they are included
  245. * for completeness.
  246. *
  247. * The connection needs to be currently active for these to work.
  248. */
  249. //@{
  250. /// Name of database we're connected to, if any.
  251. [[nodiscard]] char const *dbname() const;
  252. /// Database user ID we're connected under, if any.
  253. [[nodiscard]] char const *username() const;
  254. /// Address of server, or nullptr if none specified (i.e. default or local)
  255. [[nodiscard]] char const *hostname() const;
  256. /// Server port number we're connected to.
  257. [[nodiscard]] char const *port() const;
  258. /// Process ID for backend process, or 0 if inactive.
  259. [[nodiscard]] int PQXX_PURE backendpid() const &noexcept;
  260. /// Socket currently used for connection, or -1 for none. Use with care!
  261. /** Query the current socket number. This is intended for event loops based
  262. * on functions such as select() or poll(), where you're waiting for any of
  263. * multiple file descriptors to become ready for communication.
  264. *
  265. * Please try to stay away from this function. It is really only meant for
  266. * event loops that need to wait on more than one file descriptor. If all
  267. * you need is to block until a notification arrives, for instance, use
  268. * await_notification(). If you want to issue queries and retrieve results
  269. * in nonblocking fashion, check out the pipeline class.
  270. */
  271. [[nodiscard]] int PQXX_PURE sock() const &noexcept;
  272. /// What version of the PostgreSQL protocol is this connection using?
  273. /** The answer can be 0 (when there is no connection); 3 for protocol 3.0; or
  274. * possibly higher values as newer protocol versions come into use.
  275. */
  276. [[nodiscard]] int PQXX_PURE protocol_version() const noexcept;
  277. /// What version of the PostgreSQL server are we connected to?
  278. /** The result is a bit complicated: each of the major, medium, and minor
  279. * release numbers is written as a two-digit decimal number, and the three
  280. * are then concatenated. Thus server version 9.4.2 will be returned as the
  281. * decimal number 90402. If there is no connection to the server, this
  282. * returns zero.
  283. *
  284. * @warning When writing version numbers in your code, don't add zero at the
  285. * beginning! Numbers beginning with zero are interpreted as octal (base-8)
  286. * in C++. Thus, 070402 is not the same as 70402, and 080000 is not a number
  287. * at all because there is no digit "8" in octal notation. Use strictly
  288. * decimal notation when it comes to these version numbers.
  289. */
  290. [[nodiscard]] int PQXX_PURE server_version() const noexcept;
  291. //@}
  292. /// @name Text encoding
  293. /**
  294. * Each connection is governed by a "client encoding," which dictates how
  295. * strings and other text is represented in bytes. The database server will
  296. * send text data to you in this encoding, and you should use it for the
  297. * queries and data which you send to the server.
  298. *
  299. * Search the PostgreSQL documentation for "character set encodings" to find
  300. * out more about the available encodings, how to extend them, and how to use
  301. * them. Not all server-side encodings are compatible with all client-side
  302. * encodings or vice versa.
  303. *
  304. * Encoding names are case-insensitive, so e.g. "UTF8" is equivalent to
  305. * "utf8".
  306. *
  307. * You can change the client encoding, but this may not work when the
  308. * connection is in a special state, such as when streaming a table. It's
  309. * not clear what happens if you change the encoding during a transaction,
  310. * and then abort the transaction.
  311. */
  312. //@{
  313. /// Get client-side character encoding, by name.
  314. [[nodiscard]] std::string get_client_encoding() const;
  315. /// Set client-side character encoding, by name.
  316. /**
  317. * @param encoding Name of the character set encoding to use.
  318. */
  319. void set_client_encoding(zview encoding) &
  320. {
  321. set_client_encoding(encoding.c_str());
  322. }
  323. /// Set client-side character encoding, by name.
  324. /**
  325. * @param encoding Name of the character set encoding to use.
  326. */
  327. void set_client_encoding(char const encoding[]) &;
  328. /// Get the connection's encoding, as a PostgreSQL-defined code.
  329. [[nodiscard]] int PQXX_PRIVATE encoding_id() const;
  330. //@}
  331. /// Set session variable, using SQL's `SET` command.
  332. /** @deprecated To set a session variable, use @ref set_session_var. To set
  333. * a transaction-local variable, execute an SQL `SET` command.
  334. *
  335. * @warning When setting a string value, you must escape and quote it first.
  336. * Use the @ref quote() function to do that.
  337. *
  338. * @warning This executes an SQL query, so do not get or set variables while
  339. * a table stream or pipeline is active on the same connection.
  340. *
  341. * @param var Variable to set.
  342. * @param value New value for Var. This can be any SQL expression. If it's
  343. * a string, be sure that it's properly escaped and quoted.
  344. */
  345. [[deprecated("To set session variables, use set_session_var.")]] void
  346. set_variable(std::string_view var, std::string_view value) &;
  347. /// Set one of the session variables to a new value.
  348. /** This executes SQL, so do not do it while a pipeline or stream is active
  349. * on the connection.
  350. *
  351. * The value you set here will last for the rest of the connection's
  352. * duration, or until you set a new value.
  353. *
  354. * If you set the value while in a @ref dbtransaction (i.e. any transaction
  355. * that is not a @ref nontransaction), then rolling back the transaction will
  356. * undo the change.
  357. *
  358. * All applies to setting _session_ variables. You can also set the same
  359. * variables as _local_ variables, in which case they will always revert to
  360. * their previous value when the transaction ends (or when you overwrite them
  361. * of course). To set a local variable, simply execute an SQL statement
  362. * along the lines of "`SET LOCAL var = 'value'`" inside your transaction.
  363. *
  364. * @param var The variable to set.
  365. * @param value The new value for the variable.
  366. * @throw @ref variable_set_to_null if the value is null; this is not
  367. * allowed.
  368. */
  369. template<typename TYPE>
  370. void set_session_var(std::string_view var, TYPE const &value) &
  371. {
  372. if constexpr (nullness<TYPE>::has_null)
  373. {
  374. if (nullness<TYPE>::is_null(value))
  375. throw variable_set_to_null{
  376. internal::concat("Attempted to set variable ", var, " to null.")};
  377. }
  378. exec(internal::concat("SET ", quote_name(var), "=", quote(value)));
  379. }
  380. /// Read session variable, using SQL's `SHOW` command.
  381. /** @warning This executes an SQL query, so do not get or set variables while
  382. * a table stream or pipeline is active on the same connection.
  383. */
  384. [[deprecated("Use get_var instead.")]] std::string
  385. get_variable(std::string_view);
  386. /// Read currently applicable value of a variable.
  387. /** This function executes an SQL statement, so it won't work while a
  388. * @ref pipeline or query stream is active on the connection.
  389. *
  390. * @return a blank `std::optional` if the variable's value is null, or its
  391. * string value otherwise.
  392. */
  393. std::string get_var(std::string_view var);
  394. /// Read currently applicable value of a variable.
  395. /** This function executes an SQL statement, so it won't work while a
  396. * @ref pipeline or query stream is active on the connection.
  397. *
  398. * If there is any possibility that the variable is null, ensure that `TYPE`
  399. * can represent null values.
  400. */
  401. template<typename TYPE> TYPE get_var_as(std::string_view var)
  402. {
  403. return from_string<TYPE>(get_var(var));
  404. }
  405. /**
  406. * @name Notifications and Receivers
  407. */
  408. //@{
  409. /// Check for pending notifications and take appropriate action.
  410. /** This does not block. To wait for incoming notifications, either call
  411. * await_notification() (it calls this function); or wait for incoming data
  412. * on the connection's socket (i.e. wait to read), and then call this
  413. * function repeatedly until it returns zero. After that, there are no more
  414. * pending notifications so you may want to wait again.
  415. *
  416. * If any notifications are pending when you call this function, it
  417. * processes them by finding any receivers that match the notification string
  418. * and invoking those. If no receivers match, there is nothing to invoke but
  419. * we do consider the notification processed.
  420. *
  421. * If any of the client-registered receivers throws an exception, the
  422. * function will report it using the connection's errorhandlers. It does not
  423. * re-throw the exceptions.
  424. *
  425. * @return Number of notifications processed.
  426. */
  427. int get_notifs();
  428. /// Wait for a notification to come in.
  429. /** There are other events that will also terminate the wait, such as the
  430. * backend failing. It will also wake up periodically.
  431. *
  432. * If a notification comes in, the call will process it, along with any other
  433. * notifications that may have been pending.
  434. *
  435. * To wait for notifications into your own event loop instead, wait until
  436. * there is incoming data on the connection's socket to be read, then call
  437. * @ref get_notifs() repeatedly until it returns zero.
  438. *
  439. * @return Number of notifications processed.
  440. */
  441. int await_notification();
  442. /// Wait for a notification to come in, or for given timeout to pass.
  443. /** There are other events that will also terminate the wait, such as the
  444. * backend failing, or timeout expiring.
  445. *
  446. * If a notification comes in, the call will process it, along with any other
  447. * notifications that may have been pending.
  448. *
  449. * To wait for notifications into your own event loop instead, wait until
  450. * there is incoming data on the connection's socket to be read, then call
  451. * @ref get_notifs repeatedly until it returns zero.
  452. *
  453. * @return Number of notifications processed
  454. */
  455. int await_notification(std::time_t seconds, long microseconds);
  456. //@}
  457. /**
  458. * @name Password encryption
  459. *
  460. * Use this when setting a new password for the user if password encryption
  461. * is enabled. Inputs are the SQL name for the user for whom you with to
  462. * encrypt a password; the plaintext password; and the hash algorithm.
  463. *
  464. * The algorithm must be one of "md5", "scram-sha-256" (introduced in
  465. * PostgreSQL 10), or `nullptr`. If the pointer is null, this will query
  466. * the `password_encryption setting` from the server, and use the default
  467. * algorithm as defined there.
  468. *
  469. * @return encrypted version of the password, suitable for encrypted
  470. * PostgreSQL authentication.
  471. *
  472. * Thus you can change a user's password with:
  473. * ```cxx
  474. * void setpw(transaction_base &t, string const &user, string const &pw)
  475. * {
  476. * t.exec0("ALTER USER " + user + " "
  477. * "PASSWORD '" + t.conn().encrypt_password(user,pw) + "'");
  478. * }
  479. * ```
  480. *
  481. * When building this against a libpq older than version 10, this will use
  482. * an older function which only supports md5. In that case, requesting a
  483. * different algorithm than md5 will result in a @ref feature_not_supported
  484. * exception.
  485. */
  486. //@{
  487. /// Encrypt a password for a given user.
  488. [[nodiscard]] std::string
  489. encrypt_password(zview user, zview password, zview algorithm)
  490. {
  491. return encrypt_password(user.c_str(), password.c_str(), algorithm.c_str());
  492. }
  493. /// Encrypt a password for a given user.
  494. [[nodiscard]] std::string encrypt_password(
  495. char const user[], char const password[], char const *algorithm = nullptr);
  496. //@}
  497. /**
  498. * @name Prepared statements
  499. *
  500. * PostgreSQL supports prepared SQL statements, i.e. statements that you can
  501. * register under a name you choose, optimized once by the backend, and
  502. * executed any number of times under the given name.
  503. *
  504. * Prepared statement definitions are not sensitive to transaction
  505. * boundaries. A statement defined inside a transaction will remain defined
  506. * outside that transaction, even if the transaction itself is subsequently
  507. * aborted. Once a statement has been prepared, it will only go away if you
  508. * close the connection or explicitly "unprepare" the statement.
  509. *
  510. * Use the `pqxx::transaction_base::exec_prepared` functions to execute a
  511. * prepared statement. See @ref prepared for a full discussion.
  512. *
  513. * @warning Using prepared statements can save time, but if your statement
  514. * takes parameters, it may also make your application significantly slower!
  515. * The reason is that the server works out a plan for executing the query
  516. * when you prepare it. At that time, of course it does not know the values
  517. * for the parameters that you will pass. If you execute a query without
  518. * preparing it, then the server works out the plan on the spot, with full
  519. * knowledge of the parameter values.
  520. *
  521. * A statement's definition can refer to its parameters as `$1`, `$2`, etc.
  522. * The first parameter you pass to the call provides a value for `$1`, and
  523. * so on.
  524. *
  525. * Here's an example of how to use prepared statements.
  526. *
  527. * ```cxx
  528. * using namespace pqxx;
  529. * void foo(connection &c)
  530. * {
  531. * c.prepare("findtable", "select * from pg_tables where name=$1");
  532. * work tx{c};
  533. * result r = tx.exec_prepared("findtable", "mytable");
  534. * if (std::empty(r)) throw runtime_error{"mytable not found!"};
  535. * }
  536. * ```
  537. */
  538. //@{
  539. /// Define a prepared statement.
  540. /**
  541. * @param name unique name for the new prepared statement.
  542. * @param definition SQL statement to prepare.
  543. */
  544. void prepare(zview name, zview definition) &
  545. {
  546. prepare(name.c_str(), definition.c_str());
  547. }
  548. /**
  549. * @param name unique name for the new prepared statement.
  550. * @param definition SQL statement to prepare.
  551. */
  552. void prepare(char const name[], char const definition[]) &;
  553. /// Define a nameless prepared statement.
  554. /**
  555. * This can be useful if you merely want to pass large binary parameters to a
  556. * statement without otherwise wishing to prepare it. If you use this
  557. * feature, always keep the definition and the use close together to avoid
  558. * the nameless statement being redefined unexpectedly by code somewhere
  559. * else.
  560. */
  561. void prepare(char const definition[]) &;
  562. void prepare(zview definition) & { return prepare(definition.c_str()); }
  563. /// Drop prepared statement.
  564. void unprepare(std::string_view name);
  565. //@}
  566. // C++20: constexpr. Breaks ABI.
  567. /// Suffix unique number to name to make it unique within session context.
  568. /** Used internally to generate identifiers for SQL objects (such as cursors
  569. * and nested transactions) based on a given human-readable base name.
  570. */
  571. [[nodiscard]] std::string adorn_name(std::string_view);
  572. /**
  573. * @defgroup escaping-functions String-escaping functions
  574. */
  575. //@{
  576. /// Escape string for use as SQL string literal on this connection.
  577. /** @warning This accepts a length, and it does not require a terminating
  578. * zero byte. But if there is a zero byte, escaping stops there even if
  579. * it's not at the end of the string!
  580. */
  581. [[deprecated("Use std::string_view or pqxx:zview.")]] std::string
  582. esc(char const text[], std::size_t maxlen) const
  583. {
  584. return esc(std::string_view{text, maxlen});
  585. }
  586. /// Escape string for use as SQL string literal on this connection.
  587. [[nodiscard]] std::string esc(char const text[]) const
  588. {
  589. return esc(std::string_view{text});
  590. }
  591. #if defined(PQXX_HAVE_SPAN)
  592. /// Escape string for use as SQL string literal, into `buffer`.
  593. /** Use this variant when you want to re-use the same buffer across multiple
  594. * calls. If that's not the case, or convenience and simplicity are more
  595. * important, use the single-argument variant.
  596. *
  597. * For every byte in `text`, there must be at least 2 bytes of space in
  598. * `buffer`; plus there must be one byte of space for a trailing zero.
  599. * Throws @ref range_error if this space is not available.
  600. *
  601. * Returns a reference to the escaped string, which is actually stored in
  602. * `buffer`.
  603. */
  604. [[nodiscard]] std::string_view
  605. esc(std::string_view text, std::span<char> buffer)
  606. {
  607. auto const size{std::size(text)}, space{std::size(buffer)};
  608. auto const needed{2 * size + 1};
  609. if (space < needed)
  610. throw range_error{internal::concat(
  611. "Not enough room to escape string of ", size, " byte(s): need ",
  612. needed, " bytes of buffer space, but buffer size is ", space, ".")};
  613. auto const data{buffer.data()};
  614. return {data, esc_to_buf(text, data)};
  615. }
  616. #endif
  617. /// Escape string for use as SQL string literal on this connection.
  618. /** @warning This is meant for text strings only. It cannot contain bytes
  619. * whose value is zero ("nul bytes").
  620. */
  621. [[nodiscard]] std::string esc(std::string_view text) const;
  622. #if defined(PQXX_HAVE_CONCEPTS)
  623. /// Escape binary string for use as SQL string literal on this connection.
  624. /** This is identical to `esc_raw(data)`. */
  625. template<binary DATA> [[nodiscard]] std::string esc(DATA const &data) const
  626. {
  627. return esc_raw(data);
  628. }
  629. #endif
  630. #if defined(PQXX_HAVE_CONCEPTS) && defined(PQXX_HAVE_SPAN)
  631. /// Escape binary string for use as SQL string literal, into `buffer`.
  632. /** Use this variant when you want to re-use the same buffer across multiple
  633. * calls. If that's not the case, or convenience and simplicity are more
  634. * important, use the single-argument variant.
  635. *
  636. * For every byte in `data`, there must be at least two bytes of space in
  637. * `buffer`; plus there must be two bytes of space for a header and one for
  638. * a trailing zero. Throws @ref range_error if this space is not available.
  639. *
  640. * Returns a reference to the escaped string, which is actually stored in
  641. * `buffer`.
  642. */
  643. template<binary DATA>
  644. [[nodiscard]] zview esc(DATA const &data, std::span<char> buffer) const
  645. {
  646. auto const size{std::size(data)}, space{std::size(buffer)};
  647. auto const needed{internal::size_esc_bin(std::size(data))};
  648. if (space < needed)
  649. throw range_error{internal::concat(
  650. "Not enough room to escape binary string of ", size, " byte(s): need ",
  651. needed, " bytes of buffer space, but buffer size is ", space, ".")};
  652. std::basic_string_view<std::byte> view{std::data(data), std::size(data)};
  653. auto const out{std::data(buffer)};
  654. // Actually, in the modern format, we know beforehand exactly how many
  655. // bytes we're going to fill. Just leave out the trailing zero.
  656. internal::esc_bin(view, out);
  657. return zview{out, needed - 1};
  658. }
  659. #endif
  660. /// Escape binary string for use as SQL string literal on this connection.
  661. [[deprecated("Use std::byte for binary data.")]] std::string
  662. esc_raw(unsigned char const bin[], std::size_t len) const;
  663. /// Escape binary string for use as SQL string literal on this connection.
  664. /** You can also just use @ref esc with a binary string. */
  665. [[nodiscard]] std::string esc_raw(std::basic_string_view<std::byte>) const;
  666. #if defined(PQXX_HAVE_SPAN)
  667. /// Escape binary string for use as SQL string literal, into `buffer`.
  668. /** You can also just use @ref esc with a binary string. */
  669. [[nodiscard]] std::string
  670. esc_raw(std::basic_string_view<std::byte>, std::span<char> buffer) const;
  671. #endif
  672. #if defined(PQXX_HAVE_CONCEPTS)
  673. /// Escape binary string for use as SQL string literal on this connection.
  674. /** You can also just use @ref esc with a binary string. */
  675. template<binary DATA>
  676. [[nodiscard]] std::string esc_raw(DATA const &data) const
  677. {
  678. return esc_raw(
  679. std::basic_string_view<std::byte>{std::data(data), std::size(data)});
  680. }
  681. #endif
  682. #if defined(PQXX_HAVE_CONCEPTS) && defined(PQXX_HAVE_SPAN)
  683. /// Escape binary string for use as SQL string literal, into `buffer`.
  684. template<binary DATA>
  685. [[nodiscard]] zview esc_raw(DATA const &data, std::span<char> buffer) const
  686. {
  687. return this->esc(binary_cast(data), buffer);
  688. }
  689. #endif
  690. /// Unescape binary data, e.g. from a table field or notification payload.
  691. /** Takes a binary string as escaped by PostgreSQL, and returns a restored
  692. * copy of the original binary data.
  693. */
  694. [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
  695. unesc_raw(zview text) const
  696. {
  697. #include "pqxx/internal/ignore-deprecated-pre.hxx"
  698. return unesc_raw(text.c_str());
  699. #include "pqxx/internal/ignore-deprecated-post.hxx"
  700. }
  701. /// Unescape binary data, e.g. from a table field or notification payload.
  702. /** Takes a binary string as escaped by PostgreSQL, and returns a restored
  703. * copy of the original binary data.
  704. */
  705. [[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
  706. unesc_raw(char const text[]) const;
  707. // TODO: Make "into buffer" variant to eliminate a string allocation.
  708. /// Unescape binary data, e.g. from a table field or notification payload.
  709. /** Takes a binary string as escaped by PostgreSQL, and returns a restored
  710. * copy of the original binary data.
  711. *
  712. * (The data must be encoded in PostgreSQL's "hex" format. The legacy
  713. * "bytea" escape format, used prior to PostgreSQL 9.0, is no longer
  714. * supported.)
  715. */
  716. [[nodiscard]] std::basic_string<std::byte>
  717. unesc_bin(std::string_view text) const
  718. {
  719. std::basic_string<std::byte> buf;
  720. buf.resize(pqxx::internal::size_unesc_bin(std::size(text)));
  721. pqxx::internal::unesc_bin(text, buf.data());
  722. return buf;
  723. }
  724. /// Escape and quote a string of binary data.
  725. [[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
  726. quote_raw(unsigned char const bin[], std::size_t len) const;
  727. /// Escape and quote a string of binary data.
  728. std::string quote_raw(std::basic_string_view<std::byte>) const;
  729. #if defined(PQXX_HAVE_CONCEPTS)
  730. /// Escape and quote a string of binary data.
  731. /** You can also just use @ref quote with binary data. */
  732. template<binary DATA>
  733. [[nodiscard]] std::string quote_raw(DATA const &data) const
  734. {
  735. return quote_raw(
  736. std::basic_string_view<std::byte>{std::data(data), std::size(data)});
  737. }
  738. #endif
  739. // TODO: Make "into buffer" variant to eliminate a string allocation.
  740. /// Escape and quote an SQL identifier for use in a query.
  741. [[nodiscard]] std::string quote_name(std::string_view identifier) const;
  742. // TODO: Make "into buffer" variant to eliminate a string allocation.
  743. /// Escape and quote a table name.
  744. /** When passing just a table name, this is just another name for
  745. * @ref quote_name.
  746. */
  747. [[nodiscard]] std::string quote_table(std::string_view name) const;
  748. // TODO: Make "into buffer" variant to eliminate a string allocation.
  749. /// Escape and quote a table path.
  750. /** A table path consists of a table name, optionally prefixed by a schema
  751. * name; and if both are given, they are in turn optionally prefixed by a
  752. * database name.
  753. *
  754. * Each portion of the path (database name, schema name, table name) will be
  755. * quoted separately, and they will be joined together by dots. So for
  756. * example, `myschema.mytable` will become `"myschema"."mytable"`.
  757. */
  758. [[nodiscard]] std::string quote_table(table_path) const;
  759. // TODO: Make "into buffer" variant to eliminate a string allocation.
  760. /// Quote and comma-separate a series of column names.
  761. /** Use this to save a bit of work in cases where you repeatedly need to pass
  762. * the same list of column names, e.g. with @ref stream_to and @ref
  763. * stream_from. Some functions that need to quote the columns list
  764. * internally, will have a "raw" alternative which let you do the quoting
  765. * yourself. It's a bit of extra work, but it can in rare cases let you
  766. * eliminate some duplicate work in quoting them repeatedly.
  767. */
  768. template<PQXX_CHAR_STRINGS_ARG STRINGS>
  769. inline std::string quote_columns(STRINGS const &columns) const;
  770. // TODO: Make "into buffer" variant to eliminate a string allocation.
  771. /// Represent object as SQL string, including quoting & escaping.
  772. /**
  773. * Recognises nulls and represents them as SQL nulls. They get no quotes.
  774. */
  775. template<typename T>
  776. [[nodiscard]] inline std::string quote(T const &t) const;
  777. [[deprecated("Use std::byte for binary data.")]] std::string
  778. quote(binarystring const &) const;
  779. // TODO: Make "into buffer" variant to eliminate a string allocation.
  780. /// Escape and quote binary data for use as a BYTEA value in SQL statement.
  781. [[nodiscard]] std::string
  782. quote(std::basic_string_view<std::byte> bytes) const;
  783. // TODO: Make "into buffer" variant to eliminate a string allocation.
  784. /// Escape string for literal LIKE match.
  785. /** Use this when part of an SQL "LIKE" pattern should match only as a
  786. * literal string, not as a pattern, even if it contains "%" or "_"
  787. * characters that would normally act as wildcards.
  788. *
  789. * The string does not get string-escaped or quoted. You do that later.
  790. *
  791. * For instance, let's say you have a string `name` entered by the user,
  792. * and you're searching a `file` column for items that match `name`
  793. * followed by a dot and three letters. Even if `name` contains wildcard
  794. * characters "%" or "_", you only want those to match literally, so "_"
  795. * only matches "_" and "%" only matches a single "%".
  796. *
  797. * You do that by "like-escaping" `name`, appending the wildcard pattern
  798. * `".___"`, and finally, escaping and quoting the result for inclusion in
  799. * your query:
  800. *
  801. * ```cxx
  802. * tx.exec(
  803. * "SELECT file FROM item WHERE file LIKE " +
  804. * tx.quote(tx.esc_like(name) + ".___"));
  805. * ```
  806. *
  807. * The SQL "LIKE" operator also lets you choose your own escape character.
  808. * This is supported, but must be a single-byte character.
  809. */
  810. [[nodiscard]] std::string
  811. esc_like(std::string_view text, char escape_char = '\\') const;
  812. //@}
  813. /// Attempt to cancel the ongoing query, if any.
  814. /** You can use this from another thread, and/or while a query is executing
  815. * in a pipeline, but it's up to you to ensure that you're not canceling the
  816. * wrong query. This may involve locking.
  817. */
  818. void cancel_query();
  819. #if defined(_WIN32) || __has_include(<fcntl.h>)
  820. /// Set socket to blocking (true) or nonblocking (false).
  821. /** @warning Do not use this unless you _really_ know what you're doing.
  822. * @warning This function is available on most systems, but not necessarily
  823. * all.
  824. */
  825. void set_blocking(bool block) &;
  826. #endif // defined(_WIN32) || __has_include(<fcntl.h>)
  827. /// Set session verbosity.
  828. /** Set the verbosity of error messages to "terse", "normal" (the default),
  829. * or "verbose."
  830. *
  831. * If "terse", returned messages include severity, primary text, and
  832. * position only; this will normally fit on a single line. "normal" produces
  833. * messages that include the above plus any detail, hint, or context fields
  834. * (these might span multiple lines). "verbose" includes all available
  835. * fields.
  836. */
  837. void set_verbosity(error_verbosity verbosity) &noexcept;
  838. /// Return pointers to the active errorhandlers.
  839. /** The entries are ordered from oldest to newest handler.
  840. *
  841. * You may use this to find errorhandlers that your application wants to
  842. * delete when destroying the connection. Be aware, however, that libpqxx
  843. * may also add errorhandlers of its own, and those will be included in the
  844. * list. If this is a problem for you, derive your errorhandlers from a
  845. * custom base class derived from pqxx::errorhandler. Then use dynamic_cast
  846. * to find which of the error handlers are yours.
  847. *
  848. * The pointers point to the real errorhandlers. The container it returns
  849. * however is a copy of the one internal to the connection, not a reference.
  850. */
  851. [[nodiscard]] std::vector<errorhandler *> get_errorhandlers() const;
  852. /// Return a connection string encapsulating this connection's options.
  853. /** The connection must be currently open for this to work.
  854. *
  855. * Returns a reconstruction of this connection's connection string. It may
  856. * not exactly match the connection string you passed in when creating this
  857. * connection.
  858. */
  859. [[nodiscard]] std::string connection_string() const;
  860. /// Explicitly close the connection.
  861. /** The destructor will do this for you automatically. Still, there is a
  862. * reason to `close()` objects explicitly where possible: if an error should
  863. * occur while closing, `close()` can throw an exception. A destructor
  864. * cannot.
  865. *
  866. * Closing a connection is idempotent. Closing a connection that's already
  867. * closed does nothing.
  868. */
  869. void close();
  870. /// Seize control of a raw libpq connection.
  871. /** @warning Do not do this. Please. It's for very rare, very specific
  872. * use-cases. The mechanism may change (or break) in unexpected ways in
  873. * future versions.
  874. *
  875. * @param raw_conn a raw libpq `PQconn` pointer.
  876. */
  877. static connection seize_raw_connection(internal::pq::PGconn *raw_conn)
  878. {
  879. return connection{raw_conn};
  880. }
  881. /// Release the raw connection without closing it.
  882. /** @warning Do not do this. It's for very rare, very specific use-cases.
  883. * The mechanism may change (or break) in unexpected ways in future versions.
  884. *
  885. * The `connection` object becomes unusable after this.
  886. */
  887. internal::pq::PGconn *release_raw_connection() &&
  888. {
  889. return std::exchange(m_conn, nullptr);
  890. }
  891. private:
  892. friend class connecting;
  893. enum connect_mode
  894. {
  895. connect_nonblocking
  896. };
  897. connection(connect_mode, zview connection_string);
  898. /// For use by @ref seize_raw_connection.
  899. explicit connection(internal::pq::PGconn *raw_conn) : m_conn{raw_conn} {}
  900. /// Poll for ongoing connection, try to progress towards completion.
  901. /** Returns a pair of "now please wait to read data from socket" and "now
  902. * please wait to write data to socket." Both will be false when done.
  903. *
  904. * Throws an exception if polling indicates that the connection has failed.
  905. */
  906. std::pair<bool, bool> poll_connect();
  907. // Initialise based on connection string.
  908. void init(char const options[]);
  909. // Initialise based on parameter names and values.
  910. void init(char const *params[], char const *values[]);
  911. void complete_init();
  912. result make_result(
  913. internal::pq::PGresult *pgr, std::shared_ptr<std::string> const &query,
  914. std::string_view desc = ""sv);
  915. void PQXX_PRIVATE set_up_state();
  916. int PQXX_PRIVATE PQXX_PURE status() const noexcept;
  917. /// Escape a string, into a buffer allocated by the caller.
  918. /** The buffer must have room for at least `2*std::size(text) + 1` bytes.
  919. *
  920. * Returns the number of bytes written, including the trailing zero.
  921. */
  922. std::size_t esc_to_buf(std::string_view text, char *buf) const;
  923. friend class internal::gate::const_connection_largeobject;
  924. char const *PQXX_PURE err_msg() const noexcept;
  925. void PQXX_PRIVATE process_notice_raw(char const msg[]) noexcept;
  926. result exec_prepared(std::string_view statement, internal::c_params const &);
  927. /// Throw @ref usage_error if this connection is not in a movable state.
  928. void check_movable() const;
  929. /// Throw @ref usage_error if not in a state where it can be move-assigned.
  930. void check_overwritable() const;
  931. friend class internal::gate::connection_errorhandler;
  932. void PQXX_PRIVATE register_errorhandler(errorhandler *);
  933. void PQXX_PRIVATE unregister_errorhandler(errorhandler *) noexcept;
  934. friend class internal::gate::connection_transaction;
  935. result exec(std::string_view, std::string_view = ""sv);
  936. result
  937. PQXX_PRIVATE exec(std::shared_ptr<std::string>, std::string_view = ""sv);
  938. void PQXX_PRIVATE register_transaction(transaction_base *);
  939. void PQXX_PRIVATE unregister_transaction(transaction_base *) noexcept;
  940. friend class internal::gate::connection_stream_from;
  941. std::pair<std::unique_ptr<char, std::function<void(char *)>>, std::size_t>
  942. PQXX_PRIVATE read_copy_line();
  943. friend class internal::gate::connection_stream_to;
  944. void PQXX_PRIVATE write_copy_line(std::string_view);
  945. void PQXX_PRIVATE end_copy_write();
  946. friend class internal::gate::connection_largeobject;
  947. internal::pq::PGconn *raw_connection() const { return m_conn; }
  948. friend class internal::gate::connection_notification_receiver;
  949. void add_receiver(notification_receiver *);
  950. void remove_receiver(notification_receiver *) noexcept;
  951. friend class internal::gate::connection_pipeline;
  952. void PQXX_PRIVATE start_exec(char const query[]);
  953. bool PQXX_PRIVATE consume_input() noexcept;
  954. bool PQXX_PRIVATE is_busy() const noexcept;
  955. internal::pq::PGresult *get_result();
  956. friend class internal::gate::connection_dbtransaction;
  957. friend class internal::gate::connection_sql_cursor;
  958. result exec_params(std::string_view query, internal::c_params const &args);
  959. /// Connection handle.
  960. internal::pq::PGconn *m_conn = nullptr;
  961. /// Active transaction on connection, if any.
  962. /** We don't use this for anything, except to check for open transactions
  963. * when we close the connection or start a new transaction.
  964. *
  965. * We also don't allow move construction or move assignment while there's a
  966. * transaction, since moving the connection in that case would leave one or
  967. * more pointers back from the transaction to the connection dangling.
  968. */
  969. transaction_base const *m_trans = nullptr;
  970. std::list<errorhandler *> m_errorhandlers;
  971. using receiver_list =
  972. std::multimap<std::string, pqxx::notification_receiver *>;
  973. /// Notification receivers.
  974. receiver_list m_receivers;
  975. /// Unique number to use as suffix for identifiers (see adorn_name()).
  976. int m_unique_id = 0;
  977. };
  978. /// @deprecated Old base class for connection. They are now the same class.
  979. using connection_base = connection;
  980. /// An ongoing, non-blocking stepping stone to a connection.
  981. /** Use this when you want to create a connection to the database, but without
  982. * blocking your whole thread. It is only available on systems that have
  983. * the `<fcntl.h>` header, and Windows.
  984. *
  985. * Connecting in this way is probably not "faster" (it's more complicated and
  986. * has some extra overhead), but in some situations you can use it to make your
  987. * application as a whole faster. It all depends on having other useful work
  988. * to do in the same thread, and being able to wait on a socket. If you have
  989. * other I/O going on at the same time, your event loop can wait for both the
  990. * libpqxx socket and your own sockets, and wake up whenever any of them is
  991. * ready to do work.
  992. *
  993. * Connecting in this way is not properly "asynchronous;" it's merely
  994. * "nonblocking." This means it's not a super-high-performance mechanism like
  995. * you might get with e.g. `io_uring`. In particular, if we need to look up
  996. * the database hostname in DNS, that will happen synchronously.
  997. *
  998. * To use this, create the `connecting` object, passing a connection string.
  999. * Then loop: If @ref wait_to_read returns true, wait for the socket to have
  1000. * incoming data on it. If @ref wait_to_write returns true, wait for the
  1001. * socket to be ready for writing. Then call @ref process to process any
  1002. * incoming or outgoing data. Do all of this until @ref done returns true (or
  1003. * there is an exception). Finally, call @ref produce to get the completed
  1004. * connection.
  1005. *
  1006. * For example:
  1007. *
  1008. * ```cxx
  1009. * pqxx::connecting cg{};
  1010. *
  1011. * // Loop until we're done connecting.
  1012. * while (!cg.done())
  1013. * {
  1014. * wait_for_fd(cg.sock(), cg.wait_to_read(), cg.wait_to_write());
  1015. * cg.process();
  1016. * }
  1017. *
  1018. * pqxx::connection conn = std::move(cg).produce();
  1019. *
  1020. * // At this point, conn is a working connection. You can no longer use
  1021. * // cg at all.
  1022. * ```
  1023. */
  1024. class PQXX_LIBEXPORT connecting
  1025. {
  1026. public:
  1027. /// Start connecting.
  1028. connecting(zview connection_string = ""_zv);
  1029. connecting(connecting const &) = delete;
  1030. connecting(connecting &&) = default;
  1031. connecting &operator=(connecting const &) = delete;
  1032. connecting &operator=(connecting &&) = default;
  1033. /// Get the socket. The socket may change during the connection process.
  1034. [[nodiscard]] int sock() const &noexcept { return m_conn.sock(); }
  1035. /// Should we currently wait to be able to _read_ from the socket?
  1036. [[nodiscard]] constexpr bool wait_to_read() const &noexcept
  1037. {
  1038. return m_reading;
  1039. }
  1040. /// Should we currently wait to be able to _write_ to the socket?
  1041. [[nodiscard]] constexpr bool wait_to_write() const &noexcept
  1042. {
  1043. return m_writing;
  1044. }
  1045. /// Progress towards completion (but don't block).
  1046. void process() &;
  1047. /// Is our connection finished?
  1048. [[nodiscard]] constexpr bool done() const &noexcept
  1049. {
  1050. return not m_reading and not m_writing;
  1051. }
  1052. /// Produce the completed connection object.
  1053. /** Use this only once, after @ref done returned `true`. Once you have
  1054. * called this, the `connecting` instance has no more use or meaning. You
  1055. * can't call any of its member functions afterwards.
  1056. *
  1057. * This member function is rvalue-qualified, meaning that you can only call
  1058. * it on an rvalue instance of the class. If what you have is not an rvalue,
  1059. * turn it into one by wrapping it in `std::move()`.
  1060. */
  1061. [[nodiscard]] connection produce() &&;
  1062. private:
  1063. connection m_conn;
  1064. bool m_reading{false};
  1065. bool m_writing{true};
  1066. };
  1067. template<typename T> inline std::string connection::quote(T const &t) const
  1068. {
  1069. if constexpr (nullness<T>::always_null)
  1070. {
  1071. return "NULL";
  1072. }
  1073. else
  1074. {
  1075. if (is_null(t))
  1076. return "NULL";
  1077. auto const text{to_string(t)};
  1078. // Okay, there's an easy way to do this and there's a hard way. The easy
  1079. // way was "quote, esc(to_string(t)), quote". I'm going with the hard way
  1080. // because it's going to save some string manipulation that will probably
  1081. // incur some unnecessary memory allocations and deallocations.
  1082. std::string buf{'\''};
  1083. buf.resize(2 + 2 * std::size(text) + 1);
  1084. auto const content_bytes{esc_to_buf(text, buf.data() + 1)};
  1085. auto const closing_quote{1 + content_bytes};
  1086. buf[closing_quote] = '\'';
  1087. auto const end{closing_quote + 1};
  1088. buf.resize(end);
  1089. return buf;
  1090. }
  1091. }
  1092. template<PQXX_CHAR_STRINGS_ARG STRINGS>
  1093. inline std::string connection::quote_columns(STRINGS const &columns) const
  1094. {
  1095. return separated_list(
  1096. ","sv, std::cbegin(columns), std::cend(columns),
  1097. [this](auto col) { return this->quote_name(*col); });
  1098. }
  1099. #if defined(PQXX_HAVE_CONCEPTS)
  1100. template<internal::ZKey_ZValues MAPPING>
  1101. inline connection::connection(MAPPING const &params)
  1102. {
  1103. check_version();
  1104. std::vector<char const *> keys, values;
  1105. if constexpr (std::ranges::sized_range<MAPPING>)
  1106. {
  1107. auto const size{std::ranges::size(params) + 1};
  1108. keys.reserve(size);
  1109. values.reserve(size);
  1110. }
  1111. for (auto const &[key, value] : params)
  1112. {
  1113. keys.push_back(internal::as_c_string(key));
  1114. values.push_back(internal::as_c_string(value));
  1115. }
  1116. keys.push_back(nullptr);
  1117. values.push_back(nullptr);
  1118. init(std::data(keys), std::data(values));
  1119. }
  1120. #endif // PQXX_HAVE_CONCEPTS
  1121. } // namespace pqxx
  1122. #endif