userver: storages::postgres::ParameterStore Class Reference
No Matches
storages::postgres::ParameterStore Class Reference

#include <userver/storages/postgres/parameter_store.hpp>

Detailed Description

Class for dynamic PostgreSQL parameter list construction.

Typical use case for this container is to keep parameters around while the query is being constructed on the fly:

template <class ConnectionPtr>
auto ParameterStoreSample(const ConnectionPtr& conn, std::optional<int> a = {},
std::optional<int> b = {}, std::optional<int> c = {},
std::optional<int> d = {},
std::optional<int> e = {}) {
std::string filter;
auto append_if_has_value = [&](std::string_view name, const auto& value) {
if (value) {
auto separator = (parameters.IsEmpty() ? std::string_view{} : " AND ");
// Do NOT put parameters directly into the query! It leads to
// vulnerabilities and bad performance.
filter += fmt::format("{}{}=${}", separator, name, parameters.Size());
append_if_has_value("a", a);
append_if_has_value("b", b);
append_if_has_value("c", c);
append_if_has_value("d", d);
append_if_has_value("e", e);
if (parameters.IsEmpty()) {
throw std::runtime_error("No filters provided");
return conn->Execute("SELECT x FROM some_table WHERE " + filter, parameters);

Note that storages::postgres::Cluster::Execute with explicitly provided arguments works slightly faster:

std::size_t InsertSomeKey(storages::postgres::Cluster& pg,
std::string_view key) {
"INSERT INTO keys VALUES ($1)", key);
return res.RowsAffected();

Definition at line 26 of file parameter_store.hpp.

Public Member Functions

 ParameterStore (const ParameterStore &)=delete
 ParameterStore (ParameterStore &&)=default
ParameterStoreoperator= (const ParameterStore &)=delete
ParameterStoreoperator= (ParameterStore &&)=default
template<typename T >
ParameterStorePushBack (const T &param)
 Adds a parameter to the end of the parameter list.
bool IsEmpty () const
 Returns whether the parameter list is empty.
size_t Size () const
 Returns current size of the list.

Member Function Documentation

◆ IsEmpty()

bool storages::postgres::ParameterStore::IsEmpty ( ) const

Returns whether the parameter list is empty.

Definition at line 46 of file parameter_store.hpp.

◆ PushBack()

template<typename T >
ParameterStore & storages::postgres::ParameterStore::PushBack ( const T & param)

Adds a parameter to the end of the parameter list.

Currently only built-in/system types are supported.

Definition at line 37 of file parameter_store.hpp.

◆ Size()

size_t storages::postgres::ParameterStore::Size ( ) const

Returns current size of the list.

Definition at line 49 of file parameter_store.hpp.

The documentation for this class was generated from the following file: