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