mirror of
https://github.com/allankoechke/soci.git
synced 2026-11-30 10:58:24 +00:00
Merge branch 'pg-optimize'
Some minor PostgreSQL optimizations. See #1276.
This commit is contained in:
@@ -44,23 +44,10 @@ session sql("postgresql", "dbname=mydatabase");
|
||||
session sql("postgresql://dbname=mydatabase");
|
||||
```
|
||||
|
||||
The set of parameters used in the connection string for PostgreSQL is the same as accepted by the [PQconnectdb](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PQCONNECTDB) function from the `libpq` library.
|
||||
The set of parameters used in the connection string for PostgreSQL is the same as accepted by the [PQconnectdb](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PQCONNECTDB) function from the `libpq` library, however in addition to standard PostgreSQL connection parameters, SOCI PostgreSQL backend accepts a couple of additional ones:
|
||||
|
||||
In addition to standard PostgreSQL connection parameters, the following can be set:
|
||||
|
||||
* `singlerow` or `singlerows`
|
||||
|
||||
For example:
|
||||
|
||||
```cpp
|
||||
session sql(postgresql, "dbname=mydatabase singlerows=true");
|
||||
```
|
||||
|
||||
If the `singlerows` parameter is set to `true` or `yes`, then queries will be executed in the single-row mode, which prevents the client library from loading full query result sets into memory and instead fetches rows one by one, as they are requested by the statement's fetch() function. This mode can be of interest to those users who want to make their client applications more responsive (with more fine-grained operation) by avoiding potentially long blocking times when complete query results are loaded to client's memory.
|
||||
Note that in the single-row operation:
|
||||
|
||||
* bulk queries are not supported, and
|
||||
* in order to fulfill the expectations of the underlying client library, the complete rowset has to be exhausted before executing further queries on the same session.
|
||||
* `tracefile`: if specified, enables tracing all database activity using [PQtrace()](https://www.postgresql.org/docs/current/libpq-control.html#LIBPQ-PQTRACE) into the file with the given path. Note that this file is overwritten by default, prepend it with a plus sign, i.e. use `tracefile=+/path/to/file`, to append to the file instead.
|
||||
* `singlerow` or `singlerows`: if set to `true` or `yes`, enables single-row mode for the session (see next section).
|
||||
|
||||
Another parameter is handled specially: while libpq client library supports `tcp_user_timeout` parameter, it only provides support for it under Linux. SOCI also handles this parameter, which can change the time before a broken connection times out (which depends on the system settings but is typically relatively long), under Windows. It handles it in the same way as libpq itself, i.e. the value of this parameter is expressed in milliseconds, but because Windows sockets only use second granularity, SOCI will round the value to the nearest second. In particular, this means that this parameter must be greater than or equal to 500 to be accepted.
|
||||
|
||||
@@ -73,6 +60,20 @@ sql << "select count(*) from invoices", into(count);
|
||||
|
||||
(See the [connection](../connections.md) and [data binding](../binding.md) documentation for general information on using the `session` class.)
|
||||
|
||||
#### Single Row Mode
|
||||
|
||||
If this mode is enabled, e.g.
|
||||
|
||||
```cpp
|
||||
session sql(postgresql, "dbname=mydatabase singlerows=true");
|
||||
```
|
||||
|
||||
then queries will be executed in the single-row mode, which prevents the client library from loading full query result sets into memory and instead fetches rows one by one, as they are requested by the statement's fetch() function. This mode can be of interest to those users who want to make their client applications more responsive (with more fine-grained operation) by avoiding potentially long blocking times when complete query results are loaded to client's memory.
|
||||
Note that in the single-row operation:
|
||||
|
||||
* bulk queries are not supported, and
|
||||
* in order to fulfill the expectations of the underlying client library, the complete rowset has to be exhausted before executing further queries on the same session.
|
||||
|
||||
## SOCI Feature Support
|
||||
|
||||
### Dynamic Binding
|
||||
@@ -157,3 +158,11 @@ The PostgreSQL backend provides the following concrete classes for native API ac
|
||||
|
||||
The PostgreSQL backend supports working with data stored in columns of type UUID via simple string operations. All string representations of UUID supported by PostgreSQL are accepted on input, the backend will return the standard
|
||||
format of UUID on output. See the test `test_uuid_column_type_support` for usage examples.
|
||||
|
||||
### Optimizing Prepared Statements Deallocation
|
||||
|
||||
By default, this backend executes `DEALLOCATE` statement for each prepared statement when it is destroyed. This is correct, but may be surprisingly time-consuming and is not necessary for short-running programs as all resources associated with a connection, including any statements prepared by it, are deallocated when it is closed in any case.
|
||||
|
||||
To save time spent on deallocation, `postgresql_session_backend::set_deallocate_prepared_statements(bool)` function can be used to disable automatic deallocation of prepared statements. This function can be called at any time, but will only affect statements destroyed after its call, so it is recommended to do it early.
|
||||
|
||||
Not deallocating prepared statements may lead to memory leaks in long-running programs, so in case of such programs it is recommended to only call `set_deallocate_prepared_statements(false)` before starting a performance-sensitive operation involving many prepared statements, and then call `deallocate_all_prepared_statements()` once the operation is finished and no prepared statements remain, followed by a call to `set_deallocate_prepared_statements(true)` to restore the default behaviour.
|
||||
|
||||
@@ -399,8 +399,24 @@ struct SOCI_POSTGRESQL_DECL postgresql_session_backend : details::session_backen
|
||||
void commit() override;
|
||||
void rollback() override;
|
||||
|
||||
// This PostgreSQL-specific function can be used to prevent statement
|
||||
// deallocation, which happens by default when a prepared statement is
|
||||
// destroyed. This can be used to optimize the running time of short-lived
|
||||
// sessions, but should be avoided for long-running programs as allocated
|
||||
// statements consume server resources.
|
||||
void set_deallocate_prepared_statements(bool deallocate)
|
||||
{
|
||||
deallocatePreparedStatements_ = deallocate;
|
||||
}
|
||||
|
||||
// Does nothing if set_deallocate_prepared_statements(false) was called,
|
||||
// otherwise deallocates the statement with the given name.
|
||||
void deallocate_prepared_statement(const std::string & statementName);
|
||||
|
||||
// Deallocate all prepared statements. This should only be called when no
|
||||
// active statements exist, as it would make them unusable.
|
||||
void deallocate_all_prepared_statements();
|
||||
|
||||
bool get_next_sequence_value(session & s,
|
||||
std::string const & sequence, long long & value) override;
|
||||
|
||||
@@ -420,9 +436,13 @@ struct SOCI_POSTGRESQL_DECL postgresql_session_backend : details::session_backen
|
||||
std::string get_column_descriptions_query() const override;
|
||||
|
||||
int statementCount_;
|
||||
bool deallocatePreparedStatements_ = true;
|
||||
bool single_row_mode_;
|
||||
PGconn * conn_;
|
||||
connection_parameters connectionParameters_;
|
||||
|
||||
// File used for tracing or null if none.
|
||||
FILE* traceFile_ = nullptr;
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <string.h>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <memory>
|
||||
@@ -123,6 +124,13 @@ namespace soci
|
||||
|
||||
#ifdef _MSC_VER
|
||||
|
||||
inline FILE* fopen(const char* filename, const char* mode)
|
||||
{
|
||||
FILE* file = nullptr;
|
||||
fopen_s(&file, filename, mode);
|
||||
return file;
|
||||
}
|
||||
|
||||
inline const char* getenv(const char* name)
|
||||
{
|
||||
#pragma warning(push)
|
||||
@@ -152,6 +160,7 @@ inline char* strncpy(char* dest, const char* src, size_t n)
|
||||
|
||||
#else // !_MSC_VER
|
||||
|
||||
using std::fopen;
|
||||
using std::getenv;
|
||||
using std::sscanf;
|
||||
using std::strncpy;
|
||||
|
||||
@@ -171,16 +171,22 @@ void odbc_session_backend::configure_connection()
|
||||
"\" in unrecognizable format.");
|
||||
}
|
||||
|
||||
details::auto_statement<odbc_statement_backend> st(*this);
|
||||
|
||||
std::string const q(major_ver >= 9 ? "SET extra_float_digits = 3"
|
||||
: "SET extra_float_digits = 2");
|
||||
rc = SQLExecDirect(st.hstmt_, sqlchar_cast(q), static_cast<SQLINTEGER>(q.size()));
|
||||
|
||||
if (is_odbc_error(rc))
|
||||
// As explained in src/backends/postgresql/session.cpp, we need to
|
||||
// increase the number of digits used for floating point values to
|
||||
// ensure that all numbers round trip correctly with old PostgreSQL.
|
||||
if (major_ver < 12)
|
||||
{
|
||||
throw odbc_soci_error(SQL_HANDLE_DBC, henv_,
|
||||
"setting extra_float_digits for PostgreSQL");
|
||||
details::auto_statement<odbc_statement_backend> st(*this);
|
||||
|
||||
std::string const q(major_ver >= 9 ? "SET extra_float_digits = 3"
|
||||
: "SET extra_float_digits = 2");
|
||||
rc = SQLExecDirect(st.hstmt_, sqlchar_cast(q), static_cast<SQLINTEGER>(q.size()));
|
||||
|
||||
if (is_odbc_error(rc))
|
||||
{
|
||||
throw odbc_soci_error(SQL_HANDLE_DBC, henv_,
|
||||
"setting extra_float_digits for PostgreSQL");
|
||||
}
|
||||
}
|
||||
|
||||
// This is extracted from pgapifunc.h header from psqlODBC driver.
|
||||
|
||||
@@ -215,6 +215,28 @@ void postgresql_session_backend::connect(
|
||||
single_row_mode_ = connection_parameters::is_true_value(name, value);
|
||||
}
|
||||
|
||||
if (params.extract_option("tracefile", value) && !value.empty())
|
||||
{
|
||||
const char* mode;
|
||||
if (value.front() == '+')
|
||||
{
|
||||
mode = "a";
|
||||
value.erase(0, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
mode = "w";
|
||||
}
|
||||
|
||||
traceFile_ = fopen(value.c_str(), mode);
|
||||
if (!traceFile_)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Cannot open database trace file: \"" << value << "\".";
|
||||
throw soci_error(oss.str());
|
||||
}
|
||||
}
|
||||
|
||||
// We can't use SOCI connection string with PQconnectdb() directly because
|
||||
// libpq uses single quotes instead of double quotes used by SOCI.
|
||||
PGconn* conn = PQconnectdb(params.build_string_from_options('\'').c_str());
|
||||
@@ -231,6 +253,11 @@ void postgresql_session_backend::connect(
|
||||
throw soci_error(msg);
|
||||
}
|
||||
|
||||
if (traceFile_)
|
||||
{
|
||||
PQtrace(conn, traceFile_);
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// As explained above, implement our own support for this option under
|
||||
// Windows.
|
||||
@@ -278,15 +305,19 @@ void postgresql_session_backend::connect(
|
||||
}
|
||||
#endif // _WIN32
|
||||
|
||||
// Increase the number of digits used for floating point values to ensure
|
||||
// that the conversions to/from text round trip correctly, which is not the
|
||||
// case with the default value of 0. Use the maximal supported value, which
|
||||
// was 2 until 9.x and is 3 since it.
|
||||
// With older PostgreSQL versions we need to change the extra_float_digits
|
||||
// parameter to ensure that the conversions to/from text round trip
|
||||
// losslessly. This is not necessary since 12.0, which behaves correctly by
|
||||
// default, but for older versions use the maximal supported value, which
|
||||
// was 2 until 9.x and 3 after it.
|
||||
int const version = PQserverVersion(conn);
|
||||
hard_exec(*this, conn,
|
||||
version >= 90000 ? "SET extra_float_digits = 3"
|
||||
: "SET extra_float_digits = 2",
|
||||
"Cannot set extra_float_digits parameter");
|
||||
if (version < 120000)
|
||||
{
|
||||
hard_exec(*this, conn,
|
||||
version >= 90000 ? "SET extra_float_digits = 3"
|
||||
: "SET extra_float_digits = 2",
|
||||
"Cannot set extra_float_digits parameter");
|
||||
}
|
||||
|
||||
conn_ = conn;
|
||||
connectionParameters_ = parameters;
|
||||
@@ -329,12 +360,21 @@ void postgresql_session_backend::rollback()
|
||||
void postgresql_session_backend::deallocate_prepared_statement(
|
||||
const std::string & statementName)
|
||||
{
|
||||
if (!deallocatePreparedStatements_)
|
||||
return;
|
||||
|
||||
const std::string & query = "DEALLOCATE " + statementName;
|
||||
|
||||
hard_exec(*this, conn_, query.c_str(),
|
||||
"Cannot deallocate prepared statement.");
|
||||
}
|
||||
|
||||
void postgresql_session_backend::deallocate_all_prepared_statements()
|
||||
{
|
||||
hard_exec(*this, conn_, "DEALLOCATE ALL",
|
||||
"Cannot deallocate all prepared statements.");
|
||||
}
|
||||
|
||||
bool postgresql_session_backend::get_next_sequence_value(
|
||||
session & s, std::string const & sequence, long long & value)
|
||||
{
|
||||
@@ -350,6 +390,12 @@ void postgresql_session_backend::clean_up()
|
||||
PQfinish(conn_);
|
||||
conn_ = 0;
|
||||
}
|
||||
|
||||
if (traceFile_)
|
||||
{
|
||||
std::fclose(traceFile_);
|
||||
traceFile_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::string postgresql_session_backend::get_next_statement_name()
|
||||
|
||||
Reference in New Issue
Block a user