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{}; // NOLINT(readability-identifier-naming)
151 /// Read-only read committed transaction
152 static constexpr TransactionOptions RO{TransactionOptions::kReadOnly}; // NOLINT(readability-identifier-naming)
153 /// Read-only serializable deferrable transaction
154 static constexpr TransactionOptions Deferrable{// NOLINT(readability-identifier-naming)
156 //@}
157
158 static constexpr std::size_t kDefaultRowsInChunk = 1024;
159
160 /// @cond
161 explicit Transaction(
162 detail::ConnectionPtr&& conn,
163 const TransactionOptions& = RW,
164 OptionalCommandControl trx_cmd_ctl = {},
165 detail::SteadyClock::time_point trx_start_time = detail::SteadyClock::now()
166 );
167
168 void SetName(std::string name);
169 /// @endcond
170
171 Transaction(Transaction&&) noexcept;
172 Transaction& operator=(Transaction&&) noexcept;
173
174 Transaction(const Transaction&) = delete;
175 Transaction& operator=(const Transaction&) = delete;
176
177 ~Transaction();
178 /// @name Query execution
179 /// @{
180 /// Execute statement with arbitrary parameters.
181 ///
182 /// Suspends coroutine for execution.
183 ///
184 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
185 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
186 ///
187 /// @snippet storages/postgres/tests/landing_test.cpp TransacExec
188 template <typename... Args>
189 ResultSet Execute(const Query& query, const Args&... args) {
190 return Execute(OptionalCommandControl{}, query, args...);
191 }
192
193 /// Execute statement with arbitrary parameters and per-statement command
194 /// control.
195 ///
196 /// Suspends coroutine for execution.
197 ///
198 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
199 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
200 ///
201 /// @warning Do NOT create a query string manually by embedding arguments!
202 /// It leads to vulnerabilities and bad performance. Either pass arguments
203 /// separately, or use storages::postgres::ParameterScope.
204 template <typename... Args>
205 ResultSet Execute(OptionalCommandControl statement_cmd_ctl, const Query& query, const Args&... args) {
206 detail::StaticQueryParameters<sizeof...(args)> params;
207 params.Write(GetConnectionUserTypes(), args...);
208 return DoExecute(query, detail::QueryParameters{params}, statement_cmd_ctl);
209 }
210
211 /// Execute statement with stored parameters.
212 ///
213 /// Suspends coroutine for execution.
214 ///
215 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
216 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
217 ///
218 /// @warning Do NOT create a query string manually by embedding arguments!
219 /// It leads to vulnerabilities and bad performance. Either pass arguments
220 /// separately, or use storages::postgres::ParameterScope.
221 ResultSet Execute(const Query& query, const ParameterStore& store) {
222 return Execute(OptionalCommandControl{}, query, store);
223 }
224
225 /// Execute statement with stored parameters and per-statement command
226 /// control.
227 ///
228 /// Suspends coroutine for execution.
229 ///
230 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
231 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
232 ///
233 /// @warning Do NOT create a query string manually by embedding arguments!
234 /// It leads to vulnerabilities and bad performance. Either pass arguments
235 /// separately, or use storages::postgres::ParameterScope.
236 ResultSet Execute(OptionalCommandControl statement_cmd_ctl, const Query& query, const ParameterStore& store);
237
238 /// Execute statement that uses an array of arguments transforming that array
239 /// into N arrays of corresponding fields and executing the statement
240 /// with these arrays values.
241 /// Basically, a column-wise Execute.
242 ///
243 /// Useful for statements that unnest their arguments to avoid the need to
244 /// increase timeouts due to data amount growth, but providing an explicit
245 /// mapping from `Container::value_type` to PG type is infeasible for some
246 /// reason (otherwise, use Execute).
247 ///
248 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
249 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
250 ///
251 /// @snippet storages/postgres/tests/arrays_pgtest.cpp ExecuteDecomposeTrx
252 template <typename Container>
253 ResultSet ExecuteDecompose(const Query& query, const Container& args);
254
255 /// Execute statement that uses an array of arguments transforming that array
256 /// into N arrays of corresponding fields and executing the statement
257 /// with these arrays values.
258 /// Basically, a column-wise Execute.
259 ///
260 /// Useful for statements that unnest their arguments to avoid the need to
261 /// increase timeouts due to data amount growth, but providing an explicit
262 /// mapping from `Container::value_type` to PG type is infeasible for some
263 /// reason (otherwise, use Execute).
264 ///
265 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
266 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
267 ///
268 /// @snippet storages/postgres/tests/arrays_pgtest.cpp ExecuteDecomposeTrx
269 template <typename Container>
270 ResultSet ExecuteDecompose(OptionalCommandControl statement_cmd_ctl, const Query& query, const Container& args);
271
272 /// Execute statement that uses an array of arguments splitting that array in
273 /// chunks and executing the statement with a chunk of arguments.
274 ///
275 /// Useful for statements that unnest their arguments to avoid the need to
276 /// increase timeouts due to data amount growth.
277 ///
278 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
279 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
280 template <typename Container>
281 void ExecuteBulk(const Query& query, const Container& args, std::size_t chunk_rows = kDefaultRowsInChunk);
282
283 /// Execute statement that uses an array of arguments splitting that array in
284 /// chunks and executing the statement with a chunk of arguments.
285 ///
286 /// Useful for statements that unnest their arguments to avoid the need to
287 /// increase timeouts due to data amount growth.
288 ///
289 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
290 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
291 template <typename Container>
292 void ExecuteBulk(
293 OptionalCommandControl statement_cmd_ctl,
294 const Query& query,
295 const Container& args,
296 std::size_t chunk_rows = kDefaultRowsInChunk
297 );
298
299 /// Execute statement that uses an array of arguments transforming that array
300 /// into N arrays of corresponding fields and executing the statement
301 /// with a chunk of each of these arrays values.
302 /// Basically, a column-wise ExecuteBulk.
303 ///
304 /// Useful for statements that unnest their arguments to avoid the need to
305 /// increase timeouts due to data amount growth, but providing an explicit
306 /// mapping from `Container::value_type` to PG type is infeasible for some
307 /// reason (otherwise, use ExecuteBulk).
308 ///
309 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
310 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
311 ///
312 /// @snippet storages/postgres/tests/arrays_pgtest.cpp ExecuteDecomposeBulk
313 template <typename Container>
314 void ExecuteDecomposeBulk(const Query& query, const Container& args, std::size_t chunk_rows = kDefaultRowsInChunk);
315
316 /// Execute statement that uses an array of arguments transforming that array
317 /// into N arrays of corresponding fields and executing the statement
318 /// with a chunk of each of these arrays values.
319 /// Basically, a column-wise ExecuteBulk.
320 ///
321 /// Useful for statements that unnest their arguments to avoid the need to
322 /// increase timeouts due to data amount growth, but providing an explicit
323 /// mapping from `Container::value_type` to PG type is infeasible for some
324 /// reason (otherwise, use ExecuteBulk).
325 ///
326 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
327 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
328 ///
329 /// @snippet storages/postgres/tests/arrays_pgtest.cpp ExecuteDecomposeBulk
330 template <typename Container>
332 OptionalCommandControl statement_cmd_ctl,
333 const Query& query,
334 const Container& args,
335 std::size_t chunk_rows = kDefaultRowsInChunk
336 );
337
338 /// @brief Create a portal for fetching results of a statement with arbitrary
339 /// parameters.
340 ///
341 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
342 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
343 template <typename... Args>
344 Portal MakePortal(const Query& query, const Args&... args) {
345 return MakePortal(OptionalCommandControl{}, query, args...);
346 }
347
348 /// @brief Create a portal for fetching results of a statement with arbitrary
349 /// parameters and per-statement command control.
350 ///
351 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
352 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
353 template <typename... Args>
354 Portal MakePortal(OptionalCommandControl statement_cmd_ctl, const Query& query, const Args&... args) {
355 detail::StaticQueryParameters<sizeof...(args)> params;
356 params.Write(GetConnectionUserTypes(), args...);
357 return MakePortal(PortalName{}, query, detail::QueryParameters{params}, statement_cmd_ctl);
358 }
359
360 /// @brief Create a portal for fetching results of a statement with stored
361 /// parameters.
362 ///
363 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
364 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
365 Portal MakePortal(const Query& query, const ParameterStore& store) {
366 return MakePortal(OptionalCommandControl{}, query, store);
367 }
368
369 /// @brief Create a portal for fetching results of a statement with stored parameters
370 /// and per-statement command control.
371 ///
372 /// @note You may write a query in `.sql` file and generate a header file with Query from it.
373 /// See @ref scripts/docs/en/userver/sql_files.md for more information.
374 Portal MakePortal(OptionalCommandControl statement_cmd_ctl, const Query& query, const ParameterStore& store);
375
376 /// Set a connection parameter
377 /// https://www.postgresql.org/docs/current/sql-set.html
378 /// The parameter is set for this transaction only
379 void SetParameter(const std::string& param_name, const std::string& value);
380 //@}
381
382 /// Commit the transaction
383 /// Suspends coroutine until command complete.
384 /// After Commit or Rollback is called, the transaction is not usable any
385 /// more.
386 void Commit();
387 /// Rollback the transaction
388 /// Suspends coroutine until command complete.
389 /// After Commit or Rollback is called, the transaction is not usable any
390 /// more.
391 void Rollback();
392
393 /// Used in tests
394 OptionalCommandControl GetConnTransactionCommandControlDebug() const;
395 TimeoutDuration GetConnStatementTimeoutDebug() const;
396
397private:
399 DoExecute(const Query& query, const detail::QueryParameters& params, OptionalCommandControl statement_cmd_ctl);
400 Portal MakePortal(
401 const PortalName&,
402 const Query& query,
403 const detail::QueryParameters& params,
404 OptionalCommandControl statement_cmd_ctl
405 );
406
407 const UserTypes& GetConnectionUserTypes() const;
408
409 std::string name_;
410 detail::ConnectionPtr conn_;
411 USERVER_NAMESPACE::utils::trx_tracker::TransactionLock trx_lock_;
412};
413
414template <typename Container>
415ResultSet Transaction::ExecuteDecompose(const Query& query, const Container& args) {
416 return io::DecomposeContainerByColumns(args).Perform([&query, this](const auto&... args) {
417 return this->Execute(query, args...);
418 });
419}
420
421template <typename Container>
423Transaction::ExecuteDecompose(OptionalCommandControl statement_cmd_ctl, const Query& query, const Container& args) {
424 return io::DecomposeContainerByColumns(args).Perform([&query, &statement_cmd_ctl, this](const auto&... args) {
425 return this->Execute(statement_cmd_ctl, query, args...);
426 });
427}
428
429template <typename Container>
430void Transaction::ExecuteBulk(const Query& query, const Container& args, std::size_t chunk_rows) {
431 auto split = io::SplitContainer(args, chunk_rows);
432 for (auto&& chunk : split) {
433 Execute(query, chunk);
434 }
435}
436
437template <typename Container>
439 OptionalCommandControl statement_cmd_ctl,
440 const Query& query,
441 const Container& args,
442 std::size_t chunk_rows
443) {
444 auto split = io::SplitContainer(args, chunk_rows);
445 for (auto&& chunk : split) {
446 Execute(statement_cmd_ctl, query, chunk);
447 }
448}
449
450template <typename Container>
451void Transaction::ExecuteDecomposeBulk(const Query& query, const Container& args, std::size_t chunk_rows) {
452 io::SplitContainerByColumns(args, chunk_rows).Perform([&query, this](const auto&... args) {
453 this->Execute(query, args...);
454 });
455}
456
457template <typename Container>
459 OptionalCommandControl statement_cmd_ctl,
460 const Query& query,
461 const Container& args,
462 std::size_t chunk_rows
463) {
464 io::SplitContainerByColumns(args, chunk_rows).Perform([&query, &statement_cmd_ctl, this](const auto&... args) {
465 this->Execute(statement_cmd_ctl, query, args...);
466 });
467}
468
469} // namespace storages::postgres
470
471USERVER_NAMESPACE_END