Lightweight 0.20260303.0
Loading...
Searching...
No Matches
Migrate.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5#include "../DataMapper/BelongsTo.hpp"
6#include "../DataMapper/Field.hpp"
7#include "../DataMapper/Record.hpp"
8#include "../Utils.hpp"
9#include "Core.hpp"
10#include "MigrationPlan.hpp"
11
12#include <reflection-cpp/reflection.hpp>
13
14namespace Lightweight
15{
16
17/// @brief Index type for simplified CreateIndex API.
18/// @ingroup QueryBuilder
19enum class IndexType : std::uint8_t
20{
21 NonUnique, ///< Regular (non-unique) index
22 Unique ///< Unique index
23};
24
25/// @brief Query builder for building CREATE TABLE queries.
26///
27/// @see SqlQueryBuilder
28/// @ingroup QueryBuilder
29class [[nodiscard]] SqlCreateTableQueryBuilder final
30{
31 public:
32 /// Constructs a CREATE TABLE query builder.
33 explicit SqlCreateTableQueryBuilder(SqlCreateTablePlan& plan):
34 _plan { plan }
35 {
36 }
37
38 /// Adds a new column to the table.
40
41 /// Creates a new nullable column.
42 LIGHTWEIGHT_API SqlCreateTableQueryBuilder& Column(std::string columnName, SqlColumnTypeDefinition columnType);
43
44 /// Creates a new column that is non-nullable.
45 LIGHTWEIGHT_API SqlCreateTableQueryBuilder& RequiredColumn(std::string columnName, SqlColumnTypeDefinition columnType);
46
47 /// Adds the created_at and updated_at columns to the table.
49
50 /// Creates a new primary key column.
51 /// Primary keys are always required, unique, have an index, and are non-nullable.
52 LIGHTWEIGHT_API SqlCreateTableQueryBuilder& PrimaryKey(std::string columnName, SqlColumnTypeDefinition columnType);
53
54 /// Creates a new primary key column with auto-increment.
56 std::string columnName, SqlColumnTypeDefinition columnType = SqlColumnTypeDefinitions::Bigint {});
57
58 /// Creates a new nullable foreign key column.
59 LIGHTWEIGHT_API SqlCreateTableQueryBuilder& ForeignKey(std::string columnName,
60 SqlColumnTypeDefinition columnType,
62
63 /// Creates a new non-nullable foreign key column.
64 LIGHTWEIGHT_API SqlCreateTableQueryBuilder& RequiredForeignKey(std::string columnName,
65 SqlColumnTypeDefinition columnType,
67
68 /// Adds a composite foreign key constraint.
69 LIGHTWEIGHT_API SqlCreateTableQueryBuilder& ForeignKey(std::vector<std::string> columns,
70 std::string referencedTableName,
71 std::vector<std::string> referencedColumns);
72
73 /// Enables the UNIQUE constraint on the last declared column.
75
76 /// Enables the INDEX constraint on the last declared column.
78
79 /// Enables the UNIQUE and INDEX constraint on the last declared column and makes it an index.
81
82 private:
83 SqlCreateTablePlan& _plan;
84};
85
86/// @brief Query builder for building ALTER TABLE queries.
87///
88/// @see SqlQueryBuilder
89/// @ingroup QueryBuilder
90class [[nodiscard]] SqlAlterTableQueryBuilder final
91{
92 public:
93 /// Constructs an ALTER TABLE query builder.
95 _plan { plan }
96 {
97 }
98
99 /// Renames the table.
100 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& RenameTo(std::string_view newTableName);
101
102 /// Adds a new column to the table that is non-nullable.
103 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddColumn(std::string columnName, SqlColumnTypeDefinition columnType);
104
105 /// Adds a new column to the table that is non-nullable.
106 ///
107 /// @tparam MemberPointer The pointer to the member field in the record.
108 ///
109 /// @see AddColumn(std::string, SqlColumnTypeDefinition)
110 template <auto MemberPointer>
112 {
113 return AddColumn(std::string(FieldNameOf<MemberPointer>),
115 }
116
117 /// Adds a new column to the table that is nullable.
118 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddNotRequiredColumn(std::string columnName,
119 SqlColumnTypeDefinition columnType);
120
121 /// Adds a new column to the table that is nullable.
122 ///
123 /// @tparam MemberPointer The pointer to the member field in the record.
124 ///
125 /// @see AddNotRequiredColumn(std::string, SqlColumnTypeDefinition)
126 template <auto MemberPointer>
128 {
129 return AddNotRequiredColumn(std::string(FieldNameOf<MemberPointer>),
131 }
132
133 /// @brief Alters the column to have a new non-nullable type.
134 ///
135 /// @param columnName The name of the column to alter.
136 /// @param columnType The new type of the column.
137 /// @param nullable The new nullable state of the column.
138 ///
139 /// @return The current query builder for chaining.
140 ///
141 /// @see SqlColumnTypeDefinition
142 ///
143 /// @code
144 /// auto stmt = SqlStatement();
145 /// auto sqlMigration = stmt.Migration()
146 /// .AlterTable("Table")
147 /// .AlterColumn("column", Integer {}, SqlNullable::NotNull)
148 /// .GetPlan().ToSql();
149 /// for (auto const& sql: sqlMigration)
150 /// stmt.ExecuteDirect(sql);
151 /// @endcode
152 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AlterColumn(std::string columnName,
153 SqlColumnTypeDefinition columnType,
154 SqlNullable nullable);
155
156 /// Renames a column.
157 /// @param oldColumnName The old column name.
158 /// @param newColumnName The new column name.
159 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& RenameColumn(std::string_view oldColumnName, std::string_view newColumnName);
160
161 /// Drops a column from the table.
162 /// @param columnName The name of the column to drop.
163 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& DropColumn(std::string_view columnName);
164
165 /// Adds a new column to the table only if it does not already exist.
166 ///
167 /// @note Database support varies:
168 /// - PostgreSQL: Native IF NOT EXISTS support
169 /// - SQL Server: Uses conditional IF NOT EXISTS query
170 /// - SQLite: Limited support (may require raw SQL)
171 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddColumnIfNotExists(std::string columnName,
172 SqlColumnTypeDefinition columnType);
173
174 /// Adds a new nullable column to the table only if it does not already exist.
175 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddNotRequiredColumnIfNotExists(std::string columnName,
176 SqlColumnTypeDefinition columnType);
177
178 /// Drops a column from the table only if it exists.
179 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& DropColumnIfExists(std::string_view columnName);
180
181 /// Add an index to the table for the specified column.
182 /// @param columnName The name of the column to index.
183 ///
184 /// @code
185 /// SqlQueryBuilder q;
186 /// q.Migration().AlterTable("Table").AddIndex("column");
187 /// // Will execute CREATE INDEX "Table_column_index" ON "Table" ("column");
188 /// @endcode
189 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddIndex(std::string_view columnName);
190
191 /// Add an index to the table for the specified column that is unique.
192 /// @param columnName The name of the column to index.
193 ///
194 /// @code
195 /// SqlQueryBuilder q;
196 /// q.Migration().AlterTable("Table").AddUniqueIndex("column");
197 /// // Will execute CREATE UNIQUE INDEX "Table_column_index" ON "Table" ("column");
198 /// @endcode
199 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddUniqueIndex(std::string_view columnName);
200
201 /// Drop an index from the table for the specified column.
202 /// @param columnName The name of the column to drop the index from.
203 ///
204 /// @code
205 /// SqlQueryBuilder q;
206 /// q.Migration().AlterTable("Table").DropIndex("column");
207 /// // Will execute DROP INDEX "Table_column_index";
208 /// @endcode
209 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& DropIndex(std::string_view columnName);
210
211 /// Drop an index from the table only if it exists.
212 /// @param columnName The name of the column to drop the index from.
213 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& DropIndexIfExists(std::string_view columnName);
214
215 /// Adds a foreign key column @p columnName to @p referencedColumn to an existing column.
216 ///
217 /// @param columnName The name of the column to add.
218 /// @param referencedColumn The column to reference.
219 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddForeignKey(std::string columnName,
220 SqlForeignKeyReferenceDefinition referencedColumn);
221
222 /// Adds a foreign key column @p columnName of type @p columnType to @p referencedColumn.
223 ///
224 /// @param columnName The name of the column to add.
225 /// @param columnType The type of the column to add.
226 /// @param referencedColumn The column to reference.
227 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddForeignKeyColumn(std::string columnName,
228 SqlColumnTypeDefinition columnType,
229 SqlForeignKeyReferenceDefinition referencedColumn);
230
231 /// Adds a nullable foreign key column @p columnName of type @p columnType to @p referencedColumn.
232 ///
233 /// @param columnName The name of the column to add.
234 /// @param columnType The type of the column to add.
235 /// @param referencedColumn The column to reference.
237 std::string columnName, SqlColumnTypeDefinition columnType, SqlForeignKeyReferenceDefinition referencedColumn);
238
239 /// Drops a foreign key for the column @p columnName from the table.
240 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& DropForeignKey(std::string columnName);
241
242 /// Adds a composite foreign key constraint.
243 ///
244 /// @param columns The columns in the current table.
245 /// @param referencedTableName The referenced table name.
246 /// @param referencedColumns The referenced columns in the referenced table.
247 LIGHTWEIGHT_API SqlAlterTableQueryBuilder& AddCompositeForeignKey(std::vector<std::string> columns,
248 std::string referencedTableName,
249 std::vector<std::string> referencedColumns);
250
251 private:
252 SqlAlterTablePlan& _plan;
253};
254
255namespace detail
256{
257 template <typename Record>
258 void PopulateCreateTableBuilder(SqlCreateTableQueryBuilder& builder)
259 {
260 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
261
262#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
263 constexpr auto ctx = std::meta::access_context::current();
264 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
265 {
266 using FieldType = typename[:std::meta::type_of(el):];
267 if constexpr (FieldWithStorage<FieldType>)
268 {
269 if constexpr (IsAutoIncrementPrimaryKey<FieldType>)
271 std::string(FieldNameOf<el>),
272 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value);
273 else if constexpr (FieldType::IsPrimaryKey)
274 builder.PrimaryKey(std::string(FieldNameOf<el>),
275 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value);
276 else if constexpr (IsBelongsTo<FieldType>)
277 {
278 constexpr size_t referencedFieldIndex = []() constexpr -> size_t {
279 auto index = size_t(-1);
280 Reflection::EnumerateMembers<typename FieldType::ReferencedRecord>(
281 [&index]<size_t J, typename ReferencedFieldType>() constexpr -> void {
282 if constexpr (IsField<ReferencedFieldType>)
283 if constexpr (ReferencedFieldType::IsPrimaryKey)
284 index = J;
285 });
286 return index;
287 }();
288 builder.ForeignKey(
289 std::string(FieldNameOf<el>),
290 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value,
291 SqlForeignKeyReferenceDefinition {
292 .tableName = std::string { RecordTableName<typename FieldType::ReferencedRecord> },
293 .columnName = std::string { FieldNameOf<FieldType::ReferencedField> } });
294 }
295 else if constexpr (FieldType::IsMandatory)
296 builder.RequiredColumn(std::string(FieldNameOf<el>),
297 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value);
298 else
299 builder.Column(std::string(FieldNameOf<el>),
300 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value);
301 }
302 }
303#else
304 Reflection::EnumerateMembers<Record>([&builder]<size_t I, typename FieldType>() {
305 if constexpr (FieldWithStorage<FieldType>)
306 {
307 if constexpr (IsAutoIncrementPrimaryKey<FieldType>)
309 std::string(FieldNameAt<I, Record>()),
310 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value);
311 else if constexpr (FieldType::IsPrimaryKey)
312 builder.PrimaryKey(std::string(FieldNameAt<I, Record>()),
313 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value);
314 else if constexpr (IsBelongsTo<FieldType>)
315 {
316 constexpr size_t referencedFieldIndex = []() constexpr -> size_t {
317 auto index = size_t(-1);
318 Reflection::EnumerateMembers<typename FieldType::ReferencedRecord>(
319 [&index]<size_t J, typename ReferencedFieldType>() constexpr -> void {
320 if constexpr (IsField<ReferencedFieldType>)
321 if constexpr (ReferencedFieldType::IsPrimaryKey)
322 index = J;
323 });
324 return index;
325 }();
326 builder.ForeignKey(
327 std::string(FieldNameAt<I, Record>()),
328 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value,
329 SqlForeignKeyReferenceDefinition {
330 .tableName = std::string { RecordTableName<typename FieldType::ReferencedRecord> },
331 .columnName =
332 std::string { FieldNameAt<referencedFieldIndex, typename FieldType::ReferencedRecord>() } });
333 }
334 else if constexpr (FieldType::IsMandatory)
335 builder.RequiredColumn(std::string(FieldNameAt<I, Record>()),
336 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value);
337 else
338 builder.Column(std::string(FieldNameAt<I, Record>()),
339 detail::SqlColumnTypeDefinitionOf<typename FieldType::ValueType>::value);
340 }
341 });
342#endif
343 }
344} // namespace detail
345
346/// @brief Query builder for building INSERT queries in migrations.
347///
348/// @see SqlMigrationQueryBuilder
349/// @ingroup QueryBuilder
350class [[nodiscard]] SqlMigrationInsertBuilder final
351{
352 public:
353 /// Constructs a migration INSERT builder.
355 _plan { plan }
356 {
357 }
358
359 /// Sets a column value for the INSERT.
360 template <typename T>
361 SqlMigrationInsertBuilder& Set(std::string columnName, T const& value)
362 {
363 _plan.columns.emplace_back(std::move(columnName), SqlVariant(value));
364 return *this;
365 }
366
367 private:
368 SqlInsertDataPlan& _plan;
369};
370
371/// @brief Query builder for building UPDATE queries in migrations.
372///
373/// @see SqlMigrationQueryBuilder
374/// @ingroup QueryBuilder
375class [[nodiscard]] SqlMigrationUpdateBuilder final
376{
377 public:
378 /// Constructs a migration UPDATE builder.
380 _plan { plan }
381 {
382 }
383
384 /// Sets a column value for the UPDATE.
385 template <typename T>
386 SqlMigrationUpdateBuilder& Set(std::string columnName, T const& value)
387 {
388 _plan.setColumns.emplace_back(std::move(columnName), SqlVariant(value));
389 return *this;
390 }
391
392 /// @brief Sets a column to a raw SQL expression — for column-to-column copies
393 /// or arithmetic that cannot be represented as a literal value.
394 ///
395 /// @param columnName The target column.
396 /// @param expression The raw SQL fragment (e.g. `"OTHER_COL"`, `"CTR" + 1`) emitted
397 /// verbatim after the `=`. The caller is responsible for any
398 /// identifier quoting.
399 SqlMigrationUpdateBuilder& SetExpression(std::string columnName, std::string expression)
400 {
401 _plan.setExpressions.emplace_back(std::move(columnName), std::move(expression));
402 return *this;
403 }
404
405 /// Adds a WHERE condition to the UPDATE.
406 template <typename T>
407 SqlMigrationUpdateBuilder& Where(std::string columnName, std::string op, T const& value)
408 {
409 _plan.whereColumn = std::move(columnName);
410 _plan.whereOp = std::move(op);
411 _plan.whereValue = SqlVariant(value);
412 return *this;
413 }
414
415 /// @brief Supplies a pre-rendered WHERE-clause body for cases that don't fit the
416 /// simple `(column, op, value)` form — composite `AND`/`OR`/`NOT`, `IS NULL`,
417 /// `IN (subquery)`, `EXISTS (subquery)`, etc.
418 ///
419 /// The text is emitted verbatim after `WHERE` at execution time; the caller is
420 /// responsible for dialect-safe quoting.
421 /// @param expression Pre-rendered SQL clause body (without the leading `WHERE`).
423 {
424 _plan.whereExpression = std::move(expression);
425 return *this;
426 }
427
428 private:
429 SqlUpdateDataPlan& _plan;
430};
431
432/// @brief Query builder for building DELETE queries in migrations.
433///
434/// @see SqlMigrationQueryBuilder
435/// @ingroup QueryBuilder
436class [[nodiscard]] SqlMigrationDeleteBuilder final
437{
438 public:
439 /// Constructs a migration DELETE builder.
441 _plan { plan }
442 {
443 }
444
445 /// Adds a WHERE condition to the DELETE.
446 template <typename T>
447 SqlMigrationDeleteBuilder& Where(std::string columnName, std::string op, T const& value)
448 {
449 _plan.whereColumn = std::move(columnName);
450 _plan.whereOp = std::move(op);
451 _plan.whereValue = SqlVariant(value);
452 return *this;
453 }
454
455 /// Pre-rendered WHERE-clause body. See `SqlMigrationUpdateBuilder::WhereExpression`.
457 {
458 _plan.whereExpression = std::move(expression);
459 return *this;
460 }
461
462 private:
463 SqlDeleteDataPlan& _plan;
464};
465
466/// @brief Query builder for building SQL migration queries.
467/// @ingroup QueryBuilder
468class [[nodiscard]] SqlMigrationQueryBuilder final
469{
470 public:
471 /// Constructs a migration query builder.
472 explicit SqlMigrationQueryBuilder(SqlQueryFormatter const& formatter):
473 _formatter { formatter },
474 _migrationPlan { .formatter = formatter }
475 {
476 }
477
478 /// Sets the schema name for the migration.
479 LIGHTWEIGHT_API SqlMigrationQueryBuilder& WithSchema(std::string schemaName);
480
481 /// Creates a new database.
482 LIGHTWEIGHT_API SqlMigrationQueryBuilder& CreateDatabase(std::string_view databaseName);
483
484 /// Drops a database.
485 LIGHTWEIGHT_API SqlMigrationQueryBuilder& DropDatabase(std::string_view databaseName);
486
487 /// Creates a new table.
488 LIGHTWEIGHT_API SqlCreateTableQueryBuilder CreateTable(std::string_view tableName);
489
490 /// Creates a new table only if it does not already exist.
491 ///
492 /// @note Database support:
493 /// - SQLite: Native CREATE TABLE IF NOT EXISTS
494 /// - PostgreSQL: Native CREATE TABLE IF NOT EXISTS
495 /// - SQL Server: Uses conditional IF NOT EXISTS block
496 LIGHTWEIGHT_API SqlCreateTableQueryBuilder CreateTableIfNotExists(std::string_view tableName);
497
498 /// Alters an existing table.
499 LIGHTWEIGHT_API SqlAlterTableQueryBuilder AlterTable(std::string_view tableName);
500
501 /// Drops a table.
502 LIGHTWEIGHT_API SqlMigrationQueryBuilder& DropTable(std::string_view tableName);
503
504 /// Drops a table if it exists.
505 LIGHTWEIGHT_API SqlMigrationQueryBuilder& DropTableIfExists(std::string_view tableName);
506
507 /// Drops a table and all foreign key constraints referencing it.
508 /// On PostgreSQL, uses CASCADE. On MS SQL, drops FK constraints first.
509 LIGHTWEIGHT_API SqlMigrationQueryBuilder& DropTableCascade(std::string_view tableName);
510
511 /// Creates a new table for the given record type.
512 template <typename Record>
514 {
515 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
516
517 auto builder = CreateTable(RecordTableName<Record>);
518 detail::PopulateCreateTableBuilder<Record>(builder);
519 return builder;
520 }
521
522 /// Alters an existing table.
523 template <typename Record>
525 {
526 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
527 return AlterTable(RecordTableName<Record>);
528 }
529
530 /// Executes raw SQL.
531 LIGHTWEIGHT_API SqlMigrationQueryBuilder& RawSql(std::string_view sql);
532
533 /// Creates an index on a table.
534 ///
535 /// @param indexName The name of the index to create.
536 /// @param tableName The name of the table to create the index on.
537 /// @param columns The columns to include in the index.
538 /// @param unique If true, creates a UNIQUE index.
539 ///
540 /// @code
541 /// SqlQueryBuilder q;
542 /// q.Migration().CreateIndex("idx_user_email", "users", {"email"});
543 /// // Will execute CREATE INDEX "idx_user_email" ON "users" ("email");
544 /// @endcode
545 LIGHTWEIGHT_API SqlMigrationQueryBuilder& CreateIndex(std::string indexName,
546 std::string tableName,
547 std::vector<std::string> columns,
548 bool unique = false);
549
550 /// Creates a unique index on a table.
551 ///
552 /// @param indexName The name of the index to create.
553 /// @param tableName The name of the table to create the index on.
554 /// @param columns The columns to include in the index.
555 LIGHTWEIGHT_API SqlMigrationQueryBuilder& CreateUniqueIndex(std::string indexName,
556 std::string tableName,
557 std::vector<std::string> columns);
558
559 /// Creates an index on a table with auto-generated name.
560 ///
561 /// The index name is automatically generated as `idx_{tableName}_{col1}_{col2}_...`
562 ///
563 /// @param tableName The name of the table to create the index on.
564 /// @param columns The columns to include in the index.
565 /// @param type The type of index (NonUnique or Unique).
566 ///
567 /// @code
568 /// SqlQueryBuilder q;
569 /// q.Migration().CreateIndex("users", {"email"}, IndexType::Unique);
570 /// // Will execute CREATE UNIQUE INDEX "idx_users_email" ON "users" ("email");
571 /// @endcode
572 LIGHTWEIGHT_API SqlMigrationQueryBuilder& CreateIndex(std::string tableName,
573 std::vector<std::string> columns,
575
576 /// Creates an INSERT statement for the migration.
577 LIGHTWEIGHT_API SqlMigrationInsertBuilder Insert(std::string_view tableName);
578
579 /// Creates an UPDATE statement for the migration.
580 LIGHTWEIGHT_API SqlMigrationUpdateBuilder Update(std::string_view tableName);
581
582 /// Creates a DELETE statement for the migration.
583 LIGHTWEIGHT_API SqlMigrationDeleteBuilder Delete(std::string_view tableName);
584
585 /// Executes SQL interactively via a callback.
586 LIGHTWEIGHT_API SqlMigrationQueryBuilder& Native(std::function<std::string(SqlConnection&)> callback);
587
588 /// Starts a transaction.
590
591 /// Commits a transaction.
593
594 /// Gets the migration plan.
595 [[nodiscard]] LIGHTWEIGHT_API SqlMigrationPlan const& GetPlan() const&;
596
597 /// Gets the migration plan.
598 ///
599 /// @note This method is destructive and will invalidate the current builder.
600 LIGHTWEIGHT_API SqlMigrationPlan GetPlan() &&;
601
602 private:
603 SqlQueryFormatter const& _formatter;
604 std::string _schemaName;
605 SqlMigrationPlan _migrationPlan;
606};
607
608} // namespace Lightweight
Query builder for building ALTER TABLE queries.
Definition Migrate.hpp:91
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & DropIndex(std::string_view columnName)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & DropIndexIfExists(std::string_view columnName)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & DropColumn(std::string_view columnName)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddColumn(std::string columnName, SqlColumnTypeDefinition columnType)
Adds a new column to the table that is non-nullable.
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & RenameColumn(std::string_view oldColumnName, std::string_view newColumnName)
SqlAlterTableQueryBuilder & AddColumn()
Definition Migrate.hpp:111
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & RenameTo(std::string_view newTableName)
Renames the table.
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddIndex(std::string_view columnName)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddNotRequiredForeignKeyColumn(std::string columnName, SqlColumnTypeDefinition columnType, SqlForeignKeyReferenceDefinition referencedColumn)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddNotRequiredColumn(std::string columnName, SqlColumnTypeDefinition columnType)
Adds a new column to the table that is nullable.
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddUniqueIndex(std::string_view columnName)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & DropColumnIfExists(std::string_view columnName)
Drops a column from the table only if it exists.
SqlAlterTableQueryBuilder(SqlAlterTablePlan &plan)
Constructs an ALTER TABLE query builder.
Definition Migrate.hpp:94
SqlAlterTableQueryBuilder & AddNotRequiredColumn()
Definition Migrate.hpp:127
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & DropForeignKey(std::string columnName)
Drops a foreign key for the column columnName from the table.
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AlterColumn(std::string columnName, SqlColumnTypeDefinition columnType, SqlNullable nullable)
Alters the column to have a new non-nullable type.
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddForeignKey(std::string columnName, SqlForeignKeyReferenceDefinition referencedColumn)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddColumnIfNotExists(std::string columnName, SqlColumnTypeDefinition columnType)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddNotRequiredColumnIfNotExists(std::string columnName, SqlColumnTypeDefinition columnType)
Adds a new nullable column to the table only if it does not already exist.
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddForeignKeyColumn(std::string columnName, SqlColumnTypeDefinition columnType, SqlForeignKeyReferenceDefinition referencedColumn)
LIGHTWEIGHT_API SqlAlterTableQueryBuilder & AddCompositeForeignKey(std::vector< std::string > columns, std::string referencedTableName, std::vector< std::string > referencedColumns)
Represents a connection to a SQL database.
Query builder for building CREATE TABLE queries.
Definition Migrate.hpp:30
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & ForeignKey(std::vector< std::string > columns, std::string referencedTableName, std::vector< std::string > referencedColumns)
Adds a composite foreign key constraint.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & Timestamps()
Adds the created_at and updated_at columns to the table.
SqlCreateTableQueryBuilder(SqlCreateTablePlan &plan)
Constructs a CREATE TABLE query builder.
Definition Migrate.hpp:33
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & RequiredColumn(std::string columnName, SqlColumnTypeDefinition columnType)
Creates a new column that is non-nullable.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & RequiredForeignKey(std::string columnName, SqlColumnTypeDefinition columnType, SqlForeignKeyReferenceDefinition foreignKey)
Creates a new non-nullable foreign key column.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & ForeignKey(std::string columnName, SqlColumnTypeDefinition columnType, SqlForeignKeyReferenceDefinition foreignKey)
Creates a new nullable foreign key column.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & Index()
Enables the INDEX constraint on the last declared column.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & UniqueIndex()
Enables the UNIQUE and INDEX constraint on the last declared column and makes it an index.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & PrimaryKey(std::string columnName, SqlColumnTypeDefinition columnType)
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & Column(SqlColumnDeclaration column)
Adds a new column to the table.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & Column(std::string columnName, SqlColumnTypeDefinition columnType)
Creates a new nullable column.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & PrimaryKeyWithAutoIncrement(std::string columnName, SqlColumnTypeDefinition columnType=SqlColumnTypeDefinitions::Bigint {})
Creates a new primary key column with auto-increment.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder & Unique()
Enables the UNIQUE constraint on the last declared column.
Query builder for building DELETE queries in migrations.
Definition Migrate.hpp:437
SqlMigrationDeleteBuilder & Where(std::string columnName, std::string op, T const &value)
Adds a WHERE condition to the DELETE.
Definition Migrate.hpp:447
SqlMigrationDeleteBuilder(SqlDeleteDataPlan &plan)
Constructs a migration DELETE builder.
Definition Migrate.hpp:440
SqlMigrationDeleteBuilder & WhereExpression(std::string expression)
Pre-rendered WHERE-clause body. See SqlMigrationUpdateBuilder::WhereExpression.
Definition Migrate.hpp:456
Query builder for building INSERT queries in migrations.
Definition Migrate.hpp:351
SqlMigrationInsertBuilder(SqlInsertDataPlan &plan)
Constructs a migration INSERT builder.
Definition Migrate.hpp:354
SqlMigrationInsertBuilder & Set(std::string columnName, T const &value)
Sets a column value for the INSERT.
Definition Migrate.hpp:361
Query builder for building SQL migration queries.
Definition Migrate.hpp:469
LIGHTWEIGHT_API SqlCreateTableQueryBuilder CreateTable(std::string_view tableName)
Creates a new table.
SqlCreateTableQueryBuilder CreateTable()
Creates a new table for the given record type.
Definition Migrate.hpp:513
LIGHTWEIGHT_API SqlMigrationQueryBuilder & CommitTransaction()
Commits a transaction.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & RawSql(std::string_view sql)
Executes raw SQL.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & CreateIndex(std::string indexName, std::string tableName, std::vector< std::string > columns, bool unique=false)
LIGHTWEIGHT_API SqlMigrationDeleteBuilder Delete(std::string_view tableName)
Creates a DELETE statement for the migration.
LIGHTWEIGHT_API SqlAlterTableQueryBuilder AlterTable(std::string_view tableName)
Alters an existing table.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder CreateTableIfNotExists(std::string_view tableName)
LIGHTWEIGHT_API SqlMigrationPlan const & GetPlan() const &
Gets the migration plan.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & DropTable(std::string_view tableName)
Drops a table.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & CreateIndex(std::string tableName, std::vector< std::string > columns, IndexType type=IndexType::NonUnique)
LIGHTWEIGHT_API SqlMigrationUpdateBuilder Update(std::string_view tableName)
Creates an UPDATE statement for the migration.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & WithSchema(std::string schemaName)
Sets the schema name for the migration.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & CreateUniqueIndex(std::string indexName, std::string tableName, std::vector< std::string > columns)
LIGHTWEIGHT_API SqlMigrationInsertBuilder Insert(std::string_view tableName)
Creates an INSERT statement for the migration.
SqlAlterTableQueryBuilder AlterTable()
Alters an existing table.
Definition Migrate.hpp:524
LIGHTWEIGHT_API SqlMigrationQueryBuilder & BeginTransaction()
Starts a transaction.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & DropTableCascade(std::string_view tableName)
SqlMigrationQueryBuilder(SqlQueryFormatter const &formatter)
Constructs a migration query builder.
Definition Migrate.hpp:472
LIGHTWEIGHT_API SqlMigrationQueryBuilder & DropDatabase(std::string_view databaseName)
Drops a database.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & Native(std::function< std::string(SqlConnection &)> callback)
Executes SQL interactively via a callback.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & DropTableIfExists(std::string_view tableName)
Drops a table if it exists.
LIGHTWEIGHT_API SqlMigrationQueryBuilder & CreateDatabase(std::string_view databaseName)
Creates a new database.
Query builder for building UPDATE queries in migrations.
Definition Migrate.hpp:376
SqlMigrationUpdateBuilder & Where(std::string columnName, std::string op, T const &value)
Adds a WHERE condition to the UPDATE.
Definition Migrate.hpp:407
SqlMigrationUpdateBuilder & WhereExpression(std::string expression)
Supplies a pre-rendered WHERE-clause body for cases that don't fit the simple (column,...
Definition Migrate.hpp:422
SqlMigrationUpdateBuilder & Set(std::string columnName, T const &value)
Sets a column value for the UPDATE.
Definition Migrate.hpp:386
SqlMigrationUpdateBuilder & SetExpression(std::string columnName, std::string expression)
Sets a column to a raw SQL expression — for column-to-column copies or arithmetic that cannot be repr...
Definition Migrate.hpp:399
SqlMigrationUpdateBuilder(SqlUpdateDataPlan &plan)
Constructs a migration UPDATE builder.
Definition Migrate.hpp:379
API to format SQL queries for different SQL dialects.
Represents a record type that can be used with the DataMapper.
Definition Record.hpp:47
std::remove_cvref_t< decltype(std::declval< MemberClassType< decltype(Field)> >().*Field)>::ValueType ReferencedFieldTypeOf
Retrieves the type of a member field in a record.
Definition Field.hpp:392
IndexType
Index type for simplified CreateIndex API.
Definition Migrate.hpp:20
constexpr auto SqlColumnTypeDefinitionOf
Represents a SQL column type definition of T.
@ NonUnique
Regular (non-unique) index.
@ Unique
Unique index.
Represents a SQL ALTER TABLE plan on a given table.
Represents a SQL column declaration.
Represents a SQL DELETE data plan for migrations.
Represents a foreign key reference definition.
Represents a SQL INSERT data plan for migrations.
Represents a SQL migration plan.
Represents a SQL UPDATE data plan for migrations.
Represents a value that can be any of the supported SQL data types.