|
Lightweight 0.20261105.1
|
#include <SqlMigration.hpp>
Classes | |
| struct | ChecksumRewriteEntry |
One row in the RewriteChecksumsResult.entries list. More... | |
| struct | ColumnUpgradeEntry |
One column upgrade entry in UnicodeUpgradeResult. More... | |
| struct | HardResetResult |
Result of a HardReset call. More... | |
| struct | PlanFoldingResult |
| Snapshot of the schema the registered migrations intend to produce. More... | |
| struct | RewriteChecksumsResult |
Result of a RewriteChecksums call. More... | |
| struct | UnicodeUpgradeResult |
Result of an UnicodeUpgradeTables call. More... | |
Public Types | |
| using | MigrationList = std::list< MigrationBase const * > |
| Type alias for a list of migration pointers. | |
| using | ExecuteCallback = std::function< void(MigrationBase const &, size_t, size_t)> |
| Callback type invoked during migration execution to report progress. | |
| using | LogSink = std::function< void(std::string_view)> |
| using | CompatPolicy = std::function< std::set< std::string >(MigrationBase const &)> |
| Per-migration compat policy. | |
Public Member Functions | |
| LIGHTWEIGHT_API void | AddMigration (MigrationBase const *migration) |
| LIGHTWEIGHT_API MigrationList const & | GetAllMigrations () const noexcept |
| LIGHTWEIGHT_API MigrationBase const * | GetMigration (MigrationTimestamp timestamp) const noexcept |
| LIGHTWEIGHT_API void | RemoveMigration (MigrationBase const *migration) noexcept |
| LIGHTWEIGHT_API void | RemoveAllMigrations () |
| LIGHTWEIGHT_API std::list< MigrationBase const * > | GetPending () const |
| LIGHTWEIGHT_API void | ApplySingleMigration (MigrationBase const &migration) |
| LIGHTWEIGHT_API void | ApplySingleMigration (MigrationBase const &migration, MigrationRenderContext &context) |
Variant of ApplySingleMigration that threads a caller-owned render context through to ToSql. Use this from loops over multiple migrations so the column-width cache (and other per-run compat state) accumulates across the sequence. | |
| LIGHTWEIGHT_API void | RevertSingleMigration (MigrationBase const &migration) |
| LIGHTWEIGHT_API size_t | ApplyPendingMigrations (ExecuteCallback const &feedbackCallback={}) |
| LIGHTWEIGHT_API size_t | ApplyPendingMigrationsUpTo (MigrationTimestamp targetInclusive, ExecuteCallback const &feedbackCallback={}) |
| LIGHTWEIGHT_API void | CreateMigrationHistory () |
| Create the migration history table if it does not exist. | |
| LIGHTWEIGHT_API void | SetDefaultSchema (std::string schema) |
| Sets the default schema applied to migration connections. | |
| LIGHTWEIGHT_API std::string_view | DefaultSchema () const noexcept |
| Returns the default schema currently installed on the manager (empty when unset). | |
| LIGHTWEIGHT_API std::vector< MigrationTimestamp > | GetAppliedMigrationIds () const |
| LIGHTWEIGHT_API void | AddVirtualAppliedMigrations (std::span< MigrationTimestamp const > timestamps) |
| LIGHTWEIGHT_API void | ClearVirtualAppliedMigrations () |
| LIGHTWEIGHT_API void | SetLogSink (LogSink sink) |
| LIGHTWEIGHT_API void | Log (std::string_view message) const |
| LIGHTWEIGHT_API std::size_t | SkippedExistingRowCount () const noexcept |
Number of rows Insert(...).IfNotExists(...) steps skipped because a row with the same key values already existed, counted over the manager's lifetime. | |
| LIGHTWEIGHT_API void | AddPreMigrateStep (std::string title, PreMigrateStepOptions options, PreMigrateStep step) |
| LIGHTWEIGHT_API std::vector< PreMigrateStepInfo > | GetPreMigrateSteps () const |
| LIGHTWEIGHT_API void | RemoveAllPreMigrateSteps () noexcept |
| Removes every pre-migrate step. | |
| LIGHTWEIGHT_API PreMigrateStepsOutcome | RunPreMigrateSteps (ProgressTask &parent, ExecutionMode mode) |
| LIGHTWEIGHT_API DataMapper & | GetDataMapper () |
| LIGHTWEIGHT_API DataMapper & | GetDataMapper () const |
| Get the data mapper used for migrations. | |
| LIGHTWEIGHT_API void | CloseDataMapper () |
| LIGHTWEIGHT_API void | SetCompatPolicy (CompatPolicy policy) |
Installs a per-migration compat policy. Pass {} to clear. | |
| LIGHTWEIGHT_API CompatPolicy const & | GetCompatPolicy () const noexcept |
| Returns a view of the installed policy so it can be propagated across managers (plugin → central). Empty callable if no policy was installed. | |
| LIGHTWEIGHT_API void | ComposeCompatPolicy (CompatPolicy policy) |
| Composes an additional policy with the currently installed one. If no policy is installed, the argument becomes the policy as-is; otherwise both policies are consulted and their flag sets unioned per migration. | |
| LIGHTWEIGHT_API std::set< std::string > | CompatFlagsFor (MigrationBase const &migration) const |
Returns the compat flags the current policy assigns to migration, or an empty set if no policy is installed. | |
| LIGHTWEIGHT_API SqlTransaction | Transaction () |
| LIGHTWEIGHT_API std::vector< std::string > | PreviewMigration (MigrationBase const &migration) const |
| LIGHTWEIGHT_API std::vector< std::string > | PreviewMigrationWithContext (MigrationBase const &migration, MigrationRenderContext &context) const |
Variant of PreviewMigration that threads a caller-owned render context so the column-width cache accumulates across a sequence of preview calls. Used by PreviewPendingMigrations to render compat-aware dry runs. | |
| LIGHTWEIGHT_API PlanFoldingResult | FoldRegisteredMigrations (SqlQueryFormatter const &formatter, std::optional< MigrationTimestamp > upToInclusive=std::nullopt) const |
| Pure plan-walk that folds the effect of every registered migration. | |
| LIGHTWEIGHT_API HardResetResult | HardReset (ExecutionMode mode=ExecutionMode::Execute) |
Drops every table the registered migrations would create (incl. schema_migrations), preserving any user-created tables. | |
| LIGHTWEIGHT_API UnicodeUpgradeResult | UnicodeUpgradeTables (ExecutionMode mode=ExecutionMode::Execute, ProgressTask *progress=nullptr) |
Rewrites legacy VARCHAR/CHAR columns to NVARCHAR/NCHAR where the registered migrations now declare wide types. | |
| LIGHTWEIGHT_API RewriteChecksumsResult | RewriteChecksums (bool dryRun=false) |
Re-stamps schema_migrations.checksum rows that have drifted. | |
| LIGHTWEIGHT_API std::vector< std::string > | PreviewPendingMigrations (ExecuteCallback const &feedbackCallback={}) const |
| LIGHTWEIGHT_API std::vector< std::string > | PreviewPendingMigrationsUpTo (MigrationTimestamp targetInclusive, ExecuteCallback const &feedbackCallback={}) const |
| LIGHTWEIGHT_API std::vector< ChecksumVerificationResult > | VerifyChecksums () const |
| LIGHTWEIGHT_API void | MarkMigrationAsApplied (MigrationBase const &migration) |
| LIGHTWEIGHT_API RevertResult | RevertToMigration (MigrationTimestamp target, ExecuteCallback const &feedbackCallback={}) |
| LIGHTWEIGHT_API MigrationStatus | GetMigrationStatus () const |
| LIGHTWEIGHT_API void | ValidateDependencies () const |
| LIGHTWEIGHT_API void | RegisterRelease (std::string version, MigrationTimestamp highestTimestamp, MigrationReleaseOptions options={}) |
| LIGHTWEIGHT_API void | RemoveAllReleases () |
| Remove all registered releases. Useful for resetting state in tests. | |
| LIGHTWEIGHT_API std::vector< MigrationRelease > const & | GetAllReleases () const noexcept |
Get all registered releases, sorted ascending by highestTimestamp. | |
| LIGHTWEIGHT_API MigrationRelease const * | FindReleaseByVersion (std::string_view version) const noexcept |
| LIGHTWEIGHT_API MigrationRelease const * | FindReleaseForTimestamp (MigrationTimestamp timestamp) const noexcept |
| LIGHTWEIGHT_API MigrationList | GetMigrationsForRelease (std::string_view version) const |
| LIGHTWEIGHT_API BackupRequirement | BackupRequirementFor (std::span< MigrationTimestamp const > toRun) |
Static Public Member Functions | |
| static LIGHTWEIGHT_API MigrationManager & | GetInstance () |
Main API to use for managing SQL migrations
This class is a singleton and can be accessed using the GetInstance() method.
Definition at line 460 of file SqlMigration.hpp.
| using Lightweight::SqlMigration::MigrationManager::MigrationList = std::list<MigrationBase const*> |
Type alias for a list of migration pointers.
Definition at line 464 of file SqlMigration.hpp.
| using Lightweight::SqlMigration::MigrationManager::ExecuteCallback = std::function<void(MigrationBase const& , size_t , size_t )> |
Callback type invoked during migration execution to report progress.
Definition at line 514 of file SqlMigration.hpp.
| using Lightweight::SqlMigration::MigrationManager::LogSink = std::function<void(std::string_view)> |
Optional sink for informational status messages emitted by plugin hooks (e.g. the "Transitioning from LASTRADA_PROPERTIES …" banner). dbtool installs a sink that prints to stdout to preserve the historical CLI output; dbtool-gui installs a sink that routes through its LogInfo channel so the banner shows up in the activity log instead of going to a hidden stream.
Definition at line 627 of file SqlMigration.hpp.
| using Lightweight::SqlMigration::MigrationManager::CompatPolicy = std::function<std::set<std::string>(MigrationBase const&)> |
Per-migration compat policy.
Given a migration about to be applied (or previewed), returns the set of compat flags that should be active while rendering it. Plugins that ship legacy migrations use this to scope compat behaviour to their own timestamp range (e.g. a plugin enables lup-truncate for migrations predating a given release). Unset means "strict for every migration".
Definition at line 710 of file SqlMigration.hpp.
|
static |
Get the singleton instance of the migration manager.
Referenced by Lightweight::SqlMigration::MigrationBase::MigrationBase(), and Lightweight::SqlMigration::MigrationBase::~MigrationBase().
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::AddMigration | ( | MigrationBase const * | migration | ) |
Add a migration to the manager.
| migration | Pointer to the migration to add. |
Referenced by Lightweight::SqlMigration::MigrationBase::MigrationBase().
|
noexcept |
Get all migrations that have been added to the manager.
|
noexcept |
Get a migration by timestamp.
| timestamp | Timestamp of the migration to get. |
|
noexcept |
Remove a single migration from the manager.
Called by MigrationBase's destructor so a migration that goes out of scope does not leave a dangling pointer behind. Removing a migration that was never added is a no-op.
| migration | Pointer to the migration to remove. |
Referenced by Lightweight::SqlMigration::MigrationBase::~MigrationBase().
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::RemoveAllMigrations | ( | ) |
Remove all migrations from the manager.
This function is useful if the migration manager should be reset.
| LIGHTWEIGHT_API std::list< MigrationBase const * > Lightweight::SqlMigration::MigrationManager::GetPending | ( | ) | const |
Get all migrations that have not been applied yet.
A dependency cycle does not throw: the list then falls back to timestamp order, and the error surfaces again from ApplyPendingMigrations() / ValidateDependencies().
| std::runtime_error | Reading the applied migrations failed in a way other than the table being absent (e.g. an unexpected NULL in schema_migrations). |
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::ApplySingleMigration | ( | MigrationBase const & | migration | ) |
Apply a single migration from a migration object.
| migration | Pointer to the migration to apply. |
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::RevertSingleMigration | ( | MigrationBase const & | migration | ) |
Revert a single migration from a migration object.
| migration | Pointer to the migration to revert. |
| LIGHTWEIGHT_API size_t Lightweight::SqlMigration::MigrationManager::ApplyPendingMigrations | ( | ExecuteCallback const & | feedbackCallback = {} | ) |
Apply all migrations that have not been applied yet.
| feedbackCallback | Callback to be called for each migration. |
| LIGHTWEIGHT_API size_t Lightweight::SqlMigration::MigrationManager::ApplyPendingMigrationsUpTo | ( | MigrationTimestamp | targetInclusive, |
| ExecuteCallback const & | feedbackCallback = {} |
||
| ) |
Apply pending migrations whose timestamp is <= targetInclusive.
Honors dependency-respecting topological order, just like ApplyPendingMigrations, and threads a single render context across the run so column-width state from earlier CREATE TABLEs is visible to later compat-aware INSERT/UPDATE rendering.
If a pending migration with ts <= target declares a dependency on a migration whose timestamp is > target (i.e. excluded by the bound) and is not already applied, this throws — partial states that violate dependencies are refused up front.
| targetInclusive | Highest timestamp to apply (inclusive). |
| feedbackCallback | Callback to be called for each migration. |
targetInclusive). | std::runtime_error | if a dependency would cross the boundary. |
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::SetDefaultSchema | ( | std::string | schema | ) |
Sets the default schema applied to migration connections.
When non-empty, installs a chained SqlConnection::SetPostConnectedHook that executes the formatter's SetDefaultSchemaStatement(schema) (e.g. SET search_path TO "<schema>", public on PostgreSQL) for every new connection. SQL Server and SQLite have no portable session-level "default schema" command — for SQL Server, the connecting login's server-side DEFAULT_SCHEMA is what determines where unqualified DDL/DML lands.
schema is validated against a [A-Za-z0-9_] whitelist; rejecting invalid input by throwing a std::invalid_argument. Passing an empty string clears any previously installed schema hook.
Calling this after a connection has already been opened on the current thread does not retroactively apply the schema — the hook fires on subsequent SqlConnection::Connect calls. For dbtool and the GUI this is invoked before the first connection.
| schema | The default schema to use. Empty disables. |
| LIGHTWEIGHT_API std::vector< MigrationTimestamp > Lightweight::SqlMigration::MigrationManager::GetAppliedMigrationIds | ( | ) | const |
Get all applied migration IDs.
Returns the union of timestamps physically present in schema_migrations and the in-memory "virtual applied" overlay (see AddVirtualAppliedMigrations), sorted ascending and deduplicated. The accessor never creates the schema_migrations table — when the table does not exist the database half of the union is the empty set, so a pure-overlay state is fully observable here without any side effects.
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::AddVirtualAppliedMigrations | ( | std::span< MigrationTimestamp const > | timestamps | ) |
Contribute "virtual" applied migration IDs that participate in every GetAppliedMigrationIds() read but are not persisted to schema_migrations until the manager actually performs a write (ApplySingleMigration, MarkMigrationAsApplied, or RevertSingleMigration). Designed for plugin post-init hooks that need to bridge a foreign version-tracking table (e.g. the legacy LASTRADA_PROPERTIES NR=4 row) into the modern applied-set view without paying for table creation on read-only commands like status or list-applied.
The input is merged into an internal sorted, deduplicated vector; passing the same timestamp twice is a no-op.
| timestamps | Timestamps to add to the overlay. |
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::ClearVirtualAppliedMigrations | ( | ) |
Drop every entry from the in-memory virtual-applied overlay. Intended for test setup/teardown and for callers that want to re-derive the overlay from scratch (e.g. a dbtool-gui reconnect against a different profile). Has no effect on schema_migrations rows.
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::SetLogSink | ( | LogSink | sink | ) |
Install a log sink. Pass {} to clear.
| sink | Callable invoked once per status message. |
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::Log | ( | std::string_view | message | ) | const |
Emit a status message via the installed sink. No-op when no sink is installed — silent by default keeps the library suitable for use in embedded contexts that have no obvious output stream.
| message | The message to deliver. |
|
noexcept |
Number of rows Insert(...).IfNotExists(...) steps skipped because a row with the same key values already existed, counted over the manager's lifetime.
Each skip is also reported through Log as one line of the form Skipped existing row: <timestamp> <table> (<key>=<value>, ...). Both happen once the migration has committed, so a migration that fails and rolls back reports no skips. Callers that need the count of one run take the difference before and after it.
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::AddPreMigrateStep | ( | std::string | title, |
| PreMigrateStepOptions | options, | ||
| PreMigrateStep | step | ||
| ) |
Registers a step that migrate, apply and migrate-to-release run, in registration order, before their first pending migration (also when none is pending). Plugins register steps from their post-init hook; a step is code of that plugin, so hosts call RemoveAllPreMigrateSteps before running post-init hooks again and before unloading it.
| title | The step's title, unique among the steps. |
| options | The step's options. |
| step | The step's code. |
| std::invalid_argument | when step is empty or a step titled title exists. |
| LIGHTWEIGHT_API std::vector< PreMigrateStepInfo > Lightweight::SqlMigration::MigrationManager::GetPreMigrateSteps | ( | ) | const |
| LIGHTWEIGHT_API PreMigrateStepsOutcome Lightweight::SqlMigration::MigrationManager::RunPreMigrateSteps | ( | ProgressTask & | parent, |
| ExecutionMode | mode | ||
| ) |
Runs the pre-migrate steps in registration order, each under a sub-task of parent named like the step, on the migration connection. The caller holds the migration lock (unless it opted out of locking) and calls this before applying the first pending migration. Status and read-only commands never call it. Cancellation is checked before and after each step.
| parent | The task the steps' tasks open under. |
| mode | Whether the steps only report their plan. |
Cancelled when parent asked to cancel; the caller then applies no migration. | PreMigrateStepError | when a step throws, also something other than a std::exception ("unknown exception"); the steps after it do not run. |
| LIGHTWEIGHT_API DataMapper & Lightweight::SqlMigration::MigrationManager::GetDataMapper | ( | ) |
Get the data mapper used for migrations.
Owned by the manager and connected with the default connection string on first use. When the application replaces the default (SqlConnection::SetDefaultConnectionString), the next call reconnects the same instance - the reference stays valid - to the new default. A call from a copy of the library that never had a default set (a plugin that links Lightweight statically, calling into the host's manager from a hook) keeps the mapper as it is.
| SqlException | Connecting failed. |
Referenced by GetDataMapper().
|
inline |
Get the data mapper used for migrations.
Definition at line 692 of file SqlMigration.hpp.
References GetDataMapper().
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::CloseDataMapper | ( | ) |
Close the data mapper.
This function is useful if explicitly closing the connection is desired before the migration manager is destroyed.
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::SetCompatPolicy | ( | CompatPolicy | policy | ) |
Installs a per-migration compat policy. Pass {} to clear.
Typically called once from a plugin's static initializer. Replaces any policy previously installed — composition is the caller's responsibility for now. A policy from a plugin is code in that plugin's library: a host must clear it before it unloads the plugin, as dbtool's Tools::UnloadPlugins does.
| LIGHTWEIGHT_API SqlTransaction Lightweight::SqlMigration::MigrationManager::Transaction | ( | ) |
Get a transaction for the data mapper.
| LIGHTWEIGHT_API std::vector< std::string > Lightweight::SqlMigration::MigrationManager::PreviewMigration | ( | MigrationBase const & | migration | ) | const |
Preview SQL statements for a single migration without executing.
This is useful for dry-run mode to see what SQL would be executed.
| migration | The migration to preview. |
| LIGHTWEIGHT_API PlanFoldingResult Lightweight::SqlMigration::MigrationManager::FoldRegisteredMigrations | ( | SqlQueryFormatter const & | formatter, |
| std::optional< MigrationTimestamp > | upToInclusive = std::nullopt |
||
| ) | const |
Pure plan-walk that folds the effect of every registered migration.
Visits each migration's Up() plan in timestamp order (or up to upToInclusive if provided) and accumulates the cumulative end-state into a PlanFoldingResult. Never executes SQL or touches a database connection — the supplied formatter is only used to build the in-memory plan elements.
| formatter | Formatter used by the migration query builder while walking each migration's Up(). Any standard formatter works; the walk inspects plan element shapes, not rendered SQL. |
| upToInclusive | If set, fold only migrations with timestamp <= upToInclusive. If unset, fold all registered migrations. |
MigrationManager-attached data mapper. | LIGHTWEIGHT_API HardResetResult Lightweight::SqlMigration::MigrationManager::HardReset | ( | ExecutionMode | mode = ExecutionMode::Execute | ) |
Drops every table the registered migrations would create (incl. schema_migrations), preserving any user-created tables.
Folds all registered migrations to compute the migration-owned set, intersects with the live schema (via SqlSchema::ReadAllTables), then drops the matching live tables in reverse creation order with cascade=true ifExists=true. The schema_migrations table is dropped explicitly because it's created outside the registered-migrations stream.
Tables present in the live DB but not in the migration plan are left alone and reported under preservedTables so operators can spot them.
Also drops schema_backups: its records describe backups of the migration state being discarded.
| mode | ExecutionMode::DryRun returns the would-be plan without writing anything. |
| LIGHTWEIGHT_API UnicodeUpgradeResult Lightweight::SqlMigration::MigrationManager::UnicodeUpgradeTables | ( | ExecutionMode | mode = ExecutionMode::Execute, |
| ProgressTask * | progress = nullptr |
||
| ) |
Rewrites legacy VARCHAR/CHAR columns to NVARCHAR/NCHAR where the registered migrations now declare wide types.
Compares the folded plan's intended column types against SqlSchema::ReadAllTables output; an upgrade is triggered iff intended is NVarchar/NChar AND live is Varchar/Char with the same size. Foreign keys that touch any upgrade column are dropped before the alter and re-added afterwards; SQL Server and PostgreSQL read them from the catalog and recreate them under their own names with their own definitions (referenced schema, actions), whoever created them. Cross-backend; SQLite uses the in-tree RebuildSqliteTable recipe under the hood.
Declared names match live ones without regard to case where the dialect's identifiers are case-insensitive (SqlQueryFormatter::IdentifiersAreCaseInsensitive).
The live tables of every schema are read. A declared table resolves to the schema its migration names; else to the first schema holding that name in the connection's name resolution order (SQL Server: the user's default schema, then dbo; PostgreSQL: the search path); else to the only schema holding it. Each column is altered, and its dependents found, in the schema it was resolved to. When several schemas hold a declared name, none of them is in that order and one has a column to widen, the call throws std::runtime_error naming them.
Where a foreign key needs both sides to share one text type (SQL Server), every column a foreign key joins to an upgraded column is upgraded too, declared or not, and reported with ColumnUpgradeEntry::joinedByForeignKeyTo set. Such a column must have the same narrow type and size and must not be declared with another type; otherwise the call throws std::runtime_error naming it, in a dry run too, before anything has changed.
Each unit (see UnicodeUpgradeResult::units) runs in a transaction of its own and is committed before the next one starts; the log sink reports each committed unit. Under the simple recovery model, or while log backups run, the transaction log then only has to hold one unit, so the largest unit sets its peak. A failing unit is rolled back and stops the call with UnicodeUpgradeUnitError, which names it and says how many units were committed before it. A later call continues where this one stopped, as the plan is computed from the live schema.
A unit that fails is reported as failed on its tasks (the failing table's, the unit's and the overall one) before the call throws.
| mode | ExecutionMode::DryRun returns the would-be diff without writing anything and reports only the plan to progress. |
| progress | Receives planning, an overall task weighted by the tables' row counts (SQL Server: sys.partitions; PostgreSQL: pg_class.reltuples; otherwise COUNT(*)), one task per unit and per table; null reports nothing. Cancellation is checked after each committed unit except the last; see UnicodeUpgradeResult::wasCancelled. |
| LIGHTWEIGHT_API RewriteChecksumsResult Lightweight::SqlMigration::MigrationManager::RewriteChecksums | ( | bool | dryRun = false | ) |
Re-stamps schema_migrations.checksum rows that have drifted.
Applied migrations whose stored checksum no longer matches the current MigrationBase::ComputeChecksum output are updated in-place. Migrations that match are left alone. Rows that reference a migration which is no longer registered (e.g. removed from the codebase) are surfaced via RewriteChecksumsResult.unregisteredTimestamps and not touched.
This is a recovery tool used when a regen of generated migrations changes their byte-level shape but not their logical effect — running it without understanding why the checksum drifted would defeat the integrity check.
| dryRun | When true, returns the would-be diff without writing anything. |
| LIGHTWEIGHT_API std::vector< std::string > Lightweight::SqlMigration::MigrationManager::PreviewPendingMigrations | ( | ExecuteCallback const & | feedbackCallback = {} | ) | const |
Preview SQL statements for all pending migrations without executing.
This is useful for dry-run mode to see what SQL would be executed.
| feedbackCallback | Optional callback to be called for each migration. |
| LIGHTWEIGHT_API std::vector< std::string > Lightweight::SqlMigration::MigrationManager::PreviewPendingMigrationsUpTo | ( | MigrationTimestamp | targetInclusive, |
| ExecuteCallback const & | feedbackCallback = {} |
||
| ) | const |
Preview SQL for pending migrations whose timestamp is <= targetInclusive.
Bounded counterpart of PreviewPendingMigrations. Same dependency rules as ApplyPendingMigrationsUpTo: if any included migration depends on an excluded pending migration, this throws.
| targetInclusive | Highest timestamp to preview (inclusive). |
| feedbackCallback | Optional callback to be called for each migration. |
| std::runtime_error | if a dependency would cross the boundary. |
| LIGHTWEIGHT_API std::vector< ChecksumVerificationResult > Lightweight::SqlMigration::MigrationManager::VerifyChecksums | ( | ) | const |
Verify checksums of all applied migrations.
Compares the stored checksums in the database with the computed checksums of the current migration definitions. This helps detect if migrations have been modified after they were applied.
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::MarkMigrationAsApplied | ( | MigrationBase const & | migration | ) |
Mark a migration as applied without executing its Up() method.
This is useful for:
| migration | The migration to mark as applied. |
| std::runtime_error | if the migration is already applied. |
| LIGHTWEIGHT_API RevertResult Lightweight::SqlMigration::MigrationManager::RevertToMigration | ( | MigrationTimestamp | target, |
| ExecuteCallback const & | feedbackCallback = {} |
||
| ) |
Revert all migrations applied after the target timestamp.
This method reverts migrations in reverse chronological order, rolling back from the most recent to just after the target. The target migration itself is NOT reverted.
| target | Target timestamp to revert to. Migrations > target are reverted. |
| feedbackCallback | Optional callback for progress updates. |
| LIGHTWEIGHT_API MigrationStatus Lightweight::SqlMigration::MigrationManager::GetMigrationStatus | ( | ) | const |
Get a summary status of all migrations.
This method provides a quick overview of the migration state without needing to iterate through individual migrations.
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::ValidateDependencies | ( | ) | const |
Validate that all registered migrations have satisfiable dependencies.
For each pending migration, verifies that every declared dependency is either already applied or itself pending (so it will be applied first due to topological ordering). Also detects cycles among pending migrations.
| std::runtime_error | if any dependency is unresolved or a cycle is found. |
| LIGHTWEIGHT_API void Lightweight::SqlMigration::MigrationManager::RegisterRelease | ( | std::string | version, |
| MigrationTimestamp | highestTimestamp, | ||
| MigrationReleaseOptions | options = {} |
||
| ) |
Register a release marker for a software version.
Typically called from LIGHTWEIGHT_SQL_RELEASE(version, timestamp) at static init time. Releases are ordered by highestTimestamp; two releases may not share the same highestTimestamp, and the same version string may not be registered twice.
| version | Human-readable version, e.g. "6.7.0". |
| highestTimestamp | Highest migration timestamp (inclusive) that belongs to this release. |
| options | Release options, e.g. { .requiresBackup = true }. |
| std::runtime_error | on duplicate version or duplicate timestamp. |
|
noexcept |
Find a release by exact version string match.
|
noexcept |
Find the release whose timestamp range contains timestamp.
Returns the release with the smallest highestTimestamp that is >= timestamp. Returns nullptr if timestamp is greater than every registered release's highestTimestamp (i.e., the migration is post-all-releases / unreleased).
| LIGHTWEIGHT_API MigrationList Lightweight::SqlMigration::MigrationManager::GetMigrationsForRelease | ( | std::string_view | version | ) | const |
Get all registered migrations belonging to a given release.
A migration M belongs to release R iff prev_release_ts < M.timestamp <= R.highestTimestamp, where prev_release_ts is the previous release's timestamp (or 0 if R is the first release).
| version | The version string to look up. |
| LIGHTWEIGHT_API BackupRequirement Lightweight::SqlMigration::MigrationManager::BackupRequirementFor | ( | std::span< MigrationTimestamp const > | toRun | ) |
Whether the work a command will run needs a backup first, and whether one exists.
Only that work counts: a migration of toRun demands a backup when it RequiresBackup() or its release declares requiresBackup, and a registered pre-migrate step when its requiresBackup predicate returns true (evaluated here, on the migration connection). Pass all pending migrations for migrate, the pending ones up to the release for migrate-to-release, the named one for apply. Only when something demands a backup are schema_backups and schema_migrations read: the newest backup or restore record must cover the database's current state (see BackupRecordCovers).
| toRun | The migrations the command will run. |
required is false when nothing demands a backup. | whatever | a step's predicate throws. |