Class MySQL2Library
CL.MySQL2 — CodeLogic library providing MySQL database access with a fluent LINQ query builder, automatic table synchronization, migrations, schema backups, and multiple named database connections.
Lifecycle:
- Configure — Registers DatabaseConfiguration and MySQL2Strings.
- Initialize — Loads config, validates, creates ConnectionManager and TableSyncService. Tests the connection.
- Start — Runs a health check and logs server version.
- Stop — Closes connections and disposes resources.
public sealed class MySQL2Library : ILibrary, IDisposable
- Inheritance
-
MySQL2Library
- Implements
-
ILibrary
- Inherited Members
Properties
BackupManager
Returns the BackupManager.
public BackupManager BackupManager { get; }
Property Value
ConnectionManager
Returns the ConnectionManager.
public ConnectionManager ConnectionManager { get; }
Property Value
Exceptions
- InvalidOperationException
Thrown when the library is not initialized or disabled.
Manifest
Metadata describing this library: ID, name, version, dependencies, etc. Used by the LibraryManager for discovery, dependency resolution, and display.
public LibraryManifest Manifest { get; }
Property Value
- LibraryManifest
MigrationTracker
Returns the MigrationTracker.
public MigrationTracker MigrationTracker { get; }
Property Value
Migrations
Returns the MigrationRunner for explicit/imperative migrations.
public MigrationRunner Migrations { get; }
Property Value
SchemaState
Returns the SchemaStateStore (the __schema_state sentinel).
public SchemaStateStore SchemaState { get; }
Property Value
TableSync
Returns the TableSyncService.
public TableSyncService TableSync { get; }
Property Value
Exceptions
- InvalidOperationException
Thrown when the library is not initialized or disabled.
Methods
BeginTransactionAsync(string, CancellationToken)
Begins a new database transaction and returns a TransactionScope.
public Task<TransactionScope> BeginTransactionAsync(string connectionId = "Default", CancellationToken ct = default)
Parameters
connectionIdstringctCancellationToken
Returns
Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public void Dispose()
ExecuteSqlAsync(string, IReadOnlyDictionary<string, object?>?, string, CancellationToken)
Runs a raw non-query statement (INSERT/UPDATE/DELETE/DDL) and returns the affected row count. Same parameterization and retry/observability rules as SqlQueryAsync<T>(string, IReadOnlyDictionary<string, object?>?, string, CancellationToken).
public Task<Result<int>> ExecuteSqlAsync(string sql, IReadOnlyDictionary<string, object?>? parameters = null, string connectionId = "Default", CancellationToken ct = default)
Parameters
sqlstringparametersIReadOnlyDictionary<string, object>connectionIdstringctCancellationToken
Returns
GetCachePoolStats()
Diagnostic snapshot of every registered smart-cache pool.
public IReadOnlyList<SmartCachePoolStats> GetCachePoolStats()
Returns
GetCacheStats()
Diagnostic snapshot of the underlying QueryCache: total entries, per-table breakdown, table-version counters. Use from the admin UI to spot orphan accumulation or a hot table.
public QueryCacheStats GetCacheStats()
Returns
GetPendingMigrationsAsync(string, CancellationToken)
Returns the pending migration plan without applying anything.
public Task<IReadOnlyList<MigrationPlanItem>> GetPendingMigrationsAsync(string connectionId = "Default", CancellationToken ct = default)
Parameters
connectionIdstringctCancellationToken
Returns
GetRepository<T>(string)
Creates a Repository<T> for the given entity type.
public Repository<T> GetRepository<T>(string connectionId = "Default") where T : class, new()
Parameters
connectionIdstringThe connection ID to use. Default: "Default".
Returns
- Repository<T>
Type Parameters
TThe entity type.
HealthCheckAsync()
Returns the current health status of this library.
Called on a timer (see CodeLogic.HealthChecksConfig.IntervalSeconds) and on demand
via the --health CLI flag or CodeLogic.ICodeLogicRuntime.GetHealthAsync().
Implement this to report database connectivity, queue depth, or any other meaningful status.
public Task<HealthStatus> HealthCheckAsync()
Returns
- Task<HealthStatus>
A CodeLogic.Framework.Libraries.HealthStatus indicating Healthy, Degraded, or Unhealthy.
MigrateAsync(string, CancellationToken)
Applies all pending imperative migrations (caller-driven; not auto-run on start). See MigrateAsync(string, CancellationToken).
public Task<Result<MigrationRunResult>> MigrateAsync(string connectionId = "Default", CancellationToken ct = default)
Parameters
connectionIdstringctCancellationToken
Returns
- Task<Result<MigrationRunResult>>
OnConfigureAsync(LibraryContext)
Phase 1 — Configuration. Called first, before any other phase. Register config and localization models with the context managers. The framework generates missing config files and loads all registered configs immediately after this method returns. Do NOT access config values here — they are not loaded yet.
public Task OnConfigureAsync(LibraryContext context)
Parameters
contextLibraryContextThe library context providing scoped services and paths.
Returns
OnInitializeAsync(LibraryContext)
Phase 2 — Initialization. Called after all configs and localizations are loaded. Set up services, validate configuration, establish connections, and prepare resources. Throw an exception here to abort startup — the library will transition to CodeLogic.Framework.Libraries.LibraryState.Failed.
public Task OnInitializeAsync(LibraryContext context)
Parameters
contextLibraryContextThe library context with loaded config and localization.
Returns
OnStartAsync(LibraryContext)
Phase 3 — Start. Called after all libraries have been initialized. Start background services, open long-lived connections, begin processing. After this method returns, the library is considered fully operational. A CodeLogic.Core.Events.LibraryStartedEvent is published on the event bus.
public Task OnStartAsync(LibraryContext context)
Parameters
contextLibraryContextThe library context (same instance as Initialize).
Returns
OnStopAsync()
Phase 4 — Stop. Called in reverse start order during graceful shutdown. Stop background tasks, close connections, flush buffers, release resources. Exceptions here are logged but do not prevent other libraries from stopping. A CodeLogic.Core.Events.LibraryStoppedEvent is published on the event bus.
public Task OnStopAsync()
Returns
Query<T>(string)
Creates a fluent QueryBuilder<T> for the given entity type.
public QueryBuilder<T> Query<T>(string connectionId = "Default") where T : class, new()
Parameters
connectionIdstringThe connection ID to use. Default: "Default".
Returns
- QueryBuilder<T>
Type Parameters
TThe entity type.
RefreshCachePoolAsync(string, CancellationToken)
Triggers an out-of-schedule refresh for the named pool.
public Task RefreshCachePoolAsync(string name, CancellationToken ct = default)
Parameters
namestringctCancellationToken
Returns
RegisterCachePool(string, TimeSpan, int, Func<Task>?)
Registers a named SmartCachePool. Queries opt into the
pool via .SmartCache(name); the pool's background timer keeps
every registered query's cache entry warm.
Idempotent — calling twice with the same name returns the existing pool unchanged (refresh interval is NOT updated on re-register).
public SmartCachePool RegisterCachePool(string name, TimeSpan refreshEvery, int maxIdleFires = 10, Func<Task>? warmUp = null)
Parameters
namestringPool name (case-insensitive) referenced by
.SmartCache.refreshEveryTimeSpanHow often the pool re-runs every registered query.
maxIdleFiresintDrop a registered entry after this many consecutive refresh ticks with no read. Default 3 — at a 30-second refresh interval, an unread entry is dropped after ~90 seconds, bounding cardinality on parameterized queries.
warmUpFunc<Task>Optional warm-up callback. When supplied, the pool runs it once as a fire-and-forget task right after registration so the cache is hot before the first user request hits it. Inside the callback, just call the queries that should be warm (with their normal
.SmartCache(name)decoration) — they auto-register with the pool as usual. Exceptions are caught and logged; the pool stays lazy if warm-up fails.
Returns
RegisterMigration(IMigration)
Registers a single IMigration with the runner.
public MySQL2Library RegisterMigration(IMigration migration)
Parameters
migrationIMigration
Returns
RegisterMigrationsFrom(Assembly)
Registers every concrete IMigration in the given assembly.
public MySQL2Library RegisterMigrationsFrom(Assembly assembly)
Parameters
assemblyAssembly
Returns
RestoreSchemaAsync(string, string?, string, CancellationToken)
Restores a table's schema from a BackupManager snapshot (drops and recreates
the table from captured DDL) and clears its __schema_state row so the next sync pass
reconciles it from scratch. Operator-driven and destructive — only DDL was backed up, so the
table's rows are lost. When backupFile is null the latest backup is used.
public Task<Result<bool>> RestoreSchemaAsync(string tableName, string? backupFile = null, string connectionId = "Default", CancellationToken ct = default)
Parameters
tableNamestringbackupFilestringconnectionIdstringctCancellationToken
Returns
RollbackAsync(MigrationVersion, string, CancellationToken)
Rolls back applied migrations newer than target, newest-first. See
RollbackAsync(MigrationVersion, string, CancellationToken).
public Task<Result<MigrationRunResult>> RollbackAsync(MigrationVersion target, string connectionId = "Default", CancellationToken ct = default)
Parameters
targetMigrationVersionconnectionIdstringctCancellationToken
Returns
- Task<Result<MigrationRunResult>>
SetSyncMode(SyncMode, string)
Overrides the configured SyncMode for a connection at runtime, without editing the config file or restarting. Useful to flip Migration back to Production once a one-shot migration pass has completed.
public void SetSyncMode(SyncMode mode, string connectionId = "Default")
Parameters
SqlQueryAsync<T>(string, IReadOnlyDictionary<string, object?>?, string, CancellationToken)
Runs a raw SQL query and materializes each row into T using the
same compiled materializer as the typed query builder. Use named parameters
(@p) and pass values via parameters — never interpolate
user input into sql. Flows through observability and the transient
retry policy; results are not cached.
public Task<Result<List<T>>> SqlQueryAsync<T>(string sql, IReadOnlyDictionary<string, object?>? parameters = null, string connectionId = "Default", CancellationToken ct = default) where T : class, new()
Parameters
sqlstringparametersIReadOnlyDictionary<string, object>connectionIdstringctCancellationToken
Returns
Type Parameters
T
SqlScalarAsync<T>(string, IReadOnlyDictionary<string, object?>?, string, CancellationToken)
Runs a raw query returning a single scalar value (the first column of the first row),
converted to T. Returns default when there are no rows.
public Task<Result<T?>> SqlScalarAsync<T>(string sql, IReadOnlyDictionary<string, object?>? parameters = null, string connectionId = "Default", CancellationToken ct = default)
Parameters
sqlstringparametersIReadOnlyDictionary<string, object>connectionIdstringctCancellationToken
Returns
- Task<Result<T>>
Type Parameters
T
SyncSchemaAsync(IEnumerable<Type>, bool, string, CancellationToken)
Syncs a set of entity types as one pass. See SyncSchemaAsync(params Type[]).
public Task<Result<Dictionary<string, SyncResult>>> SyncSchemaAsync(IEnumerable<Type> entities, bool createBackup = true, string connectionId = "Default", CancellationToken ct = default)
Parameters
entitiesIEnumerable<Type>The entity types whose tables to reconcile.
createBackupboolWhether to back up schemas before altering existing tables.
connectionIdstringThe connection ID to use.
ctCancellationTokenCancellation token.
Returns
- Task<Result<Dictionary<string, SyncResult>>>
SyncSchemaAsync(params Type[])
Syncs an entire set of entity types as one pass under a single cross-node lock, honoring the configured SyncMode. This is the recommended entry point for application startup: it applies the CRC fast-path per table and, in Migration, logs the "already current — switch back to Production" warning once nothing is left to do.
public Task<Result<Dictionary<string, SyncResult>>> SyncSchemaAsync(params Type[] entities)
Parameters
entitiesType[]The entity types whose tables to reconcile.
Returns
- Task<Result<Dictionary<string, SyncResult>>>
SyncTableAsync<T>(bool, string)
Syncs the table schema for the specified entity type. The type is also registered with the library so that entity-level workers (e.g. retention purge) pick it up.
public Task<Result<SyncResult>> SyncTableAsync<T>(bool createBackup = true, string connectionId = "Default") where T : class
Parameters
Returns
- Task<Result<SyncResult>>
Type Parameters
T
TestConnectionAsync(string, CancellationToken)
Tests the MySQL connection for the given connection ID.
public Task<Result<bool>> TestConnectionAsync(string connectionId = "Default", CancellationToken ct = default)
Parameters
connectionIdstringctCancellationToken