Table of Contents

Namespace CL.MySQL2.Services

Classes

BackupManager

Creates and manages schema backup files for MySQL tables and databases. Backups contain DDL (CREATE TABLE statements) and are stored as .sql files.

ConnectionManager

Manages MySQL database connections — registration, pooling, health checking, and transaction orchestration for multiple named connection IDs.

GroupedQuery<TKey, TSource>

Intermediate query produced by GroupBy<TKey>(Expression<Func<T, TKey>>). Not directly executable — the only exit is Select<TResult>(Expression<Func<IGrouping<TKey, TSource>, TResult>>) which collapses the groups back into a shaped result set. Calls inside the projection lambda (g.Sum, g.Average, g.Count, g.Key, …) translate to SQL aggregates against the current GROUP BY.

JoinedQuery<TLeft, TRight, TResult>

A typed two-table join. Built by Join<TRight, TKey, TResult>(Expression<Func<T, TKey>>, Expression<Func<TRight, TKey>>, Expression<Func<T, TRight, TResult>>, JoinType); the left side is aliased t0 and the right side t1. The result selector projects matched rows into TResult — only the referenced columns are transferred, materialized by a compiled (reflection-free) row mapper.

Supports Where(Expression<Func<TLeft, TRight, bool>>), OrderBy<TKey>(Expression<Func<TLeft, TRight, TKey>>) / OrderByDescending<TKey>(Expression<Func<TLeft, TRight, TKey>>), Take(int) / Skip(int), and the ToListAsync / FirstOrDefaultAsync / CountAsync terminals.

Not cacheable in this version. The result cache stamps entries with a single table's version counter, so a join entry could not be invalidated when the other joined table mutates. Rather than ship a cache that silently serves stale joins, .WithCache / .SmartCache are intentionally absent here. Multi-table invalidation is on the roadmap.

MigrationPlanItem

A pending migration in the plan returned by GetPendingAsync(string, CancellationToken).

MigrationRecord

Represents a single applied migration record from the tracking table.

MigrationRunResult

Outcome of a migrate or rollback pass.

MigrationRunner

Discovers, orders, and runs IMigration instances on top of the MigrationTracker's __migrations history. Migrations are applied in MigrationVersion order, each in its own transaction, gated by the app version and serialized across nodes by the shared SchemaSyncLock.

MigrationTracker

Tracks applied database migrations in a dedicated __migrations table. Supports recording migrations and querying applied history.

NullCacheCoordinator

Single-node default: no fan-out, and every node (there is only one) always wins the refresh lease — so behaviour is identical to the pre-coordination library.

ProjectedQuery<TSource, TResult>

