1818#include < string>
1919#include < utility>
2020
21+ std::atomic<std::uint32_t > pg_conn_t ::connection_id{0 };
22+
2123pg_conn_t ::pg_conn_t (std::string const &conninfo)
22- : m_conn(PQconnectdb(conninfo.c_str()))
24+ : m_conn(PQconnectdb(conninfo.c_str())),
25+ m_connection_id (connection_id.fetch_add(1 ))
2326{
2427 if (!m_conn) {
2528 throw std::runtime_error{" Connecting to database failed." };
2629 }
2730 if (PQstatus (m_conn.get ()) != CONNECTION_OK) {
2831 throw fmt_error (" Connecting to database failed: {}." , error_msg ());
2932 }
33+
34+ if (get_logger ().log_sql ()) {
35+ auto const results = exec (" SELECT pg_backend_pid()" );
36+ log_sql (" (C{}) New database connection (backend_pid={})" ,
37+ m_connection_id, results.get (0 , 0 ));
38+ }
39+ }
40+
41+ void pg_conn_t::close ()
42+ {
43+ log_sql (" (C{}) Closing database connection" , m_connection_id);
44+ m_conn.reset ();
3045}
3146
3247char const *pg_conn_t ::error_msg() const noexcept
@@ -49,7 +64,7 @@ pg_result_t pg_conn_t::exec(char const *sql) const
4964{
5065 assert (m_conn);
5166
52- log_sql (" {} " , sql);
67+ log_sql (" (C{}) {} " , m_connection_id , sql);
5368 pg_result_t res{PQexec (m_conn.get (), sql)};
5469 if (res.status () != PGRES_COMMAND_OK && res.status () != PGRES_TUPLES_OK) {
5570 throw fmt_error (" Database error: {}" , error_msg ());
@@ -66,7 +81,7 @@ void pg_conn_t::copy_start(char const *sql) const
6681{
6782 assert (m_conn);
6883
69- log_sql (" {} " , sql);
84+ log_sql (" (C{}) {} " , m_connection_id , sql);
7085 pg_result_t const res{PQexec (m_conn.get (), sql)};
7186 if (res.status () != PGRES_COPY_IN) {
7287 throw fmt_error (" Database error on COPY: {}" , error_msg ());
@@ -78,7 +93,8 @@ void pg_conn_t::copy_send(std::string const &data,
7893{
7994 assert (m_conn);
8095
81- log_sql_data (" Copy data to '{}':\n {}" , context, data);
96+ log_sql_data (" (C{}) Copy data to '{}':\n {}" , m_connection_id, context,
97+ data);
8298 int const r = PQputCopyData (m_conn.get (), data.c_str (), (int )data.size ());
8399
84100 switch (r) {
@@ -141,7 +157,7 @@ pg_result_t pg_conn_t::exec_prepared_internal(char const *stmt, int num_params,
141157 assert (m_conn);
142158
143159 if (get_logger ().log_sql ()) {
144- log_sql (" EXECUTE {}({})" , stmt,
160+ log_sql (" (C{}) EXECUTE {}({})" , m_connection_id , stmt,
145161 concat_params (num_params, param_values));
146162 }
147163
0 commit comments