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