A query pipeline whose output rows are TResult, produced by projecting from an underlying entity type TSource. Built by QueryBuilder<T>.Select<TResult> (and, once task #4 lands, by GroupedQuery<TKey, TSource>.Select<TResult>).

QueryBuilder<T>

Fluent query builder for entity type T. Chains WHERE, ORDER BY, JOIN, GROUP BY, LIMIT/OFFSET clauses and executes terminal operations returning CodeLogic.Core.Results.Result<T>.

QueryCache

Facade over ICacheStore providing query-result caching with two key properties:

  • Time-quantized keys — DateTime parameters derived from UtcNow are rounded to a configurable window before hashing, so .Where(x => x.At >= UtcNow.AddDays(-30)) no longer produces a unique key per call.
  • Table-version invalidation — mutations bump a per-table version counter that participates in the cache key; prior entries simply become un-hittable and are swept on eviction. No need to track-and-evict individual keys.

Keeps a static facade so existing callers (QueryBuilder, Repository) compile unchanged.

QueryCacheStats

Diagnostic snapshot of QueryCache state. Surfaced via GetCacheStats() for the admin UI so operators can see what's actually living in cache without dumping values.

QueryObservability

Process-wide sink for query lifecycle notifications. Query pipelines call the lightweight Record* methods without needing an CodeLogic.Core.Events.IEventBus instance passed through. The library wires the sink to CodeLogic's event bus at init time.

Repository<T>

Generic repository providing CRUD for entity type T. Uses compiled materializers via CL.MySQL2.Core.EntityMetadata<T> — no per-row reflection.

RetentionWorker

Background worker that purges old rows from entities marked with RetainDaysAttribute. Runs once per 24 hours; on first start it runs after a short delay so library startup isn't blocked by a potentially long delete.

Each purge pass runs DELETE FROM {table} WHERE {col} < NOW() - INTERVAL N DAY LIMIT batchSize repeatedly until a pass deletes zero rows. That keeps individual transactions small (friendly to InnoDB's undo log) while still converging on empty.

SchemaStateRecord

A single row from the __schema_state sentinel table.

SchemaStateStore

Owns the __schema_state sentinel table: one row per model holding a CRC of the model's desired schema plus reconciliation status and audit metadata. The CRC lets schema sync skip a table entirely (no information_schema diffing) when nothing has changed.

SchemaSyncLock

A cross-node advisory lock around a schema-sync / migration pass, implemented with MySQL's connection-scoped GET_LOCK. Because the lock is released automatically when the holding connection closes, this type keeps a single dedicated connection open for its whole lifetime and releases the lock (and the connection) on DisposeAsync().

ServerInfo

Basic MySQL server metadata.

SmartCachePool

A named group of cached queries that is kept warm by a background timer. Queries opt in via .SmartCache("poolName"); on first execution they register their refresh factory with the pool. Every RefreshEvery the pool re-runs every registered factory and overwrites the cache entry, so subsequent reads never block on the DB. Entries stay warm forever once registered — the pool never evicts them.

SmartCachePoolRegistry

Process-wide registry of named SmartCachePool instances. Pools are declared once at app startup (typically in a plugin's OnInitializeAsync) and referenced from queries by name.

SmartCachePoolStats

Diagnostic snapshot of a pool's state.

TableSyncService

Synchronizes database table schema with entity class definitions. Uses CL.MySQL2.Core.SchemaAnalyzer to detect and apply CREATE/ALTER TABLE statements.

TransactionScope

Wraps a MySqlConnector.MySqlTransaction with an async-disposable pattern. When disposed without an explicit CommitAsync(CancellationToken) or RollbackAsync(CancellationToken) call, the transaction is automatically rolled back.

Interfaces

ICacheCoordinator

Cross-node coordination for the query cache. The default (NullCacheCoordinator) is single-node and does nothing; a distributed adapter (Redis pub/sub, NATS, etc.) is supplied by the consumer via UseCoordinator(ICacheCoordinator) — exactly the same plug-in model as ICacheStore. The library ships no transport dependency of its own.

Two responsibilities:

  1. Invalidation fan-outPublishInvalidationAsync(string, CancellationToken) broadcasts a local table mutation so peers drop their cached entries. Without this, each process keeps its own per-table version counter and a mutation on one node never invalidates the others.
  2. Single-flight refreshTryAcquireRefreshLeaseAsync(string, TimeSpan, CancellationToken) lets exactly one node own a SmartCachePool's refresh each tick, so N nodes don't all hit the database. This assumes a shared ICacheStore (e.g. Redis): the lease holder refreshes and writes; the others read the shared entry.
ICacheStore

Abstraction over the cache backend. The default implementation is in-process (CL.MySQL2.Services.InProcessCacheStore). Distributed adapters (Redis, memcached) can implement this without touching callers.

IMigrationContext

The surface available to an IMigration while it runs. Everything here executes on the migration's own connection and transaction (DDL excepted — MySQL auto-commits it). Provides raw SQL helpers plus a bridge into the declarative schema sync so a migration can bring a table to its current model shape and then transform data in the same step.

Enums

SchemaSyncStatus

Reconciliation status recorded per table in __schema_state.