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-2020, 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 #include "pqxx/compiler-public.hxx"
17 #include "pqxx/internal/compiler-internal-pre.hxx"
18 
19 #include <cstddef>
20 #include <ctime>
21 #include <functional>
22 #include <list>
23 #include <map>
24 #include <memory>
25 #include <string_view>
26 #include <tuple>
27 
28 #if __has_include(<ranges>)
29 #  include <ranges>
30 #endif
31 
32 #include "pqxx/errorhandler.hxx"
33 #include "pqxx/except.hxx"
34 #include "pqxx/prepared_statement.hxx"
35 #include "pqxx/strconv.hxx"
36 #include "pqxx/util.hxx"
37 #include "pqxx/zview.hxx"
38 
39 
40 /**
41  * @addtogroup connection
42  *
43  * Use of the libpqxx library starts here.
44  *
45  * Everything that can be done with a database through libpqxx must go through
46  * a @c connection object.  It connects to a database when you create it, and
47  * it terminates that communication during destruction.
48  *
49  * Many things come together in this class.  Handling of error and warning
50  * messages, for example, is defined by @c errorhandler objects in the context
51  * of a connection.  Prepared statements are also defined here.
52  *
53  * When you connect to a database, you pass a connection string containing any
54  * parameters and options, such as the server address and the database name.
55  *
56  * These are identical to the ones in libpq, the C language binding upon which
57  * libpqxx itself is built:
58  *
59  * https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
60  *
61  * There are also environment variables you can set to provide defaults, again
62  * as defined by libpq:
63  *
64  * https://www.postgresql.org/docs/current/libpq-envars.html
65  */
66 
67 namespace pqxx::internal
68 {
69 class sql_cursor;
70 
71 #if defined(PQXX_HAVE_CONCEPTS)
72 /// Concept: T is a range of pairs of zero-terminated strings.
73 template<typename T>
74 concept ZKey_ZValues = std::ranges::input_range<T> and requires()
75 {
76   {std::tuple_size<typename std::ranges::iterator_t<T>::value_type>::value};
77 }
78 and std::tuple_size_v<typename std::ranges::iterator_t<T>::value_type> == 2 and
79   requires(T t)
80 {
81   {
82     std::get<0>(*std::cbegin(t))
83   }
84   ->ZString;
85   {
86     std::get<1>(*std::cbegin(t))
87   }
88   ->ZString;
89 };
90 #endif // PQXX_HAVE_CONCEPTS
91 } // namespace pqxx::internal
92 
93 
94 namespace pqxx::internal::gate
95 {
96 class connection_dbtransaction;
97 class connection_errorhandler;
98 class connection_largeobject;
99 class connection_notification_receiver;
100 class connection_pipeline;
101 class connection_sql_cursor;
102 class connection_stream_from;
103 class connection_stream_to;
104 class connection_transaction;
105 class const_connection_largeobject;
106 } // namespace pqxx::internal::gate
107 
108 
109 namespace pqxx
110 {
111 /// Encrypt a password.  @deprecated Use connection::encrypt_password instead.
112 [[nodiscard]] std::string PQXX_LIBEXPORT
113 encrypt_password(char const user[], char const password[]);
114 
115 /// Encrypt password.  @deprecated Use connection::encrypt_password instead.
116 [[nodiscard]] inline std::string
encrypt_password(std::string const & user,std::string const & password)117 encrypt_password(std::string const &user, std::string const &password)
118 {
119   return encrypt_password(user.c_str(), password.c_str());
120 }
121 
122 
123 /// Error verbosity levels.
124 enum class error_verbosity : int
125 {
126   // These values must match those in libpq's PGVerbosity enum.
127   terse = 0,
128   normal = 1,
129   verbose = 2
130 };
131 
132 
133 /// Connection to a database.
134 /** This is the first class to look at when you wish to work with a database
135  * through libpqxx.  The connection opens during construction, and closes upon
136  * destruction.
137  *
138  * When creating a connection, you can pass a connection URI or a postgres
139  * connection string, to specify the database server's address, a login
140  * username, and so on.  If none is given, the connection will try to obtain
141  * them from certain environment variables.  If those are not set either, the
142  * default is to try and connect to the local system's port 5432.
143  *
144  * Find more about connection strings here:
145  *
146  * https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
147  *
148  * The variables are documented here:
149  *
150  * https://www.postgresql.org/docs/current/libpq-envars.html
151  *
152  * To query or manipulate the database once connected, use one of the
153  * transaction classes (see pqxx/transaction_base.hxx) and perhaps also the
154  * transactor framework (see pqxx/transactor.hxx).
155  *
156  * When a connection breaks, you will typically get a broken_connection
157  * exception.  This can happen at almost any point.
158  *
159  * @warning On Unix-like systems, including GNU and BSD systems, your program
160  * may receive the SIGPIPE signal when the connection to the backend breaks. By
161  * default this signal will abort your program.  Use "signal(SIGPIPE, SIG_IGN)"
162  * if you want your program to continue running after a connection fails.
163  */
164 class PQXX_LIBEXPORT connection
165 {
166 public:
connection()167   connection() : connection{""} {}
168 
connection(std::string const & options)169   explicit connection(std::string const &options) : connection{options.c_str()}
170   {
171     // (Delegates to other constructor which calls check_version for us.)
172   }
173 
connection(char const options[])174   explicit connection(char const options[])
175   {
176     check_version();
177     init(options);
178   }
179 
connection(zview options)180   explicit connection(zview options) : connection{options.c_str()}
181   {
182     // (Delegates to other constructor which calls check_version for us.)
183   }
184 
185   /// Move constructor.
186   /** Moving a connection is not allowed if it has an open transaction, or has
187    * error handlers or notification receivers registered on it.  In those
188    * situations, other objects may hold references to the old object which
189    * would become invalid and might produce hard-to-diagnose bugs.
190    */
191   connection(connection &&rhs);
192 
193 #if defined(PQXX_HAVE_CONCEPTS)
194   /// Connect, passing options as a range of key/value pairs.
195   /** @warning Experimental.  Requires C++20 "concepts" support.  Define
196    * @c PQXX_HAVE_CONCEPTS to enable it.
197    *
198    * There's no need to escape the parameter values.
199    *
200    * See the PostgreSQL libpq documentation for the full list of possible
201    * options:
202    *
203    * https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
204    *
205    * The options can be anything that can be iterated as a series of pairs of
206    * zero-terminated strings: @c std::pair<std::string, std::string>`, or
207    * @c std::tuple<pqxx::zview, char const *>, or
208    * @c std::map<std::string, pqxx::zview>, and so on.
209    */
210   template<internal::ZKey_ZValues MAPPING>
211   inline connection(MAPPING const &params);
212 #endif // PQXX_HAVE_CONCEPTS
213 
~connection()214   ~connection()
215   {
216     try
217     {
218       close();
219     }
220     catch (std::exception const &)
221     {}
222   }
223 
224   /// Move assignment.
225   /** Neither connection can have an open transaction, registered error
226    * handlers, or registered notification receivers.
227    */
228   connection &operator=(connection &&rhs);
229 
230   connection(connection const &) = delete;
231   connection &operator=(connection const &) = delete;
232 
233   /// Is this connection open at the moment?
234   /** @warning This function is @b not needed in most code.  Resist the
235    * temptation to check it after opening a connection.  Instead, just use the
236    * connection and rely on getting a broken_connection exception if it failed.
237    */
238   [[nodiscard]] bool PQXX_PURE is_open() const noexcept;
239 
240   /// Invoke notice processor function.  The message should end in newline.
241   void process_notice(char const[]) noexcept;
242   /// Invoke notice processor function.  Newline at end is recommended.
process_notice(std::string const & msg)243   void process_notice(std::string const &msg) noexcept
244   {
245     process_notice(zview{msg});
246   }
247   /// Invoke notice processor function.  Newline at end is recommended.
248   /** The zview variant, with a message ending in newline, is the most
249    * efficient way to call process_notice.
250    */
251   void process_notice(zview) noexcept;
252 
253   /// Enable tracing to a given output stream, or nullptr to disable.
254   void trace(std::FILE *) noexcept;
255 
256   /**
257    * @name Connection properties
258    *
259    * These are probably not of great interest, since most are derived from
260    * information supplied by the client program itself, but they are included
261    * for completeness.
262    *
263    * The connection needs to be currently active for these to work.
264    */
265   //@{
266   /// Name of database we're connected to, if any.
267   [[nodiscard]] char const *dbname() const;
268 
269   /// Database user ID we're connected under, if any.
270   [[nodiscard]] char const *username() const;
271 
272   /// Address of server, or nullptr if none specified (i.e. default or local)
273   [[nodiscard]] char const *hostname() const;
274 
275   /// Server port number we're connected to.
276   [[nodiscard]] char const *port() const;
277 
278   /// Process ID for backend process, or 0 if inactive.
279   [[nodiscard]] int PQXX_PURE backendpid() const noexcept;
280 
281   /// Socket currently used for connection, or -1 for none.  Use with care!
282   /** Query the current socket number.  This is intended for event loops based
283    * on functions such as select() or poll(), where multiple file descriptors
284    * are watched.
285    *
286    * Please try to stay away from this function.  It is really only meant for
287    * event loops that need to wait on more than one file descriptor.  If all
288    * you need is to block until a notification arrives, for instance, use
289    * await_notification().  If you want to issue queries and retrieve results
290    * in nonblocking fashion, check out the pipeline class.
291    *
292    * @warning Don't store this value anywhere, and always be prepared for the
293    * possibility that, at any given time, there may not be a socket!  The
294    * socket may change or even go away during any invocation of libpqxx code on
295    * the connection.
296    */
297   [[nodiscard]] int PQXX_PURE sock() const noexcept;
298 
299   /// What version of the PostgreSQL protocol is this connection using?
300   /** The answer can be 0 (when there is no connection); 3 for protocol 3.0; or
301    * possibly higher values as newer protocol versions come into use.
302    */
303   [[nodiscard]] int PQXX_PURE protocol_version() const noexcept;
304 
305   /// What version of the PostgreSQL server are we connected to?
306   /** The result is a bit complicated: each of the major, medium, and minor
307    * release numbers is written as a two-digit decimal number, and the three
308    * are then concatenated.  Thus server version 9.4.2 will be returned as the
309    * decimal number 90402.  If there is no connection to the server, this
310    * returns zero.
311    *
312    * @warning When writing version numbers in your code, don't add zero at the
313    * beginning!  Numbers beginning with zero are interpreted as octal (base-8)
314    * in C++.  Thus, 070402 is not the same as 70402, and 080000 is not a number
315    * at all because there is no digit "8" in octal notation.  Use strictly
316    * decimal notation when it comes to these version numbers.
317    */
318   [[nodiscard]] int PQXX_PURE server_version() const noexcept;
319   //@}
320 
321   /// @name Text encoding
322   /**
323    * Each connection is governed by a "client encoding," which dictates how
324    * strings and other text is represented in bytes.  The database server will
325    * send text data to you in this encoding, and you should use it for the
326    * queries and data which you send to the server.
327    *
328    * Search the PostgreSQL documentation for "character set encodings" to find
329    * out more about the available encodings, how to extend them, and how to use
330    * them.  Not all server-side encodings are compatible with all client-side
331    * encodings or vice versa.
332    *
333    * Encoding names are case-insensitive, so e.g. "UTF8" is equivalent to
334    * "utf8".
335    *
336    * You can change the client encoding, but this may not work when the
337    * connection is in a special state, such as when streaming a table.  It's
338    * not clear what happens if you change the encoding during a transaction,
339    * and then abort the transaction.
340    */
341   //@{
342   /// Get client-side character encoding, by name.
343   [[nodiscard]] std::string get_client_encoding() const;
344 
345   /// Set client-side character encoding, by name.
346   /**
347    * @param encoding Name of the character set encoding to use.
348    */
set_client_encoding(std::string const & encoding)349   void set_client_encoding(std::string const &encoding)
350   {
351     set_client_encoding(encoding.c_str());
352   }
353 
354   /// Set client-side character encoding, by name.
355   /**
356    * @param encoding Name of the character set encoding to use.
357    */
358   void set_client_encoding(char const encoding[]);
359 
360   /// Get the connection's encoding, as a PostgreSQL-defined code.
361   [[nodiscard]] int PQXX_PRIVATE encoding_id() const;
362 
363   //@}
364 
365   /// Set session variable, using SQL's @c SET command.
366   /** Set a session variable for this connection.  See the PostgreSQL
367    * documentation for a list of variables that can be set and their
368    * permissible values.
369    *
370    * If a transaction is currently in progress, aborting that transaction will
371    * normally discard the newly set value.  That is not true for nontransaction
372    * however, since it does not start a real backend transaction.
373    *
374    * @warning This executes an SQL query, so do not get or set variables while
375    * a table stream or pipeline is active on the same connection.
376    *
377    * @param var Variable to set.
378    * @param value New value for Var: an identifier, a quoted string, or a
379    * number.
380    */
381   void set_variable(std::string_view var, std::string_view value);
382 
383   /// Read session variable, using SQL's @c SHOW command.
384   /** @warning This executes an SQL query, so do not get or set variables while
385    * a table stream or pipeline is active on the same connection.
386    */
387   std::string get_variable(std::string_view);
388   //@}
389 
390 
391   /**
392    * @name Notifications and Receivers
393    */
394   //@{
395   /// Check for pending notifications and take appropriate action.
396   /**
397    * All notifications found pending at call time are processed by finding
398    * any matching receivers and invoking those.  If no receivers matched the
399    * notification string, none are invoked but the notification is considered
400    * processed.
401    *
402    * Exceptions thrown by client-registered receivers are reported using the
403    * connection's errorhandlers, but the exceptions themselves are not passed
404    * on outside this function.
405    *
406    * @return Number of notifications processed.
407    */
408   int get_notifs();
409 
410 
411   /// Wait for a notification to come in.
412   /** The wait may also be terminated by other events, such as the connection
413    * to the backend failing.
414    *
415    * If a notification comes in, the call will process it.  It will also
416    * process any notifications that may have been pending.
417    *
418    * @return Number of notifications processed.
419    */
420   int await_notification();
421 
422   /// Wait for a notification to come in, or for given timeout to pass.
423   /** The wait may also be terminated by other events, such as the connection
424    * to the backend failing.
425    *
426    * If a notification comes in, the call will process it.  It will also
427    * process any notifications that may have been pending.
428    *
429    * @return Number of notifications processed
430    */
431   int await_notification(std::time_t seconds, long microseconds);
432   //@}
433 
434   /// Encrypt a password for a given user.
435   /** Use this when setting a new password for the user if password encryption
436    * is enabled.  Inputs are the SQL name for the user for whom you with to
437    * encrypt a password; the plaintext password; and the hash algorithm.
438    *
439    * The algorithm must be one of "md5", "scram-sha-256" (introduced in
440    * PostgreSQL 10), or @c nullptr.  If the pointer is null, this will query
441    * the @c password_encryption setting from the server, and use the default
442    * algorithm as defined there.
443    *
444    * @return encrypted version of the password, suitable for encrypted
445    * PostgreSQL authentication.
446    *
447    * Thus the password for a user can be changed with:
448    * @code
449    * void setpw(transaction_base &t, string const &user, string const &pw)
450    * {
451    *   t.exec0("ALTER USER " + user + " "
452    *   	"PASSWORD '" + t.conn().encrypt_password(user,pw) + "'");
453    * }
454    * @endcode
455    *
456    * When building this against a libpq older than version 10, this will use
457    * an older function which only supports md5.  In that case, requesting a
458    * different algorithm than md5 will result in a @c feature_not_supported
459    * exception.
460    */
461   [[nodiscard]] std::string encrypt_password(
462     char const user[], char const password[], char const *algorithm = nullptr);
463   [[nodiscard]] std::string
encrypt_password(zview user,zview password,zview algorithm)464   encrypt_password(zview user, zview password, zview algorithm)
465   {
466     return encrypt_password(user.c_str(), password.c_str(), algorithm.c_str());
467   }
468 
469   /**
470    * @name Prepared statements
471    *
472    * PostgreSQL supports prepared SQL statements, i.e. statements that can be
473    * registered under a client-provided name, optimized once by the backend,
474    * and executed any number of times under the given name.
475    *
476    * Prepared statement definitions are not sensitive to transaction
477    * boundaries. A statement defined inside a transaction will remain defined
478    * outside that transaction, even if the transaction itself is subsequently
479    * aborted.  Once a statement has been prepared, it will only go away if you
480    * close the connection or explicitly "unprepare" the statement.
481    *
482    * Use the @c pqxx::transaction_base::exec_prepared functions to execute a
483    * prepared statement.  See \ref prepared for a full discussion.
484    *
485    * @warning Using prepared statements can save time, but if your statement
486    * takes parameters, it may also make your application significantly slower!
487    * The reason is that the server works out a plan for executing the query
488    * when you prepare it.  At that time, the values for the parameters are of
489    * course not yet known.  If you execute a query without preparing it, then
490    * the server works out the plan on the spot, with knowledge of the parameter
491    * values.  It can use knowlege about these values for optimisation, and the
492    * prepared version does not have this knowledge.
493    *
494    * @{
495    */
496 
497   /// Define a prepared statement.
498   /**
499    * The statement's definition can refer to a parameter using the parameter's
500    * positional number n in the definition.  For example, the first parameter
501    * can be used as a variable "$1", the second as "$2" and so on.
502    *
503    * Here's an example of how to use prepared statements.
504    *
505    * @code
506    * using namespace pqxx;
507    * void foo(connection &c)
508    * {
509    *   c.prepare("findtable", "select * from pg_tables where name=$1");
510    *   work tx{c};
511    *   result r = tx.exec_prepared("findtable", "mytable");
512    *   if (std::empty(r)) throw runtime_error{"mytable not found!"};
513    * }
514    * @endcode
515    *
516    * @param name unique name for the new prepared statement.
517    * @param definition SQL statement to prepare.
518    */
519   void prepare(char const name[], char const definition[]);
520 
prepare(std::string const & name,std::string const & definition)521   void prepare(std::string const &name, std::string const &definition)
522   {
523     prepare(name.c_str(), definition.c_str());
524   }
525 
prepare(zview name,zview definition)526   void prepare(zview name, zview definition)
527   {
528     prepare(name.c_str(), definition.c_str());
529   }
530 
531   /// Define a nameless prepared statement.
532   /**
533    * This can be useful if you merely want to pass large binary parameters to a
534    * statement without otherwise wishing to prepare it.  If you use this
535    * feature, always keep the definition and the use close together to avoid
536    * the nameless statement being redefined unexpectedly by code somewhere
537    * else.
538    */
539   void prepare(char const definition[]);
prepare(zview definition)540   void prepare(zview definition) { return prepare(definition.c_str()); }
541 
542   /// Drop prepared statement.
543   void unprepare(std::string_view name);
544 
545   /**
546    * @}
547    */
548 
549   /// Suffix unique number to name to make it unique within session context.
550   /** Used internally to generate identifiers for SQL objects (such as cursors
551    * and nested transactions) based on a given human-readable base name.
552    */
553   [[nodiscard]] std::string adorn_name(std::string_view);
554 
555   /**
556    * @defgroup escaping-functions String-escaping functions
557    */
558   //@{
559 
560   /// Escape string for use as SQL string literal on this connection.
561   /** @warning This accepts a length, and it does not require a terminating
562    * zero byte.  But if there is a zero byte, escaping stops there even if
563    * it's not at the end of the string!
564    */
esc(char const text[],std::size_t maxlen) const565   [[nodiscard]] std::string esc(char const text[], std::size_t maxlen) const
566   {
567     return esc(std::string_view(text, maxlen));
568   }
569 
570   /// Escape string for use as SQL string literal on this connection.
esc(char const text[]) const571   [[nodiscard]] std::string esc(char const text[]) const
572   {
573     return esc(std::string_view(text));
574   }
575 
576   /// Escape string for use as SQL string literal on this connection.
577   /** @warning If the string contains a zero byte, escaping stops there even
578    * if it's not at the end of the string!
579    */
580   [[nodiscard]] std::string esc(std::string_view text) const;
581 
582   /// Escape binary string for use as SQL string literal on this connection.
583   /** @deprecated Use @c std::basic_string_view<std::byte> instead.
584    */
585   [[nodiscard]] std::string
586   esc_raw(unsigned char const bin[], std::size_t len) const;
587 
588   /// Escape binary string for use as SQL string literal on this connection.
589   [[nodiscard]] std::string esc_raw(std::basic_string_view<std::byte>) const;
590 
591   /// Unescape binary data, e.g. from a table field or notification payload.
592   /** Takes a binary string as escaped by PostgreSQL, and returns a restored
593    * copy of the original binary data.
594    */
unesc_raw(std::string const & text) const595   [[nodiscard]] std::string unesc_raw(std::string const &text) const
596   {
597     return unesc_raw(text.c_str());
598   }
599 
600   /// Unescape binary data, e.g. from a table field or notification payload.
601   /** Takes a binary string as escaped by PostgreSQL, and returns a restored
602    * copy of the original binary data.
603    */
unesc_raw(zview text) const604   [[nodiscard]] std::string unesc_raw(zview text) const
605   {
606     return unesc_raw(text.c_str());
607   }
608 
609   /// Unescape binary data, e.g. from a table field or notification payload.
610   /** Takes a binary string as escaped by PostgreSQL, and returns a restored
611    * copy of the original binary data.
612    */
613   [[nodiscard]] std::string unesc_raw(char const text[]) const;
614 
615   /// Escape and quote a string of binary data.
616   /** @deprecated Use @c std::basic_string_view<std::byte> instead.
617    */
618   [[nodiscard]] std::string
619   quote_raw(unsigned char const bin[], std::size_t len) const;
620 
621   /// Escape and quote a string of binary data.
622   [[nodiscard]] std::string quote_raw(std::basic_string_view<std::byte>) const;
623 
624   /// Escape and quote an SQL identifier for use in a query.
625   [[nodiscard]] std::string quote_name(std::string_view identifier) const;
626 
627   /// Represent object as SQL string, including quoting & escaping.
628   /**
629    * Nulls are recognized and represented as SQL nulls.  They get no quotes.
630    */
631   template<typename T>[[nodiscard]] inline std::string quote(T const &t) const;
632 
633   /// @deprecated Use @c basic_string or @c basic_string_view of @c std::byte.
634   [[nodiscard]] std::string quote(binarystring const &) const;
635 
636   [[nodiscard]] std::string
637   quote(std::basic_string_view<std::byte> bytes) const;
638 
639   /// Escape string for literal LIKE match.
640   /** Use this when part of an SQL "LIKE" pattern should match only as a
641    * literal string, not as a pattern, even if it contains "%" or "_"
642    * characters that would normally act as wildcards.
643    *
644    * The string does not get string-escaped or quoted.  You do that later.
645    *
646    * For instance, let's say you have a string @c name entered by the user,
647    * and you're searching a @c file column for items that match @c name
648    * followed by a dot and three letters.  Even if @c name contains wildcard
649    * characters "%" or "_", you only want those to match literally, so "_"
650    * only matches "_" and "%" only matches a single "%".
651    *
652    * You do that by "like-escaping" @c name, appending the wildcard pattern
653    * @c ".___", and finally, escaping and quoting the result for inclusion in
654    * your query:
655    *
656    *    tx.exec(
657    *        "SELECT file FROM item WHERE file LIKE " +
658    *        tx.quote(tx.esc_like(name) + ".___"));
659    *
660    * The SQL "LIKE" operator also lets you choose your own escape character.
661    * This is supported, but must be a single-byte character.
662    */
663   [[nodiscard]] std::string
664   esc_like(std::string_view text, char escape_char = '\\') const;
665   //@}
666 
667   /// Attempt to cancel the ongoing query, if any.
668   /** You can use this from another thread, and/or while a query is executing
669    * in a pipeline, but it's up to you to ensure that you're not canceling the
670    * wrong query.  This may involve locking.
671    */
672   void cancel_query();
673 
674   /// Set session verbosity.
675   /** Set the verbosity of error messages to "terse", "normal" (the default),
676    * or "verbose."
677    *
678    *  If "terse", returned messages include severity, primary text, and
679    * position only; this will normally fit on a single line. "normal" produces
680    * messages that include the above plus any detail, hint, or context fields
681    * (these might span multiple lines).  "verbose" includes all available
682    * fields.
683    */
684   void set_verbosity(error_verbosity verbosity) noexcept;
685 
686   /// Return pointers to the active errorhandlers.
687   /** The entries are ordered from oldest to newest handler.
688    *
689    * You may use this to find errorhandlers that your application wants to
690    * delete when destroying the connection.  Be aware, however, that libpqxx
691    * may also add errorhandlers of its own, and those will be included in the
692    * list.  If this is a problem for you, derive your errorhandlers from a
693    * custom base class derived from pqxx::errorhandler.  Then use dynamic_cast
694    * to find which of the error handlers are yours.
695    *
696    * The pointers point to the real errorhandlers.  The container it returns
697    * however is a copy of the one internal to the connection, not a reference.
698    */
699   [[nodiscard]] std::vector<errorhandler *> get_errorhandlers() const;
700 
701   /// Return a connection string encapsulating this connection's options.
702   /** The connection must be currently open for this to work.
703    *
704    * Returns a reconstruction of this connection's connection string.  It may
705    * not exactly match the connection string you passed in when creating this
706    * connection.
707    */
708   [[nodiscard]] std::string connection_string() const;
709 
710   /// Explicitly close the connection.
711   /** You won't normally need this.  Destroying a connection object will have
712    * the same effect.
713    */
714   void close();
715 
716 private:
717   // Initialise based on connection string.
718   void init(char const options[]);
719   // Initialise based on parameter names and values.
720   void init(char const *params[], char const *values[]);
721   void complete_init();
722 
723   void wait_read() const;
724   void wait_read(std::time_t seconds, long microseconds) const;
725 
726   result make_result(
727     internal::pq::PGresult *pgr, std::shared_ptr<std::string> const &query);
728 
729   void PQXX_PRIVATE set_up_state();
730 
731   int PQXX_PRIVATE PQXX_PURE status() const noexcept;
732 
733   /// Escape a string, into a buffer allocated by the caller.
734   /** The buffer must have room for at least @c 2*std::size(text)+1 bytes.
735    *
736    * Returns the number of bytes written, including the trailing zero.
737    */
738   std::size_t esc_to_buf(std::string_view text, char *buf) const;
739 
740   friend class internal::gate::const_connection_largeobject;
741   char const *PQXX_PURE err_msg() const noexcept;
742 
743   void PQXX_PRIVATE process_notice_raw(char const msg[]) noexcept;
744 
745   result exec_prepared(std::string_view statement, internal::params const &);
746 
747   /// Throw @c usage_error if this connection is not in a movable state.
748   void check_movable() const;
749   /// Throw @c usage_error if not in a state where it can be move-assigned.
750   void check_overwritable() const;
751 
752   friend class internal::gate::connection_errorhandler;
753   void PQXX_PRIVATE register_errorhandler(errorhandler *);
754   void PQXX_PRIVATE unregister_errorhandler(errorhandler *) noexcept;
755 
756   friend class internal::gate::connection_transaction;
757   result PQXX_PRIVATE exec(std::string_view);
758   result PQXX_PRIVATE exec(std::shared_ptr<std::string>);
759   void PQXX_PRIVATE register_transaction(transaction_base *);
760   void PQXX_PRIVATE unregister_transaction(transaction_base *) noexcept;
761 
762   friend class internal::gate::connection_stream_from;
763   std::pair<std::unique_ptr<char, std::function<void(char *)>>, std::size_t>
764     PQXX_PRIVATE read_copy_line();
765 
766   friend class internal::gate::connection_stream_to;
767   void PQXX_PRIVATE write_copy_line(std::string_view);
768   void PQXX_PRIVATE end_copy_write();
769 
770   friend class internal::gate::connection_largeobject;
raw_connection() const771   internal::pq::PGconn *raw_connection() const { return m_conn; }
772 
773   friend class internal::gate::connection_notification_receiver;
774   void add_receiver(notification_receiver *);
775   void remove_receiver(notification_receiver *) noexcept;
776 
777   friend class internal::gate::connection_pipeline;
778   void PQXX_PRIVATE start_exec(char const query[]);
779   bool PQXX_PRIVATE consume_input() noexcept;
780   bool PQXX_PRIVATE is_busy() const noexcept;
781   internal::pq::PGresult *get_result();
782 
783   friend class internal::gate::connection_dbtransaction;
784   friend class internal::gate::connection_sql_cursor;
785 
786   result exec_params(std::string_view query, internal::params const &args);
787 
788   /// Connection handle.
789   internal::pq::PGconn *m_conn = nullptr;
790 
791   /// Active transaction on connection, if any.
792   internal::unique<transaction_base> m_trans;
793 
794   std::list<errorhandler *> m_errorhandlers;
795 
796   using receiver_list =
797     std::multimap<std::string, pqxx::notification_receiver *>;
798   /// Notification receivers.
799   receiver_list m_receivers;
800 
801   /// Unique number to use as suffix for identifiers (see adorn_name()).
802   int m_unique_id = 0;
803 };
804 
805 
806 /// @deprecated Old base class for connection.  They are now the same class.
807 using connection_base = connection;
808 
809 
quote(T const & t) const810 template<typename T> inline std::string connection::quote(T const &t) const
811 {
812   if constexpr (nullness<T>::always_null)
813   {
814     return "NULL";
815   }
816   else
817   {
818     if (is_null(t))
819       return "NULL";
820     auto const text{to_string(t)};
821 
822     // Okay, there's an easy way to do this and there's a hard way.  The easy
823     // way was "quote, esc(to_string(t)), quote".  I'm going with the hard way
824     // because it's going to save some string manipulation that will probably
825     // incur some unnecessary memory allocations and deallocations.
826     std::string buf{'\''};
827     buf.resize(2 + 2 * std::size(text) + 1);
828     auto const content_bytes{esc_to_buf(text, buf.data() + 1)};
829     auto const closing_quote{1 + content_bytes};
830     buf[closing_quote] = '\'';
831     auto const end{closing_quote + 1};
832     buf.resize(end);
833     return buf;
834   }
835 }
836 
837 
838 #if defined(PQXX_HAVE_CONCEPTS)
839 template<internal::ZKey_ZValues MAPPING>
connection(MAPPING const & params)840 inline connection::connection(MAPPING const &params)
841 {
842   check_version();
843 
844   std::vector<char const *> keys, values;
845   if constexpr (std::ranges::sized_range<MAPPING>)
846   {
847     auto const size{std::ranges::size(params) + 1};
848     keys.reserve(size);
849     values.reserve(size);
850   }
851   for (auto const &[key, value] : params)
852   {
853     keys.push_back(internal::as_c_string(key));
854     values.push_back(internal::as_c_string(value));
855   }
856   keys.push_back(nullptr);
857   values.push_back(nullptr);
858   init(keys.data(), values.data());
859 }
860 #endif // PQXX_HAVE_CONCEPTS
861 } // namespace pqxx
862 
863 
864 namespace pqxx::internal
865 {
866 PQXX_LIBEXPORT void wait_read(internal::pq::PGconn const *);
867 PQXX_LIBEXPORT void wait_read(
868   internal::pq::PGconn const *, std::time_t seconds, long microseconds);
869 PQXX_LIBEXPORT void wait_write(internal::pq::PGconn const *);
870 } // namespace pqxx::internal
871 
872 #include "pqxx/internal/compiler-internal-post.hxx"
873 #endif
874