Path: redb/redb.SQLite/RedbService.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.SQLite/RedbService.cs
----
#pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation)
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Data;
using redb.Core.Providers;
using redb.Core.Query;
using redb.Core.Serialization;
using redb.Core.Utils;
using redb.Core.Security;
using redb.Core.Models.Contracts;
using redb.Core.Models.Configuration;
using redb.SQLite.Data;
using redb.SQLite.Providers;
using redb.SQLite.Sql;
namespace redb.SQLite;
///
/// SQLite implementation of IRedbService.
/// Inherits all common logic from RedbServiceBase.
/// Only provides SQLite-specific provider factories.
///
public class RedbService : RedbServiceBase
{
private static readonly SqliteDialect _dialect = new();
///
/// Creates a new SQLite RedbService instance.
///
public RedbService(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
// === SQLITE-SPECIFIC IMPLEMENTATIONS ===
protected override string DatabaseTypeName => "SQLite";
protected override ISqlDialect SqlDialect => _dialect;
/// The indexes of a fresh SQLite database of this build (SqliteIndexCatalog, generated and pinned by a test).
protected override IReadOnlyList ExpectedIndexes => SqliteIndexCatalog.Base;
protected override string GetVersionSql => "SELECT sqlite_version()";
// Bytes, like pg_database_size on PostgreSQL: the pages the database file holds.
protected override string GetDatabaseSizeSql => "SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()";
protected override string ContextNotRegisteredError =>
"IRedbContext is not registered in DI container. Add SqliteRedbContext to configuration.";
// === PROVIDER FACTORIES ===
protected override ISchemeSyncProvider CreateSchemeSyncProvider(
IRedbContext context, RedbServiceConfiguration config, string cacheDomain, ILogger? logger)
=> new SqliteSchemeSyncProvider(context, config, cacheDomain, logger);
protected override IPermissionProvider CreatePermissionProvider(
IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger)
=> new SqlitePermissionProvider(context, securityContext, logger);
protected override IUserProvider CreateUserProvider(
IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger)
=> new SqliteUserProvider(context, securityContext, ResolvePasswordHasher(), logger);
protected override IRoleProvider CreateRoleProvider(
IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger)
=> new SqliteRoleProvider(context, securityContext, logger);
protected override IListProvider CreateListProvider(
IRedbContext context, RedbServiceConfiguration config, ISchemeSyncProvider schemeSync, ILogger? logger)
=> new SqliteListProvider(context, config, schemeSync, logger);
protected override IObjectStorageProvider CreateObjectStorageProvider(
IRedbContext context, IRedbObjectSerializer serializer, IPermissionProvider permissionProvider,
IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync,
RedbServiceConfiguration config, IListProvider listProvider, ILogger? logger,
redb.Core.Interception.RedbSaveInterceptorPipeline? saveInterceptors)
=> new SqliteObjectStorageProvider(context, serializer, permissionProvider,
securityContext, schemeSync, config, listProvider, logger, saveInterceptors);
protected override ITreeProvider CreateTreeProvider(
IRedbContext context, IObjectStorageProvider objectStorage, IPermissionProvider permissionProvider,
IRedbObjectSerializer serializer, IRedbSecurityContext securityContext,
ISchemeSyncProvider schemeSync, RedbServiceConfiguration config, ILogger? logger,
redb.Core.Interception.RedbSaveInterceptorPipeline? saveInterceptors)
=> new SqliteTreeProvider(context, objectStorage, permissionProvider,
serializer, securityContext, schemeSync, config, logger, saveInterceptors);
protected override ILazyPropsLoader CreateLazyPropsLoader(
IRedbContext context, ISchemeSyncProvider schemeSync, IRedbObjectSerializer serializer,
RedbServiceConfiguration config, string cacheDomain, IListProvider listProvider, ILogger? logger)
=> new LazyPropsLoader(context, schemeSync, serializer, config, listProvider, logger);
protected override IQueryableProvider CreateQueryableProvider(
IRedbContext context, IRedbObjectSerializer serializer, ISchemeSyncProvider schemeSync,
IRedbSecurityContext securityContext, ILazyPropsLoader lazyPropsLoader,
RedbServiceConfiguration config, string cacheDomain, ILogger? logger)
=> new SqliteQueryableProvider(context, serializer, schemeSync, securityContext,
lazyPropsLoader, config, cacheDomain, logger);
protected override IValidationProvider CreateValidationProvider(
IRedbContext context, ILogger? logger)
=> new SqliteValidationProvider(context, logger);
protected override Core.Providers.IMaintenanceProvider CreateMaintenanceProvider(
IRedbContext context, int analysisLimit, ILogger? logger)
=> new Providers.SqliteMaintenanceProvider(context, analysisLimit, logger);
// === DATABASE SCHEMA MANAGEMENT ===
///
protected override async Task TableExistsAsync(string tableName)
{
var sql = "SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = @p0)";
return await Context.ExecuteScalarAsync(sql, tableName);
}
///
protected override string ReadEmbeddedSql()
{
var assembly = typeof(RedbService).Assembly;
var resourceName = "redb.SQLite.sql.redbSqlite.sql";
using var stream = assembly.GetManifestResourceStream(resourceName)
?? throw new InvalidOperationException(
$"Embedded resource '{resourceName}' not found. Ensure the project was built correctly.");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
///
protected override string? ReadEmbeddedPvtBundleSql()
{
// SQLite has no server-side v2-pvt module (no stored functions). The Pro
// tier generates query SQL in C# (ProSqlBuilder); the Free tier will host
// equivalents in the native extension. Either way, nothing to deploy here.
return null;
}
///
///
/// The script runs under a savepoint and is rolled back as a whole when a statement fails: the schema lock commits
/// its transaction when it is released, so the statements before the failure stayed in the file, and the next start
/// took the file with _schemes for an existing schema and ran the upgrade steps over the half of it.
///
protected override async Task ExecuteSchemaScriptAsync(string sql)
{
await Context.ExecuteAsync("SAVEPOINT redb_schema_create");
try
{
await Context.ExecuteAsync(sql);
}
catch (Exception failure)
{
try
{
await Context.ExecuteAsync("ROLLBACK TO redb_schema_create");
await Context.ExecuteAsync("RELEASE redb_schema_create");
}
catch (Exception rollbackFailure)
{
// SQLite may have ended the transaction itself (a full disk): the creation error is the one to report.
failure.Data["redb.SchemaCreateRollbackFailure"] = rollbackFailure.Message;
}
throw;
}
await Context.ExecuteAsync("RELEASE redb_schema_create");
}
///
/// The schema version this build writes into PRAGMA user_version — the SQLite counterpart of
/// pvt_module_version(): the one number that says which upgrades a database file has had.
/// Bump it when gains a step; a database stamped with an
/// older number gets every step (they are idempotent), a current one skips the pass entirely.
///
///
/// 1 — V4: hashes as BLOB(16) ().
/// 2 — V4 (UNIQUE Э2): _structures._unique, _structures._unique_version, _values._unique BLOB(16),
/// the partial unique index, and the same two columns on _scheme_metadata_cache.
/// 3 — V4 (UNIQUE Э1): _objects._value_unique and its partial unique index.
/// 4 — V4 (LAZY Л2): _structures._lazy and _scheme_metadata_cache._lazy (the virtual marker).
/// 5 — V4 (LAZY Л2): resync _scheme_metadata_cache._lazy from _structures (repairs caches
/// synced between the column upgrade and the marker write).
/// 6 — V4 (LAZY Л2): stamp bump only. The SQLite metadata-cache WARMUP (`Warmup_AllMetadataCaches`)
/// carried a stale column list and re-nulled the marker after step 5 on files stamped 5;
/// the list is fixed and the resync of step 5 runs again for them.
/// 7 — FK-column indexes IX__values__ListItem_not_null / IX__values__Object_not_null (partial):
/// without them every DELETE of a referenced object or list item scans the whole _values
/// for the FK check (perf finding, 2026-09-10).
/// 10 — the indexes another index of the same table fully replaces are dropped, the set PostgreSQL
/// dropped in its module 0.7.13 (2026-10-14).
/// 11 — value-leading indexes IX__values__structure_<value>_object for every value column, the set
/// PostgreSQL got in its module 0.7.16; the object-leading *_not_null, ix__values__array_null_structure
/// and the IX__values__scalar_*_object of SQLite Pro dropped (2026-10-17).
/// 12 — IX__values__structure_object_string (partial, text values only): which objects hold a text value of a
/// field, without reading the text. A filter Field == null over a text field reads it (2026-10-21).
/// 13 — the table _schema_compat: which builds a file still serves (). A build
/// whose schema version is below the file's leaves the file as it is and opens it when that row allows,
/// otherwise it stops with RedbSchemaNewerException (2026-11-14).
/// 14 — _structures._renamed_from and _schemes._renamed_from: the previous names the sync records when it applies a
/// rename ([RedbRename], RedbScheme.RenamedFrom), read to stop a class older than the rename (2026-11-18).
/// 15 — TimeOnly and TimeSpan as Ticks in _Long: _types._db_type and _scheme_metadata_cache.db_type say Long for
/// them. Older builds read and write them as text, so the file refuses them (
/// 15, 2026-11-21).
/// 16 — _schemes._version: the version of the Props class the scheme was last synchronised with
/// (RedbScheme.Version); the sync deletes a structure or changes its type only for a class of a higher version
/// (2026-11-29). Older builds ignore the column, so the oldest reader stays as it was.
/// 17 — IX__values__array_parent_id is dropped where a non-partial index led by _array_parent_id remains
/// (IX__values__array_parent_index), the step PostgreSQL module 0.7.33 makes (2026-11-30).
///
public static int SchemaVersion { get; } = 17;
///
/// The oldest schema version that may open a file of this build: written into _schema_compat with every
/// stamp. Raise it only when a step breaks the C# of older builds (a dropped or renamed column or table they read);
/// never lower it. is the redb package version that first shipped that schema
/// version, named to the operator of an older build that may not open the file.
///
// 15: an older build would write TimeOnly/TimeSpan as text into a file whose readers take ticks (step 15).
private const int SchemaCompatMinReader = 15;
private const string SchemaCompatPackage = "4.8.0";
///
/// The schema upgrades of under the schema lock, the version asked again
/// under it: two processes opening one old file (a panel and a worker of one host) ran the same steps at once, and
/// a step that checks and then acts (a column, an index rebuilt under its name) failed in the second.
///
/// False when the file belongs to a newer build: then nothing was changed, and nothing else may be.
private async Task ApplySchemaUpgradesAsync()
{
var fileVersion = await Context.ExecuteScalarAsync("PRAGMA user_version");
if (fileVersion > SchemaVersion)
{
await AcceptNewerFileAsync(fileVersion);
return false;
}
// The unique key of root structures is not a numbered step: a file with duplicates holding values goes on
// without it, and every start tries again until they are resolved.
if (fileVersion >= SchemaVersion && !await IsRootStructureKeyMissingAsync())
return true;
await using (await AcquireSchemaLockAsync())
{
// A newer build may have opened the file while this one waited.
fileVersion = await Context.ExecuteScalarAsync("PRAGMA user_version");
if (fileVersion > SchemaVersion)
{
await AcceptNewerFileAsync(fileVersion);
return false;
}
if (fileVersion < SchemaVersion)
await ApplySchemaUpgradeStepsAsync();
await EnsureRootStructureKeyAsync();
}
return true;
}
///
/// The file was written by a newer build: never taken back. Opened, with one warning per process, when its
/// _schema_compat row allows this build; otherwise start-up stops with
/// . A newer file without the row states nothing and is
/// treated as not allowing.
///
private async Task AcceptNewerFileAsync(long fileVersion)
{
long? minReader = null;
string? package = null;
if (await TableExistsAsync("_schema_compat"))
{
var rows = await Context.QueryAsync(
"SELECT _min_reader AS MinReader, _package AS Package FROM _schema_compat LIMIT 1");
if (rows.Count > 0)
{
minReader = rows[0].MinReader;
package = rows[0].Package;
}
}
var deployed = fileVersion.ToString(System.Globalization.CultureInfo.InvariantCulture);
var own = SchemaVersion.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (minReader is null || minReader > SchemaVersion)
throw new redb.Core.Exceptions.RedbSchemaNewerException(DatabaseTypeName, deployed, own, package);
WarnNewerOnce(DatabaseTypeName, deployed, own, Logger);
}
private sealed class SchemaCompatRow
{
public long MinReader { get; set; }
public string? Package { get; set; }
}
///
protected override Task OpenSchemaLockAsync(CancellationToken cancellationToken)
// Inside a transaction of this service the write lock of the file is already ours.
=> Task.FromResult(Context.IsInTransaction ? SchemaLockHandle.None : new WriteLock(Context));
///
/// The schema lock of SQLite: the single write lock of the file, taken by an immediate transaction of the
/// service's own connection, and every statement of the work runs in it. A lock on a connection of its own would
/// make the service wait for itself. An attempt that finds the file locked past the busy time-out of the
/// connection gives way; disposing commits what was done, as each statement committed on its own before.
///
private sealed class WriteLock(IRedbContext context) : SchemaLockHandle
{
private IRedbTransaction? _transaction;
public override string Name => "BEGIN IMMEDIATE";
public override async Task TryAcquireAsync(CancellationToken cancellationToken)
{
// Microsoft.Data.Sqlite retries a busy BEGIN until the command time-out of the connection (Default Timeout,
// 30 s unless the connection string says otherwise), so one attempt lasts up to that; the wait of the
// service overshoots its time-out by at most as much.
try
{
_transaction = await context.BeginTransactionAsync(cancellationToken: cancellationToken);
return true;
}
catch (Microsoft.Data.Sqlite.SqliteException ex) when (ex.SqliteErrorCode is 5 or 6)
{
// SQLITE_BUSY / SQLITE_LOCKED: another process writes.
return false;
}
}
public override async ValueTask DisposeAsync()
{
if (_transaction == null) return;
try
{
if (_transaction.IsActive)
await _transaction.CommitAsync();
}
finally
{
await _transaction.DisposeAsync();
}
}
}
///
/// Schema upgrades for a database created by an older build — the SQLite counterpart of the
/// "0. Schema upgrades" step of the PostgreSQL/MSSQL module bundle. Every statement is idempotent,
/// and the pass as a whole is gated by PRAGMA user_version: without the gate the
/// typeof() checks below would scan _objects on every start. Runs before
/// .
///
private async Task ApplySchemaUpgradeStepsAsync()
{
var deployed = await Context.ExecuteScalarAsync("PRAGMA user_version");
if (deployed >= SchemaVersion)
return;
// 1 — V4: hashes are BLOB(16) in RFC 4122 byte order (SqliteHash). Databases created before V4
// hold them as 36-character TEXT. SQLite keeps the storage class a value was written with,
// whatever the column declares, so a declared-TEXT column takes the BLOB and no ALTER is
// needed: convert the values in place; typeof() tells the two apart.
foreach (var (table, column) in new[] { ("_objects", "_hash"), ("_schemes", "_structure_hash"), ("_users", "_hash") })
{
await Context.ExecuteAsync(
$"UPDATE {table} SET {column} = {SqliteHash.FromText(column)} WHERE typeof({column}) = 'text'");
}
// 2 - V4 (UNIQUE stage 2): [RedbUnique] key metadata and the key hash column - the SQLite
// delivery of the module block "0. Schema upgrades" (PG/MSSQL 00_module_init.sql). SQLite
// ALTER TABLE ADD COLUMN has no IF NOT EXISTS, so each is guarded by pragma_table_info.
foreach (var (table, column, type) in new[]
{
("_structures", "_unique", "INTEGER"),
("_structures", "_unique_version", "INTEGER"),
("_values", "_unique", "BLOB"),
("_scheme_metadata_cache", "_unique", "INTEGER"),
("_scheme_metadata_cache", "_unique_version", "INTEGER"),
})
{
if (!await ColumnExistsAsync(table, column))
await Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN {column} {type} NULL");
}
await Context.ExecuteAsync(
"CREATE UNIQUE INDEX IF NOT EXISTS \"UIX__values__structure_unique\" " +
"ON _values (_id_structure, _unique) " +
"WHERE _unique IS NOT NULL");
// 3 - V4 (UNIQUE stage 1): the object key column and its unique index (length 440 is
// enforced in C# - SQLite does not check VARCHAR lengths).
if (!await ColumnExistsAsync("_objects", "_value_unique"))
await Context.ExecuteAsync("ALTER TABLE _objects ADD COLUMN _value_unique TEXT NULL");
await Context.ExecuteAsync(
"CREATE UNIQUE INDEX IF NOT EXISTS \"UIX__objects__scheme_unique\" " +
"ON _objects (_id_scheme, _value_unique) WHERE _value_unique IS NOT NULL");
// 4 - V4 (LAZY L2): the lazy-reference marker, read from `virtual` at synchronisation.
foreach (var (table, column) in new[] { ("_structures", "_lazy"), ("_scheme_metadata_cache", "_lazy") })
{
if (!await ColumnExistsAsync(table, column))
await Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN {column} INTEGER NULL");
}
// 5 - V4 (LAZY L2): repair caches that were synced before the marker landed.
await Context.ExecuteAsync(
"UPDATE _scheme_metadata_cache SET _lazy = (SELECT s._lazy FROM _structures s WHERE s._id = _structure_id)");
// 7 - FK-column indexes of _values (perf, 2026-09-10): _Object and _ListItem carry
// foreign keys, and without a leading index every DELETE of a referenced object or
// list item scans the whole table for the FK check (measured: seconds per check on
// ~8.4M rows, milliseconds with the index). Partial form keeps them nearly empty -
// reference fields are a small fraction of rows - so writes barely pay.
await Context.ExecuteAsync(
"CREATE INDEX IF NOT EXISTS \"IX__values__ListItem_not_null\" " +
"ON _values (_ListItem) WHERE _ListItem IS NOT NULL");
await Context.ExecuteAsync(
"CREATE INDEX IF NOT EXISTS \"IX__values__Object_not_null\" " +
"ON _values (_Object) WHERE _Object IS NOT NULL");
// 8 - S2 (subtree-unique plan): the key index covers keyed rows at ANY position now -
// nested scalar keys carry _array_parent_id, and the old positional filter kept them
// OUT of the index, so their "uniqueness" silently never fired. Recreate on the old
// predicate; fresh databases get the final form from redbSqlite.sql.
var oldKeyIndexForm = await Context.ExecuteScalarAsync(
"SELECT 1 FROM sqlite_master WHERE type = 'index' " +
"AND name = 'UIX__values__structure_unique' AND sql LIKE '%_array_parent_id%'");
if (oldKeyIndexForm.HasValue)
{
await Context.ExecuteAsync("DROP INDEX \"UIX__values__structure_unique\"");
await Context.ExecuteAsync(
"CREATE UNIQUE INDEX \"UIX__values__structure_unique\" " +
"ON _values (_id_structure, _unique) WHERE _unique IS NOT NULL");
}
// 9 - S3 (subtree-unique plan): element-key scope of collection keys, and the
// free-form _tags marker on schemes, structures and the metadata cache.
foreach (var (table, column, type) in new[]
{
("_structures", "_unique_scope", "INTEGER"),
("_structures", "_tags", "TEXT"),
("_schemes", "_tags", "TEXT"),
("_scheme_metadata_cache", "_unique_scope", "INTEGER"),
("_scheme_metadata_cache", "_tags", "TEXT"),
})
{
if (!await ColumnExistsAsync(table, column))
await Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN {column} {type} NULL");
}
await Context.ExecuteAsync(
"CREATE INDEX IF NOT EXISTS \"IX__structures__tags\" " +
"ON _structures (_tags) WHERE _tags IS NOT NULL");
await Context.ExecuteAsync(
"UPDATE _scheme_metadata_cache SET " +
"_unique_scope = (SELECT s._unique_scope FROM _structures s WHERE s._id = _structure_id), " +
"_tags = (SELECT s._tags FROM _structures s WHERE s._id = _structure_id)");
// 10 - index cleanup (2026-10-14): indexes another index of the same table fully replaces,
// the set PostgreSQL dropped in its module 0.7.13. Runs once, on the stamp: an index put back
// by hand stays. The statements that put them back:
// CREATE INDEX "IX__values__object_structure_array_index" ON _values (_id_object, _id_structure, _array_index) WHERE _array_index IS NOT NULL;
// CREATE INDEX "IX__structures__not_collection" ON _structures (_id, _name, _id_scheme) WHERE _collection_type IS NULL;
// CREATE INDEX "IX__functions__schemes" ON _functions (_id_scheme);
// CREATE INDEX "IX__permissions__roles" ON _permissions (_id_role);
// CREATE INDEX "IX__dependencies__schemes_1" ON _dependencies (_id_scheme_1);
// CREATE INDEX "IX__users_roles__roles" ON _users_roles (_id_role);
// IX__values__structure_object_lookup stays, unlike PostgreSQL: the streams form reads
// string fields through it.
foreach (var index in new[]
{
"IX__values__object_structure_array_index", "IX__structures__not_collection",
"IX__functions__schemes", "IX__permissions__roles", "IX__dependencies__schemes_1",
"IX__users_roles__roles",
})
{
await Context.ExecuteAsync($"DROP INDEX IF EXISTS \"{index}\"");
}
// 11 - value-leading indexes (2026-10-17), see redbSqlite.sql. Built before the old ones are
// dropped. An index of one of these names with any other definition is rebuilt: CREATE INDEX IF
// NOT EXISTS alone would keep it. sqlite_master keeps the statement as written, so it is compared
// with whitespace collapsed and IF NOT EXISTS taken out. An index built here gets planner
// statistics at once, bounded as the maintenance ANALYZE is: without them SQLite costs it blind.
var built = new List();
foreach (var column in ValueColumns)
{
var name = $"IX__values__structure_{column.ToLowerInvariant()}_object";
var definition = $"CREATE INDEX \"{name}\" ON _values (_id_structure, _{column}, _id_object, _array_index) WHERE _{column} IS NOT NULL";
var existing = await Context.ExecuteScalarAsync(
$"SELECT sql FROM sqlite_master WHERE type = 'index' AND name = '{name}'");
if (existing != null && NormalizeIndexSql(existing) != definition)
{
await Context.ExecuteAsync($"DROP INDEX \"{name}\"");
existing = null;
}
if (existing == null)
{
await Context.ExecuteAsync(definition);
built.Add(name);
}
}
if (built.Count > 0)
{
var limit = Configuration.MaintenanceAnalysisLimit;
await Context.ExecuteAsync($"PRAGMA analysis_limit = {(limit > 0 ? limit : 0)}");
foreach (var name in built)
await Context.ExecuteAsync($"ANALYZE \"{name}\"");
}
foreach (var index in new[]
{
"IX__values__String_not_null", "IX__values__Long_not_null", "IX__values__DateTimeOffset_not_null",
"IX__values__Numeric_not_null", "ix__values__array_null_structure",
"IX__values__scalar_String_object", "IX__values__scalar_Long_object",
"IX__values__scalar_Numeric_object", "IX__values__scalar_DateTimeOffset_object",
})
{
await Context.ExecuteAsync($"DROP INDEX IF EXISTS \"{index}\"");
}
// 12 - which objects hold a text value of a field (2026-10-21), see redbSqlite.sql. The text column is
// in no other index by object, so a check that a text field is absent read every row from the table.
// Statistics at once, as in step 11.
var stringIndexExists = await Context.ExecuteScalarAsync(
"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'IX__values__structure_object_string'");
if (!stringIndexExists.HasValue)
{
await Context.ExecuteAsync(
"CREATE INDEX \"IX__values__structure_object_string\" ON _values (_id_structure, _id_object) WHERE _String IS NOT NULL");
var limit = Configuration.MaintenanceAnalysisLimit;
await Context.ExecuteAsync($"PRAGMA analysis_limit = {(limit > 0 ? limit : 0)}");
await Context.ExecuteAsync("ANALYZE \"IX__values__structure_object_string\"");
}
// 13 - _schema_compat: which builds the file still serves. Written by the stamp below, with every stamp.
// 14 - the previous names of renamed structures and schemes ([RedbRename], RedbScheme.RenamedFrom).
foreach (var table in new[] { "_structures", "_schemes" })
{
if (!await ColumnExistsAsync(table, "_renamed_from"))
await Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN _renamed_from TEXT NULL");
}
// 15 - TimeOnly and TimeSpan are stored as Ticks in _Long: the type rows and their copy in the metadata cache
// say Long. Values already stored as text are not converted (UPGRADING.md gives the statement).
await Context.ExecuteAsync(
"UPDATE _types SET _db_type = 'Long' WHERE _id IN (-9223372036854775685, -9223372036854775684) AND _db_type <> 'Long'");
await Context.ExecuteAsync(
"UPDATE _scheme_metadata_cache SET db_type = 'Long' WHERE _type_id IN (-9223372036854775685, -9223372036854775684) AND db_type <> 'Long'");
// 16 - the version of the Props class a scheme was last synchronised with (RedbScheme.Version).
if (!await ColumnExistsAsync("_schemes", "_version"))
await Context.ExecuteAsync("ALTER TABLE _schemes ADD COLUMN _version INTEGER NULL");
// 17 - IX__values__array_parent_id (_array_parent_id) is the leading column of IX__values__array_parent_index,
// which serves its lookups and the ON DELETE CASCADE of FK__values__array_parent. Dropped only where another
// non-partial index led by _array_parent_id remains: a file created by an old version may lack the wide one, and
// the cascade must keep an index. Put back by hand:
// CREATE INDEX "IX__values__array_parent_id" ON _values (_array_parent_id);
var wideParentIndexes = await Context.ExecuteScalarAsync(
"SELECT COUNT(*) FROM pragma_index_list('_values') l " +
"WHERE l.name <> 'IX__values__array_parent_id' AND l.partial = 0 " +
"AND EXISTS (SELECT 1 FROM pragma_index_info(l.name) i WHERE i.seqno = 0 AND i.name = '_array_parent_id')");
if (wideParentIndexes > 0)
await Context.ExecuteAsync("DROP INDEX IF EXISTS \"IX__values__array_parent_id\"");
await StampSchemaVersionAsync();
}
/// Value columns of _values that get a value-leading index (schema step 11).
private static readonly string[] ValueColumns =
["String", "Long", "Numeric", "Double", "DateTimeOffset", "Boolean", "Guid", "ListItem", "Object"];
/// A CREATE INDEX statement as sqlite_master keeps it, reduced to one spelling.
private static string NormalizeIndexSql(string sql)
=> System.Text.RegularExpressions.Regex.Replace(sql, @"\s+", " ").Trim()
.Replace("CREATE INDEX IF NOT EXISTS ", "CREATE INDEX ", StringComparison.OrdinalIgnoreCase);
///
/// The version of this build into PRAGMA user_version, and into _schema_compat which builds the file
/// still serves (step 13; written with every stamp, so a file created from the schema script has it too).
///
private async Task StampSchemaVersionAsync()
{
await Context.ExecuteAsync(
"CREATE TABLE IF NOT EXISTS _schema_compat(_min_reader INTEGER NOT NULL, _package TEXT NOT NULL)");
await Context.ExecuteAsync("DELETE FROM _schema_compat");
await Context.ExecuteAsync(
$"INSERT INTO _schema_compat(_min_reader, _package) VALUES ({SchemaCompatMinReader}, '{SchemaCompatPackage}')");
await Context.ExecuteAsync($"PRAGMA user_version = {SchemaVersion}");
}
private async Task ColumnExistsAsync(string table, string column)
=> (await Context.ExecuteScalarAsync(
$"SELECT 1 FROM pragma_table_info('{table}') WHERE name = '{column}' LIMIT 1")).HasValue;
///
/// Applies corrections to seeded metadata on a database that already exists.
///
///
/// PostgreSQL and MSSQL get this for free: a corrected seed rides
/// sql/v2-pvt/*.sql, and EnsurePvtModuleDeployedAsync reapplies the bundle whenever
/// pvt_module_version() disagrees with the dialect. SQLite has no such channel — it has no
/// stored functions, so it has no module and no version to compare, and
/// returns null on purpose. redbSqlite.sql is applied
/// only when the tables are absent. Without the step below, a fix to seeded data would reach new
/// databases and no existing one, however many times the package is upgraded.
///
///
///
/// Every statement here must be idempotent: this runs on every start, not once.
///
///
private async Task ApplySeedCorrectionsAsync()
{
// DateOnly was seeded with _db_type = 'DateTime', a value no JSON projection branches on, so
// every DateOnly property materialised as 0001-01-01. Retyping it to 'DateTimeOffset' routes it
// through the branch that already exists; the stored value is untouched, it has always been
// midnight of that date in _values._DateTimeOffset.
var fixedRows = await Context.ExecuteAsync(
"UPDATE _types SET _db_type = 'DateTimeOffset' " +
"WHERE _id = " + RedbTypeIds.DateOnly + " AND _db_type <> 'DateTimeOffset'");
if (fixedRows <= 0)
return;
// The scheme metadata cache copies _db_type, so readers would keep answering from the stale
// copy. Dropping the affected rows is enough — the cache is rebuilt on demand.
await Context.ExecuteAsync(
"DELETE FROM _scheme_metadata_cache WHERE _scheme_id IN " +
"(SELECT DISTINCT _id_scheme FROM _structures WHERE _id_type = " + RedbTypeIds.DateOnly + ")");
}
///
/// SQLite ships no v2-pvt bundle, so the base version check is a no-op; the schema-upgrade pass
/// is the SQLite delivery of the same contract and must reach an existing file through
/// InitializeAsync() exactly as the module block "0. Schema upgrades" reaches PostgreSQL
/// and MSSQL, not only through . A file without the schema is
/// left to (or the first synchronisation) to report;
/// itself runs the pass after creation, so the base call made
/// from there is skipped. AutoApplyDatabaseUpgrades is ignored on SQLite by contract.
///
protected override async Task EnsurePvtModuleDeployedAsync()
{
await EnsureNativeExtensionVersionAsync();
if (_ensuringDatabase) return;
if (!await TableExistsAsync("_schemes")) return;
await ApplySchemaUpgradesAsync();
await KeepPlannerStatisticsAsync();
}
/// Value rows from which a file without planner statistics is analyzed at start-up.
internal const int PlannerStatisticsThreshold = 10_000;
///
/// Planner statistics of the file (KeepSqlitePlannerStatistics). Without sqlite_stat1 SQLite costs an
/// index lookup at a few rows whatever the table holds, and may put the scheme's index of _objects on the outer
/// loop of a statement that a page of a hundred rows should drive. A file an application filled has none: SQLite
/// gathers them only on ANALYZE. So a file with no statistics for _objects and _values and at least
/// value rows is analyzed here, sampled by MaintenanceAnalysisLimit;
/// a smaller file is left alone, because statistics of a nearly empty file stay behind as it grows and mislead more
/// than none. A file that has statistics gets PRAGMA optimize, which analyzes again, sampled the same way, only
/// the tables whose row count changed tenfold since. A file that cannot be written is left as it is.
///
private async Task KeepPlannerStatisticsAsync()
{
if (!Configuration.KeepSqlitePlannerStatistics)
return;
try
{
var limit = Configuration.MaintenanceAnalysisLimit;
await Context.ExecuteAsync($"PRAGMA analysis_limit = {(limit > 0 ? limit : 0)}");
var haveStatistics = await Context.ExecuteScalarAsync(
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'") != null
&& await Context.ExecuteScalarAsync(
"SELECT 1 FROM sqlite_stat1 WHERE tbl IN ('_objects', '_values') LIMIT 1") != null;
if (haveStatistics)
{
// 0x10002: analyze where it pays (0x02), over every table, not only those this connection has read (0x10000).
await Context.ExecuteAsync("PRAGMA optimize = 0x10002");
return;
}
var rows = await Context.ExecuteScalarAsync(
$"SELECT count(*) FROM (SELECT 1 FROM _values LIMIT {PlannerStatisticsThreshold})") ?? 0;
if (rows < PlannerStatisticsThreshold)
return;
var started = System.Diagnostics.Stopwatch.StartNew();
await Context.ExecuteAsync("ANALYZE");
Logger?.LogInformation("Planner statistics gathered for the SQLite file in {Elapsed} ms (sample limit {Limit}).",
started.ElapsedMilliseconds, limit);
}
catch (Microsoft.Data.Sqlite.SqliteException ex) when (ex.SqliteErrorCode is 5 or 6 or 8)
{
// SQLITE_BUSY, SQLITE_LOCKED, SQLITE_READONLY: another process holds the file, or it is opened read-only.
Logger?.LogWarning(ex, "Planner statistics of the SQLite file were not refreshed: the file cannot be written now. " +
"IMaintenanceProvider.AnalyzeAsync gathers them on demand.");
}
}
///
/// The SQLite delivery of the module version gate: the loaded native extension must report the version the
/// dialect requires. Nothing to apply on a mismatch - the library ships with the package - so it is refused,
/// naming the file. Skipped when no extension is configured (the Pro tier compiles its queries in C#).
///
private async Task EnsureNativeExtensionVersionAsync()
{
var path = SqliteDataSource.NativeExtensionPath;
var versionFn = SqlDialect.Query_PvtModuleVersionFunction();
var required = SqlDialect.Query_PvtRequiredVersion();
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(versionFn) || string.IsNullOrEmpty(required))
return;
string? deployed;
try
{
deployed = await Context.ExecuteScalarAsync($"SELECT {versionFn}()");
}
catch (Microsoft.Data.Sqlite.SqliteException ex) when (ex.Message.Contains("no such function", StringComparison.Ordinal))
{
// An extension from before the version function: refused below by name.
deployed = null;
}
SqliteNativeExtension.EnsureVersion(path, deployed, required);
}
private bool _ensuringDatabase;
///
public override async Task EnsureDatabaseAsync()
{
// Asked before the base call, which creates the tables when they are missing: a freshly created
// database is already correct and needs no correction pass.
var existedBefore = await TableExistsAsync("_schemes");
_ensuringDatabase = true;
try { await base.EnsureDatabaseAsync(); }
finally { _ensuringDatabase = false; }
if (!existedBefore)
{
// Created by this build: every upgrade is already in the schema script.
await StampSchemaVersionAsync();
return;
}
// A file of a newer build is left as it is, seed corrections included.
if (await ApplySchemaUpgradesAsync())
await ApplySeedCorrectionsAsync();
}
}