format_sql.hpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. //
  2. // Copyright (c) 2019-2025 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BOOST_MYSQL_FORMAT_SQL_HPP
  8. #define BOOST_MYSQL_FORMAT_SQL_HPP
  9. #include <boost/mysql/character_set.hpp>
  10. #include <boost/mysql/constant_string_view.hpp>
  11. #include <boost/mysql/error_code.hpp>
  12. #include <boost/mysql/string_view.hpp>
  13. #include <boost/mysql/detail/access.hpp>
  14. #include <boost/mysql/detail/config.hpp>
  15. #include <boost/mysql/detail/format_sql.hpp>
  16. #include <boost/mysql/detail/output_string.hpp>
  17. #include <boost/config.hpp>
  18. #include <boost/core/span.hpp>
  19. #include <boost/system/result.hpp>
  20. #include <initializer_list>
  21. #include <string>
  22. #include <type_traits>
  23. #include <utility>
  24. namespace boost {
  25. namespace mysql {
  26. /**
  27. * \brief An extension point to customize SQL formatting.
  28. * \details
  29. * This type can be specialized for custom types to make them formattable.
  30. * This makes them satisfy the `Formattable` concept, and thus usable in
  31. * \ref format_sql and similar functions.
  32. * \n
  33. * A `formatter` specialization for a type `T` should have the following form:
  34. * ```
  35. * template <>
  36. * struct formatter<T>
  37. * {
  38. * const char* parse(const char* begin, const char* end); // parse format specs
  39. * void format(const T& value, format_context_base& ctx) const; // perform the actual formatting
  40. * };
  41. * ```
  42. * \n
  43. * When a value with a custom formatter is formatted (using \ref format_sql or a similar
  44. * function), the library performs the following actions: \n
  45. * - An instance of `formatter<T>` is default-constructed, where `T` is the type of the
  46. * value being formatted after removing const and references.
  47. * - The `parse` function is invoked on the constructed instance,
  48. * with `[begin, end)` pointing to the format specifier
  49. * that the current replacement field has. If `parse` finds specifiers it understands, it should
  50. * remember them, usually setting some flag in the `formatter` instance.
  51. * `parse` must return an iterator to the first
  52. * unparsed character in the range (or the `end` iterator, if everything was parsed).
  53. * Some examples of what would get passed to `parse`:
  54. * - In `"SELECT {}"`, the range would be empty.
  55. * - In `"SELECT {:abc}"`, the range would be `"abc"`.
  56. * - In `"SELECT {0:i}"`, the range would be `"i"`.
  57. * - If `parse` didn't manage to parse all the passed specifiers (i.e. if it returned an iterator
  58. * different to the passed's end), a \ref client_errc::format_string_invalid_specifier
  59. * is emitted and the format operation finishes.
  60. * - Otherwise, `format` is invoked on the formatter instance, passing the value to be formatted
  61. * and the \ref format_context_base where format operation is running.
  62. * This function should perform the actual formatting, usually calling
  63. * \ref format_sql_to on the passed context.
  64. *
  65. * \n
  66. * Don't specialize `formatter` for built-in types, like `int`, `std::string` or
  67. * optionals (formally, any type satisfying `WritableField`), as the specializations will be ignored.
  68. */
  69. template <class T>
  70. struct formatter
  71. #ifndef BOOST_MYSQL_DOXYGEN
  72. : detail::formatter_is_unspecialized
  73. {
  74. }
  75. #endif
  76. ;
  77. /**
  78. * \brief A type-erased reference to a `Formattable` value.
  79. * \details
  80. * This type can hold references to any value that satisfies the `Formattable`
  81. * concept. The `formattable_ref` type itself satisfies `Formattable`,
  82. * and can thus be used as an argument to format functions.
  83. *
  84. * \par Object lifetimes
  85. * This is a non-owning type. It should be only used as a function argument,
  86. * to avoid lifetime issues.
  87. */
  88. class formattable_ref
  89. {
  90. detail::formattable_ref_impl impl_;
  91. #ifndef BOOST_MYSQL_DOXYGEN
  92. friend struct detail::access;
  93. #endif
  94. public:
  95. /**
  96. * \brief Constructor.
  97. * \details
  98. * Constructs a type-erased formattable reference from a concrete
  99. * `Formattable` type.
  100. * \n
  101. * This constructor participates in overload resolution only if
  102. * the passed value meets the `Formattable` concept and
  103. * is not a `formattable_ref` or a reference to one.
  104. *
  105. * \par Exception safety
  106. * No-throw guarantee.
  107. *
  108. * \par Object lifetimes
  109. * value is potentially stored as a view, although some cheap-to-copy
  110. * types may be stored as values.
  111. */
  112. template <
  113. BOOST_MYSQL_FORMATTABLE Formattable
  114. #ifndef BOOST_MYSQL_DOXYGEN
  115. ,
  116. class = typename std::enable_if<
  117. detail::is_formattable_type<Formattable>() &&
  118. !detail::is_formattable_ref<Formattable>::value>::type
  119. #endif
  120. >
  121. formattable_ref(Formattable&& value) noexcept
  122. : impl_(detail::make_formattable_ref(std::forward<Formattable>(value)))
  123. {
  124. }
  125. };
  126. /**
  127. * \brief A named format argument, to be used in initializer lists.
  128. * \details
  129. * Represents a name, value pair to be passed to a formatting function.
  130. * This type should only be used in initializer lists, as a function argument.
  131. *
  132. * \par Object lifetimes
  133. * This is a non-owning type. Both the argument name and value are stored
  134. * as views.
  135. */
  136. class format_arg
  137. {
  138. #ifndef BOOST_MYSQL_DOXYGEN
  139. struct
  140. {
  141. string_view name;
  142. detail::formattable_ref_impl value;
  143. } impl_;
  144. friend struct detail::access;
  145. #endif
  146. public:
  147. /**
  148. * \brief Constructor.
  149. * \details
  150. * Constructs an argument from a name and a value.
  151. *
  152. * \par Exception safety
  153. * No-throw guarantee.
  154. *
  155. * \par Object lifetimes
  156. * Both `name` and `value` are stored as views.
  157. */
  158. format_arg(string_view name, formattable_ref value) noexcept
  159. : impl_{name, detail::access::get_impl(value)}
  160. {
  161. }
  162. };
  163. /**
  164. * \brief Base class for concrete format contexts.
  165. * \details
  166. * Conceptually, a format context contains: \n
  167. * \li The result string. Output operations append characters to this output string.
  168. * `format_context_base` is agnostic to the output string type.
  169. * \li \ref format_options required to format values.
  170. * \li An error state (\ref error_state) that is set by output operations when they fail.
  171. * The error state is propagated to \ref basic_format_context::get.
  172. * \n
  173. * References to this class are useful when you need to manipulate
  174. * a format context without knowing the type of the actual context that will be used,
  175. * like when specializing \ref formatter.
  176. * \n
  177. * This class can't be
  178. * instantiated directly - use \ref basic_format_context, instead.
  179. * Do not subclass it, either.
  180. */
  181. class format_context_base
  182. {
  183. #ifndef BOOST_MYSQL_DOXYGEN
  184. struct
  185. {
  186. detail::output_string_ref output;
  187. format_options opts;
  188. error_code ec;
  189. } impl_;
  190. friend struct detail::access;
  191. friend class detail::format_state;
  192. #endif
  193. BOOST_MYSQL_DECL void format_arg(detail::formattable_ref_impl arg, string_view format_spec);
  194. protected:
  195. format_context_base(detail::output_string_ref out, format_options opts, error_code ec = {}) noexcept
  196. : impl_{out, opts, ec}
  197. {
  198. }
  199. format_context_base(detail::output_string_ref out, const format_context_base& rhs) noexcept
  200. : impl_{out, rhs.impl_.opts, rhs.impl_.ec}
  201. {
  202. }
  203. void assign(const format_context_base& rhs) noexcept
  204. {
  205. // output never changes, it always points to the derived object's storage
  206. impl_.opts = rhs.impl_.opts;
  207. impl_.ec = rhs.impl_.ec;
  208. }
  209. public:
  210. /**
  211. * \brief Adds raw SQL to the output string (low level).
  212. * \details
  213. * Adds raw, unescaped SQL to the output string. Doesn't alter the error state.
  214. * \n
  215. * By default, the passed SQL should be available at compile-time.
  216. * Use \ref runtime if you need to use runtime values.
  217. * \n
  218. * This is a low level function. In general, prefer \ref format_sql_to, instead.
  219. *
  220. * \par Exception safety
  221. * Basic guarantee. Memory allocations may throw.
  222. *
  223. * \par Object lifetimes
  224. * The passed string is copied as required and doesn't need to be kept alive.
  225. */
  226. format_context_base& append_raw(constant_string_view sql)
  227. {
  228. impl_.output.append(sql.get());
  229. return *this;
  230. }
  231. /**
  232. * \brief Formats a value and adds it to the output string (low level).
  233. * \details
  234. * value is formatted according to its type, applying the passed format specifiers.
  235. * If formatting generates an error (for instance, a string with invalid encoding is passed),
  236. * the error state may be set.
  237. * \n
  238. * This is a low level function. In general, prefer \ref format_sql_to, instead.
  239. *
  240. * \par Exception safety
  241. * Basic guarantee. Memory allocations may throw.
  242. *
  243. * \par Errors
  244. * The error state may be updated with the following errors: \n
  245. * \li \ref client_errc::invalid_encoding if a string with byte sequences that can't be decoded
  246. * with the current character set is passed.
  247. * \li \ref client_errc::unformattable_value if a NaN or infinity `float` or `double` is passed.
  248. * \li \ref client_errc::format_string_invalid_specifier if `format_specifiers` includes
  249. * specifiers not supported by the type being formatted.
  250. * \li Any other error code that user-supplied formatter specializations may add using \ref add_error.
  251. */
  252. format_context_base& append_value(
  253. formattable_ref value,
  254. constant_string_view format_specifiers = string_view()
  255. )
  256. {
  257. format_arg(detail::access::get_impl(value), format_specifiers.get());
  258. return *this;
  259. }
  260. /**
  261. * \brief Adds an error to the current error state.
  262. * \details
  263. * This function can be used by custom formatters to report that they
  264. * received a value that can't be formatted. For instance, it's used by
  265. * the built-in string formatter when a string with an invalid encoding is supplied.
  266. * \n
  267. * If the error state is not set before calling this function, the error
  268. * state is updated to `ec`. Otherwise, the error is ignored.
  269. * This implies that once the error state is set, it can't be reset.
  270. * \n
  271. * \par Exception safety
  272. * No-throw guarantee.
  273. */
  274. void add_error(error_code ec) noexcept
  275. {
  276. if (!impl_.ec)
  277. impl_.ec = ec;
  278. }
  279. /**
  280. * \brief Retrieves the current error state.
  281. *
  282. * \par Exception safety
  283. * No-throw guarantee.
  284. */
  285. error_code error_state() const noexcept { return impl_.ec; }
  286. /**
  287. * \brief Retrieves the format options.
  288. *
  289. * \par Exception safety
  290. * No-throw guarantee.
  291. */
  292. format_options format_opts() const noexcept { return impl_.opts; }
  293. };
  294. /**
  295. * \brief Format context for incremental SQL formatting.
  296. * \details
  297. * The primary interface for incremental SQL formatting. Contrary to \ref format_context_base,
  298. * this type is aware of the output string's actual type. `basic_format_context` owns
  299. * an instance of `OutputString`. Format operations will append characters to such string.
  300. * \n
  301. * Objects of this type are single-use: once the result has been retrieved using \ref get,
  302. * they cannot be re-used. This is a move-only type.
  303. */
  304. template <BOOST_MYSQL_OUTPUT_STRING OutputString>
  305. class basic_format_context : public format_context_base
  306. {
  307. OutputString output_{};
  308. detail::output_string_ref ref() noexcept { return detail::output_string_ref::create(output_); }
  309. public:
  310. /**
  311. * \brief Constructor.
  312. * \details
  313. * Uses a default-constructed `OutputString` as output string, and an empty
  314. * error code as error state. This constructor can only be called if `OutputString`
  315. * is default-constructible.
  316. *
  317. * \par Exception safety
  318. * Strong guarantee: exceptions thrown by default-constructing `OutputString` are propagated.
  319. */
  320. explicit basic_format_context(format_options opts)
  321. #ifndef BOOST_MYSQL_DOXYGEN // TODO: remove when https://github.com/boostorg/docca/issues/169 gets done
  322. noexcept(std::is_nothrow_default_constructible<OutputString>::value)
  323. #endif
  324. : format_context_base(ref(), opts)
  325. {
  326. }
  327. /**
  328. * \brief Constructor.
  329. * \details
  330. * Move constructs an `OutputString` using `storage`. After construction,
  331. * the output string is cleared. Uses an empty
  332. * error code as error state. This constructor allows re-using existing
  333. * memory for the output string.
  334. * \n
  335. *
  336. * \par Exception safety
  337. * Basic guarantee: exceptions thrown by move-constructing `OutputString` are propagated.
  338. */
  339. basic_format_context(format_options opts, OutputString&& storage)
  340. #ifndef BOOST_MYSQL_DOXYGEN // TODO: remove when https://github.com/boostorg/docca/issues/169 gets done
  341. noexcept(std::is_nothrow_move_constructible<OutputString>::value)
  342. #endif
  343. : format_context_base(ref(), opts), output_(std::move(storage))
  344. {
  345. output_.clear();
  346. }
  347. #ifndef BOOST_MYSQL_DOXYGEN
  348. basic_format_context(const basic_format_context&) = delete;
  349. basic_format_context& operator=(const basic_format_context&) = delete;
  350. #endif
  351. /**
  352. * \brief Move constructor.
  353. * \details
  354. * Move constructs an `OutputString` using `rhs`'s output string.
  355. * `*this` will have the same format options and error state than `rhs`.
  356. * `rhs` is left in a valid but unspecified state.
  357. *
  358. * \par Exception safety
  359. * Basic guarantee: exceptions thrown by move-constructing `OutputString` are propagated.
  360. */
  361. basic_format_context(basic_format_context&& rhs)
  362. #ifndef BOOST_MYSQL_DOXYGEN // TODO: remove when https://github.com/boostorg/docca/issues/169 gets done
  363. noexcept(std::is_nothrow_move_constructible<OutputString>::value)
  364. #endif
  365. : format_context_base(ref(), rhs), output_(std::move(rhs.output_))
  366. {
  367. }
  368. /**
  369. * \brief Move assignment.
  370. * \details
  371. * Move assigns `rhs`'s output string to `*this` output string.
  372. * `*this` will have the same format options and error state than `rhs`.
  373. * `rhs` is left in a valid but unspecified state.
  374. *
  375. * \par Exception safety
  376. * Basic guarantee: exceptions thrown by move-constructing `OutputString` are propagated.
  377. */
  378. basic_format_context& operator=(basic_format_context&& rhs)
  379. #ifndef BOOST_MYSQL_DOXYGEN // TODO: remove when https://github.com/boostorg/docca/issues/169 gets done
  380. noexcept(std::is_nothrow_move_assignable<OutputString>::value)
  381. #endif
  382. {
  383. output_ = std::move(rhs.output_);
  384. assign(rhs);
  385. return *this;
  386. }
  387. /**
  388. * \brief Retrieves the result of the formatting operation.
  389. * \details
  390. * After running the relevant formatting operations (using \ref append_raw,
  391. * \ref append_value or \ref format_sql_to), call this function to retrieve the
  392. * overall result of the operation.
  393. * \n
  394. * If \ref error_state is a non-empty error code, returns it as an error.
  395. * Otherwise, returns the output string, move-constructing it into the `system::result` object.
  396. * \n
  397. * This function is move-only: once called, `*this` is left in a valid but unspecified state.
  398. *
  399. * \par Exception safety
  400. * Basic guarantee: exceptions thrown by move-constructing `OutputString` are propagated.
  401. */
  402. system::result<OutputString> get() &&
  403. #ifndef BOOST_MYSQL_DOXYGEN // TODO: remove when https://github.com/boostorg/docca/issues/169 gets done
  404. noexcept(std::is_nothrow_move_constructible<OutputString>::value)
  405. #endif
  406. {
  407. auto ec = error_state();
  408. if (ec)
  409. return ec;
  410. return std::move(output_);
  411. }
  412. };
  413. /**
  414. * \brief Format context for incremental SQL formatting.
  415. * \details
  416. * Convenience type alias for `basic_format_context`'s most common case.
  417. */
  418. using format_context = basic_format_context<std::string>;
  419. /**
  420. * \brief Composes a SQL query client-side appending it to a format context.
  421. * \details
  422. * Parses `format_str` as a format string, substituting replacement fields (like `{}`, `{1}` or `{name}`)
  423. * by formatted arguments, extracted from `args`.
  424. * \n
  425. * Formatting is performed as if \ref format_context_base::append_raw and
  426. * \ref format_context_base::append_value were called on `ctx`, effectively appending
  427. * characters to its output string.
  428. * \n
  429. * Compared to \ref format_sql, this function is more flexible, allowing the following use cases: \n
  430. * \li Appending characters to an existing context. Can be used to concatenate the output of successive
  431. * format operations efficiently.
  432. * \li Using string types different to `std::string` (works with any \ref basic_format_context).
  433. * \li Avoiding exceptions (see \ref basic_format_context::get).
  434. *
  435. *
  436. * \par Exception safety
  437. * Basic guarantee. Memory allocations may throw.
  438. *
  439. * \par Errors
  440. * \li \ref client_errc::invalid_encoding if `args` contains a string with byte sequences
  441. * that can't be decoded with the current character set.
  442. * \li \ref client_errc::unformattable_value if `args` contains a floating-point value
  443. * that is NaN or infinity.
  444. * \li \ref client_errc::format_string_invalid_specifier if a replacement field includes
  445. * a specifier not supported by the type being formatted.
  446. * \li Any other error generated by user-defined \ref formatter specializations.
  447. * \li \ref client_errc::format_string_invalid_syntax if `format_str` can't be parsed as
  448. * a format string.
  449. * \li \ref client_errc::format_string_invalid_encoding if `format_str` contains byte byte sequences
  450. * that can't be decoded with the current character set.
  451. * \li \ref client_errc::format_string_manual_auto_mix if `format_str` contains a mix of automatic
  452. * (`{}`) and manual indexed (`{1}`) replacement fields.
  453. * \li \ref client_errc::format_arg_not_found if an argument referenced by `format_str` isn't present
  454. * in `args` (there aren't enough arguments or a named argument is not found).
  455. */
  456. template <BOOST_MYSQL_FORMATTABLE... Formattable>
  457. void format_sql_to(format_context_base& ctx, constant_string_view format_str, Formattable&&... args)
  458. {
  459. std::initializer_list<format_arg> args_il{
  460. {string_view(), std::forward<Formattable>(args)}
  461. ...
  462. };
  463. detail::vformat_sql_to(ctx, format_str, args_il);
  464. }
  465. /**
  466. * \copydoc format_sql_to
  467. * \details
  468. * \n
  469. * This overload allows using named arguments.
  470. */
  471. inline void format_sql_to(
  472. format_context_base& ctx,
  473. constant_string_view format_str,
  474. std::initializer_list<format_arg> args
  475. )
  476. {
  477. detail::vformat_sql_to(ctx, format_str, args);
  478. }
  479. /**
  480. * \brief Composes a SQL query client-side.
  481. * \details
  482. * Parses `format_str` as a format string, substituting replacement fields (like `{}`, `{1}` or `{name}`)
  483. * by formatted arguments, extracted from `args`. `opts` is using to parse the string and format string
  484. * arguments.
  485. * \n
  486. * Formatting is performed as if \ref format_context::append_raw and \ref format_context::append_value
  487. * were called on a context created by this function.
  488. * \n
  489. *
  490. * \par Exception safety
  491. * Strong guarantee. Memory allocations may throw. `boost::system::system_error` is thrown if an error
  492. * is found while formatting. See below for more info.
  493. *
  494. * \par Errors
  495. * \li \ref client_errc::invalid_encoding if `args` contains a string with byte sequences
  496. * that can't be decoded with the current character set.
  497. * \li \ref client_errc::unformattable_value if `args` contains a floating-point value
  498. * that is NaN or infinity.
  499. * \li \ref client_errc::format_string_invalid_specifier if a replacement field includes
  500. * a specifier not supported by the type being formatted.
  501. * \li Any other error generated by user-defined \ref formatter specializations.
  502. * \li \ref client_errc::format_string_invalid_syntax if `format_str` can't be parsed as
  503. * a format string.
  504. * \li \ref client_errc::format_string_invalid_encoding if `format_str` contains byte byte sequences
  505. * that can't be decoded with the current character set.
  506. * \li \ref client_errc::format_string_manual_auto_mix if `format_str` contains a mix of automatic
  507. * (`{}`) and manual indexed (`{1}`) replacement fields.
  508. * \li \ref client_errc::format_arg_not_found if an argument referenced by `format_str` isn't present
  509. * in `args` (there aren't enough arguments or a named argument is not found).
  510. */
  511. template <BOOST_MYSQL_FORMATTABLE... Formattable>
  512. std::string format_sql(format_options opts, constant_string_view format_str, Formattable&&... args);
  513. /**
  514. * \copydoc format_sql
  515. * \details
  516. * \n
  517. * This overload allows using named arguments.
  518. */
  519. BOOST_MYSQL_DECL
  520. std::string format_sql(
  521. format_options opts,
  522. constant_string_view format_str,
  523. std::initializer_list<format_arg> args
  524. );
  525. } // namespace mysql
  526. } // namespace boost
  527. #include <boost/mysql/impl/format_sql.hpp>
  528. #ifdef BOOST_MYSQL_HEADER_ONLY
  529. #include <boost/mysql/impl/format_sql.ipp>
  530. #endif
  531. #endif