6#include "DataMapper/DataMapper.hpp"
8#include "SqlQuery/Migrate.hpp"
9#include "SqlQuery/MigrationPlan.hpp"
10#include "SqlSchema.hpp"
11#include "SqlTransaction.hpp"
86 std::size_t stepIndex,
87 std::string failedSql,
119 return _driverMessage;
123 Operation _operation;
126 std::size_t _stepIndex;
127 std::string _failedSql;
128 std::string _driverMessage;
251 std::function<
void(
MigrationBase const& ,
size_t ,
size_t )>;
377 std::vector<MigrationTimestamp>
413 std::map<SqlSchema::FullyQualifiedTableName, TableState>
tables;
461 SqlQueryFormatter const& formatter, std::optional<MigrationTimestamp> upToInclusive = std::nullopt)
const;
502 SqlSchema::FullyQualifiedTableName
table;
583 [[nodiscard]] LIGHTWEIGHT_API std::vector<ChecksumVerificationResult>
VerifyChecksums()
const;
641 [[nodiscard]] LIGHTWEIGHT_API std::vector<MigrationRelease>
const&
GetAllReleases() const noexcept;
689#define LIGHTWEIGHT_MIGRATION_PLUGIN() \
691 extern "C" LIGHTWEIGHT_EXPORT Lightweight::SqlMigration::MigrationManager* AcquireMigrationManager() \
693 return &Lightweight::SqlMigration::MigrationManager::GetInstance(); \
710 _timestamp { timestamp },
759 [[nodiscard]]
virtual std::string_view
GetAuthor() const noexcept
785 [[nodiscard]] std::string_view
GetTitle() const noexcept
802 std::string_view _title;
826 template <u
int64_t TsValue>
827 class Migration:
public MigrationBase
834 static constexpr MigrationTimestamp TimeStamp { TsValue };
841 Migration(std::string_view title,
842 std::function<
void(SqlMigrationQueryBuilder&)>
const& up,
843 std::function<
void(SqlMigrationQueryBuilder&)>
const& down = {}):
856 Migration(std::string_view title,
857 MigrationMetadata metadata,
858 std::function<
void(SqlMigrationQueryBuilder&)>
const& up,
859 std::function<
void(SqlMigrationQueryBuilder&)>
const& down = {}):
863 _metadata { std::move(metadata) }
870 void Up(SqlMigrationQueryBuilder& builder)
const override
878 void Down(SqlMigrationQueryBuilder& builder)
const override
887 [[nodiscard]]
bool HasDownImplementation() const noexcept
override
889 return static_cast<bool>(_down);
893 [[nodiscard]] std::vector<MigrationTimestamp> GetDependencies()
const override
895 return _metadata.dependencies;
899 [[nodiscard]] std::string_view GetAuthor() const noexcept
override
901 return _metadata.author;
905 [[nodiscard]] std::string_view GetDescription() const noexcept
override
907 return _metadata.description;
911 std::function<void(SqlMigrationQueryBuilder&)> _up;
912 std::function<void(SqlMigrationQueryBuilder&)> _down;
913 MigrationMetadata _metadata {};
928 template <
typename T>
929 inline constexpr MigrationTimestamp TimestampOf = T::TimeStamp;
937 struct ReleaseRegistrar
940 ReleaseRegistrar(std::string version, MigrationTimestamp highestTimestamp)
951#define _LIGHTWEIGHT_CONCATENATE(s1, s2) s1##s2
952#define _LIGHTWEIGHT_CONCATENATE_INNER(s1, s2) _LIGHTWEIGHT_CONCATENATE(s1, s2)
958#define LIGHTWEIGHT_MIGRATION_INSTANCE(timestamp) migration_##timestamp
978#define LIGHTWEIGHT_SQL_MIGRATION(timestamp, description) \
979 struct Migration_##timestamp: public Lightweight::SqlMigration::MigrationBase \
982 static constexpr Lightweight::SqlMigration::MigrationTimestamp TimeStamp { static_cast<uint64_t>(timestamp) }; \
983 explicit Migration_##timestamp(): \
984 Lightweight::SqlMigration::MigrationBase(TimeStamp, description) \
988 void Up(Lightweight::SqlMigrationQueryBuilder& plan) const override; \
989 void Down(Lightweight::SqlMigrationQueryBuilder& ) const override {} \
992 static Migration_##timestamp _LIGHTWEIGHT_CONCATENATE(migration_, timestamp); \
994 void Migration_##timestamp::Up(Lightweight::SqlMigrationQueryBuilder& plan) const
1015#define LIGHTWEIGHT_SQL_RELEASE(version, highestTimestamp) \
1016 static ::Lightweight::SqlMigration::detail::ReleaseRegistrar _LIGHTWEIGHT_CONCATENATE_INNER(_lw_release_, __COUNTER__) \
1018 (version), ::Lightweight::SqlMigration::MigrationTimestamp \
1020 (highestTimestamp) \
Main API for mapping records to and from the database using high level C++ syntax.
Query builder for building SQL migration queries.
virtual void Up(SqlMigrationQueryBuilder &plan) const =0
MigrationTimestamp GetTimestamp() const noexcept
std::string_view GetTitle() const noexcept
virtual std::vector< MigrationTimestamp > GetDependencies() const
virtual std::string_view GetAuthor() const noexcept
virtual std::string_view GetDescription() const noexcept
MigrationBase(MigrationBase const &)=default
Default copy constructor.
LIGHTWEIGHT_API std::string ComputeChecksum(SqlQueryFormatter const &formatter) const
MigrationBase(MigrationTimestamp timestamp, std::string_view title)
Constructs a migration with the given timestamp and title.
virtual void Down(SqlMigrationQueryBuilder &plan) const
virtual bool HasDownImplementation() const noexcept
MigrationBase & operator=(MigrationBase const &)=default
Default copy assignment operator.
std::string const & GetMigrationTitle() const noexcept
Human-readable title of the failing migration.
Operation GetOperation() const noexcept
Whether the failure occurred while applying or reverting.
MigrationException(Operation operation, MigrationTimestamp timestamp, std::string title, std::size_t stepIndex, std::string failedSql, SqlErrorInfo driverError)
std::string const & GetFailedSql() const noexcept
The exact SQL statement that the driver rejected.
std::string const & GetDriverMessage() const noexcept
Operation
Whether the failure happened while applying (Up) or reverting (Down).
MigrationTimestamp GetMigrationTimestamp() const noexcept
Timestamp of the failing migration.
std::size_t GetStepIndex() const noexcept
Zero-based step index inside the plan of the failing migration.
LIGHTWEIGHT_API void MarkMigrationAsApplied(MigrationBase const &migration)
LIGHTWEIGHT_API void ComposeCompatPolicy(CompatPolicy policy)
Composes an additional policy with the currently installed one. If no policy is installed,...
std::function< void(MigrationBase const &, size_t, size_t)> ExecuteCallback
Callback type invoked during migration execution to report progress.
LIGHTWEIGHT_API DataMapper & GetDataMapper()
Get the data mapper used for migrations.
LIGHTWEIGHT_API RevertResult RevertToMigration(MigrationTimestamp target, ExecuteCallback const &feedbackCallback={})
LIGHTWEIGHT_API void AddMigration(MigrationBase const *migration)
LIGHTWEIGHT_API HardResetResult HardReset(bool dryRun=false)
Drops every table the registered migrations would create (incl. schema_migrations),...
std::list< MigrationBase const * > MigrationList
Type alias for a list of migration pointers.
LIGHTWEIGHT_API MigrationList const & GetAllMigrations() const noexcept
LIGHTWEIGHT_API void RemoveAllMigrations()
LIGHTWEIGHT_API std::vector< std::string > PreviewPendingMigrationsUpTo(MigrationTimestamp targetInclusive, ExecuteCallback const &feedbackCallback={}) const
LIGHTWEIGHT_API size_t ApplyPendingMigrationsUpTo(MigrationTimestamp targetInclusive, ExecuteCallback const &feedbackCallback={})
LIGHTWEIGHT_API std::vector< std::string > PreviewPendingMigrations(ExecuteCallback const &feedbackCallback={}) const
LIGHTWEIGHT_API void RevertSingleMigration(MigrationBase const &migration)
LIGHTWEIGHT_API void CloseDataMapper()
LIGHTWEIGHT_API DataMapper & GetDataMapper() const
Get the data mapper used for migrations.
LIGHTWEIGHT_API void RemoveAllReleases()
Remove all registered releases. Useful for resetting state in tests.
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 SqlTransaction Transaction()
LIGHTWEIGHT_API void RegisterRelease(std::string version, MigrationTimestamp highestTimestamp)
LIGHTWEIGHT_API MigrationBase const * GetMigration(MigrationTimestamp timestamp) const noexcept
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 ins...
LIGHTWEIGHT_API std::list< MigrationBase const * > GetPending() const noexcept
LIGHTWEIGHT_API std::vector< ChecksumVerificationResult > VerifyChecksums() const
LIGHTWEIGHT_API MigrationRelease const * FindReleaseByVersion(std::string_view version) const noexcept
LIGHTWEIGHT_API RewriteChecksumsResult RewriteChecksums(bool dryRun=false)
Re-stamps schema_migrations.checksum rows that have drifted.
LIGHTWEIGHT_API CompatPolicy const & GetCompatPolicy() const noexcept
Returns a view of the installed policy so it can be propagated across managers (plugin → central)....
LIGHTWEIGHT_API MigrationRelease const * FindReleaseForTimestamp(MigrationTimestamp timestamp) const noexcept
LIGHTWEIGHT_API MigrationList GetMigrationsForRelease(std::string_view version) const
LIGHTWEIGHT_API std::vector< std::string > PreviewMigration(MigrationBase const &migration) const
LIGHTWEIGHT_API size_t ApplyPendingMigrations(ExecuteCallback const &feedbackCallback={})
LIGHTWEIGHT_API void CreateMigrationHistory()
Create the migration history table if it does not exist.
LIGHTWEIGHT_API MigrationStatus GetMigrationStatus() const
LIGHTWEIGHT_API void SetCompatPolicy(CompatPolicy policy)
Installs a per-migration compat policy. Pass {} to clear.
LIGHTWEIGHT_API void ValidateDependencies() const
std::function< std::set< std::string >(MigrationBase const &)> CompatPolicy
Per-migration compat policy.
LIGHTWEIGHT_API UnicodeUpgradeResult UnicodeUpgradeTables(bool dryRun=false)
Rewrites legacy VARCHAR/CHAR columns to NVARCHAR/NCHAR where the registered migrations now declare wi...
LIGHTWEIGHT_API std::vector< MigrationRelease > const & GetAllReleases() const noexcept
Get all registered releases, sorted ascending by highestTimestamp.
LIGHTWEIGHT_API void ApplySingleMigration(MigrationBase const &migration)
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 accu...
static LIGHTWEIGHT_API MigrationManager & GetInstance()
LIGHTWEIGHT_API std::vector< MigrationTimestamp > GetAppliedMigrationIds() const
std::variant< SqlCreateTablePlan, SqlAlterTablePlan, SqlDropTablePlan, SqlCreateIndexPlan, SqlRawSqlPlan, SqlInsertDataPlan, SqlUpdateDataPlan, SqlDeleteDataPlan > SqlMigrationPlanElement
Represents a single SQL migration plan element.
Opt-in behavioural knobs that the ToSql migration-plan renderer honours.
Represents an ODBC SQL error.
MigrationTimestamp timestamp
The timestamp of the verified migration.
std::string computedChecksum
The checksum computed from the current migration definition.
std::string storedChecksum
The checksum stored in the database.
bool matches
Whether the stored and computed checksums match.
std::string_view title
The title of the verified migration.
One row in the RewriteChecksumsResult.entries list.
std::string_view title
Title of the registered migration (or "(Unknown Migration)").
MigrationTimestamp timestamp
The migration whose stored checksum was rewritten.
std::string oldChecksum
Stored checksum before the rewrite. Empty if there was none.
std::string newChecksum
Stored checksum after the rewrite.
One column upgrade entry in UnicodeUpgradeResult.
SqlColumnTypeDefinition liveType
Live byte-counted type the column currently has.
SqlSchema::FullyQualifiedTableName table
Fully-qualified name of the table that owns the column.
SqlColumnTypeDefinition intendedType
Char-counted type the migrations now declare for this column.
bool nullable
Whether the column is nullable (preserved across the type rewrite).
std::string column
Name of the column being upgraded.
Result of a HardReset call.
std::vector< SqlSchema::FullyQualifiedTableName > absentTables
std::vector< SqlSchema::FullyQualifiedTableName > preservedTables
std::vector< SqlSchema::FullyQualifiedTableName > droppedTables
bool schemaMigrationsDropped
One data step (INSERT/UPDATE/DELETE/RawSql) tagged with its source migration.
std::string sourceTitle
Title of the migration that contributed this data step.
SqlMigrationPlanElement element
The plan element itself (INSERT, UPDATE, DELETE, or RawSql).
MigrationTimestamp sourceTimestamp
Timestamp of the migration that contributed this data step.
Per-table state: ordered column declarations + per-table FK list.
std::vector< SqlColumnDeclaration > columns
Ordered column declarations as they would be emitted in CREATE TABLE.
std::vector< SqlCompositeForeignKeyConstraint > compositeForeignKeys
Snapshot of the schema the registered migrations intend to produce.
std::vector< SqlCreateIndexPlan > indexes
Indexes that survive folding (created on tables still present at end).
std::map< SqlSchema::FullyQualifiedTableName, TableState > tables
std::vector< MigrationRelease > releases
Releases declared via LIGHTWEIGHT_SQL_RELEASE that fall within the fold range.
std::vector< DataStep > dataSteps
std::vector< SqlSchema::FullyQualifiedTableName > creationOrder
std::vector< std::pair< MigrationTimestamp, std::string > > foldedMigrations
Result of a RewriteChecksums call.
bool wasDryRun
True if the call ran in dry-run mode.
std::vector< MigrationTimestamp > unregisteredTimestamps
Applied rows whose migration is no longer registered.
std::vector< ChecksumRewriteEntry > entries
One entry per rewritten or would-be-rewritten row.
Result of an UnicodeUpgradeTables call.
std::vector< ColumnUpgradeEntry > columns
std::vector< SqlCompositeForeignKeyConstraint > rebuiltForeignKeys
MigrationTimestamp highestTimestamp
Highest migration timestamp contained in this release (inclusive).
std::string version
Human-readable version string, e.g. "6.7.0".
size_t mismatchCount
Number of applied migrations with checksum mismatches.
size_t appliedCount
Number of migrations that have been applied.
size_t totalRegistered
Total number of registered migrations.
size_t pendingCount
Number of migrations waiting to be applied.
size_t unknownAppliedCount
Number of applied migrations not found in registered list.
constexpr std::weak_ordering operator<=>(MigrationTimestamp const &other) const noexcept=default
Three-way comparison operator.
uint64_t value
The numeric timestamp value identifying the migration.
std::vector< MigrationTimestamp > revertedTimestamps
Successfully reverted migrations.
std::optional< MigrationTimestamp > failedAt
Migration that failed, if any.
std::string sqlState
SQLSTATE diagnostic code from the driver, if available.
std::string errorMessage
Short error message if failed (driver message only)
std::size_t failedStepIndex
SQLINTEGER nativeErrorCode
Native driver error code, if available.