connection_base.hxx 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. /** Definition of the pqxx::connection_base abstract base class.
  2. *
  3. * pqxx::connection_base encapsulates a frontend to backend connection
  4. *
  5. * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/connection_base instead.
  6. *
  7. * Copyright (c) 2000-2019, 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 mistake,
  11. * or contact the author.
  12. */
  13. #ifndef PQXX_H_CONNECTION_BASE
  14. #define PQXX_H_CONNECTION_BASE
  15. #include "pqxx/compiler-public.hxx"
  16. #include "pqxx/compiler-internal-pre.hxx"
  17. #include <bitset>
  18. #include <list>
  19. #include <map>
  20. #include <memory>
  21. #include "pqxx/errorhandler.hxx"
  22. #include "pqxx/except.hxx"
  23. #include "pqxx/prepared_statement.hxx"
  24. #include "pqxx/strconv.hxx"
  25. #include "pqxx/util.hxx"
  26. #include "pqxx/version.hxx"
  27. /* Use of the libpqxx library starts here.
  28. *
  29. * Everything that can be done with a database through libpqxx must go through
  30. * a connection object derived from connection_base.
  31. */
  32. /* Methods tested in eg. self-test program test1 are marked with "//[t01]"
  33. */
  34. namespace pqxx
  35. {
  36. namespace internal
  37. {
  38. class reactivation_avoidance_exemption;
  39. class sql_cursor;
  40. class reactivation_avoidance_counter
  41. {
  42. public:
  43. reactivation_avoidance_counter() =default;
  44. void add(int n) noexcept { m_counter += n; }
  45. void clear() noexcept { m_counter = 0; }
  46. int get() const noexcept { return m_counter; }
  47. private:
  48. int m_counter = 0;
  49. };
  50. }
  51. /// Encrypt password for given user.
  52. /** Use this when setting a new password for the user if password encryption is
  53. * enabled. Inputs are the username the password is for, and the plaintext
  54. * password.
  55. *
  56. * @return encrypted version of the password, suitable for encrypted PostgreSQL
  57. * authentication.
  58. *
  59. * Thus the password for a user can be changed with:
  60. * @code
  61. * void setpw(transaction_base &t, const string &user, const string &pw)
  62. * {
  63. * t.exec("ALTER USER " + user + " "
  64. * "PASSWORD '" + encrypt_password(user,pw) + "'");
  65. * }
  66. * @endcode
  67. */
  68. std::string PQXX_LIBEXPORT encrypt_password( //[t00]
  69. const std::string &user,
  70. const std::string &password);
  71. namespace internal
  72. {
  73. namespace gate
  74. {
  75. class connection_dbtransaction;
  76. class connection_errorhandler;
  77. class connection_largeobject;
  78. class connection_notification_receiver;
  79. class connection_parameterized_invocation;
  80. class connection_pipeline;
  81. class connection_prepare_invocation;
  82. class connection_reactivation_avoidance_exemption;
  83. class connection_sql_cursor;
  84. class connection_transaction;
  85. class const_connection_largeobject;
  86. } // namespace pqxx::internal::gate
  87. } // namespace pqxx::internal
  88. /// connection_base abstract base class; represents a connection to a database.
  89. /** This is the first class to look at when you wish to work with a database
  90. * through libpqxx. Depending on the implementing concrete child class, a
  91. * connection can be automatically opened when it is constructed, or when it is
  92. * first used, or somewhere inbetween. The connection is automatically closed
  93. * upon destruction (if it hasn't been closed already).
  94. *
  95. * To query or manipulate the database once connected, use one of the
  96. * transaction classes (see pqxx/transaction_base.hxx) or preferably the
  97. * transactor framework (see pqxx/transactor.hxx).
  98. *
  99. * If a network connection to the database server fails, the connection will be
  100. * restored automatically (although any transaction going on at the time will
  101. * have to be aborted). This also means that any information set in previous
  102. * transactions that is not stored in the database, such as temp tables or
  103. * connection-local variables defined with PostgreSQL's SET command, will be
  104. * lost. Whenever you create such state, either keept it local to one
  105. * transaction, where possible, or inhibit automatic reactivation of the
  106. * connection using the inhibit_reactivation() method.
  107. *
  108. * When a connection breaks, you will typically get a broken_connection
  109. * exception. This can happen at almost any point, and the details may depend
  110. * on which connection class (all derived from this one) you use.
  111. *
  112. * As a general rule, always avoid raw queries if libpqxx offers a dedicated
  113. * function for the same purpose. There may be hidden logic to hide certain
  114. * complications from you, such as reinstating session variables when a
  115. * broken or disabled connection is reactivated.
  116. *
  117. * @warning On Unix-like systems, including GNU and BSD systems, your program
  118. * may receive the SIGPIPE signal when the connection to the backend breaks. By
  119. * default this signal will abort your program. Use "signal(SIGPIPE, SIG_IGN)"
  120. * if you want your program to continue running after a connection fails.
  121. */
  122. class PQXX_LIBEXPORT connection_base
  123. {
  124. public:
  125. /// Explicitly close connection.
  126. void disconnect() noexcept; //[t02]
  127. /// Is this connection open at the moment?
  128. /** @warning This function is @b not needed in most code. Resist the
  129. * temptation to check it after opening a connection; instead, rely on the
  130. * broken_connection exception that will be thrown on connection failure.
  131. */
  132. bool PQXX_PURE is_open() const noexcept; //[t01]
  133. /**
  134. * @name Activation
  135. *
  136. * @warning Connection deactivation/reactivation will probably be removed in
  137. * libpqxx 7. If your application relies on an ability to "put connections
  138. * to sleep" and reactivate them later, you'll need to wrap them in some way
  139. * to handle this.
  140. *
  141. * Connections can be temporarily deactivated, or they can break because of
  142. * overly impatient firewalls dropping TCP connections. Where possible,
  143. * libpqxx will try to re-activate these when resume using them, or you can
  144. * wake them up explicitly. You probably won't need this feature, but you
  145. * should be aware of it.
  146. */
  147. //@{
  148. /// @deprecated Explicitly activate deferred or deactivated connection.
  149. /** Use of this method is entirely optional. Whenever a connection is used
  150. * while in a deferred or deactivated state, it will transparently try to
  151. * bring itself into an activated state. This function is best viewed as an
  152. * explicit hint to the connection that "if you're not in an active state, now
  153. * would be a good time to get into one." Whether a connection is currently
  154. * in an active state or not makes no real difference to its functionality.
  155. * There is also no particular need to match calls to activate() with calls to
  156. * deactivate(). A good time to call activate() might be just before you
  157. * first open a transaction on a lazy connection.
  158. */
  159. PQXX_DEPRECATED void activate(); //[t12]
  160. /// @deprecated Explicitly deactivate connection.
  161. /** Like its counterpart activate(), this method is entirely optional.
  162. * Calling this function really only makes sense if you won't be using this
  163. * connection for a while and want to reduce the number of open connections on
  164. * the database server.
  165. * There is no particular need to match or pair calls to deactivate() with
  166. * calls to activate(), but calling deactivate() during a transaction is an
  167. * error.
  168. */
  169. PQXX_DEPRECATED void deactivate(); //[t12]
  170. /// @deprecated Disallow (or permit) connection recovery
  171. /** A connection whose underlying socket is not currently connected to the
  172. * server will normally (re-)establish communication with the server whenever
  173. * needed, or when the client program requests it (although for reasons of
  174. * integrity, never inside a transaction; but retrying the whole transaction
  175. * may implicitly cause the connection to be restored). In normal use this is
  176. * quite a convenient thing to have and presents a simple, safe, predictable
  177. * interface.
  178. *
  179. * There is at least one situation where this feature is not desirable,
  180. * however. Although most session state (prepared statements, session
  181. * variables) is automatically restored to its working state upon connection
  182. * reactivation, temporary tables and so-called WITH HOLD cursors (which can
  183. * live outside transactions) are not.
  184. *
  185. * Cursors that live outside transactions are automatically handled, and the
  186. * library will quietly ignore requests to deactivate or reactivate
  187. * connections while they exist; it does not want to give you the illusion of
  188. * being back in your transaction when in reality you just dropped a cursor.
  189. * With temporary tables this is not so easy: there is no easy way for the
  190. * library to detect their creation or track their lifetimes.
  191. *
  192. * So if your program uses temporary tables, and any part of this use happens
  193. * outside of any database transaction (or spans multiple transactions), some
  194. * of the work you have done on these tables may unexpectedly be undone if the
  195. * connection is broken or deactivated while any of these tables exists, and
  196. * then reactivated or implicitly restored before you are finished with it.
  197. *
  198. * If this describes any part of your program, guard it against unexpected
  199. * reconnections by inhibiting reconnection at the beginning. And if you want
  200. * to continue doing work on the connection afterwards that no longer requires
  201. * the temp tables, you can permit it again to get the benefits of connection
  202. * reactivation for the remainder of the program.
  203. *
  204. * @param inhibit should reactivation be inhibited from here on?
  205. *
  206. * @warning Some connection types (the lazy and asynchronous types) defer
  207. * completion of the socket-level connection until it is actually needed by
  208. * the client program. Inhibiting reactivation before this connection is
  209. * really established will prevent these connection types from doing their
  210. * work. For those connection types, if you are sure that reactivation needs
  211. * to be inhibited before any query goes across the connection, activate() the
  212. * connection first. This will ensure that definite activation happens before
  213. * you inhibit it.
  214. */
  215. PQXX_DEPRECATED void inhibit_reactivation(bool inhibit) //[t86]
  216. { m_inhibit_reactivation=inhibit; }
  217. /// Make the connection fail. @warning Do not use this except for testing!
  218. /** Breaks the connection in some unspecified, horrible, dirty way to enable
  219. * failure testing.
  220. *
  221. * Do not use this in normal programs. This is only meant for testing.
  222. */
  223. void simulate_failure(); //[t94]
  224. //@}
  225. /// Invoke notice processor function. The message should end in newline.
  226. void process_notice(const char[]) noexcept; //[t14]
  227. /// Invoke notice processor function. Newline at end is recommended.
  228. void process_notice(const std::string &) noexcept; //[t14]
  229. /// Enable tracing to a given output stream, or nullptr to disable.
  230. void trace(std::FILE *) noexcept; //[t03]
  231. /**
  232. * @name Connection properties
  233. *
  234. * These are probably not of great interest, since most are derived from
  235. * information supplied by the client program itself, but they are included
  236. * for completeness.
  237. */
  238. //@{
  239. /// Name of database we're connected to, if any.
  240. /** @warning This activates the connection, which may fail with a
  241. * broken_connection exception.
  242. */
  243. const char *dbname(); //[t01]
  244. /// Database user ID we're connected under, if any.
  245. /** @warning This activates the connection, which may fail with a
  246. * broken_connection exception.
  247. */
  248. const char *username(); //[t01]
  249. /// Address of server, or nullptr if none specified (i.e. default or local)
  250. /** @warning This activates the connection, which may fail with a
  251. * broken_connection exception.
  252. */
  253. const char *hostname(); //[t01]
  254. /// Server port number we're connected to.
  255. /** @warning This activates the connection, which may fail with a
  256. * broken_connection exception.
  257. */
  258. const char *port(); //[t01]
  259. /// Process ID for backend process.
  260. /** Use with care: connections may be lost and automatically re-established
  261. * without your knowledge, in which case this process ID may no longer be
  262. * correct. You may, however, assume that this number remains constant and
  263. * reliable within the span of a successful backend transaction. If the
  264. * transaction fails, which may be due to a lost connection, then this number
  265. * will have become invalid at some point within the transaction.
  266. *
  267. * @return Process identifier, or 0 if not currently connected.
  268. */
  269. int PQXX_PURE backendpid() const noexcept; //[t01]
  270. /// Socket currently used for connection, or -1 for none. Use with care!
  271. /** Query the current socket number. This is intended for event loops based
  272. * on functions such as select() or poll(), where multiple file descriptors
  273. * are watched.
  274. *
  275. * Please try to stay away from this function. It is really only meant for
  276. * event loops that need to wait on more than one file descriptor. If all you
  277. * need is to block until a notification arrives, for instance, use
  278. * await_notification(). If you want to issue queries and retrieve results in
  279. * nonblocking fashion, check out the pipeline class.
  280. *
  281. * @warning Don't store this value anywhere, and always be prepared for the
  282. * possibility that, at any given time, there may not be a socket! The
  283. * socket may change or even go away or be established during any invocation
  284. * of libpqxx code on the connection, no matter how trivial.
  285. */
  286. int PQXX_PURE sock() const noexcept; //[t87]
  287. /**
  288. * @name Capabilities
  289. *
  290. * Some functionality may only be available in certain versions of the
  291. * backend, or only when speaking certain versions of the communications
  292. * protocol that connects us to the backend.
  293. */
  294. //@{
  295. /// Session capabilities.
  296. /** No capabilities are defined at the moment: all capabilities that older
  297. * versions checked for are now always supported.
  298. */
  299. enum capability
  300. {
  301. /// Not a capability value; end-of-enumeration marker
  302. cap_end,
  303. };
  304. /// Does this connection seem to support the given capability?
  305. /** Don't try to be smart by caching this information anywhere. Obtaining it
  306. * is quite fast (especially after the first time) and what's more, a
  307. * capability may "suddenly" appear or disappear if the connection is broken
  308. * or deactivated, and then restored. This may happen silently any time no
  309. * backend transaction is active; if it turns out that the server was upgraded
  310. * or restored from an older backup, or the new connection goes to a different
  311. * backend, then the restored session may have different capabilities than
  312. * were available previously.
  313. *
  314. * Some guesswork is involved in establishing the presence of any capability;
  315. * try not to rely on this function being exactly right.
  316. *
  317. * @warning Make sure your connection is active before calling this function,
  318. * or the answer will always be "no." In particular, if you are using this
  319. * function on a newly-created lazyconnection, activate the connection first.
  320. */
  321. bool supports(capability c) const noexcept //[t88]
  322. { return m_caps.test(c); }
  323. /// What version of the PostgreSQL protocol is this connection using?
  324. /** The answer can be 0 (when there is no connection); 3 for protocol 3.0; or
  325. * possibly higher values as newer protocol versions are taken into use.
  326. *
  327. * If the connection is broken and restored, the restored connection could
  328. * possibly use a different server and protocol version. This would normally
  329. * happen if the server is upgraded without shutting down the client program,
  330. * for example.
  331. */
  332. int PQXX_PURE protocol_version() const noexcept; //[t01]
  333. /// What version of the PostgreSQL server are we connected to?
  334. /** The result is a bit complicated: each of the major, medium, and minor
  335. * release numbers is written as a two-digit decimal number, and the three
  336. * are then concatenated. Thus server version 9.4.2 will be returned as the
  337. * decimal number 90402. If there is no connection to the server, this
  338. * returns zero.
  339. *
  340. * @warning When writing version numbers in your code, don't add zero at the
  341. * beginning! Numbers beginning with zero are interpreted as octal (base-8)
  342. * in C++. Thus, 070402 is not the same as 70402, and 080000 is not a number
  343. * at all because there is no digit "8" in octal notation. Use strictly
  344. * decimal notation when it comes to these version numbers.
  345. */
  346. int PQXX_PURE server_version() const noexcept; //[t01]
  347. //@}
  348. /// @name Text encoding
  349. /**
  350. * Each connection is governed by a "client encoding," which dictates how
  351. * strings and other text is represented in bytes. The database server will
  352. * send text data to you in this encoding, and you should use it for the
  353. * queries and data which you send to the server.
  354. *
  355. * Search the PostgreSQL documentation for "character set encodings" to find
  356. * out more about the available encodings, how to extend them, and how to use
  357. * them. Not all server-side encodings are compatible with all client-side
  358. * encodings or vice versa.
  359. *
  360. * Encoding names are case-insensitive, so e.g. "UTF8" is equivalent to
  361. * "utf8".
  362. *
  363. * You can change the client encoding, but this may not work when the
  364. * connection is in a special state, such as when streaming a table. It's
  365. * not clear what happens if you change the encoding during a transaction,
  366. * and then abort the transaction.
  367. */
  368. //@{
  369. /// Get client-side character encoding, by name.
  370. std::string get_client_encoding() const;
  371. /// Set client-side character encoding, by name.
  372. /**
  373. * @param Encoding Name of the character set encoding to use.
  374. */
  375. void set_client_encoding(const std::string &encoding); //[t07]
  376. /// Set client-side character encoding, by name.
  377. /**
  378. * @param Encoding Name of the character set encoding to use.
  379. */
  380. void set_client_encoding(const char encoding[]); //[t07]
  381. /// Get the connection's encoding, as a PostgreSQL-defined code.
  382. int PQXX_PRIVATE encoding_id() const;
  383. //@}
  384. /// Set session variable
  385. /** Set a session variable for this connection, using the SET command. If the
  386. * connection to the database is lost and recovered, the last-set value will
  387. * be restored automatically. See the PostgreSQL documentation for a list of
  388. * variables that can be set and their permissible values.
  389. * If a transaction is currently in progress, aborting that transaction will
  390. * normally discard the newly set value. However nontransaction (which
  391. * doesn't start a real backend transaction) is an exception.
  392. *
  393. * @warning Do not mix the set_variable interface with manual setting of
  394. * variables by executing the corresponding SQL commands, and do not get or
  395. * set variables while a tablestream or pipeline is active on the same
  396. * connection.
  397. * @param Var Variable to set
  398. * @param Value Value vor Var to assume: an identifier, a quoted string, or a
  399. * number.
  400. */
  401. void set_variable( //[t60]
  402. const std::string &Var,
  403. const std::string &Value);
  404. /// Read session variable
  405. /** Will try to read the value locally, from the list of variables set with
  406. * the set_variable function. If that fails, the database is queried.
  407. * @warning Do not mix the set_variable interface with manual setting of
  408. * variables by executing the corresponding SQL commands, and do not get or
  409. * set variables while a tablestream or pipeline is active on the same
  410. * connection.
  411. */
  412. std::string get_variable(const std::string &); //[t60]
  413. //@}
  414. /**
  415. * @name Notifications and Receivers
  416. */
  417. //@{
  418. /// Check for pending notifications and take appropriate action.
  419. /**
  420. * All notifications found pending at call time are processed by finding
  421. * any matching receivers and invoking those. If no receivers matched the
  422. * notification string, none are invoked but the notification is considered
  423. * processed.
  424. *
  425. * Exceptions thrown by client-registered receivers are reported using the
  426. * connection's errorhandlers, but the exceptions themselves are not passed
  427. * on outside this function.
  428. *
  429. * @return Number of notifications processed
  430. */
  431. int get_notifs(); //[t04]
  432. /// Wait for a notification to come in
  433. /** The wait may also be terminated by other events, such as the connection
  434. * to the backend failing. Any pending or received notifications are
  435. * processed as part of the call.
  436. *
  437. * @return Number of notifications processed
  438. */
  439. int await_notification(); //[t78]
  440. /// Wait for a notification to come in, or for given timeout to pass
  441. /** The wait may also be terminated by other events, such as the connection
  442. * to the backend failing. Any pending or received notifications are
  443. * processed as part of the call.
  444. * @return Number of notifications processed
  445. */
  446. int await_notification(long seconds, long microseconds); //[t79]
  447. //@}
  448. /**
  449. * @name Prepared statements
  450. *
  451. * PostgreSQL supports prepared SQL statements, i.e. statements that can be
  452. * registered under a client-provided name, optimized once by the backend, and
  453. * executed any number of times under the given name.
  454. *
  455. * Prepared statement definitions are not sensitive to transaction boundaries;
  456. * a statement defined inside a transaction will remain defined outside that
  457. * transaction, even if the transaction itself is subsequently aborted. Once
  458. * a statement has been prepared, only closing the connection or explicitly
  459. * "unpreparing" it can make it go away.
  460. *
  461. * Use the @c pqxx::transaction_base::exec_prepared functions to execute a
  462. * prepared statement. Use @c prepared().exists() to find out whether a
  463. * statement has been prepared under a given name. See \ref prepared for a
  464. * full discussion.
  465. *
  466. * Never try to prepare, execute, or unprepare a prepared statement manually
  467. * using direct SQL queries. Always use the functions provided by libpqxx.
  468. *
  469. * @{
  470. */
  471. /// Define a prepared statement.
  472. /**
  473. * The statement's definition can refer to a parameter using the parameter's
  474. * positional number n in the definition. For example, the first parameter
  475. * can be used as a variable "$1", the second as "$2" and so on.
  476. *
  477. * Here's an example of how to use prepared statements. Note the unusual
  478. * syntax for passing parameters: every new argument is a parenthesized
  479. * expression that is simply tacked onto the end of the statement!
  480. *
  481. * @code
  482. * using namespace pqxx;
  483. * void foo(connection_base &C)
  484. * {
  485. * C.prepare("findtable", "select * from pg_tables where name=$1");
  486. * work W{C};
  487. * result R = W.exec_prepared("findtable", "mytable");
  488. * if (R.empty()) throw runtime_error{"mytable not found!"};
  489. * }
  490. * @endcode
  491. *
  492. * To save time, prepared statements aren't really registered with the backend
  493. * until they are first used. If this is not what you want, e.g. because you
  494. * have very specific realtime requirements, you can use the @c prepare_now()
  495. * function to force immediate preparation.
  496. *
  497. * The statement may not be registered with the backend until it is actually
  498. * used. So if, for example, the statement is syntactically incorrect, you
  499. * may see a syntax_error here, or later when you try to call the statement,
  500. * or during a @c prepare_now() call.
  501. *
  502. * @param name unique name for the new prepared statement.
  503. * @param definition SQL statement to prepare.
  504. */
  505. void prepare(const std::string &name, const std::string &definition);
  506. /// Define a nameless prepared statement.
  507. /**
  508. * This can be useful if you merely want to pass large binary parameters to a
  509. * statement without otherwise wishing to prepare it. If you use this
  510. * feature, always keep the definition and the use close together to avoid
  511. * the nameless statement being redefined unexpectedly by code somewhere else.
  512. */
  513. void prepare(const std::string &definition);
  514. /// Drop prepared statement.
  515. void unprepare(const std::string &name);
  516. /// Request that prepared statement be registered with the server.
  517. /** If the statement had already been fully prepared, this will do nothing.
  518. *
  519. * If the connection should break and be transparently restored, then the new
  520. * connection will again defer registering the statement with the server.
  521. * Since connections are never restored inside backend transactions, doing
  522. * this once at the beginning of your transaction ensures that the statement
  523. * will not be re-registered during that transaction. In most cases, however,
  524. * it's probably better not to use this and let the connection decide when and
  525. * whether to register prepared statements that you've defined.
  526. */
  527. void prepare_now(const std::string &name);
  528. /**
  529. * @}
  530. */
  531. /// @deprecated Pre-C++11 transactor function.
  532. /**
  533. * This has been superseded by the new transactor framework and
  534. * @c pqxx::perform.
  535. *
  536. * Invokes the given transactor, making at most Attempts attempts to perform
  537. * the encapsulated code. If the code throws any exception other than
  538. * broken_connection, it will be aborted right away.
  539. *
  540. * @param T The transactor to be executed.
  541. * @param Attempts Maximum number of attempts to be made to execute T.
  542. */
  543. template<typename TRANSACTOR>
  544. PQXX_DEPRECATED void perform(const TRANSACTOR &T, int Attempts); //[t04]
  545. /// @deprecated Pre-C++11 transactor function. Use @c pqxx::perform instead.
  546. /**
  547. * This has been superseded by the new transactor framework and
  548. * @c pqxx::perform.
  549. *
  550. * @param T The transactor to be executed.
  551. */
  552. template<typename TRANSACTOR>
  553. PQXX_DEPRECATED void perform(const TRANSACTOR &T)
  554. {
  555. #include "pqxx/internal/ignore-deprecated-pre.hxx"
  556. perform(T, 3);
  557. #include "pqxx/internal/ignore-deprecated-post.hxx"
  558. }
  559. /// Suffix unique number to name to make it unique within session context
  560. /** Used internally to generate identifiers for SQL objects (such as cursors
  561. * and nested transactions) based on a given human-readable base name.
  562. */
  563. std::string adorn_name(const std::string &); //[90]
  564. /**
  565. * @defgroup escaping-functions String-escaping functions
  566. */
  567. //@{
  568. /// Escape string for use as SQL string literal on this connection
  569. std::string esc(const char str[]);
  570. /// Escape string for use as SQL string literal on this connection
  571. std::string esc(const char str[], size_t maxlen);
  572. /// Escape string for use as SQL string literal on this connection
  573. std::string esc(const std::string &str);
  574. /// Escape binary string for use as SQL string literal on this connection
  575. std::string esc_raw(const unsigned char str[], size_t len);
  576. /// Unescape binary data, e.g. from a table field or notification payload.
  577. /** Takes a binary string as escaped by PostgreSQL, and returns a restored
  578. * copy of the original binary data.
  579. */
  580. std::string unesc_raw(const std::string &text)
  581. { return unesc_raw(text.c_str()); }
  582. /// Unescape binary data, e.g. from a table field or notification payload.
  583. /** Takes a binary string as escaped by PostgreSQL, and returns a restored
  584. * copy of the original binary data.
  585. */
  586. std::string unesc_raw(const char *text);
  587. /// Escape and quote a string of binary data.
  588. std::string quote_raw(const unsigned char str[], size_t len);
  589. /// Escape and quote an SQL identifier for use in a query.
  590. std::string quote_name(const std::string &identifier);
  591. /// Represent object as SQL string, including quoting & escaping.
  592. /** Nulls are recognized and represented as SQL nulls. */
  593. template<typename T>
  594. std::string quote(const T &t)
  595. {
  596. if (string_traits<T>::is_null(t)) return "NULL";
  597. return "'" + this->esc(to_string(t)) + "'";
  598. }
  599. std::string quote(const binarystring &);
  600. /// Escape string for literal LIKE match.
  601. /** Use this when part of an SQL "LIKE" pattern should match only as a
  602. * literal string, not as a pattern, even if it contains "%" or "_"
  603. * characters that would normally act as wildcards.
  604. *
  605. * The string does not get string-escaped or quoted. You do that later.
  606. *
  607. * For instance, let's say you have a string @c name entered by the user,
  608. * and you're searching a @c file column for items that match @c name
  609. * followed by a dot and three letters. Even if @c name contains wildcard
  610. * characters "%" or "_", you only want those to match literally, so "_"
  611. * only matches "_" and "%" only matches a single "%".
  612. *
  613. * You do that by "like-escaping" @c name, appending the wildcard pattern
  614. * @c ".___", and finally, escaping and quoting the result for inclusion in
  615. * your query:
  616. *
  617. * tx.exec(
  618. * "SELECT file FROM item WHERE file LIKE " +
  619. * tx.quote(tx.esc_like(name) + ".___"));
  620. *
  621. * The SQL "LIKE" operator also lets you choose your own escape character.
  622. * This is supported, but must be a single-byte character.
  623. */
  624. std::string esc_like(const std::string &str, char escape_char='\\') const;
  625. //@}
  626. /// Attempt to cancel the ongoing query, if any.
  627. void cancel_query();
  628. /// Error verbosity levels.
  629. enum error_verbosity
  630. {
  631. // These values must match those in libpq's PGVerbosity enum.
  632. terse=0,
  633. normal=1,
  634. verbose=2
  635. };
  636. /// Set session verbosity.
  637. /** Set the verbosity of error messages to "terse", "normal" (i.e. default) or
  638. * "verbose."
  639. *
  640. * If "terse", returned messages include severity, primary text, and position
  641. * only; this will normally fit on a single line. "normal" produces messages
  642. * that include the above plus any detail, hint, or context fields (these
  643. * might span multiple lines). "verbose" includes all available fields.
  644. */
  645. void set_verbosity(error_verbosity verbosity) noexcept;
  646. /// Retrieve current error verbosity
  647. error_verbosity get_verbosity() const noexcept {return m_verbosity;}
  648. /// Return pointers to the active errorhandlers.
  649. /** The entries are ordered from oldest to newest handler.
  650. *
  651. * You may use this to find errorhandlers that your application wants to
  652. * delete when destroying the connection. Be aware, however, that libpqxx
  653. * may also add errorhandlers of its own, and those will be included in the
  654. * list. If this is a problem for you, derive your errorhandlers from a
  655. * custom base class derived from pqxx::errorhandler. Then use dynamic_cast
  656. * to find which of the error handlers are yours.
  657. *
  658. * The pointers point to the real errorhandlers. The container it returns
  659. * however is a copy of the one internal to the connection, not a reference.
  660. */
  661. std::vector<errorhandler *> get_errorhandlers() const;
  662. protected:
  663. explicit connection_base(connectionpolicy &pol) :
  664. m_policy{pol}
  665. {
  666. // Check library version. The check_library_version template is declared
  667. // for any library version, but only actually defined for the version of
  668. // the libpqxx binary against which the code is linked.
  669. //
  670. // If the library binary is a different version than the one declared in
  671. // these headers, then this call will fail to link: there will be no
  672. // definition for the function with these exact template parameter values.
  673. // There will be a definition, but the version in the parameter values will
  674. // be different.
  675. //
  676. // There is no particular reason to do this here in this constructor, except
  677. // to ensure that every meaningful libpqxx client will execute it. The call
  678. // must be in the execution path somewhere or the compiler won't try to link
  679. // it. We can't use it to initialise a global or class-static variable,
  680. // because a smart compiler might resolve it at compile time.
  681. //
  682. // On the other hand, we don't want to make a useless function call too
  683. // often for performance reasons. A local static variable is initialised
  684. // only on the definition's first execution. Compilers will be well
  685. // optimised for this behaviour, so there's a minimal one-time cost.
  686. static const auto version_ok =
  687. internal::check_library_version<PQXX_VERSION_MAJOR, PQXX_VERSION_MINOR>();
  688. ignore_unused(version_ok);
  689. clearcaps();
  690. }
  691. void init();
  692. void close() noexcept;
  693. void wait_read() const;
  694. void wait_read(long seconds, long microseconds) const;
  695. void wait_write() const;
  696. private:
  697. result make_result(internal::pq::PGresult *rhs, const std::string &query);
  698. void clearcaps() noexcept;
  699. void PQXX_PRIVATE set_up_state();
  700. void PQXX_PRIVATE check_result(const result &);
  701. void PQXX_PRIVATE internal_set_trace() noexcept;
  702. int PQXX_PRIVATE PQXX_PURE status() const noexcept;
  703. friend class internal::gate::const_connection_largeobject;
  704. const char * PQXX_PURE err_msg() const noexcept;
  705. void PQXX_PRIVATE reset();
  706. std::string PQXX_PRIVATE raw_get_var(const std::string &);
  707. void PQXX_PRIVATE process_notice_raw(const char msg[]) noexcept;
  708. void read_capabilities();
  709. prepare::internal::prepared_def &find_prepared(const std::string &);
  710. prepare::internal::prepared_def &register_prepared(const std::string &);
  711. friend class internal::gate::connection_prepare_invocation;
  712. /// @deprecated Use exec_prepared instead.
  713. PQXX_DEPRECATED result prepared_exec(
  714. const std::string &,
  715. const char *const[],
  716. const int[],
  717. const int[],
  718. int,
  719. result_format format);
  720. result exec_prepared(const std::string &statement, const internal::params &, result_format format = result_format::text);
  721. bool prepared_exists(const std::string &) const;
  722. /// Connection handle.
  723. internal::pq::PGconn *m_conn = nullptr;
  724. connectionpolicy &m_policy;
  725. /// Active transaction on connection, if any.
  726. internal::unique<transaction_base> m_trans;
  727. /// Set libpq notice processor to call connection's error handlers chain.
  728. void set_notice_processor();
  729. /// Clear libpq notice processor.
  730. void clear_notice_processor();
  731. std::list<errorhandler *> m_errorhandlers;
  732. /// File to trace to, if any
  733. std::FILE *m_trace = nullptr;
  734. using receiver_list =
  735. std::multimap<std::string, pqxx::notification_receiver *>;
  736. /// Notification receivers.
  737. receiver_list m_receivers;
  738. /// Variables set in this session
  739. std::map<std::string, std::string> m_vars;
  740. using PSMap = std::map<std::string, prepare::internal::prepared_def>;
  741. /// Prepared statements existing in this section
  742. PSMap m_prepared;
  743. /// Server version
  744. int m_serverversion = 0;
  745. /// Stacking counter: known objects that can't be auto-reactivated
  746. internal::reactivation_avoidance_counter m_reactivation_avoidance;
  747. /// Unique number to use as suffix for identifiers (see adorn_name())
  748. int m_unique_id = 0;
  749. /// Have we successfully established this connection?
  750. bool m_completed = false;
  751. /// Is reactivation currently inhibited?
  752. bool m_inhibit_reactivation = false;
  753. /// Set of session capabilities
  754. std::bitset<cap_end> m_caps;
  755. /// Current verbosity level
  756. error_verbosity m_verbosity = normal;
  757. friend class internal::gate::connection_errorhandler;
  758. void PQXX_PRIVATE register_errorhandler(errorhandler *);
  759. void PQXX_PRIVATE unregister_errorhandler(errorhandler *) noexcept;
  760. friend class internal::gate::connection_transaction;
  761. result PQXX_PRIVATE exec(const char[], int Retries);
  762. void PQXX_PRIVATE register_transaction(transaction_base *);
  763. void PQXX_PRIVATE unregister_transaction(transaction_base *) noexcept;
  764. bool PQXX_PRIVATE read_copy_line(std::string &);
  765. void PQXX_PRIVATE write_copy_line(const std::string &);
  766. void PQXX_PRIVATE end_copy_write();
  767. void PQXX_PRIVATE raw_set_var(const std::string &, const std::string &);
  768. void PQXX_PRIVATE add_variables(const std::map<std::string, std::string> &);
  769. friend class internal::gate::connection_largeobject;
  770. internal::pq::PGconn *raw_connection() const { return m_conn; }
  771. friend class internal::gate::connection_notification_receiver;
  772. void add_receiver(notification_receiver *);
  773. void remove_receiver(notification_receiver *) noexcept;
  774. friend class internal::gate::connection_pipeline;
  775. void PQXX_PRIVATE start_exec(const std::string &);
  776. bool PQXX_PRIVATE consume_input() noexcept;
  777. bool PQXX_PRIVATE is_busy() const noexcept;
  778. internal::pq::PGresult *get_result();
  779. friend class internal::gate::connection_dbtransaction;
  780. friend class internal::gate::connection_sql_cursor;
  781. void add_reactivation_avoidance_count(int);
  782. friend class internal::gate::connection_reactivation_avoidance_exemption;
  783. friend class internal::gate::connection_parameterized_invocation;
  784. /// @deprecated Use exec_params instead.
  785. PQXX_DEPRECATED result parameterized_exec(
  786. const std::string &query,
  787. const char *const params[],
  788. const int paramlengths[],
  789. const int binaries[],
  790. int nparams);
  791. result exec_params(
  792. const std::string &query,
  793. const internal::params &args);
  794. connection_base(const connection_base &) =delete;
  795. connection_base &operator=(const connection_base &) =delete;
  796. };
  797. namespace internal
  798. {
  799. /// Scoped exemption to reactivation avoidance
  800. class PQXX_LIBEXPORT reactivation_avoidance_exemption
  801. {
  802. public:
  803. explicit reactivation_avoidance_exemption(connection_base &C);
  804. ~reactivation_avoidance_exemption();
  805. void close_connection() noexcept { m_open = false; }
  806. private:
  807. connection_base &m_home;
  808. int m_count;
  809. bool m_open;
  810. };
  811. void wait_read(const internal::pq::PGconn *);
  812. void wait_read(const internal::pq::PGconn *, long seconds, long microseconds);
  813. void wait_write(const internal::pq::PGconn *);
  814. } // namespace pqxx::internal
  815. } // namespace pqxx
  816. #include "pqxx/compiler-internal-post.hxx"
  817. #endif