Lightweight 0.20260921.0
Loading...
Searching...
No Matches
SqlQueryFormatter.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5#include "Api.hpp"
6#include "SqlConnection.hpp"
7#include "SqlQuery/MigrationPlan.hpp"
8#include "SqlServerType.hpp"
9
10#include <string>
11#include <string_view>
12
13namespace Lightweight
14{
15
16class SqlAdvisoryLockHandler;
17class SqlRetryClassifier;
18
19/// API to format SQL queries for different SQL dialects.
20class [[nodiscard]] LIGHTWEIGHT_API SqlQueryFormatter
21{
22 public:
23 /// Default constructor.
24 SqlQueryFormatter() = default;
25 /// Default move constructor.
27 /// Default copy constructor.
29 /// Default move assignment operator.
31 /// Default copy assignment operator.
33 virtual ~SqlQueryFormatter() = default;
34
35 /// Converts a boolean value to a string literal.
36 [[nodiscard]] virtual std::string_view BooleanLiteral(bool value) const noexcept = 0;
37
38 /// Returns the SQL function name used to retrieve the current date.
39 [[nodiscard]] virtual std::string_view DateFunction() const noexcept = 0;
40
41 /// Converts a string value to a string literal.
42 [[nodiscard]] virtual std::string StringLiteral(std::string_view value) const noexcept = 0;
43
44 /// Converts a character value to a string literal.
45 [[nodiscard]] virtual std::string StringLiteral(char value) const noexcept = 0;
46
47 /// Converts a binary value to a hex-encoded string literal.
48 [[nodiscard]] virtual std::string BinaryLiteral(std::span<uint8_t const> data) const = 0;
49
50 /// Formats a qualified table name with proper quoting for this database.
51 /// @param schema The schema name (can be empty for default schema)
52 /// @param table The table name
53 /// @return The properly quoted qualified table name (e.g., "schema"."table" or [schema].[table])
54 [[nodiscard]] virtual std::string QualifiedTableName(std::string_view schema, std::string_view table) const = 0;
55
56 /// Constructs an SQL INSERT query.
57 ///
58 /// @param intoTable The table to insert into.
59 /// @param fields The fields to insert into.
60 /// @param values The values to insert.
61 ///
62 /// The fields and values must be in the same order.
63 [[nodiscard]] virtual std::string Insert(std::string_view intoTable,
64 std::string_view fields,
65 std::string_view values) const = 0;
66
67 /// Constructs an SQL INSERT query with a schema prefix.
68 [[nodiscard]] virtual std::string Insert(std::string_view schema,
69 std::string_view intoTable,
70 std::string_view fields,
71 std::string_view values) const = 0;
72
73 /// Retrieves the last insert ID of the given table.
74 [[nodiscard]] virtual std::string QueryLastInsertId(std::string_view tableName) const = 0;
75
76 /// Constructs an SQL SELECT query for all rows.
77 [[nodiscard]] virtual std::string SelectAll(bool distinct,
78 std::string_view fields,
79 std::string_view fromTable,
80 std::string_view fromTableAlias,
81 std::string_view tableJoins,
82 std::string_view whereCondition,
83 std::string_view orderBy,
84 std::string_view groupBy) const = 0;
85
86 /// Constructs an SQL SELECT query for the first row.
87 ///
88 /// When @p groupBy is non-empty it is emitted between the WHERE and the ORDER BY clause, so
89 /// the row limit given by @p count applies to the grouped result set.
90 [[nodiscard]] virtual std::string SelectFirst(bool distinct,
91 std::string_view fields,
92 std::string_view fromTable,
93 std::string_view fromTableAlias,
94 std::string_view tableJoins,
95 std::string_view whereCondition,
96 std::string_view orderBy,
97 std::string_view groupBy,
98 size_t count) const = 0;
99
100 /// Constructs an SQL SELECT query for a range of rows.
101 [[nodiscard]] virtual std::string SelectRange(bool distinct,
102 std::string_view fields,
103 std::string_view fromTable,
104 std::string_view fromTableAlias,
105 std::string_view tableJoins,
106 std::string_view whereCondition,
107 std::string_view orderBy,
108 std::string_view groupBy,
109 std::size_t offset,
110 std::size_t limit) const = 0;
111
112 /// Constructs an SQL SELECT query retrieve the count of rows matching the given condition.
113 ///
114 /// When @p groupBy is non-empty the query counts the rows of each group, i.e. it yields one
115 /// row per group rather than a single total.
116 [[nodiscard]] virtual std::string SelectCount(bool distinct,
117 std::string_view fromTable,
118 std::string_view fromTableAlias,
119 std::string_view tableJoins,
120 std::string_view whereCondition,
121 std::string_view groupBy) const = 0;
122
123 /// Constructs an SQL UPDATE query.
124 [[nodiscard]] virtual std::string Update(std::string_view table,
125 std::string_view tableAlias,
126 std::string_view setFields,
127 std::string_view whereCondition) const = 0;
128
129 /// Constructs an SQL DELETE query.
130 [[nodiscard]] virtual std::string Delete(std::string_view fromTable,
131 std::string_view fromTableAlias,
132 std::string_view tableJoins,
133 std::string_view whereCondition) const = 0;
134
135 /// Alias for a list of SQL statement strings.
136 using StringList = std::vector<std::string>;
137
138 /// Convert the given column type definition to the SQL type.
139 [[nodiscard]] virtual std::string ColumnType(SqlColumnTypeDefinition const& type) const = 0;
140
141 /// Constructs an SQL CREATE TABLE query.
142 ///
143 /// @param schema The schema name of the table to create.
144 /// @param tableName The name of the table to create.
145 /// @param columns The columns of the table.
146 /// @param foreignKeys The foreign key constraints of the table.
147 /// @param ifNotExists If true, generates CREATE TABLE IF NOT EXISTS instead of CREATE TABLE.
148 [[nodiscard]] virtual StringList CreateTable(std::string_view schema,
149 std::string_view tableName,
150 std::vector<SqlColumnDeclaration> const& columns,
151 std::vector<SqlCompositeForeignKeyConstraint> const& foreignKeys,
152 bool ifNotExists = false) const = 0;
153
154 /// Constructs an SQL ALTER TABLE query.
155 [[nodiscard]] virtual StringList AlterTable(std::string_view schema,
156 std::string_view tableName,
157 std::vector<SqlAlterTableCommand> const& commands) const = 0;
158
159 /// Constructs an SQL DROP TABLE query.
160 ///
161 /// @param schema The schema name of the table to drop.
162 /// @param tableName The name of the table to drop.
163 /// @param ifExists If true, generates DROP TABLE IF EXISTS instead of DROP TABLE.
164 /// @param cascade If true, drops all foreign key constraints referencing this table first.
165 [[nodiscard]] virtual StringList DropTable(std::string_view schema,
166 std::string_view const& tableName,
167 bool ifExists = false,
168 bool cascade = false) const = 0;
169
170 /// Returns the SQL query to retrieve the full server version string.
171 ///
172 /// This query returns detailed version information specific to each database:
173 /// - SQL Server: Returns result of SELECT @@VERSION (includes build, edition, OS info)
174 /// - PostgreSQL: Returns result of SELECT version() (includes build info)
175 /// - SQLite: Returns result of SELECT sqlite_version()
176 [[nodiscard]] virtual std::string QueryServerVersion() const = 0;
177
178 /// Retrieves the SQL query formatter for SQLite.
179 static SqlQueryFormatter const& Sqlite();
180
181 /// Retrieves the SQL query formatter for Microsoft SQL server.
182 static SqlQueryFormatter const& SqlServer();
183
184 /// Retrieves the SQL query formatter for PostgreSQL.
185 static SqlQueryFormatter const& PostgrSQL();
186
187 /// Retrieves the SQL query formatter for the given SqlServerType.
188 static SqlQueryFormatter const* Get(SqlServerType serverType) noexcept;
189
190 /// @brief Whether the dialect must rebuild a table to apply an `ALTER TABLE` schema change that it
191 /// cannot express in place — adding/dropping a foreign-key constraint, or altering a column's
192 /// type/nullability (`ALTER TABLE … ADD/DROP CONSTRAINT` / `… ALTER COLUMN`).
193 ///
194 /// SQLite returns `true`; every other backend defaults to `false`. The migration executor consults
195 /// this (via @ref SqlConnection::RequiresTableRebuildForSchemaChange) to decide whether to take the
196 /// table-rebuild path for the `-- LIGHTWEIGHT_SQLITE_GUARD:` sentinels these dialects emit.
197 [[nodiscard]] virtual bool RequiresTableRebuildForSchemaChange() const noexcept
198 {
199 return false;
200 }
201
202 /// @brief Whether the dialect provides a batched, whole-database schema-introspection
203 /// fast path that `SqlSchema::ReadAllTables` can use instead of the per-table ODBC
204 /// catalog loop.
205 ///
206 /// Defaults to `false`, meaning the generic per-table catalog reader is used.
207 /// SQL Server returns `true`: it can answer the entire schema with a handful of
208 /// `sys.*` queries, collapsing thousands of per-table round-trips into a few.
209 /// The batched path must produce byte-identical schema metadata to the legacy path.
210 ///
211 /// @return `true` if the dialect supports the batched fast path, `false` otherwise.
212 [[nodiscard]] virtual bool SupportsBatchedSchemaIntrospection() const noexcept
213 {
214 return false;
215 }
216
217 /// @brief Largest number of values this dialect should be handed in a single `WHERE ... IN (...)`
218 /// predicate.
219 ///
220 /// The batched relation loading behind `Query<Record>().With<&Record::relation>()` resolves a whole
221 /// result set through `IN` predicates over the collected keys. Those keys are rendered as literals,
222 /// so a large batch would otherwise produce one enormous expression — SQL Server raises
223 /// "an expression services limit has been reached", and SQLite has its own parser limits. Splitting
224 /// the batch into chunks of this size keeps every generated statement inside what the dialect
225 /// accepts; the cost is one extra round-trip per chunk, still a constant number of queries per
226 /// relation instead of one per record.
227 ///
228 /// @return The maximum number of values per `IN` predicate. Defaults to 1000 for every dialect.
229 [[nodiscard]] virtual size_t MaxInPredicateValues() const noexcept
230 {
231 return 1000;
232 }
233
234 /// @brief Builds the canonical foreign-key constraint name for a set of columns.
235 ///
236 /// Produces `FK_<table>_<col1>[_<col2>…]`. A single-column FK collapses to
237 /// `FK_<table>_<col>`; a composite FK includes every column so that a composite
238 /// FK whose first column matches an existing single-column FK doesn't collide
239 /// on the constraint name (which MSSQL enforces as globally unique per DB).
240 ///
241 /// Consumers include the SQL Server, PostgreSQL and SQLite formatters —
242 /// centralising the convention here keeps CREATE/ALTER emission in sync with
243 /// DROP CONSTRAINT lookup (e.g. `SQLiteRebuildDropForeignKey`).
244 template <typename Range>
245 [[nodiscard]] static std::string BuildForeignKeyConstraintName(std::string_view tableName, Range const& columns)
246 {
247 std::string name { "FK_" };
248 name.append(tableName);
249 for (auto const& col: columns)
250 {
251 name.push_back('_');
252 name.append(col);
253 }
254 return name;
255 }
256
257 /// @brief Returns the SQL statement to execute after connect to make
258 /// `schema` the connection-level default for unqualified DDL/DML.
259 ///
260 /// Returns an empty string when the DBMS has no session-level concept of a
261 /// default schema (SQL Server, SQLite). Callers must skip emission for
262 /// empty results. PostgreSQL implements this via `SET search_path TO ...`.
263 ///
264 /// The `schema` value is interpolated into the statement; callers must
265 /// validate it (e.g. whitelist `[A-Za-z0-9_]`) before invoking.
266 [[nodiscard]] virtual std::string SetDefaultSchemaStatement(std::string_view schema) const
267 {
268 (void) schema;
269 return {};
270 }
271
272 /// @brief Returns the dialect-specific handler used by `SqlScopedLock` to
273 /// acquire and release named cross-process advisory locks.
274 ///
275 /// The returned reference is to a process-singleton, valid for the lifetime
276 /// of the program. Each backend implements its own primitive — SQL Server
277 /// uses `sp_getapplock`, PostgreSQL uses `pg_advisory_lock`, SQLite uses
278 /// a lock table — and the implementation lives in the backend's formatter
279 /// translation unit, so adding a new dialect only touches that unit and
280 /// `SqlScopedLock` itself stays dialect-agnostic.
281 [[nodiscard]] virtual SqlAdvisoryLockHandler const& AdvisoryLockOps() const = 0;
282
283 /// Returns the dialect's transient-error classifier, used by @c SqlRetryPolicy to decide
284 /// whether a failed statement is worth another attempt.
285 ///
286 /// Routing the classification through the formatter is what keeps per-DBMS error-code
287 /// knowledge out of business logic — the same reason @ref AdvisoryLockOps() exists.
288 [[nodiscard]] virtual SqlRetryClassifier const& RetryOps() const noexcept = 0;
289
290 protected:
291 /// Formats a table name with optional schema prefix.
292 static std::string FormatTableName(std::string_view schema, std::string_view table);
293};
294
295} // namespace Lightweight
API to format SQL queries for different SQL dialects.
virtual size_t MaxInPredicateValues() const noexcept
Largest number of values this dialect should be handed in a single WHERE ... IN (....
virtual bool SupportsBatchedSchemaIntrospection() const noexcept
Whether the dialect provides a batched, whole-database schema-introspection fast path that SqlSchema:...
virtual std::string SetDefaultSchemaStatement(std::string_view schema) const
Returns the SQL statement to execute after connect to make schema the connection-level default for un...
SqlQueryFormatter(SqlQueryFormatter const &)=default
Default copy constructor.
SqlQueryFormatter()=default
Default constructor.
SqlQueryFormatter & operator=(SqlQueryFormatter &&)=default
Default move assignment operator.
virtual SqlAdvisoryLockHandler const & AdvisoryLockOps() const =0
Returns the dialect-specific handler used by SqlScopedLock to acquire and release named cross-process...
static std::string BuildForeignKeyConstraintName(std::string_view tableName, Range const &columns)
Builds the canonical foreign-key constraint name for a set of columns.
virtual std::string_view DateFunction() const noexcept=0
Returns the SQL function name used to retrieve the current date.
std::vector< std::string > StringList
Alias for a list of SQL statement strings.
SqlQueryFormatter(SqlQueryFormatter &&)=default
Default move constructor.
virtual SqlRetryClassifier const & RetryOps() const noexcept=0
SqlQueryFormatter & operator=(SqlQueryFormatter const &)=default
Default copy assignment operator.
virtual std::string_view BooleanLiteral(bool value) const noexcept=0
Converts a boolean value to a string literal.
Dialect-specific classification of SQL errors into transient and permanent.
std::variant< SqlAlterTableCommands::RenameTable, SqlAlterTableCommands::AddColumn, SqlAlterTableCommands::AddColumnIfNotExists, SqlAlterTableCommands::AlterColumn, SqlAlterTableCommands::AddIndex, SqlAlterTableCommands::RenameColumn, SqlAlterTableCommands::DropColumn, SqlAlterTableCommands::DropColumnIfExists, SqlAlterTableCommands::DropIndex, SqlAlterTableCommands::DropIndexIfExists, SqlAlterTableCommands::AddForeignKey, SqlAlterTableCommands::AddCompositeForeignKey, SqlAlterTableCommands::DropForeignKey > SqlAlterTableCommand
Represents a single SQL ALTER TABLE command.
Represents a SQL column declaration.
Represents a composite foreign key constraint.