|
Lightweight 0.20261105.1
|
SQL migrations provide a structured way to evolve your database schema over time. Each migration represents a discrete change (creating tables, adding columns, etc.) that can be applied or reverted independently.
Key benefits:
The simplest way to create a migration:
The migration is automatically registered with the MigrationManager when the program starts, and unregistered again when it is destroyed. Registration is tied to the object's lifetime, so a migration that does not live for the whole program – one with automatic storage duration, say – leaves no dangling pointer behind in the manager it registered with.
For more control, including rollback support:
Migration timestamps use the format YYYYMMDDHHMMSS (14 digits):
dbtool new-migration <title> creates a source file with the current UTC time filled in (see dbtool.md).
Timestamps must be:
When creating migrations in a shared library plugin, add this macro to exactly one source file:
The LIGHTWEIGHT_MIGRATION_PLUGIN() macro exports the AcquireMigrationManager() function that dbtool uses to load migrations from the plugin.
A plugin can also export two optional hooks, described in dbtool.md:
| Macro | Runs |
|---|---|
LIGHTWEIGHT_MIGRATION_PLUGIN_POSTINIT(connection, manager) | before every dbtool command, read-only ones included; failures are logged only |
LIGHTWEIGHT_MIGRATION_PLUGIN_POSTMIGRATE(connection, manager) | after a successful migrate / migrate-to-release / apply, under the migration lock; a failure fails the command |
The post-init hook may also call manager.AddPreMigrateStep(...) to register work that runs before the first migration; see Pre-migrate steps.
Create a new table with various column types:
Column modifiers (chain after column declaration):
.Unique() - Add unique constraint.Index() - Create an index on this column.UniqueIndex() - Create a unique indexConditional creation:
Modify an existing table:
Available operations:
| Method | Description |
|---|---|
.AddColumn(name, type) | Add a non-nullable column |
.AddNotRequiredColumn(name, type) | Add a nullable column |
.RenameColumn(old, new) | Rename a column |
.DropColumn(name) | Remove a column |
.AlterColumn(name, type, nullable) | Change column type or nullability |
.AddIndex(column) | Create an index |
.AddUniqueIndex(column) | Create a unique index |
.DropIndex(column) | Remove an index |
.AddForeignKey(column, ref) | Add foreign key to existing column |
.AddForeignKeyColumn(name, type, ref) | Add new column with foreign key |
.DropForeignKey(column) | Remove foreign key constraint |
.RenameTo(newName) | Rename the table |
SQLite note: SQLite has no native
ALTER TABLE … ALTER COLUMNor… ADD/DROP CONSTRAINT, so.AlterColumn(...),.AddForeignKey(...), and.DropForeignKey(...)are applied by rebuilding the table. That rebuild runs only when the migration is applied throughMigrationManager(ApplyPendingMigrations()); the generatedToSql()text for these operations is a-- LIGHTWEIGHT_SQLITE_GUARD:sentinel comment that does nothing if executed directly. Applying such a migration viaSqlStatement::MigrateDirectthrows rather than silently skipping the change.
Conditional operations:
Remove a table:
Conditional drop:
Cascade drop (removes foreign key constraints):
Insert data during migrations:
A database may already contain a reference row that a later migration inserts, for example one applied earlier by a hotfix. A plain Insert then fails with a duplicate key and stops the whole migration. IfNotExists names the key columns that identify the row and makes the insert skip it when a row with the same key values exists:
It runs as one statement on every backend, with the table schema-qualified the same way as a plain insert. Run through MigrationManager (and so through dbtool), every value is bound as a parameter:
--dry-run, ToSql) show the same statement with the values as literals, rendered exactly as a plain Insert renders them, so a checksum does not depend on how the values reach the database. Adding IfNotExists changes a migration's checksum; a plain Insert renders, checksums and runs exactly as before. ToBoundSql returns the bound form.SqlStatement::MigrateDirect and other callers that execute ToSql() output run the literal form instead; it skips existing rows the same way.IfNotExists insert first runs SET NOCOUNT OFF, since the skip is read from the affected-row count; the setting stays in effect for the session afterwards.SET LANGUAGE British) is read as yyyy-dd-mm; a plain Insert literal is read the same way, and a DATE or DATETIME2 column is not affected.SqlDynamicNumeric (also at high scale such as DECIMAL(28,12)), binary values and bool are bound natively and store exactly as their literals.Insert stored.A double is bound as its binary value. In FLOAT/REAL columns and in DECIMAL columns of low scale (e.g. 40.3399, 0.5, -12.25 into DECIMAL(10,4)) it stores exactly as the literal of a plain Insert. Known divergences, where the literal is parsed as a decimal instead:
123456.789012 into DECIMAL(28,12) stores 123456.789011999994 bound and 123456.789012000000 as a literal;0.30000000000000004, 1e-7), which the bound value carries;3.0 bound as "3.0", as a literal as "3".Do not key IfNotExists on such a double: in these cases the bound key misses a row a plain Insert stored, and the insert then adds a duplicate. Use SqlNumeric / SqlDynamicNumeric for exact decimal values.
IfNotExists only prevents the duplicate; it never updates.AND: .IfNotExists({ "Kind", "Id" }).std::invalid_argument when a key column is not one of the Set columns, or when its value is NULL (= never matches NULL, so the row would be inserted again on every run). IfNotExists({}) throws right away.MigrationManager::SkippedExistingRowCount()) and reported through the manager's log sink as Skipped existing row: <timestamp> <table> (<key>=<value>, ...). See dbtool for how dbtool prints it.Update existing data:
Remove data:
Create standalone indexes:
Composite indexes:
Pass a SqlCreateIndexOptions to index only the rows that match a predicate. SQLite and PostgreSQL call this a partial index, SQL Server a filtered index; all three accept the same WHERE clause after the column list.
A typical use is deduplicating on an optional key: rows that have a key must be unique, rows without one may repeat. An unconditional unique index would reject the second row with an empty key.
whereExpression is the predicate body without the leading WHERE. It is emitted verbatim, so quote identifiers and literals yourself. To stay portable, keep to what SQL Server accepts in a filter: comparisons of a column with a constant, IS [NOT] NULL and IN (...) lists, joined with AND (no OR, functions or computed expressions).
SQL Server: a filtered index requires
ANSI_WARNINGS ONboth to be created and for everyINSERT,UPDATEandDELETEon its table; otherwise SQL Server fails the statement with error 1934. Lightweight's default string-truncation mode (SqlStringTruncationMode::Truncate) turnsANSI_WARNINGSoff, so connections that apply or write through a filtered index must useSqlStringTruncationMode::Error, set per connection withSqlConnection::SetStringTruncationModeor for new connections withSqlConnection::SetDefaultStringTruncationMode. SQLite and PostgreSQL have no such requirement.
Limitation: the backup tool (
dbtool backup/SqlBackup) reads indexes from the live schema and does not capture index predicates yet. It backs a partial index up as an index over all rows, and a single-column partial unique index can also mark its column unique. Restoring data that relies on the predicate (such as two rows with an emptydedup_key) therefore fails for such tables.
For database-specific features or complex operations:
| C++ Type | SQL Type | Notes |
|---|---|---|
Integer() | INTEGER | 32-bit integer |
Smallint() | SMALLINT | 16-bit integer |
Bigint() | BIGINT | 64-bit integer |
Tinyint() | TINYINT | 8-bit integer |
Real() | REAL/FLOAT | Floating point |
Bool() | BOOLEAN/BIT | Boolean |
Char(n) | CHAR(n) | Fixed-length string |
Varchar(n) | VARCHAR(n) | Variable-length string |
NChar(n) | NCHAR(n) | Fixed-length Unicode string |
NVarchar(n) | NVARCHAR(n) | Variable-length Unicode string |
Text() | TEXT | Large text |
DateTime() | DATETIME/TIMESTAMP | Date and time |
Date() | DATE | Date only |
Time() | TIME | Time only |
Guid() | UNIQUEIDENTIFIER/UUID | UUID/GUID |
Decimal(p, s) | DECIMAL(p, s) | Fixed-point number |
Binary(n) | BINARY(n) | Fixed-length binary |
VarBinary(n) | VARBINARY(n) | Variable-length binary |
To declare one of SQL Server's legacy large-object types, set legacyLob on the matching type: Varchar { .legacyLob = true } is TEXT, NVarchar { .legacyLob = true } is NTEXT and VarBinary { .legacyLob = true } is IMAGE. Other databases ignore the flag. SqlSchema sets it on the columns it reads, so a backup and restore keeps these types. SQL Server has restrictions of its own here: these columns cannot be indexed, sorted or be part of a key, and ALTER COLUMN cannot turn a TEXT column into NTEXT.
Usage:
When the target database expects unqualified DDL to land in a non-default schema (e.g. lasa instead of dbo / public), tell the manager about it before opening the first connection:
SetDefaultSchema installs a post-connect hook that emits the dialect- specific "make this the session default" statement for every new connection:
SET search_path TO "lasa", public. Both schema_migrations and unqualified DDL inside migrations land in lasa.DEFAULT_SCHEMA server-side (ALTER USER … WITH DEFAULT_SCHEMA = lasa). Migrations that need to write to a specific schema regardless of the login default should use the WithSchema(...) builder.On PostgreSQL a CreateTable built with WithSchema(...) names the schema for the table and its indexes (earlier releases created them in the search_path schema). So the schema must exist, and a database migrated by an earlier release reports checksum mismatches for those migrations until dbtool rewrite-checksums rewrites them. The table's inline foreign keys still name the referenced table without a schema; they resolve through the search_path, so the referenced table must lie in a schema on the search_path.
Schema names are validated against [A-Za-z0-9_] and rejected via std::invalid_argument otherwise. Passing "" clears any previously installed hook.
dbtool exposes this via the --schema flag and dbtool-gui exposes it as a "Schema" input on both the Profile and the direct-ODBC connection tabs.
Long-running library calls report their work through Lightweight::ProgressTask, an interface the host (a CLI, a GUI) implements and passes in; the library only calls it. Tasks nest: a task opens sub-tasks with BeginSubTask, advances with Advance, and destroying a task marks it finished. A total of 0 makes a task indeterminate (the host shows that it runs, not how far it got). Long loops poll IsCancellationRequested() at safe points. UnicodeUpgradeTables takes an ExecutionMode and a ProgressTask* (null reports nothing); RunPreMigrateSteps takes a ProgressTask&. NullProgressTask reports nothing and is never cancelled, for hosts that pass none. UnicodeUpgradeTables reports planning, an overall task weighted by the planned tables' row counts, a task per unit and per table. It checks for cancellation after each committed unit except the last and then returns with UnicodeUpgradeResult::wasCancelled set (committedUnitCount says how many units it committed); a later call continues with the next unit. dbtool draws the task tree with its --progress styles. A task that fails calls Fail(reason) before it ends, so the host shows it as failed (a row that stays visible), not as done.
A plugin can register work that runs before the first pending migration, such as widening columns the migrations then rely on. Register it from the post-init hook:
migrate, apply and migrate-to-release run the steps in registration order whenever they reach their apply phase, also with nothing pending (apply once its migration is found; migrate-to-release after its "already at or past" check). Status and read-only commands never run them.ExecutionMode::DryRun the step reports its plan and changes nothing. A dry run calls the steps, like it previews migrations, without taking the lock.ProgressTask, titled like the step.PreMigrateStepError before any migration runs; later steps do not run, and the step's task ends as failed. A step that can live with a problem calls progress.Log(ProgressTask::LogLevel::Warning, ...) and returns normally; the migrations then continue.RunPreMigrateSteps checks IsCancellationRequested() before and after each step and returns PreMigrateStepsOutcome::Cancelled; the caller then applies no migration.RemoveAllPreMigrateSteps() before running post-init hooks again (a reconnect) and before unloading a plugin, so a step is never registered twice nor outlives its library.requiresBackup:** an optional predicate in PreMigrateStepOptions, evaluated on the migration connection before the run, says whether this run of the step demands a backup (see Backup requirement). Hosts evaluate it on every check, not only before a run (dbtool-gui after each connect, run and backup), and on whatever thread they check from, a worker or a GUI's own thread. Keep it reasonably cheap, and free of thread affinity.Work that is hard to undo can demand a backup of the database first. Three things can:
MigrationBase::RequiresBackup(), set through MigrationMetadata::requiresBackup;LIGHTWEIGHT_SQL_RELEASE("3.0.0", 20260501120000, { .requiresBackup = true }); (or MigrationManager::RegisterRelease(version, timestamp, { .requiresBackup = true }));requiresBackup predicate returns true.MigrationManager::BackupRequirementFor(toRun) answers whether the work a command is about to run needs a backup and whether one exists. Only the work the command will run counts: pass all pending migrations for migrate, the pending ones up to the release for migrate-to-release, the named one for apply. Step predicates are evaluated by that call, on the migration connection. A predicate that throws makes the call throw.
| Member | Meaning |
|---|---|
required | Something demands a backup. |
reasons | What demands it, in this order: releases, migrations, steps. A migration whose release already demands one is not named again. |
satisfied | True when nothing is required; otherwise the newest backup or restore record covers the database's current state. |
lastBackup | The newest backup or restore record; waived rows are skipped. |
When nothing demands a backup, neither schema_backups nor schema_migrations is read or created.
Freshness rule (BackupRecordCovers): a backup that saw exactly the current migration history covers. ReadMigrationHistoryState returns a digest: the SHA-256 of the physical schema_migrations rows sorted by version, one <version>|<applied_at> line each (applied_at as milliseconds since the Unix epoch, empty when null; the virtual-applied overlay does not count). A backup or restore record covers when its stored digest equals the current one, so any migration applied, re-applied, rolled back or re-stamped since changes the result. Only values read from the database are compared; created_at is informational. A waived row (or any unknown kind) never covers.
A record is built from a MigrationHistoryState (BackupRecord::observedState), never from a clock. Read the state before the backup reads any data, and for a restore after it finished.
Only backups recorded by Lightweight's tools (dbtool, dbtool-gui) count, because only they write schema_backups rows. An archive made by other means satisfies nothing.
The migration lock stops other migrations, not the application's own writes made between the backup and the migration. Stop the application during such an upgrade.
Some databases predate the migration set — they were created by older tooling and differ from what the migrations declare. A compat policy returns, per migration, a set of opt-in flags that relax strict rendering for exactly those migrations. Migration plugins usually install one; it can also be set directly:
| Flag | Effect |
|---|---|
lup-truncate | String values in Insert / Update steps are truncated to the destination column's width, with a warning, instead of failing. |
fk-match-referenced-text | A foreign-key column declared by CreateTable / AlterTable (AddForeignKeyColumn) takes the narrow/wide variant of the column it references when the two differ only in that respect (CHAR(n)↔NCHAR(n), VARCHAR(n)↔NVARCHAR(n)). The referenced column's type is read from the live database (or from an earlier migration of the same run), and each change is logged as a warning. SQL Server only — PostgreSQL and SQLite store both kinds the same way. |
Flags only change the SQL sent to the database. Checksums are computed from the migration as declared, so the same migration has the same checksum on every database.
A policy installed by a plugin is code from that plugin's library. dbtool and dbtool-gui clear the policy, the migrations and the releases before they unload plugins (Lightweight::Tools::UnloadPlugins): at exit, after a failed plugin load, and in dbtool-gui whenever it reloads the plugin list, where the reloaded plugins' static initializers install their policy again. A host that loads plugins itself must do the same, or the manager calls into an unloaded library: at the next migration it applies, or in its destructor when the process exits.
Generate SQL without executing:
Revert migrations:
Mark a migration as applied without executing:
Lightweight automatically creates a schema_migrations table to track applied migrations:
| Column | Type | Description |
|---|---|---|
| version | BIGINT | Migration timestamp |
| checksum | VARCHAR(64) | SHA-256 checksum of migration SQL |
| applied_at | DATETIME | When the migration was applied |
dbtool and dbtool-gui append a row to schema_backups after a verified backup or a restore, and when a run goes ahead without a required backup because the user waived it. The table is created on first use and dropped by HardReset (its rows describe the migration state being discarded). Read and write it with ReadLatestBackupRecord / WriteBackupRecord; see Backup requirement for how it is used.
| Column | Type | Description |
|---|---|---|
| id | BIGINT | Assigned by the database; the newest record has the highest |
| created_at | DATETIME | Informational, UTC: for a backup when it started reading the database, for a restore when it finished |
| archive_file_name | NVARCHAR(255) | Archive name without its directory; empty for waived |
| archive_sha256 | VARCHAR(64) | SHA-256 of the archive file, lowercase hex; empty for waived |
| last_migration | BIGINT | Highest version in schema_migrations at created_at; null when there was none |
| migration_state_digest | VARCHAR(64) | Digest of the schema_migrations history the backup saw (read before it started; a restore: after it finished) |
| tool_version | VARCHAR(128) | The tool that wrote the row, e.g. dbtool 1.2.3 |
| kind | VARCHAR(16) | backup, restore or waived |
Use SqlScopedLock (the generic distributed-lock RAII type) to prevent concurrent migrations:
SqlScopedLock is not migration-specific — any caller that needs a named cross-process token can use it (cron leadership, "only one worker
processes batch X", queue ownership, …). Pick any string for the lock name; two processes that pass the same string will serialise on it.
For structured error handling — distinguishing timeout from deadlock from driver error programmatically — use the non-throwing SqlScopedLock::TryConstruct(connection, name, timeout) factory, which returns std::expected<SqlScopedLock, SqlLockError>.
The dialect-specific primitive is selected automatically by the active SqlQueryFormatter:
sp_getapplock / sp_releaseapplockpg_advisory_lock / pg_advisory_unlock_lightweight_locks table guarded by a unique constraintOn SQLite the bookkeeping table _lightweight_locks is treated as infrastructure — dbtool hard-reset drops it alongside schema_migrations rather than mistaking it for user data.
IfNotExists/IfExists variants when idempotency is important.dbtool backup before applying migrations to production.--dry-run before applying: