Path: redb/redb.SQLite/sql/SqliteDialect.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/sql/SqliteDialect.cs ---- using System.Globalization; using redb.SQLite.Data; using redb.Core.Query; using redb.Core.Utils; namespace redb.SQLite.Sql; /// /// SQLite implementation of ISqlDialect. /// Uses CASE WHEN for PVT (tested - 15 ms on 15K objects!). /// public class SqliteDialect : ISqlDialect { public string ProviderName => "SQLite"; public string FormatPagination(int? limit, int? offset) { // SQLite quirk: OFFSET is only valid in the "LIMIT n OFFSET m" form — bare // "OFFSET m" is a syntax error (unlike PG/MSSQL). When a caller wants OFFSET // without an upper bound (LINQ `.Skip(n)` with no `.Take()`), we emit // "LIMIT -1 OFFSET m" — SQLite treats LIMIT -1 as unlimited. // Observed via PropsPasswordHistoryStore.RecordAsync's // `Query<>().OrderByDescending(...).Skip(keep).Select(...).ToListAsync()` // cleanup path: "SQLite Error 1: 'near OFFSET: syntax error'". if (!limit.HasValue && !(offset.HasValue && offset.Value > 0)) return string.Empty; var hasOffset = offset.HasValue && offset.Value > 0; var limitClause = limit.HasValue ? $"LIMIT {limit.Value}" : (hasOffset ? "LIMIT -1" : string.Empty); var offsetClause = hasOffset ? $"OFFSET {offset!.Value}" : string.Empty; return string.IsNullOrEmpty(offsetClause) ? limitClause : $"{limitClause} {offsetClause}"; } public string WrapSubquery(string subquery, string alias) => $"({subquery}) AS {alias}"; /// /// PVT via array_agg with GROUP BY. /// Test showed: 0.293 ms vs 0.339 ms (subquery) - 15% faster! /// Works for ALL types including UUID. /// public string FormatPvtColumn(long structureId, string dbColumn, string alias) // SQLite has no array_agg(...)[1]; MAX(...) FILTER returns the single // scalar value per object (Pro shape). Works for all types incl. uuid/bool. => $"MAX({dbColumn}) FILTER (WHERE _id_structure = {structureId}) AS \"{alias}\""; public string FormatArrayContains(string column, string paramName) => $"{column} IN (SELECT value FROM json_each({paramName}))"; public string GetDbTypeName(string redbType) => redbType switch { "Long" => "INTEGER", "String" => "TEXT", "Boolean" => "INTEGER", "DateTime" => "TEXT", "DateTimeOffset" => "TEXT", "Double" => "REAL", "Numeric" => "REAL", "Guid" => "TEXT", "ByteArray" => "BLOB", _ => "TEXT" }; public string FormatParameter(int index) => $"${index}"; public string QuoteIdentifier(string name) // SQLite escapes a double quote by doubling it, same as PostgreSQL (SQLI-PoC p.7). => "\"" + name.Replace("\"", "\"\"") + "\""; /// /// Returns the expression unchanged, because in SQLite there is nothing to attach. Its only /// case-insensitive collation, NOCASE, folds ASCII and nothing else, and LIKE is implemented as /// a function so collations do not reach it at all. The fix therefore lives one level down: /// SqliteRedbConnection overrides the built-in like, lower and /// upper with Unicode-aware implementations when the feature is enabled, which is the /// same technique SQLite's own ICU extension uses. /// public string FoldCase(string expression) => expression; public string FormatCaseInsensitiveLike(string column, string parameter) // SQLite has no ILIKE; LIKE is ASCII case-insensitive by default. // ESCAPE '\\' is REQUIRED because UserProviderBase.EscapeLikeWildcards // escapes '_', '%', '\' with a leading backslash to make them literal. // PG defaults to '\' as the LIKE escape, SQLite/MSSQL do NOT — without // this clause a search for an exact email like 'reset_53f4f0f9@…' (which // becomes the pattern 'reset\_53f4f0f9@…') is compared as the literal // string starting with 'reset\_' rather than 'reset_', and no row matches. => $"{column} LIKE {parameter} ESCAPE '\\'"; // Dates are stored as a REAL UTC Julian day (SqliteJulian), the number a bound parameter carries: a text literal // would land as TEXT in _DateTimeOffset, read back but never match a filter. "R" round-trips the double exactly. public string FormatDateTimeLiteral(DateTime dt) => SqliteJulian.ToJulian(DateTimeConverter.NormalizeForStorage(dt)).ToString("R", CultureInfo.InvariantCulture); public string FormatDateTimeOffsetLiteral(DateTimeOffset dto) => SqliteJulian.ToJulian(dto).ToString("R", CultureInfo.InvariantCulture); // The driver writes a Guid parameter as upper-case text, and SQLite compares text case-sensitively. public string FormatGuidLiteral(Guid value) => "'" + value.ToString("D").ToUpperInvariant() + "'"; public string FormatBooleanLiteral(bool value) => value ? "1" : "0"; // ============================================================ // === ROLES SQL === // ============================================================ public string Roles_SelectById() => "SELECT _id AS Id, _name AS Name, _id_configuration AS IdConfiguration FROM _roles WHERE _id = $1"; public string Roles_SelectByName() => "SELECT _id AS Id, _name AS Name, _id_configuration AS IdConfiguration FROM _roles WHERE _name = $1"; public string Roles_SelectAll() => "SELECT _id AS Id, _name AS Name, _id_configuration AS IdConfiguration FROM _roles ORDER BY _name"; public string Roles_Insert() => "INSERT INTO _roles (_id, _name) VALUES ($1, $2)"; public string Roles_UpdateName() => "UPDATE _roles SET _name = $1 WHERE _id = $2"; public string Roles_Delete() => "DELETE FROM _roles WHERE _id = $1"; public string Roles_ExistsByName() => "SELECT _id FROM _roles WHERE _name = $1"; public string Roles_ExistsByNameExcluding() => "SELECT _id FROM _roles WHERE _name = $1 AND _id != $2"; public string Roles_Count() => "SELECT COUNT(*) FROM _roles"; public string Roles_UpdateConfiguration() => "UPDATE _roles SET _id_configuration = $1 WHERE _id = $2"; public string Roles_SelectConfigurationId() => "SELECT _id_configuration FROM _roles WHERE _id = $1"; // ============================================================ // === USERS_ROLES SQL === // ============================================================ public string UsersRoles_Insert() => "INSERT INTO _users_roles (_id, _id_user, _id_role) VALUES ($1, $2, $3)"; public string UsersRoles_Delete() => "DELETE FROM _users_roles WHERE _id_user = $1 AND _id_role = $2"; public string UsersRoles_DeleteByUser() => "DELETE FROM _users_roles WHERE _id_user = $1"; public string UsersRoles_DeleteByRole() => "DELETE FROM _users_roles WHERE _id_role = $1"; public string UsersRoles_Exists() => "SELECT _id FROM _users_roles WHERE _id_user = $1 AND _id_role = $2"; public string UsersRoles_SelectRolesByUser() => """ SELECT r._id AS Id, r._name AS Name, r._id_configuration AS IdConfiguration FROM _roles r INNER JOIN _users_roles ur ON ur._id_role = r._id WHERE ur._id_user = $1 ORDER BY r._name """; public string UsersRoles_SelectUsersByRole() => """ SELECT u._id, u._login, u._name, u._password, u._phone, u._email, u._enabled, u._date_register, u._date_dismiss, u._key, u._code_int, u._code_string, u._code_guid, u._note, u._hash FROM _users u INNER JOIN _users_roles ur ON ur._id_user = u._id WHERE ur._id_role = $1 ORDER BY u._name """; public string UsersRoles_CountByRole() => "SELECT COUNT(*) FROM _users_roles WHERE _id_role = $1"; // ============================================================ // === USERS SQL === // ============================================================ public string Users_ExistsById() => "SELECT _id FROM _users WHERE _id = $1"; public string Users_SelectIdByLogin() => "SELECT _id FROM _users WHERE _login = $1"; // ============================================================ // === PERMISSIONS SQL === // ============================================================ public string Permissions_DeleteByRole() => "DELETE FROM _permissions WHERE _id_role = $1"; /// /// Effective permission for (object, user). SQLite has no parameterized table /// function, so this queries the v_user_permissions VIEW (recursive tree /// inheritance + global fallback). System user (id=0) is short-circuited to full /// rights in PermissionProviderBase before this runs. Columns match UserPermissionResult. /// (The optimized per-object get_user_permissions_for_object() remains a Free /// C-function task for the non-.NET / Python surface.) /// public string Permissions_GetEffectiveForObject() => """ SELECT $1 AS object_id, user_id, permission_source_id, permission_type, _id_role, _id_user, can_select, can_insert, can_update, can_delete FROM v_user_permissions WHERE user_id = $2 AND object_id IN ($1, 0) ORDER BY CASE WHEN object_id = $1 THEN 0 ELSE 1 END LIMIT 1 """; // The rule of Permissions_GetEffectiveForObject per id: the rows of the object itself, else the global ones // (object_id 0). Several rows of one object come in no fixed order, as there; the caller keeps the first. public string Permissions_GetEffectiveForObjects() => """ SELECT ids.value AS object_id, p.user_id, p.permission_source_id, p.permission_type, p._id_role, p._id_user, p.can_select, p.can_insert, p.can_update, p.can_delete FROM json_each($1) ids JOIN v_user_permissions p ON p.user_id = $2 AND p.object_id IN (ids.value, 0) ORDER BY ids.value, CASE WHEN p.object_id = ids.value THEN 0 ELSE 1 END """; public string Permissions_SelectReadableObjectIds() => """ SELECT DISTINCT object_id FROM v_user_permissions WHERE user_id = $1 AND can_select = 1 """; public string Permissions_Insert() => """ INSERT INTO _permissions (_id, _id_user, _id_role, _id_ref, _select, _insert, _update, _delete) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) """; public string Permissions_Update() => "UPDATE _permissions SET _select = $1, _insert = $2, _update = $3, _delete = $4 WHERE _id = $5"; public string Permissions_Delete() => "DELETE FROM _permissions WHERE _id = $1"; public string Permissions_SelectById() => """ SELECT _id AS Id, _id_user AS IdUser, _id_role AS IdRole, _id_ref AS IdRef, _select AS "Select", _insert AS "Insert", _update AS "Update", _delete AS "Delete" FROM _permissions WHERE _id = $1 """; public string Permissions_SelectAllColumns() => """ SELECT _id AS Id, _id_user AS IdUser, _id_role AS IdRole, _id_ref AS IdRef, _select AS "Select", _insert AS "Insert", _update AS "Update", _delete AS "Delete" FROM _permissions """; public string Permissions_CountFrom() => "SELECT COUNT(*) FROM _permissions"; public string Permissions_SelectByUser() => """ SELECT _id AS Id, _id_user AS IdUser, _id_role AS IdRole, _id_ref AS IdRef, _select AS "Select", _insert AS "Insert", _update AS "Update", _delete AS "Delete" FROM _permissions WHERE _id_user = $1 """; public string Permissions_SelectByRole() => """ SELECT _id AS Id, _id_user AS IdUser, _id_role AS IdRole, _id_ref AS IdRef, _select AS "Select", _insert AS "Insert", _update AS "Update", _delete AS "Delete" FROM _permissions WHERE _id_role = $1 """; public string Permissions_SelectByObject() => """ SELECT _id AS Id, _id_user AS IdUser, _id_role AS IdRole, _id_ref AS IdRef, _select AS "Select", _insert AS "Insert", _update AS "Update", _delete AS "Delete" FROM _permissions WHERE _id_ref = $1 OR _id_ref = 0 """; public string Permissions_SelectByUserRoleObject() => """ SELECT _id AS Id, _select AS "Select", _insert AS "Insert", _update AS "Update", _delete AS "Delete" FROM _permissions WHERE _id_user IS NOT DISTINCT FROM $1 AND _id_role IS NOT DISTINCT FROM $2 AND _id_ref = $3 """; public string Permissions_DeleteByUserRoleObject() => """ DELETE FROM _permissions WHERE _id_user IS NOT DISTINCT FROM $1 AND _id_role IS NOT DISTINCT FROM $2 AND _id_ref = $3 """; public string Permissions_DeleteByUser() => "DELETE FROM _permissions WHERE _id_user = $1"; public string Permissions_Count() => "SELECT COUNT(*) FROM _permissions"; public string Permissions_CountByUser() => "SELECT COUNT(*) FROM _permissions WHERE _id_user = $1"; public string Permissions_CountByRole() => "SELECT COUNT(*) FROM _permissions WHERE _id_role = $1"; public string Permissions_SelectUserRoleIds() => "SELECT _id_role AS IdRole FROM _users_roles WHERE _id_user = $1"; // ============================================================ // === USERS SQL (full) === // ============================================================ public string Users_SelectAllColumns() => """ SELECT _id AS Id, _login AS Login, _name AS Name, _password AS Password, _phone AS Phone, _email AS Email, _enabled AS Enabled, _date_register AS DateRegister, _date_dismiss AS DateDismiss, _key AS Key, _code_int AS CodeInt, _code_string AS CodeString, _code_guid AS CodeGuid, _note AS Note, _hash AS Hash FROM _users """; public string Users_CountFrom() => "SELECT COUNT(*) FROM _users"; public string Users_SelectById() => """ SELECT _id AS Id, _login AS Login, _name AS Name, _password AS Password, _phone AS Phone, _email AS Email, _enabled AS Enabled, _date_register AS DateRegister, _date_dismiss AS DateDismiss, _key AS Key, _code_int AS CodeInt, _code_string AS CodeString, _code_guid AS CodeGuid, _note AS Note, _hash AS Hash FROM _users WHERE _id = $1 """; public string Users_SelectByIds() => """ SELECT _id AS Id, _login AS Login, _name AS Name, _password AS Password, _phone AS Phone, _email AS Email, _enabled AS Enabled, _date_register AS DateRegister, _date_dismiss AS DateDismiss, _key AS Key, _code_int AS CodeInt, _code_string AS CodeString, _code_guid AS CodeGuid, _note AS Note, _hash AS Hash FROM _users WHERE _id IN (SELECT value FROM json_each($1)) """; public string Users_SelectByLogin() => """ SELECT _id AS Id, _login AS Login, _name AS Name, _password AS Password, _phone AS Phone, _email AS Email, _enabled AS Enabled, _date_register AS DateRegister, _date_dismiss AS DateDismiss, _key AS Key, _code_int AS CodeInt, _code_string AS CodeString, _code_guid AS CodeGuid, _note AS Note, _hash AS Hash FROM _users WHERE _login = $1 """; // Case-insensitive email lookup. SQLite has no native LOWER on NVARCHAR with // proper Unicode case-folding by default, but for ASCII emails LOWER() suffices. // Mirrors the PostgreSQL recipe — see PostgreSqlDialect for the contract notes. public string Users_SelectByEmail() => """ SELECT _id AS Id, _login AS Login, _name AS Name, _password AS Password, _phone AS Phone, _email AS Email, _enabled AS Enabled, _date_register AS DateRegister, _date_dismiss AS DateDismiss, _key AS Key, _code_int AS CodeInt, _code_string AS CodeString, _code_guid AS CodeGuid, _note AS Note, _hash AS Hash FROM _users WHERE LOWER(_email) = LOWER($1) AND _enabled = 1 LIMIT 1 """; public string Users_Insert() => """ INSERT INTO _users (_id, _login, _password, _name, _phone, _email, _enabled, _date_register, _date_dismiss, _key, _code_int, _code_string, _code_guid, _note, _hash) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, unhex(replace($15,'-',''))) """; public string Users_Update() => """ UPDATE _users SET _login = $1, _name = $2, _phone = $3, _email = $4, _enabled = $5, _date_dismiss = $6, _key = $7, _code_int = $8, _code_string = $9, _code_guid = $10, _note = $11, _hash = unhex(replace($12,'-','')) WHERE _id = $13 """; // _login is immutable (Postgres trigger contract; keep dialect parity even though // SQLite has no equivalent trigger). Tombstone via _name only. public string Users_SoftDelete() => "UPDATE _users SET _name = $1, _enabled = $2, _date_dismiss = $3 WHERE _id = $4"; public string Users_UpdatePassword() => "UPDATE _users SET _password = $1 WHERE _id = $2"; public string Users_UpdateStatus() => "UPDATE _users SET _enabled = $1, _date_dismiss = $2 WHERE _id = $3"; public string Users_ExistsByLogin() => "SELECT _id FROM _users WHERE _login = $1"; public string Users_ExistsByLoginExcluding() => "SELECT _id FROM _users WHERE _login = $1 AND _id != $2"; public string Users_ExistsByEmail() => "SELECT _id FROM _users WHERE _email = $1 LIMIT 1"; public string Users_Count() => "SELECT COUNT(*) FROM _users"; public string Users_CountEnabled() => "SELECT COUNT(*) FROM _users WHERE _enabled = true"; public string Users_SelectConfigurationId() => "SELECT _id_configuration FROM _users WHERE _id = $1"; public string Users_UpdateConfiguration() => "UPDATE _users SET _id_configuration = $1 WHERE _id = $2"; public string Roles_SelectIdByName() => "SELECT _id AS Id FROM _roles WHERE _name = $1"; public string Roles_ExistsById() => "SELECT _id FROM _roles WHERE _id = $1"; // ============================================================ // === SCHEMES SQL === // ============================================================ public string Schemes_SelectByName() => "SELECT _id, _name, _alias, _name_space, _structure_hash, _tags, _renamed_from, _version, _type FROM _schemes WHERE _name = $1"; public string Schemes_SelectById() => "SELECT _id, _name, _alias, _name_space, _structure_hash, _tags, _renamed_from, _version, _type FROM _schemes WHERE _id = $1"; public string Schemes_SelectAll() => "SELECT _id, _name, _alias, _name_space, _structure_hash, _tags, _renamed_from, _version, _type FROM _schemes"; public string Schemes_Insert() => "INSERT INTO _schemes (_id, _name, _alias, _type) VALUES ($1, $2, $3, $4)"; // Targeted at _name only — INSERT OR IGNORE would also swallow a PK collision on _id and hide a // different bug. Upsert syntax needs SQLite 3.24+; the provider requires 3.44+. public string Schemes_InsertIfAbsent() => "INSERT INTO _schemes (_id, _name, _alias, _type, _name_space) VALUES ($1, $2, $3, $4, $5) ON CONFLICT(_name) DO NOTHING"; public string Schemes_UpdateHash() => "UPDATE _schemes SET _structure_hash = unhex(replace($1,'-','')) WHERE _id = $2"; public string Schemes_UpdateVersion() => "UPDATE _schemes SET _version = $1 WHERE _id = $2 AND COALESCE(_version, 0) < $1"; public string Schemes_Rename() => "UPDATE _schemes SET _name = $1, _renamed_from = $2 WHERE _id = $3"; public string Schemes_SelectRenamed() => "SELECT _id, _name, _renamed_from FROM _schemes WHERE _renamed_from IS NOT NULL"; public string Schemes_UpdateAlias() => "UPDATE _schemes SET _alias = $1 WHERE _id = $2"; public string Schemes_UpdateNameSpace() => "UPDATE _schemes SET _name_space = $1 WHERE _id = $2"; public string Schemes_SelectHashById() => "SELECT _structure_hash FROM _schemes WHERE _id = $1"; public string Schemes_ExistsByName() => "SELECT _id FROM _schemes WHERE _name = $1 LIMIT 1"; public string Schemes_SelectObjectByName() => "SELECT _id, _name, _alias, _name_space, _structure_hash, _tags, _renamed_from, _version, _type FROM _schemes WHERE _name = $1 AND _type = $2"; public string Schemes_InsertObject() => "INSERT INTO _schemes (_id, _name, _type) VALUES ($1, $2, $3)"; public string Schemes_InsertObjectIfAbsent() => "INSERT INTO _schemes (_id, _name, _type) VALUES ($1, $2, $3) ON CONFLICT(_name) DO NOTHING"; // ============================================================ // === STRUCTURES SQL === // ============================================================ public string Structures_SelectByScheme() => """ SELECT _id, _id_parent, _id_scheme, _id_override, _id_type, _id_list, _name, _alias, _order, _readonly, _allow_not_null, _collection_type, _key_type, _is_compress, _store_null, _unique, _unique_version, _unique_scope, _lazy, _tags, _renamed_from, _default_value, _default_editor FROM _structures WHERE _id_scheme = $1 """; public string Structures_SelectBySchemeShort() => "SELECT _id, _id_parent, _id_scheme, _id_type, _name, _order, _collection_type, _key_type, _allow_not_null, _store_null, _unique, _unique_scope, _lazy FROM _structures WHERE _id_scheme = $1"; public string Structures_SelectBySchemeCacheable() => """ SELECT _id, _id_parent, _id_scheme, _id_type, _name, _alias, _order, _readonly, _allow_not_null, _collection_type, _key_type, _unique, _unique_version, _unique_scope, _lazy FROM _structures WHERE _id_scheme = $1 """; public string Structures_Insert() => """ INSERT INTO _structures (_id, _id_scheme, _id_parent, _name, _alias, _id_type, _allow_not_null, _collection_type, _key_type, _order, _lazy) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) """; public string Structures_UpdateType() => "UPDATE _structures SET _id_type = $1 WHERE _id = $2"; public string Structures_UpdateCollectionType() => "UPDATE _structures SET _collection_type = $1 WHERE _id = $2"; public string Structures_UpdateKeyType() => "UPDATE _structures SET _key_type = $1 WHERE _id = $2"; public string Structures_UpdateAlias() => "UPDATE _structures SET _alias = $1 WHERE _id = $2"; public string Structures_UpdateAllowNotNull() => "UPDATE _structures SET _allow_not_null = $1 WHERE _id = $2"; public string Structures_UpdateLazy() => "UPDATE _structures SET _lazy = $1 WHERE _id = $2"; public string Session_SetLazyRefs() => "SELECT redb_lazy_refs($1)"; // Free native extension; Pro SQLite has no session channel (recorded boundary) public string Structures_UpdateUnique() => "UPDATE _structures SET _unique = $1, _unique_version = $2, _unique_scope = $3 WHERE _id = $4"; public string Structures_UpdateTags() => "UPDATE _structures SET _tags = $1 WHERE _id = $2"; public string Structures_Rename() => "UPDATE _structures SET _name = $1, _renamed_from = $2 WHERE _id = $3"; public string Schemes_UpdateTags() => "UPDATE _schemes SET _tags = $1 WHERE _id = $2"; public string Structures_SelectById() => """ SELECT _id, _id_parent, _id_scheme, _id_override, _id_type, _id_list, _name, _alias, _order, _readonly, _allow_not_null, _collection_type, _key_type, _is_compress, _store_null, _unique, _unique_version, _unique_scope, _lazy, _tags, _renamed_from, _default_value, _default_editor FROM _structures WHERE _id = $1 """; // Keyable rows only (root scalars and S2 nested scalars - never collection elements, which // carry _array_index), live objects only: the trash (-10) released its keys and must not get // them back from a recompute. _unique comes back as BLOB(16); SqliteHash reads it. public string Values_SelectRootScalarsByStructure() => """ SELECT v._id as Id, v._id_structure as IdStructure, v._id_object as IdObject, v._String as String, v._Long as Long, v._Guid as Guid, v._Double as Double, v._DateTimeOffset as DateTimeOffset, v._Boolean as Boolean, v._ByteArray as ByteArray, v._Numeric as Numeric, v._unique as "Unique" FROM _values v JOIN _objects o ON o._id = v._id_object AND o._id_scheme <> -10 WHERE v._id_structure = $1 AND v._array_index IS NULL ORDER BY v._id """; // _unique comes back as BLOB(16); SqliteHash reads it. public string Values_SelectElementRowsByStructure() => """ SELECT v._id as Id, v._id_structure as IdStructure, v._id_object as IdObject, v._String as String, v._Long as Long, v._Guid as Guid, v._Double as Double, v._DateTimeOffset as DateTimeOffset, v._Boolean as Boolean, v._ByteArray as ByteArray, v._Numeric as Numeric, v._ListItem as ListItem, v._Object as Object, v._array_parent_id as ArrayParentId, v._unique as "Unique" FROM _values v JOIN _objects o ON o._id = v._id_object AND o._id_scheme <> -10 WHERE v._id_structure = $1 AND v._array_index IS NOT NULL ORDER BY v._id """; // The Guid parameter binds as uuid TEXT; the column holds BLOB(16) (SqliteHash). public string Values_UpdateUnique() => "UPDATE _values SET _unique = unhex(replace($1,'-','')) WHERE _id = $2"; public string Values_ClearUniqueByStructure() => "UPDATE _values SET _unique = NULL WHERE _id_structure = $1 AND _unique IS NOT NULL"; // No positional filter: UIX__values__structure_unique guarantees at most one row per // (structure, key) across root, nested and element rows alike. public string Values_SelectObjectIdByUnique() => "SELECT _id_object FROM _values WHERE _id_structure = $1 AND _unique = unhex(replace($2,'-',''))"; public string Values_ExistsUnhashedByStructure(string typedColumn) => $""" SELECT 1 FROM _values v JOIN _objects o ON o._id = v._id_object AND o._id_scheme <> -10 WHERE v._id_structure = $1 AND v._unique IS NULL AND v.{typedColumn} IS NOT NULL AND v._array_index IS NULL LIMIT 1 """; public string Values_SelectByStructure() => """ SELECT v._id as Id, v._id_structure as IdStructure, v._id_object as IdObject, v._String as String, v._Long as Long, v._Guid as Guid, v._Double as Double, v._DateTimeOffset as DateTimeOffset, v._Boolean as Boolean, v._ByteArray as ByteArray, v._Numeric as Numeric, v._array_parent_id as ArrayParentId, v._array_index as ArrayIndex FROM _values v WHERE v._id_structure = $1 """; public string Values_SetByteArrayScalar() => "UPDATE _values SET _ByteArray = $1, _Guid = NULL, _Long = NULL WHERE _id = $2"; public string Values_DeleteByteArrayElements() => "DELETE FROM _values WHERE _id_structure = $1 AND _array_parent_id IN (SELECT _id FROM _values WHERE _id_structure = $1)"; public string Structures_DeleteByIds(IEnumerable ids) => $"DELETE FROM _structures WHERE _id IN ({string.Join(",", ids)})"; // === ROOT STRUCTURE KEY === // SQLite counts two NULL parents as distinct in IX__structures: a partial unique index over the root rows. private const string RootKeyName = "UX__structures__root"; // The structure $1 and every structure below it, as CTE t. private const string SubtreeCte = "WITH RECURSIVE t(_id) AS (SELECT _id FROM _structures WHERE _id = $1 " + "UNION ALL SELECT c._id FROM _structures c JOIN t ON c._id_parent = t._id)"; public string? Structures_RootKeyExists() => $"SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = '{RootKeyName}'"; public string Structures_CreateRootKey() => $"CREATE UNIQUE INDEX \"{RootKeyName}\" ON _structures (_id_scheme, _name) WHERE _id_parent IS NULL"; public string Structures_SelectRootDuplicates() => """ SELECT s._id, s._id_parent, s._id_scheme, s._name FROM _structures s JOIN (SELECT _id_scheme, _name FROM _structures WHERE _id_parent IS NULL GROUP BY _id_scheme, _name HAVING COUNT(*) > 1) d ON d._id_scheme = s._id_scheme AND d._name = s._name WHERE s._id_parent IS NULL ORDER BY s._id_scheme, s._name, s._id """; // One writer at a time: the schema lock (the write lock of the file) already keeps every other writer out. public string? Structures_LockSubtree() => null; public string Structures_SubtreeIsReferenced(bool withMigrations) => SubtreeCte + " SELECT CASE WHEN " + "EXISTS (SELECT 1 FROM _values v JOIN t ON v._id_structure = t._id) OR " + "EXISTS (SELECT 1 FROM _structures o JOIN t ON o._id_override = t._id)" + (withMigrations ? " OR EXISTS (SELECT 1 FROM _migrations m JOIN t ON m._structure_id = t._id)" : "") + " THEN 1 ELSE 0 END"; public string Structures_DeleteSubtreeMetadataCache() => $"DELETE FROM _scheme_metadata_cache WHERE _structure_id IN ({SubtreeCte} SELECT _id FROM t)"; public string Structures_DeleteById() => "DELETE FROM _structures WHERE _id = $1"; public string Schemes_CountMetadataCache() => "SELECT COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id = $1"; // ============================================================ // === TYPES SQL === // ============================================================ public string Types_SelectByName() => "SELECT _id, _name FROM _types WHERE _name = $1"; public string Types_SelectAll() => "SELECT _id AS Id, _name AS Name, _db_type AS DbType, _type AS Type1 FROM _types"; // ============================================================ // === SCHEME FUNCTIONS (SQLite-specific) === // ============================================================ // Port of sync_metadata_cache_for_scheme(): DELETE the scheme's cache rows, // then re-insert the denormalized _structures ⋈ _types projection. Two // statements; executed via ExecuteNonQuery (runs the whole batch). $1 = scheme id. public string Schemes_SyncMetadataCache() => """ DELETE FROM _scheme_metadata_cache WHERE _scheme_id = $1; INSERT INTO _scheme_metadata_cache ( _scheme_id, _structure_id, _parent_structure_id, _id_override, _name, _alias, _type_id, _list_id, type_name, db_type, type_semantic, _scheme_type, scheme_type_name, _order, _collection_type, collection_type_name, _key_type, key_type_name, _readonly, _allow_not_null, _is_compress, _store_null, _unique, _unique_version, _unique_scope, _lazy, _tags, _default_value, _default_editor) SELECT s._id_scheme, s._id, s._id_parent, s._id_override, s._name, s._alias, t._id, s._id_list, t._name, t._db_type, t._type, sch._type, scht._name, s._order, s._collection_type, ct._name, s._key_type, kt._name, s._readonly, s._allow_not_null, s._is_compress, s._store_null, s._unique, s._unique_version, s._unique_scope, s._lazy, s._tags, s._default_value, s._default_editor FROM _structures s JOIN _types t ON t._id = s._id_type JOIN _schemes sch ON sch._id = s._id_scheme LEFT JOIN _types scht ON scht._id = sch._type LEFT JOIN _types ct ON ct._id = s._collection_type LEFT JOIN _types kt ON kt._id = s._key_type WHERE s._id_scheme = $1; """; public string Schemes_MigrateStructureType() => "SELECT * FROM migrate_structure_type($1, $2, $3, $4)"; public string Schemes_GetStructureTree() => "SELECT get_scheme_structure_tree($1)"; // ============================================================ // === TREE SQL === // ============================================================ public string Tree_SelectChildrenJson() => // No subquery wrapper / `WHERE json_data IS NOT NULL`: that referenced the // computed get_object_json column from the outer query, which made SQLite // materialize get_object_json for EVERY scheme-matched row before filtering by // _id_parent (O(objects-in-scheme) per call -> N+1 tree load was ~50ms/node). // The _id_parent filter now runs before materialization; the C# caller already // skips empty json, so the NULL guard is redundant. ~130x faster per node. """ SELECT get_object_json(o._id, 1) AS json_data FROM _objects o WHERE o._id_parent = $1 AND o._id_scheme = $2 ORDER BY o._name, o._id """; public string Tree_SelectPolymorphicChildren() => """ SELECT o._id as ObjectId, o._id_scheme as SchemeId, get_object_json(o._id, 1) as JsonData FROM _objects o WHERE o._id_parent = $1 ORDER BY o._name, o._id """; public string Tree_SelectSchemeAndJson() => "SELECT _id_scheme as SchemeId, get_object_json(_id, 1) as JsonData FROM _objects WHERE _id = $1"; public string Tree_SelectChildrenBySchemeBase() => """ SELECT _id as Id, _id_parent as IdParent, _id_scheme as IdScheme, _name as Name, _id_owner as IdOwner, _id_who_change as IdWhoChange, _date_create as DateCreate, _date_modify as DateModify, _date_begin as DateBegin, _date_complete as DateComplete, _key as Key, _value_long as ValueLong, _value_string as ValueString, _value_guid as ValueGuid, _value_bool as ValueBool, _value_double as ValueDouble, _value_numeric as ValueNumeric, _value_datetime as ValueDatetime, _value_bytes as ValueBytes, _note as Note, _hash as Hash, _value_unique as ValueUnique FROM _objects WHERE _id_parent = $1 AND _id_scheme = $2 ORDER BY _name, _id """; public string Tree_SelectChildrenBase() => """ SELECT _id as Id, _id_parent as IdParent, _id_scheme as IdScheme, _name as Name, _id_owner as IdOwner, _id_who_change as IdWhoChange, _date_create as DateCreate, _date_modify as DateModify, _date_begin as DateBegin, _date_complete as DateComplete, _key as Key, _value_long as ValueLong, _value_string as ValueString, _value_guid as ValueGuid, _value_bool as ValueBool, _value_double as ValueDouble, _value_numeric as ValueNumeric, _value_datetime as ValueDatetime, _value_bytes as ValueBytes, _note as Note, _hash as Hash, _value_unique as ValueUnique FROM _objects WHERE _id_parent = $1 ORDER BY _name, _id """; public string Tree_ObjectExists() => "SELECT _id FROM _objects WHERE _id = $1 LIMIT 1"; public string Tree_UpdateParent() => // _hash = NULL: the parent is part of the object hash and this update bypasses the save // path - a cached copy must not keep answering with the old parent. "UPDATE _objects SET _id_parent = $1, _date_modify = $2, _id_who_change = $3, _hash = NULL WHERE _id = $4"; public string Tree_DeleteValuesByObjectIds() => "DELETE FROM _values WHERE _id_object IN (SELECT value FROM json_each($1))"; public string Tree_DeleteObjectsByIds() => "DELETE FROM _objects WHERE _id IN (SELECT value FROM json_each($1))"; // changes() of the delete misses the children the _id_parent cascade removed first; the transaction holds the // write lock when this runs, so the rows it counts are the rows the delete removes. public string? ObjectStorage_CountObjectsByIds() => "SELECT COUNT(*) FROM _objects WHERE _id IN (SELECT value FROM json_each($1))"; public string Tree_SelectSubtreeRows() => """ WITH RECURSIVE sub AS ( SELECT o._id, o._id_parent, o._id_scheme, o._name, 1 AS depth FROM _objects o WHERE o._id_parent = $1 AND ($2 IS NULL OR o._id_scheme = $2) UNION ALL SELECT o._id, o._id_parent, o._id_scheme, o._name, s.depth + 1 FROM _objects o JOIN sub s ON o._id_parent = s._id WHERE s.depth < $3 AND ($2 IS NULL OR o._id_scheme = $2) ) SELECT _id AS Id, _id_parent AS IdParent, _id_scheme AS IdScheme, depth AS Depth FROM sub ORDER BY _name, _id """; public string Tree_SelectAncestorRows() => """ WITH RECURSIVE up AS ( SELECT o._id, o._id_parent, o._id_scheme, 0 AS depth FROM _objects o WHERE o._id = $1 UNION ALL SELECT o._id, o._id_parent, o._id_scheme, u.depth + 1 FROM _objects o JOIN up u ON o._id = u._id_parent WHERE u.depth < $2 ) SELECT _id AS Id, _id_parent AS IdParent, _id_scheme AS IdScheme, depth AS Depth FROM up ORDER BY depth """; public string Tree_SelectIdsWithAncestors() => """ WITH RECURSIVE up AS ( SELECT o._id, o._id_parent, 0 AS depth FROM _objects o WHERE o._id IN (SELECT value FROM json_each($1)) UNION ALL SELECT o._id, o._id_parent, u.depth + 1 FROM _objects o JOIN up u ON o._id = u._id_parent WHERE u.depth < $2 ) SELECT DISTINCT _id FROM up """; // ============================================================ // === OBJECT STORAGE SQL === // ============================================================ public string ObjectStorage_SelectObjectById() => """ SELECT _id as Id, _id_scheme as IdScheme, _hash as Hash, _name as Name, _id_parent as IdParent, _id_owner as IdOwner, _id_who_change as IdWhoChange, _date_create as DateCreate, _date_modify as DateModify, _date_begin as DateBegin, _date_complete as DateComplete, _key as Key, _value_long as ValueLong, _value_string as ValueString, _value_guid as ValueGuid, _value_bool as ValueBool, _value_double as ValueDouble, _value_numeric as ValueNumeric, _value_datetime as ValueDatetime, _value_bytes as ValueBytes, _note as Note, _value_unique as ValueUnique FROM _objects WHERE _id = $1 """; public string ObjectStorage_SelectIdHash() => "SELECT _id as Id, _hash as Hash FROM _objects WHERE _id = $1"; public string ObjectStorage_SelectIdBySchemeValueUnique() => "SELECT _id FROM _objects WHERE _id_scheme = $1 AND _value_unique = $2"; // P7: an in-batch key exchange releases before it takes - inside the batch transaction. public string ObjectStorage_ClearValueUniqueByIds(IEnumerable ids) => $"UPDATE _objects SET _value_unique = NULL WHERE _value_unique IS NOT NULL AND _id IN ({string.Join(",", ids)})"; public string Values_ClearUniqueByValueIds(IEnumerable ids) => $"UPDATE _values SET _unique = NULL WHERE _unique IS NOT NULL AND _id IN ({string.Join(",", ids)})"; public string ObjectStorage_SelectIdHashScheme() => "SELECT _id as Id, _hash as Hash, _id_scheme as IdScheme FROM _objects WHERE _id = $1"; public string ObjectStorage_SelectObjectsByIds() => """ SELECT _id as Id, _id_scheme as IdScheme, _id_parent as IdParent, _id_owner as IdOwner, _id_who_change as IdWhoChange, _name as Name, _hash as Hash, _date_create as DateCreate, _date_modify as DateModify, _date_begin as DateBegin, _date_complete as DateComplete, _key as Key, _note as Note, _value_long as ValueLong, _value_string as ValueString, _value_guid as ValueGuid, _value_bool as ValueBool, _value_double as ValueDouble, _value_numeric as ValueNumeric, _value_datetime as ValueDatetime, _value_bytes as ValueBytes, _value_unique as ValueUnique FROM _objects WHERE _id IN (SELECT value FROM json_each($1)) """; public string ObjectStorage_DeleteById() => "DELETE FROM _objects WHERE _id = $1"; public string ObjectStorage_DeleteByIds() => "DELETE FROM _objects WHERE _id IN (SELECT value FROM json_each($1))"; public string ObjectStorage_InsertObject() => """ INSERT INTO _objects ( _id, _id_scheme, _name, _note, _date_create, _date_modify, _id_owner, _id_who_change, _id_parent, _hash, _value_string, _value_long, _value_guid, _value_bool, _value_double, _value_numeric, _value_datetime, _value_bytes, _key, _date_begin, _date_complete, _value_unique ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, unhex(replace($10,'-','')), $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22) """; public string ObjectStorage_UpdateObject() => """ UPDATE _objects SET _name = $1, _note = $2, _date_modify = $3, _id_who_change = $4, _hash = unhex(replace($5,'-','')), _value_string = $6, _value_long = $7, _value_guid = $8, _value_bool = $9, _value_double = $10, _value_numeric = $11, _value_datetime = $12, _value_bytes = $13, _key = $14, _date_begin = $15, _date_complete = $16, _value_unique = $17 WHERE _id = $18 """; public string ObjectStorage_DeleteValuesByObjectId() => "DELETE FROM _values WHERE _id_object = $1"; public string ObjectStorage_GetObjectJson() => "SELECT get_object_json($1, $2)"; public string ObjectStorage_GetObjectsJsonBulk() => // $1 = JSON array of ids (bound as JSON text); SQLite has no unnest. """ SELECT get_object_json(value, $2) FROM json_each($1) """; public string ObjectStorage_SelectStructuresWithMetadata() => """ SELECT s._id as Id, s._id_parent as IdParent, s._name as Name, COALESCE(t._db_type, 'String') as DbType, s._collection_type as CollectionType, s._key_type as KeyType, COALESCE(s._store_null, false) as StoreNull, COALESCE(s._unique, false) as "Unique", s._unique_scope as UniqueScope, COALESCE(t._type, 'string') as TypeSemantic FROM _structures s LEFT JOIN _types t ON s._id_type = t._id WHERE s._id_scheme = $1 """; public string ObjectStorage_SelectTypeById() => "SELECT _id as Id, _name as Name, _db_type as DbType, _type as Type1 FROM _types WHERE _id = $1"; public string ObjectStorage_CheckObjectExists() => "SELECT _id FROM _objects WHERE _id = $1 LIMIT 1"; public string ObjectStorage_SelectSchemeById() => "SELECT _id as Id, _name as Name FROM _schemes WHERE _id = $1"; public string ObjectStorage_SelectValuesForObjects() => """ SELECT _id as Id, _id_structure as IdStructure, _id_object as IdObject, _string as String, _long as Long, _guid as Guid, _double as Double, _datetimeoffset as DateTimeOffset, _boolean as Boolean, _bytearray as ByteArray, _numeric as Numeric, _listitem as ListItem, _object as Object, _array_parent_id as ArrayParentId, _array_index as ArrayIndex FROM _values WHERE _id_object IN (SELECT value FROM json_each($1)) """; public string ObjectStorage_SelectSchemeIdsForObjects() => "SELECT _id as ObjectId, _id_scheme as SchemeId FROM _objects WHERE _id IN (SELECT value FROM json_each($1))"; public string ObjectStorage_SelectValueById() => """ SELECT _id as Id, _id_structure as IdStructure, _id_object as IdObject, _string as String, _long as Long, _guid as Guid, _double as Double, _datetimeoffset as DateTimeOffset, _boolean as Boolean, _bytearray as ByteArray, _numeric as Numeric, _listitem as ListItem, _object as Object, _array_parent_id as ArrayParentId, _array_index as ArrayIndex FROM _values WHERE _id = $1 """; public string ObjectStorage_SelectAllTypes() => "SELECT _id as Id, _name as Name, _db_type as DbType, _type as Type1 FROM _types"; public string ObjectStorage_SelectExistingIds() => "SELECT _id as Id FROM _objects WHERE _id IN (SELECT value FROM json_each($1))"; public string ObjectStorage_SelectExistingCreateDates() => "SELECT o._id as Id, o._date_create as DateCreate, s._structure_hash as SchemeHash, s._id as SchemeId FROM _objects o JOIN _schemes s ON s._id = o._id_scheme WHERE o._id IN (SELECT value FROM json_each($1)) " + "UNION ALL SELECT 0, NULL, s._structure_hash, s._id FROM _schemes s WHERE s._id IN (SELECT value FROM json_each($2))"; public string ObjectStorage_SelectIdHashPairs() => "SELECT _id as Id, _hash as Hash FROM _objects WHERE _id IN (SELECT value FROM json_each($1))"; public string ObjectStorage_SelectSchemesByIds() => """ SELECT _id as Id, _name as Name, _alias as Alias, _name_space as NameSpace, _structure_hash as StructureHash, _type as Type FROM _schemes WHERE _id IN (SELECT value FROM json_each($1)) """; public string ObjectStorage_LockObjectsForUpdate() => // SQLite has no row-level FOR UPDATE (writers are serialized DB-wide) and // no ANY(array) — bind the id array as JSON and expand via json_each. "SELECT _id FROM _objects WHERE _id IN (SELECT value FROM json_each($1)) ORDER BY _id"; public string ObjectStorage_SelectSchemeIdByObjectId() => "SELECT _id_scheme FROM _objects WHERE _id = $1"; // ============================================================ // === LIST SQL === // ============================================================ public string Lists_SelectById() => "SELECT _id, _name FROM _lists WHERE _id = $1"; public string Lists_SelectByName() => "SELECT _id, _name FROM _lists WHERE _name = $1"; public string Lists_SelectAll() => "SELECT _id, _name FROM _lists ORDER BY _name"; public string Lists_Insert() => "INSERT INTO _lists (_id, _name, _alias) VALUES ($1, $2, $3)"; public string Lists_Update() => "UPDATE _lists SET _name = $1, _alias = $2 WHERE _id = $3"; public string Lists_Delete() => "DELETE FROM _lists WHERE _id = $1"; public string Lists_IsUsedInStructures() => "SELECT _id FROM _structures WHERE _id_list = $1 LIMIT 1"; // ============================================================ // === LIST ITEMS SQL === // ============================================================ public string ListItems_SelectById() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id = $1"; public string ListItems_SelectByIds() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id IN (SELECT value FROM json_each($1))"; public string ListItems_SelectByListId() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id_list = $1 ORDER BY _value"; public string ListItems_SelectByListIdAndValue() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id_list = $1 AND _value = $2"; public string ListItems_Insert() => "INSERT INTO _list_items (_id, _id_list, _value, _alias, _id_object) VALUES ($1, $2, $3, $4, $5)"; public string ListItems_UpdateAliasAndObject() => "UPDATE _list_items SET _alias = $1, _id_object = $2 WHERE _id = $3"; public string ListItems_Update() => "UPDATE _list_items SET _value = $1, _alias = $2, _id_object = $3 WHERE _id = $4"; public string ListItems_Delete() => "DELETE FROM _list_items WHERE _id = $1"; public string ListItems_SelectByObjectId() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id_object = $1"; // ============================================================ // === MAINTENANCE SQL === // ============================================================ // analysis_limit bounds the per-index sample (0 = unbounded): a full ANALYZE of a // multi-gigabyte file runs for minutes, the bounded form for seconds, and the planner // estimates it produces are just as good for redb's query shapes. public string Maintenance_Analyze(int analysisLimit) => analysisLimit > 0 ? $"PRAGMA analysis_limit={analysisLimit}; ANALYZE" : "ANALYZE"; // SQLite has no usage counters at all - Seeks/Scans/Updates/LastUsed stay NULL by design. // EstimatedRows comes from sqlite_stat1 (first number of the stat field = table rows the // index covers); size needs the dbstat virtual table, which not every build compiles in - // hence the size-less fallback below. public string Maintenance_SelectIndexStats() => """ SELECT NULL AS "Schema", m.tbl_name AS "Table", m.name AS "Name", CASE WHEN il."unique" IS NULL THEN NULL ELSE il."unique" END AS "IsUnique", (SELECT group_concat(name, ',') FROM (SELECT ii.name AS name FROM pragma_index_info(m.name) ii ORDER BY ii.seqno)) AS "ColumnsCsv", NULL AS "IncludedColumnsCsv", CASE WHEN il.origin = 'pk' THEN 1 ELSE 0 END AS "IsPrimaryKey", CASE WHEN il.origin = 'u' THEN 1 ELSE 0 END AS "IsUniqueConstraint", NULL AS "IsClustered", (SELECT CASE WHEN EXISTS ( SELECT 1 FROM pragma_foreign_key_list(m.tbl_name) fk WHERE fk."from" IN (SELECT ii2.name FROM pragma_index_info(m.name) ii2) ) THEN 1 ELSE 0 END) AS "BacksForeignKey", (SELECT SUM(d.pgsize) FROM dbstat d WHERE d.name = m.name) AS "SizeBytes", CAST(substr(s.stat, 1, CASE WHEN instr(s.stat, ' ') = 0 THEN length(s.stat) ELSE instr(s.stat, ' ') - 1 END) AS INTEGER) AS "EstimatedRows", NULL AS "Seeks", NULL AS "Scans", NULL AS "Updates", NULL AS "LastUsed" FROM sqlite_master m LEFT JOIN pragma_index_list(m.tbl_name) il ON il.name = m.name LEFT JOIN sqlite_stat1 s ON s.idx = m.name WHERE m.type = 'index' AND m.tbl_name NOT LIKE 'sqlite_%' ORDER BY m.tbl_name, m.name """; // The index check: the named indexes of the redb tables (an autoindex of a constraint has no name of ours). Key // columns from index_xinfo (key = 1, the rowid left out); SQLite has no included columns and no invalid index. public string? Schema_SelectIndexShapes() => """ SELECT m.name AS "Name", m.tbl_name AS "Table", COALESCE(il."unique", 0) AS "IsUnique", (SELECT group_concat(name, ',') FROM (SELECT x.name AS name FROM pragma_index_xinfo(m.name) x WHERE x.key = 1 AND x.cid >= 0 ORDER BY x.seqno)) AS "KeyColumnsCsv", NULL AS "IncludedColumnsCsv", 1 AS "IsValid" FROM sqlite_master m LEFT JOIN pragma_index_list(m.tbl_name) il ON il.name = m.name WHERE m.type = 'index' AND m.tbl_name LIKE '\_%' ESCAPE '\' AND m.name NOT LIKE 'sqlite_autoindex%' """; // The repair's look for rows a unique index on the place of a value would refuse; the predicate is the index's own. public string? Schema_SelectValueIndexDuplicates(IReadOnlyList keyColumns, string? predicate) => $""" SELECT _id_object AS "ObjectId", _id_structure AS "StructureId", COUNT(*) AS "Rows" FROM _values {(predicate == null ? "" : "WHERE " + predicate)} GROUP BY {string.Join(", ", keyColumns)} HAVING COUNT(*) > 1 ORDER BY _id_object, _id_structure LIMIT 100 """; // Maximum-compat fallback: no dbstat (may not be compiled in) and no sqlite_stat1 (does // not exist before the first ANALYZE) - names, columns and origin are always available. public string Maintenance_SelectIndexStatsNoSize() => """ SELECT NULL AS "Schema", m.tbl_name AS "Table", m.name AS "Name", CASE WHEN il."unique" IS NULL THEN NULL ELSE il."unique" END AS "IsUnique", (SELECT group_concat(name, ',') FROM (SELECT ii.name AS name FROM pragma_index_info(m.name) ii ORDER BY ii.seqno)) AS "ColumnsCsv", NULL AS "IncludedColumnsCsv", CASE WHEN il.origin = 'pk' THEN 1 ELSE 0 END AS "IsPrimaryKey", CASE WHEN il.origin = 'u' THEN 1 ELSE 0 END AS "IsUniqueConstraint", NULL AS "IsClustered", (SELECT CASE WHEN EXISTS ( SELECT 1 FROM pragma_foreign_key_list(m.tbl_name) fk WHERE fk."from" IN (SELECT ii2.name FROM pragma_index_info(m.name) ii2) ) THEN 1 ELSE 0 END) AS "BacksForeignKey", NULL AS "SizeBytes", NULL AS "EstimatedRows", NULL AS "Seeks", NULL AS "Scans", NULL AS "Updates", NULL AS "LastUsed" FROM sqlite_master m LEFT JOIN pragma_index_list(m.tbl_name) il ON il.name = m.name WHERE m.type = 'index' AND m.tbl_name NOT LIKE 'sqlite_%' ORDER BY m.tbl_name, m.name """; // SQLite takes a single table too ("ANALYZE tbl"), so the facade needs no excuse here. The // sample bound is set the same way as for the whole database. public string Maintenance_AnalyzeTable(string? schema, string table, int analysisLimit) => analysisLimit > 0 ? $"PRAGMA analysis_limit={analysisLimit}; ANALYZE {QuoteIdentifier(table)};" : $"ANALYZE {QuoteIdentifier(table)};"; public string Maintenance_SelectTableExists() => "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = $1 AND ($2 IS NULL OR $2 = 'main')"; // Rows come from sqlite_stat1 (the row whose idx IS NULL describes the table itself), sizes // from dbstat when it is compiled in. No dates: SQLite records none, so HasStatistics is all // the truth there is. public string Maintenance_SelectTableStats() => """ SELECT NULL AS "Schema", m.name AS "Table", (SELECT CAST(substr(s.stat, 1, CASE WHEN instr(s.stat, ' ') = 0 THEN length(s.stat) ELSE instr(s.stat, ' ') - 1 END) AS INTEGER) FROM sqlite_stat1 s WHERE s.tbl = m.name ORDER BY (s.idx IS NULL) DESC LIMIT 1) AS "EstimatedRows", (SELECT SUM(d.pgsize) FROM dbstat d WHERE d.name = m.name) AS "DataSizeBytes", (SELECT SUM(d.pgsize) FROM dbstat d WHERE d.name IN (SELECT i.name FROM sqlite_master i WHERE i.type = 'index' AND i.tbl_name = m.name)) AS "IndexesSizeBytes", NULL AS "DeadRows", NULL AS "LastAnalyze", NULL AS "LastAutoAnalyze", NULL AS "LastVacuum", (SELECT COUNT(*) FROM sqlite_stat1 s WHERE s.tbl = m.name) > 0 AS "HasStatistics" FROM sqlite_master m WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%' ORDER BY m.name """; // Same query without dbstat: sizes are the only thing it cannot answer. private string Maintenance_SelectTableStatsNoSize() => """ SELECT NULL AS "Schema", m.name AS "Table", (SELECT CAST(substr(s.stat, 1, CASE WHEN instr(s.stat, ' ') = 0 THEN length(s.stat) ELSE instr(s.stat, ' ') - 1 END) AS INTEGER) FROM sqlite_stat1 s WHERE s.tbl = m.name ORDER BY (s.idx IS NULL) DESC LIMIT 1) AS "EstimatedRows", NULL AS "DataSizeBytes", NULL AS "IndexesSizeBytes", NULL AS "DeadRows", NULL AS "LastAnalyze", NULL AS "LastAutoAnalyze", NULL AS "LastVacuum", (SELECT COUNT(*) FROM sqlite_stat1 s WHERE s.tbl = m.name) > 0 AS "HasStatistics" FROM sqlite_master m WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%' ORDER BY m.name """; // A database nobody has analysed yet: sqlite_stat1 does not exist, and a statement that names // it fails to prepare - which is why neither form above can serve this case. There is no // estimate and no statistics, and that is the answer, not an error. private string Maintenance_SelectTableStatsNoStatistics() => """ SELECT NULL AS "Schema", m.name AS "Table", NULL AS "EstimatedRows", (SELECT SUM(d.pgsize) FROM dbstat d WHERE d.name = m.name) AS "DataSizeBytes", (SELECT SUM(d.pgsize) FROM dbstat d WHERE d.name IN (SELECT i.name FROM sqlite_master i WHERE i.type = 'index' AND i.tbl_name = m.name)) AS "IndexesSizeBytes", NULL AS "DeadRows", NULL AS "LastAnalyze", NULL AS "LastAutoAnalyze", NULL AS "LastVacuum", 0 AS "HasStatistics" FROM sqlite_master m WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%' ORDER BY m.name """; // Neither dbstat nor sqlite_stat1: names only, everything else honestly null. private string Maintenance_SelectTableStatsBare() => """ SELECT NULL AS "Schema", m.name AS "Table", NULL AS "EstimatedRows", NULL AS "DataSizeBytes", NULL AS "IndexesSizeBytes", NULL AS "DeadRows", NULL AS "LastAnalyze", NULL AS "LastAutoAnalyze", NULL AS "LastVacuum", 0 AS "HasStatistics" FROM sqlite_master m WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%' ORDER BY m.name """; public System.Collections.Generic.IReadOnlyList Maintenance_SelectTableStatsForms() => new[] { Maintenance_SelectTableStats(), // dbstat + sqlite_stat1 Maintenance_SelectTableStatsNoSize(), // sqlite_stat1 only Maintenance_SelectTableStatsNoStatistics(), // dbstat only - a database never analysed Maintenance_SelectTableStatsBare() // neither }; // No usage counters at all, so no window to report - null, not a fabricated timestamp. public string Maintenance_SelectStatisticsWindow() => """ SELECT NULL AS "CountersSince", NULL AS "IsReplica" """; // ============================================================ // === VALIDATION SQL === // ============================================================ public string Validation_SelectAllTypes() => "SELECT _id, _name, _db_type, _type FROM _types"; public string Validation_SelectSchemeByName() => "SELECT _id, _id_parent, _name, _alias, _name_space, _structure_hash, _type FROM _schemes WHERE _name = $1"; public string Validation_SelectStructuresBySchemeId() => @"SELECT s._id, s._id_parent, s._id_scheme, s._id_override, s._id_type, s._id_list, s._name, s._alias, s._order, s._readonly, s._allow_not_null, s._collection_type, s._key_type, s._is_compress, s._store_null, s._unique, s._unique_version, s._default_value, s._default_editor FROM _structures s WHERE s._id_scheme = $1"; // ============================================================ // === LAZY LOADER SQL === // ============================================================ public string LazyLoader_SelectObjectBase() => @"SELECT _id, _id_scheme, _hash, _name, _id_parent, _id_owner, _id_who_change, _date_create, _date_modify, _date_begin, _date_complete, _key, _value_long, _value_string, _value_guid, _value_bool, _value_double, _value_numeric, _value_datetime, _value_bytes, _note FROM _objects WHERE _id = $1"; public string LazyLoader_GetObjectJson() => "SELECT get_object_json($1, $2)"; public string LazyLoader_GetObjectJsonBatch() => // $1 = JSON array of ids; SQLite has no unnest -> json_each. @"SELECT value AS ""Id"", get_object_json(value, $2) AS ""JsonData"" FROM json_each($1)"; public string LazyLoader_SelectObjectHash() => "SELECT _hash FROM _objects WHERE _id = $1"; public string Transaction_SavepointBegin() => "SAVEPOINT redb_batch_save"; public string? Transaction_SavepointRelease() => "RELEASE SAVEPOINT redb_batch_save"; public string Transaction_SavepointRollback() => "ROLLBACK TO SAVEPOINT redb_batch_save"; // ============================================================ // === QUERY PROVIDER SQL === // ============================================================ public string Query_CheckPermissionSql() => "SELECT EXISTS(SELECT 1 FROM v_user_permissions WHERE user_id = $2 AND object_id IN ($1, 0) AND can_select = 1) as has_permission"; public string Query_SqlPreviewTemplate() => "SELECT {0}($1, $2, $3, $4, $5, $6, $7) as sql_preview"; /// /// SQLite: the descendants of the given objects down to depthLimit levels below them. /// public string Query_GetDescendantIdsFromAncestorsSql(string idsString, int depthLimit) => $@"WITH RECURSIVE descendants AS ( SELECT _id, 1 as level FROM _objects WHERE _id_parent IN ({idsString}) UNION ALL SELECT o._id, d.level + 1 FROM _objects o INNER JOIN descendants d ON o._id_parent = d._id WHERE d.level < {depthLimit} ) SELECT DISTINCT _id FROM descendants"; /// /// SQLite: WITH RECURSIVE for traversing ancestors. /// public string Query_GetParentIdsFromDescendantsSql(string idsString, int depthLimit) => $@"WITH RECURSIVE ancestors AS ( SELECT _id, _id_parent, 0 as level FROM _objects WHERE _id IN ({idsString}) UNION ALL SELECT o._id, o._id_parent, ancestors.level + 1 FROM _objects o INNER JOIN ancestors ON ancestors._id_parent = o._id WHERE ancestors.level < {depthLimit} ) SELECT DISTINCT _id FROM ancestors WHERE _id_parent IS NULL OR level > 0"; /// /// SQLite: Load objects by IDs as JSON using get_object_json function. /// public string Query_LoadObjectsByIdsSql(string idsString, int maxDepth) => $@"SELECT get_object_json(id.value, {maxDepth}) as ""Value"" FROM json_each('[{idsString}]') as id ORDER BY id.value"; public string Query_TreeSqlPreviewTemplate(string functionName) => $"SELECT {functionName}($1, $2, $3, $4, $5, $6, $7, $8) as sql_preview"; // ============================================================ // === SQL PREVIEW FUNCTION NAMES === // ============================================================ public string Query_SqlPreviewFunction() => "get_search_sql_preview"; public string Query_TreeSqlPreviewBaseFunction() => "get_search_tree_sql_preview_base"; // ============================================================ // === v2-pvt MODULE ENTRY-POINTS (free Sqlite) === // Two-step pipeline: ask DB to BUILD the inner _id-list SQL, // then wrap on the C# side with a materializer/COUNT/EXISTS. // SQLite deploys no v2-pvt SQL module: the native C extension hosts those functions. // redb.SQLite/sql/v2-pvt/ is the port's logic spec (PG PL/pgSQL), not deployed SQL - see its // README.md. Init-time check lives in RedbServiceBase.InitializeAsync using // Query_PvtModuleVersionFunction(). // ============================================================ // SQLite has NO server-side v2-pvt module (no stored functions). Every PVT // hook returns null, which signals the engine to skip the native PVT path: // - the Pro tier generates query SQL in C# (ProSqlBuilder); // - the Free tier will host equivalents in the native C extension later. // Returning null from Query_PvtModuleVersionFunction also disables the // init-time `SELECT pvt_module_version()` probe in RedbServiceBase. // v2-pvt is hosted in the native C extension (redbsqlite.dll/.so/.dylib). The Free // query path (QueryProviderBase) asks the DB to BUILD the inner _id-list SQL // via pvt_build_query_sql(...), then wraps it client-side. filter/order are // bound as $1/$2; scheme/limit/offset/depth/distinct/mode/treeIds are inlined. public string? Query_BuildPvtSqlFunction() => "pvt_build_query_sql"; public string? Query_BuildPvtSqlInvocation( long schemeId, int? limit, int offset, int maxDepth, bool distinct, string sourceMode, long[]? treeIds, bool hasDistinctOn = false) { var lim = limit.HasValue ? limit.Value.ToString() : "NULL"; var tree = (treeIds == null || treeIds.Length == 0) ? "NULL" : "'[" + string.Join(",", treeIds) + "]'"; // pvt_build_query_sql(scheme, filter, limit, offset, order, max_depth, // distinct, source_mode, tree_ids, include_seed, // polymorphic [, distinct_on]) var call = $"pvt_build_query_sql({schemeId}, json($1), {lim}, {offset}, json($2), " + $"{maxDepth}, {(distinct ? 1 : 0)}, '{sourceMode}', {tree}, 1, 1" + (hasDistinctOn ? ", json($3)" : "") + ")"; return "SELECT " + call; } // The inner order is numbered before the join and restored after it. public string? Query_WrapPvtWithObjectRows(string innerSql) => $""" SELECT o._id as Id, o._id_scheme as IdScheme, o._id_parent as IdParent, o._id_owner as IdOwner, o._id_who_change as IdWhoChange, o._name as Name, o._hash as Hash, o._date_create as DateCreate, o._date_modify as DateModify, o._date_begin as DateBegin, o._date_complete as DateComplete, o._key as Key, o._note as Note, o._value_long as ValueLong, o._value_string as ValueString, o._value_guid as ValueGuid, o._value_bool as ValueBool, o._value_double as ValueDouble, o._value_numeric as ValueNumeric, o._value_datetime as ValueDatetime, o._value_bytes as ValueBytes, o._value_unique as ValueUnique FROM (SELECT ordered._id, row_number() OVER () AS _rn FROM ( {innerSql} ) ordered) sub JOIN _objects o ON o._id = sub._id ORDER BY sub._rn """; public string? Query_WrapPvtWithCount(string innerSql) => $"SELECT count(*) FROM (\n{innerSql}\n) t"; public string? Query_WrapPvtWithExists(string innerSql) => $"SELECT EXISTS(SELECT 1 FROM (\n{innerSql}\n) t)"; public string? Query_WrapPvtWithIds(string innerSql) => $"SELECT t._id FROM (\n{innerSql}\n) t"; // The v2-pvt module of SQLite is the native extension (redbsqlite.dll/.so/.dylib), versioned by // PVT_MODULE_VERSION in native/src/redb_pvt.c. The Free service asks this function at // initialization and refuses an extension of another version (SqliteNativeExtension) - the base // gate would try to apply a SQL bundle, and there is none. Bump both on every change of the C code. public string? Query_PvtModuleVersionFunction() => "pvt_module_version"; public string? Query_PvtRequiredVersion() => "0.6.13"; // The native extension ships with the package and is matched exactly; a newer database file is judged by its // _schema_compat row (RedbService), not by a function. public string? Query_PvtModuleCompatFunction() => null; public string? Query_BuildPvtProjectionSqlFunction() => null; public string? Query_BuildPvtProjectionSqlInvocation( long schemeId, int? limit, int offset, int maxDepth, bool distinct, string sourceMode, long[]? treeIds, bool hasDistinctOn = false) => null; public string? Query_WrapPvtProjectionRowsAsJson(string innerSql, bool includeId) => null; // ============================================================ // === SOFT DELETE === // ============================================================ /// /// Soft-delete: move the given objects + all descendants under a fresh trash /// container (scheme -10). Native SQLite (no server function, Core untouched): /// the sequence is first raised above every stored id (as the key generator does, see /// SqliteKeyGenerator.IdSpaceTopSql), then the trash id is allocated from the AUTOINCREMENT _global_identity and read via /// last_insert_rowid() — per-connection, so it stays stable across the statements /// regardless of concurrent writers. The batch opens no transaction of its own: the provider /// runs it inside one (ExecuteAtomicAsync, joining the caller's), whose owner rolls back a /// failure between the statements. A SAVEPOINT in the text itself became a transaction /// nobody owned when a statement after it failed - pooled with the database write lock. /// The final SELECT is last (Core's QueryAsync reads only the first result set). /// Params: $1=objectIds (array -> JSON), $2=userId, $3=trashParentId (nullable). /// Returns: trash_id, marked_count. /// public string SoftDelete_MarkForDeletion() => $""" UPDATE sqlite_sequence SET seq = max(seq, {(global::redb.SQLite.Data.SqliteKeyGenerator.IdSpaceTopSql)}) WHERE name = '_global_identity'; INSERT INTO _global_identity DEFAULT VALUES; INSERT INTO _objects (_id, _id_scheme, _id_parent, _id_owner, _id_who_change, _name, _value_long, _key, _value_string) VALUES (last_insert_rowid(), -10, $3, $2, $2, '__TRASH__' || $2 || '_' || CAST(strftime('%s','now') AS INTEGER), 0, 0, 'pending'); UPDATE _objects SET _id_parent = last_insert_rowid(), _id_scheme = -10, _value_unique = NULL, -- V4 (decision 9): the trash releases object keys too _hash = NULL, -- full-object hash: parent and key change here outside the save path; no cached copy may outlive the move _date_modify = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE _id IN ( WITH RECURSIVE d(_id) AS ( SELECT _id FROM _objects WHERE _id IN (SELECT value FROM json_each($1)) AND _id_scheme <> -10 UNION SELECT o._id FROM _objects o JOIN d ON o._id_parent = d._id WHERE o._id_scheme <> -10 ) SELECT _id FROM d ); UPDATE _objects SET _value_long = changes() WHERE _id = last_insert_rowid(); -- V4 (UNIQUE, decision 9): the trash releases the value keys too, in the same transaction; -- without this the trash scheme (-10) is one more uniqueness namespace (PG/MSSQL parity). UPDATE _values SET _unique = NULL WHERE _unique IS NOT NULL AND _id_object IN (SELECT _id FROM _objects WHERE _id_parent = last_insert_rowid() AND _id_scheme = -10); DELETE FROM _global_identity WHERE _id = last_insert_rowid(); SELECT last_insert_rowid() AS trash_id, (SELECT _value_long FROM _objects WHERE _id = last_insert_rowid()) AS marked_count; """; /// /// Physically delete one batch of objects from a trash container (children of $1). /// FK ON DELETE CASCADE handles _values. Progress kept on the container (_key /// cumulative, _value_string status); this batch's count is stashed in the /// container's _value_double so the final SELECT can return it (changes() can't be /// read after the progress UPDATE). The empty container is left as a 'completed' /// marker (scheme -10, invisible to normal queries) — PG deletes it; cosmetic. /// /// References (_values._Object, a foreign key with no ON DELETE action): a reference held by /// a trashed object is removed with the batch, so the order containers are purged in never /// matters; an object referenced by a live object is skipped - never deleted, never unlinked. /// When only such objects are left the container is marked 'failed' and the background /// worker stops claiming it. The batch is chosen twice by the same ordered predicate - the /// reference removal in between touches no live holder, so both picks are the same rows. /// /// /// No transaction in the text (see ): the provider runs /// the batch inside one. /// /// Params: $1=trashId, $2=batchSize. Returns: deleted_count, remaining_count. /// /// /// The purge statement above ends with the result row, so the finished container outlived every /// purge on SQLite while PostgreSQL and MSSQL remove it in the function. Params: $1=trashId. /// public string? SoftDelete_DeleteCompletedTrashContainer() => """ DELETE FROM _objects WHERE _id = $1 AND _id_scheme = -10 AND NOT EXISTS (SELECT 1 FROM _objects WHERE _id_parent = $1) """; public string SoftDelete_PurgeTrash() => """ UPDATE _objects SET _value_string = 'running', _date_modify = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE _id = $1 AND _value_string = 'pending'; DELETE FROM _values WHERE _Object IN ( SELECT o._id FROM _objects o WHERE o._id_parent = $1 AND NOT EXISTS (SELECT 1 FROM _values lv JOIN _objects r ON r._id = lv._id_object WHERE lv._Object = o._id AND r._id_scheme <> -10) ORDER BY o._id LIMIT $2) AND EXISTS (SELECT 1 FROM _objects h WHERE h._id = _values._id_object AND h._id_scheme = -10); DELETE FROM _objects WHERE _id IN ( SELECT o._id FROM _objects o WHERE o._id_parent = $1 AND NOT EXISTS (SELECT 1 FROM _values lv JOIN _objects r ON r._id = lv._id_object WHERE lv._Object = o._id AND r._id_scheme <> -10) ORDER BY o._id LIMIT $2); UPDATE _objects SET _value_double = changes(), _key = _key + changes(), _value_string = CASE WHEN (SELECT COUNT(*) FROM _objects WHERE _id_parent = $1) = 0 THEN 'completed' WHEN changes() = 0 THEN 'failed' ELSE 'running' END, _date_modify = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE _id = $1; SELECT (SELECT CAST(_value_double AS INTEGER) FROM _objects WHERE _id = $1) AS deleted_count, (SELECT COUNT(*) FROM _objects WHERE _id_parent = $1) AS remaining_count; """; /// /// Objects of a trash container referenced by live objects, with the referencing objects. /// Params: $1=trashId. Returns: referenced_id, referencing_id (at most 100 pairs). /// public string SoftDelete_SelectLiveReferrersOfTrash() => """ SELECT DISTINCT o._id AS referenced_id, r._id AS referencing_id FROM _objects o INNER JOIN _values v ON v._Object = o._id INNER JOIN _objects r ON r._id = v._id_object WHERE o._id_parent = $1 AND r._id_scheme <> -10 ORDER BY 1, 2 LIMIT 100 """; /// /// Gets deletion progress for a specific trash container. /// Params: $1=trashId (bigint) /// Returns: trash_id, total, deleted, status, started_at, owner_id /// public string SoftDelete_GetDeletionProgress() => """ SELECT _id AS trash_id, COALESCE(_value_long, 0) AS total, COALESCE(_key, 0) AS deleted, COALESCE(_value_string, 'pending') AS status, _date_create AS started_at, _id_owner AS owner_id FROM _objects WHERE _id = $1 AND _id_scheme = -10 """; /// /// Gets all active deletions for a user. /// Params: $1=userId (bigint) /// Returns: trash_id, total, deleted, status, started_at, owner_id /// public string SoftDelete_GetUserActiveDeletions() => """ SELECT _id AS trash_id, COALESCE(_value_long, 0) AS total, COALESCE(_key, 0) AS deleted, COALESCE(_value_string, 'pending') AS status, _date_create AS started_at, _id_owner AS owner_id FROM _objects WHERE _id_owner = $1 AND _id_scheme = -10 AND _id_parent IS NULL AND _value_string IN ('pending', 'running') ORDER BY _date_create DESC """; /// /// Gets orphaned deletion tasks for recovery at startup. /// CLUSTER-SAFE: Only returns pending OR running with stale _date_modify. /// Params: $1=timeoutMinutes (int) /// Returns: trash_id, total, deleted, status, owner_id /// public string SoftDelete_GetOrphanedTasks() => """ SELECT _id AS trash_id, COALESCE(_value_long, 0) AS total, COALESCE(_key, 0) AS deleted, COALESCE(_value_string, 'pending') AS status, _id_owner AS owner_id FROM _objects WHERE _id_scheme = -10 AND _id_parent IS NULL AND ( _value_string = 'pending' OR ( _value_string = 'running' AND _date_modify < strftime('%Y-%m-%dT%H:%M:%fZ','now','-' || $1 || ' minutes') ) ) ORDER BY _date_create """; /// /// Atomically claim an orphaned task for processing. /// CLUSTER-SAFE: UPDATE with condition prevents race. /// Params: $1=trashId, $2=timeoutMinutes /// Returns: claimed count (1=success, 0=already taken) /// public string SoftDelete_ClaimOrphanedTask() => """ UPDATE _objects SET _value_string = 'running', _date_modify = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE _id = $1 AND _id_scheme = -10 AND ( _value_string = 'pending' OR ( _value_string = 'running' AND _date_modify < strftime('%Y-%m-%dT%H:%M:%fZ','now','-' || $2 || ' minutes') ) ) """; // ============================================================ // === METADATA CACHE WARMUP === // ============================================================ // Port of warmup_all_metadata_caches(). No DB-side loop: rebuild ALL schemes // in one INSERT…SELECT (same projection as the per-scheme sync, no WHERE), then // return per-scheme stats rows for WarmupCacheResult. RedbServiceBase runs this // once in InitializeAsync via QueryAsync (final SELECT supplies the rows). public string Warmup_AllMetadataCaches() => """ DELETE FROM _scheme_metadata_cache; INSERT INTO _scheme_metadata_cache ( _scheme_id, _structure_id, _parent_structure_id, _id_override, _name, _alias, _type_id, _list_id, type_name, db_type, type_semantic, _scheme_type, scheme_type_name, _order, _collection_type, collection_type_name, _key_type, key_type_name, _readonly, _allow_not_null, _is_compress, _store_null, _unique, _unique_version, _unique_scope, _lazy, _tags, _default_value, _default_editor) SELECT s._id_scheme, s._id, s._id_parent, s._id_override, s._name, s._alias, t._id, s._id_list, t._name, t._db_type, t._type, sch._type, scht._name, s._order, s._collection_type, ct._name, s._key_type, kt._name, s._readonly, s._allow_not_null, s._is_compress, s._store_null, s._unique, s._unique_version, s._unique_scope, s._lazy, s._tags, s._default_value, s._default_editor FROM _structures s JOIN _types t ON t._id = s._id_type JOIN _schemes sch ON sch._id = s._id_scheme LEFT JOIN _types scht ON scht._id = sch._type LEFT JOIN _types ct ON ct._id = s._collection_type LEFT JOIN _types kt ON kt._id = s._key_type; SELECT s._id AS scheme_id, COUNT(c._structure_id) AS structures_count, s._name AS scheme_name FROM _schemes s LEFT JOIN _scheme_metadata_cache c ON c._scheme_id = s._id GROUP BY s._id, s._name ORDER BY s._id; """; }