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 /// Adds a WHERE condition to the UPDATE.
393 template <typename T>
394 SqlMigrationUpdateBuilder& Where(std::string columnName, std::string op, T const& value)
395 {
396 _plan.whereColumn = std::move(columnName);
397 _plan.whereOp = std::move(op);
398 _plan.whereValue = SqlVariant(value);
399 return *this;
400 }
401
402 private:
403 SqlUpdateDataPlan& _plan;
404};
405
406/// @brief Query builder for building DELETE queries in migrations.
407///
408/// @see SqlMigrationQueryBuilder
409/// @ingroup QueryBuilder
410class [[nodiscard]] SqlMigrationDeleteBuilder final
411{
412 public:
413 /// Constructs a migration DELETE builder.
415 _plan { plan }
416 {
417 }
418
419 /// Adds a WHERE condition to the DELETE.
420 template <typename T>
421 SqlMigrationDeleteBuilder& Where(std::string columnName, std::string op, T const& value)
422 {
423 _plan.whereColumn = std::move(columnName);
424 _plan.whereOp = std::move(op);
425 _plan.whereValue = SqlVariant(value);
426 return *this;
427 }
428
429 private:
430 SqlDeleteDataPlan& _plan;
431};
432
433/// @brief Query builder for building SQL migration queries.
434/// @ingroup QueryBuilder
435class [[nodiscard]] SqlMigrationQueryBuilder final
436{
437 public:
438 /// Constructs a migration query builder.
439 explicit SqlMigrationQueryBuilder(SqlQueryFormatter const& formatter):
440 _formatter { formatter },
441 _migrationPlan { .formatter = formatter }
442 {
443 }
444
445 /// Sets the schema name for the migration.
446 LIGHTWEIGHT_API SqlMigrationQueryBuilder& WithSchema(std::string schemaName);
447
448 /// Creates a new database.
449 LIGHTWEIGHT_API SqlMigrationQueryBuilder& CreateDatabase(std::string_view databaseName);
450
451 /// Drops a database.
452 LIGHTWEIGHT_API SqlMigrationQueryBuilder& DropDatabase(std::string_view databaseName);
453
454 /// Creates a new table.
455 LIGHTWEIGHT_API SqlCreateTableQueryBuilder CreateTable(std::string_view tableName);
456
457 /// Creates a new table only if it does not already exist.
458 ///
459 /// @note Database support:
460 /// - SQLite: Native CREATE TABLE IF NOT EXISTS
461 /// - PostgreSQL: Native CREATE TABLE IF NOT EXISTS
462 /// - SQL Server: Uses conditional IF NOT EXISTS block
463 LIGHTWEIGHT_API SqlCreateTableQueryBuilder CreateTableIfNotExists(std::string_view tableName);
464
465 /// Alters an existing table.
466 LIGHTWEIGHT_API SqlAlterTableQueryBuilder AlterTable(std::string_view tableName);
467
468 /// Drops a table.
469 LIGHTWEIGHT_API SqlMigrationQueryBuilder& DropTable(std::string_view tableName);
470
471 /// Drops a table if it exists.
472 LIGHTWEIGHT_API SqlMigrationQueryBuilder& DropTableIfExists(std::string_view tableName);
473
474 /// Drops a table and all foreign key constraints referencing it.
475 /// On PostgreSQL, uses CASCADE. On MS SQL, drops FK constraints first.
476 LIGHTWEIGHT_API SqlMigrationQueryBuilder& DropTableCascade(std::string_view tableName);
477
478 /// Creates a new table for the given record type.
479 template <typename Record>
481 {
482 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
483
484 auto builder = CreateTable(RecordTableName<Record>);
485 detail::PopulateCreateTableBuilder<Record>(builder);
486 return builder;
487 }
488
489 /// Alters an existing table.
490 template <typename Record>
492 {
493 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
494 return AlterTable(RecordTableName<Record>);
495 }
496
497 /// Executes raw SQL.
498 LIGHTWEIGHT_API SqlMigrationQueryBuilder& RawSql(std::string_view sql);
499
500 /// Creates an index on a table.
501 ///
502 /// @param indexName The name of the index to create.
503 /// @param tableName The name of the table to create the index on.
504 /// @param columns The columns to include in the index.
505 /// @param unique If true, creates a UNIQUE index.
506 ///
507 /// @code
508 /// SqlQueryBuilder q;
509 /// q.Migration().CreateIndex("idx_user_email", "users", {"email"});
510 /// // Will execute CREATE INDEX "idx_user_email" ON "users" ("email");
511 /// @endcode
512 LIGHTWEIGHT_API SqlMigrationQueryBuilder& CreateIndex(std::string indexName,
513 std::string tableName,
514 std::vector<std::string> columns,
515 bool unique = false);
516
517 /// Creates a unique index on a table.
518 ///
519 /// @param indexName The name of the index to create.
520 /// @param tableName The name of the table to create the index on.
521 /// @param columns The columns to include in the index.
522 LIGHTWEIGHT_API SqlMigrationQueryBuilder& CreateUniqueIndex(std::string indexName,
523 std::string tableName,
524 std::vector<std::string> columns);
525
526 /// Creates an index on a table with auto-generated name.
527 ///
528 /// The index name is automatically generated as `idx_{tableName}_{col1}_{col2}_...`
529 ///
530 /// @param tableName The name of the table to create the index on.
531 /// @param columns The columns to include in the index.
532 /// @param type The type of index (NonUnique or Unique).
533 ///
534 /// @code
535 /// SqlQueryBuilder q;
536 /// q.Migration().CreateIndex("users", {"email"}, IndexType::Unique);
537 /// // Will execute CREATE UNIQUE INDEX "idx_users_email" ON "users" ("email");
538 /// @endcode
539 LIGHTWEIGHT_API SqlMigrationQueryBuilder& CreateIndex(std::string tableName,
540 std::vector<std::string> columns,
542
543 /// Creates an INSERT statement for the migration.
544 LIGHTWEIGHT_API SqlMigrationInsertBuilder Insert(std::string_view tableName);
545
546 /// Creates an UPDATE statement for the migration.
547 LIGHTWEIGHT_API SqlMigrationUpdateBuilder Update(std::string_view tableName);
548
549 /// Creates a DELETE statement for the migration.
550 LIGHTWEIGHT_API SqlMigrationDeleteBuilder Delete(std::string_view tableName);
551
552 /// Executes SQL interactively via a callback.
553 LIGHTWEIGHT_API SqlMigrationQueryBuilder& Native(std::function<std::string(SqlConnection&)> callback);
554
555 /// Starts a transaction.
557
558 /// Commits a transaction.
560
561 /// Gets the migration plan.
562 [[nodiscard]] LIGHTWEIGHT_API SqlMigrationPlan const& GetPlan() const&;
563
564 /// Gets the migration plan.
565 ///
566 /// @note This method is destructive and will invalidate the current builder.
567 LIGHTWEIGHT_API SqlMigrationPlan GetPlan() &&;
568
569 private:
570 SqlQueryFormatter const& _formatter;
571 std::string _schemaName;
572 SqlMigrationPlan _migrationPlan;
573};
574
575} // 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:411
SqlMigrationDeleteBuilder & Where(std::string columnName, std::string op, T const &value)
Adds a WHERE condition to the DELETE.
Definition Migrate.hpp:421
SqlMigrationDeleteBuilder(SqlDeleteDataPlan &plan)
Constructs a migration DELETE builder.
Definition Migrate.hpp:414
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:436
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:480
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:491
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:439
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:394
SqlMigrationUpdateBuilder & Set(std::string columnName, T const &value)
Sets a column value for the UPDATE.
Definition Migrate.hpp:386
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.