userver: userver/storages/postgres/transaction.hpp Source File
Loading...
Searching...
No Matches
transaction.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/postgres/transaction.hpp
4/// @brief Transactions
5
6#include <memory>
7#include <string>
8
9#include <userver/storages/postgres/detail/connection_ptr.hpp>
10#include <userver/storages/postgres/detail/query_parameters.hpp>
11#include <userver/storages/postgres/detail/time_types.hpp>
12#include <userver/storages/postgres/options.hpp>
13#include <userver/storages/postgres/parameter_store.hpp>
14#include <userver/storages/postgres/portal.hpp>
15#include <userver/storages/postgres/postgres_fwd.hpp>
16#include <userver/storages/postgres/query.hpp>
17#include <userver/storages/postgres/result_set.hpp>
18#include <userver/utils/trx_tracker.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22namespace storages::postgres {
23
24/// @page pg_transactions uPg: Transactions
25///
26/// All queries that are run on a PostgreSQL cluster are executed inside
27/// a transaction, even if a single-query interface is used.
28///
29/// A uPg transaction can be started using all isolation levels and modes
30/// supported by PostgreSQL server as specified in documentation here
31/// https://www.postgresql.org/docs/current/static/sql-set-transaction.html.
32/// When starting a transaction, the options are specified using
33/// TransactionOptions structure.
34///
35/// For convenience and improvement of readability there are constants
36/// defined: Transaction::RW, Transaction::RO and Transaction::Deferrable.
37///
38/// @see TransactionOptions
39///
40/// Transaction object ensures that a transaction started in a PostgreSQL
41/// connection will be either committed or rolled back and the connection
42/// will returned back to a connection pool.
43///
44/// @todo Code snippet with transaction starting and committing
45///
46/// Next: @ref pg_run_queries
47///
48/// See also: @ref pg_process_results
49///
50/// ----------
51///
52/// @htmlonly <div class="bottom-nav"> @endhtmlonly
53/// ⇦ @ref pg_driver | @ref pg_run_queries ⇨
54/// @htmlonly </div> @endhtmlonly
55
56/// @page pg_run_queries uPg: Running queries
57///
58/// All queries are executed through a transaction object, event when being
59/// executed through singe-query interface, so here only executing queries
60/// with transaction will be covered. Single-query interface is basically
61/// the same except for additional options.
62///
63/// uPg provides means to execute text queries only. There is no query
64/// generation, but can be used by other tools to execute SQL queries.
65///
66/// @warning A query must contain a single query, multiple statements delimited
67/// by ';' are not supported.
68///
69/// All queries are parsed and prepared during the first invocation and are
70/// executed as prepared statements afterwards.
71///
72/// Any query execution can throw an exception. Please see @ref pg_errors for
73/// more information on possible errors.
74///
75/// @par Queries without parameters
76///
77/// Executing a query without any parameters is rather straightforward.
78/// @code
79/// auto trx = cluster->Begin(/* transaction options */);
80/// auto res = trx.Execute("select foo, bar from foobar");
81/// trx.Commit();
82/// @endcode
83///
84/// The cluster also provides interface for single queries
85/// @code
86/// #include <service/sql_queries.hpp>
87///
88/// auto res = cluster->Execute(/* transaction options */, sql::kMyQuery);
89/// @endcode
90///
91/// You may store SQL queries in separate `.sql` files and access them via
92/// sql_queries.hpp include header. See @ref scripts/docs/en/userver/sql_files.md
93/// for more information.
94///
95/// @par Queries with parameters
96///
97/// uPg supports SQL dollar notation for parameter placeholders. The statement
98/// is prepared at first execution and then only arguments for a query is sent
99/// to the server.
100///
101/// A parameter can be of any type that is supported by the driver.
102/// See @ref scripts/docs/en/userver/pg_types.md for more information.
103///
104/// @code
105/// auto trx = cluster->Begin(/* transaction options */);
106/// auto res = trx.Execute(
107/// "select foo, bar from foobar where foo > $1 and bar = $2", 42, "baz");
108/// trx.Commit();
109/// @endcode
110///
111/// @note You may write a query in `.sql` file and generate a header file with Query from it.
112/// See @ref scripts/docs/en/userver/sql_files.md for more information.
113/// @see Transaction
114/// @see ResultSet
115///
116/// ----------
117///
118/// @htmlonly <div class="bottom-nav"> @endhtmlonly
119/// ⇦ @ref pg_transactions | @ref pg_process_results ⇨
120/// @htmlonly </div> @endhtmlonly
121
122// clang-format off
123/// @brief PostgreSQL transaction.
124///
125/// RAII wrapper for running transactions on PostgreSQL connections. Should be
126/// retrieved by calling storages::postgres::Cluster::Begin().
127///
128/// Non-copyable.
129///
130/// If the transaction is not explicitly finished (either committed or rolled back)
131/// it will roll itself back in the destructor.
132///
133/// @par Usage synopsis
134/// @code
135/// auto trx = someCluster.Begin(/* transaction options */);
136/// auto res = trx.Execute("select col1, col2 from schema.table");
137/// DoSomething(res);
138/// res = trx.Execute("update schema.table set col1 = $1 where col2 = $2", v1, v2);
139/// // If in the above lines an exception is thrown, then the transaction is
140/// // rolled back in the destructor of trx.
141/// trx.Commit();
142/// @endcode
143// clang-format on
144
146public:
147 //@{
148 /** @name Shortcut transaction options constants */
149 /// Read-write read committed transaction
150 static constexpr TransactionOptions RW{};
151 /// Read-only read committed transaction
152 static constexpr TransactionOptions RO{TransactionOptions::kReadOnly};
153 /// Read-only serializable deferrable transaction
155 //@}
156
157 static constexpr std::size_t kDefaultRowsInChunk = 1024;
158
159 /// @cond
160 explicit Transaction(
161 detail::ConnectionPtr&& conn,
162 const TransactionOptions& = RW,
163 OptionalCommandControl trx_cmd_ctl = {},
164 detail::SteadyClock::time_point trx_start_time = detail::SteadyClock::now()
165 );
166
167 void SetName(std::string name);
168 /// @endcond
169
170 Transaction(Transaction&&) noexcept;
171 Transaction& operator=(Transaction&&) noexcept;
172
173 Transaction(const Transaction&) = delete;
174 Transaction& operator=(const Transaction&) = delete;
175
176 ~Transaction();
177 /// @name Query execution
178 /// @{
179 /// Execute statement with arbitrary parameters.
180 ///
181 /// Suspends coroutine for execution.
182 ///
183 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
184 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
185 ///
186 /// @snippet storages/postgres/tests/landing_test.cpp TransacExec
187 template <typename... Args>
188 ResultSet Execute(const Query& query, const Args&... args) {
189 return Execute(OptionalCommandControl{}, query, args...);
190 }
191
192 /// Execute statement with arbitrary parameters and per-statement command
193 /// control.
194 ///
195 /// Suspends coroutine for execution.
196 ///
197 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
198 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
199 ///
200 /// @warning Do NOT create a query string manually by embedding arguments!
201 /// It leads to vulnerabilities and bad performance. Either pass arguments
202 /// separately, or use storages::postgres::ParameterScope.
203 template <typename... Args>
204 ResultSet Execute(OptionalCommandControl statement_cmd_ctl, const Query& query, const Args&... args) {
205 detail::StaticQueryParameters<sizeof...(args)> params;
206 params.Write(GetConnectionUserTypes(), args...);
207 return DoExecute(query, detail::QueryParameters{params}, statement_cmd_ctl);
208 }
209
210 /// Execute statement with stored parameters.
211 ///
212 /// Suspends coroutine for execution.
213 ///
214 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
215 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
216 ///
217 /// @warning Do NOT create a query string manually by embedding arguments!
218 /// It leads to vulnerabilities and bad performance. Either pass arguments
219 /// separately, or use storages::postgres::ParameterScope.
220 ResultSet Execute(const Query& query, const ParameterStore& store) {
221 return Execute(OptionalCommandControl{}, query, store);
222 }
223
224 /// Execute statement with stored parameters and per-statement command
225 /// control.
226 ///
227 /// Suspends coroutine for execution.
228 ///
229 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
230 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
231 ///
232 /// @warning Do NOT create a query string manually by embedding arguments!
233 /// It leads to vulnerabilities and bad performance. Either pass arguments
234 /// separately, or use storages::postgres::ParameterScope.
235 ResultSet Execute(OptionalCommandControl statement_cmd_ctl, const Query& query, const ParameterStore& store);
236
237 /// Execute statement that uses an array of arguments transforming that array
238 /// into N arrays of corresponding fields and executing the statement
239 /// with these arrays values.
240 /// Basically, a column-wise Execute.
241 ///
242 /// Useful for statements that unnest their arguments to avoid the need to
243 /// increase timeouts due to data amount growth, but providing an explicit
244 /// mapping from `Container::value_type` to PG type is infeasible for some
245 /// reason (otherwise, use Execute).
246 ///
247 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
248 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
249 ///
250 /// @snippet storages/postgres/tests/arrays_pgtest.cpp ExecuteDecomposeTrx
251 template <typename Container>
252 ResultSet ExecuteDecompose(const Query& query, const Container& args);
253
254 /// Execute statement that uses an array of arguments transforming that array
255 /// into N arrays of corresponding fields and executing the statement
256 /// with these arrays values.
257 /// Basically, a column-wise Execute.
258 ///
259 /// Useful for statements that unnest their arguments to avoid the need to
260 /// increase timeouts due to data amount growth, but providing an explicit
261 /// mapping from `Container::value_type` to PG type is infeasible for some
262 /// reason (otherwise, use Execute).
263 ///
264 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
265 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
266 ///
267 /// @snippet storages/postgres/tests/arrays_pgtest.cpp ExecuteDecomposeTrx
268 template <typename Container>
269 ResultSet ExecuteDecompose(OptionalCommandControl statement_cmd_ctl, const Query& query, const Container& args);
270
271 /// Execute statement that uses an array of arguments splitting that array in
272 /// chunks and executing the statement with a chunk of arguments.
273 ///
274 /// Useful for statements that unnest their arguments to avoid the need to
275 /// increase timeouts due to data amount growth.
276 ///
277 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
278 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
279 template <typename Container>
280 void ExecuteBulk(const Query& query, const Container& args, std::size_t chunk_rows = kDefaultRowsInChunk);
281
282 /// Execute statement that uses an array of arguments splitting that array in
283 /// chunks and executing the statement with a chunk of arguments.
284 ///
285 /// Useful for statements that unnest their arguments to avoid the need to
286 /// increase timeouts due to data amount growth.
287 ///
288 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
289 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
290 template <typename Container>
291 void ExecuteBulk(
292 OptionalCommandControl statement_cmd_ctl,
293 const Query& query,
294 const Container& args,
295 std::size_t chunk_rows = kDefaultRowsInChunk
296 );
297
298 /// Execute statement that uses an array of arguments transforming that array
299 /// into N arrays of corresponding fields and executing the statement
300 /// with a chunk of each of these arrays values.
301 /// Basically, a column-wise ExecuteBulk.
302 ///
303 /// Useful for statements that unnest their arguments to avoid the need to
304 /// increase timeouts due to data amount growth, but providing an explicit
305 /// mapping from `Container::value_type` to PG type is infeasible for some
306 /// reason (otherwise, use ExecuteBulk).
307 ///
308 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
309 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
310 ///
311 /// @snippet storages/postgres/tests/arrays_pgtest.cpp ExecuteDecomposeBulk
312 template <typename Container>
313 void ExecuteDecomposeBulk(const Query& query, const Container& args, std::size_t chunk_rows = kDefaultRowsInChunk);
314
315 /// Execute statement that uses an array of arguments transforming that array
316 /// into N arrays of corresponding fields and executing the statement
317 /// with a chunk of each of these arrays values.
318 /// Basically, a column-wise ExecuteBulk.
319 ///
320 /// Useful for statements that unnest their arguments to avoid the need to
321 /// increase timeouts due to data amount growth, but providing an explicit
322 /// mapping from `Container::value_type` to PG type is infeasible for some
323 /// reason (otherwise, use ExecuteBulk).
324 ///
325 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
326 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
327 ///
328 /// @snippet storages/postgres/tests/arrays_pgtest.cpp ExecuteDecomposeBulk
329 template <typename Container>
331 OptionalCommandControl statement_cmd_ctl,
332 const Query& query,
333 const Container& args,
334 std::size_t chunk_rows = kDefaultRowsInChunk
335 );
336
337 /// @brief Create a portal for fetching results of a statement with arbitrary
338 /// parameters.
339 ///
340 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
341 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
342 template <typename... Args>
343 Portal MakePortal(const Query& query, const Args&... args) {
344 return MakePortal(OptionalCommandControl{}, query, args...);
345 }
346
347 /// @brief Create a portal for fetching results of a statement with arbitrary
348 /// parameters and per-statement command control.
349 ///
350 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
351 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
352 template <typename... Args>
353 Portal MakePortal(OptionalCommandControl statement_cmd_ctl, const Query& query, const Args&... args) {
354 detail::StaticQueryParameters<sizeof...(args)> params;
355 params.Write(GetConnectionUserTypes(), args...);
356 return MakePortal(PortalName{}, query, detail::QueryParameters{params}, statement_cmd_ctl);
357 }
358
359 /// @brief Create a portal for fetching results of a statement with stored
360 /// parameters.
361 ///
362 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
363 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
364 Portal MakePortal(const Query& query, const ParameterStore& store) {
365 return MakePortal(OptionalCommandControl{}, query, store);
366 }
367
368 /// @brief Create a portal for fetching results of a statement with stored parameters
369 /// and per-statement command control.
370 ///
371 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
372 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
373 Portal MakePortal(OptionalCommandControl statement_cmd_ctl, const Query& query, const ParameterStore& store);
374
375 /// Set a connection parameter
376 /// https://www.postgresql.org/docs/current/sql-set.html
377 /// The parameter is set for this transaction only
378 void SetParameter(const std::string& param_name, const std::string& value);
379 //@}
380
381 /// Commit the transaction
382 /// Suspends coroutine until command complete.
383 /// After Commit or Rollback is called, the transaction is not usable any
384 /// more.
385 void Commit();
386 /// Rollback the transaction
387 /// Suspends coroutine until command complete.
388 /// After Commit or Rollback is called, the transaction is not usable any
389 /// more.
390 void Rollback();
391
392 /// Used in tests
393 OptionalCommandControl GetConnTransactionCommandControlDebug() const;
394 TimeoutDuration GetConnStatementTimeoutDebug() const;
395
396private:
398 DoExecute(const Query& query, const detail::QueryParameters& params, OptionalCommandControl statement_cmd_ctl);
399 Portal MakePortal(
400 const PortalName&,
401 const Query& query,
402 const detail::QueryParameters& params,
403 OptionalCommandControl statement_cmd_ctl
404 );
405
406 const UserTypes& GetConnectionUserTypes() const;
407
408 std::string name_;
409 detail::ConnectionPtr conn_;
410 USERVER_NAMESPACE::utils::trx_tracker::TransactionLock trx_lock_;
411};
412
413template <typename Container>
414ResultSet Transaction::ExecuteDecompose(const Query& query, const Container& args) {
415 return io::DecomposeContainerByColumns(args).Perform([&query, this](const auto&... args) {
416 return this->Execute(query, args...);
417 });
418}
419
420template <typename Container>
422Transaction::ExecuteDecompose(OptionalCommandControl statement_cmd_ctl, const Query& query, const Container& args) {
423 return io::DecomposeContainerByColumns(args).Perform([&query, &statement_cmd_ctl, this](const auto&... args) {
424 return this->Execute(statement_cmd_ctl, query, args...);
425 });
426}
427
428template <typename Container>
429void Transaction::ExecuteBulk(const Query& query, const Container& args, std::size_t chunk_rows) {
430 auto split = io::SplitContainer(args, chunk_rows);
431 for (auto&& chunk : split) {
432 Execute(query, chunk);
433 }
434}
435
436template <typename Container>
438 OptionalCommandControl statement_cmd_ctl,
439 const Query& query,
440 const Container& args,
441 std::size_t chunk_rows
442) {
443 auto split = io::SplitContainer(args, chunk_rows);
444 for (auto&& chunk : split) {
445 Execute(statement_cmd_ctl, query, chunk);
446 }
447}
448
449template <typename Container>
450void Transaction::ExecuteDecomposeBulk(const Query& query, const Container& args, std::size_t chunk_rows) {
451 io::SplitContainerByColumns(args, chunk_rows).Perform([&query, this](const auto&... args) {
452 this->Execute(query, args...);
453 });
454}
455
456template <typename Container>
458 OptionalCommandControl statement_cmd_ctl,
459 const Query& query,
460 const Container& args,
461 std::size_t chunk_rows
462) {
463 io::SplitContainerByColumns(args, chunk_rows).Perform([&query, &statement_cmd_ctl, this](const auto&... args) {
464 this->Execute(statement_cmd_ctl, query, args...);
465 });
466}
467
468} // namespace storages::postgres
469
470USERVER_NAMESPACE_END