format_sql.hpp 19 KB

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