Path: redb/redb.Core/Query/ISqlDialect.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.Core/Query/ISqlDialect.cs
----
using System.Collections.Generic;
namespace redb.Core.Query;
///
/// SQL syntax abstraction for different DBMS support.
///
/// IMPORTANT: Implementations in different projects MAY DIFFER!
/// - PostgreSqlDialect: CASE WHEN (tested - 15 ms on 15K objects)
/// - MsSqlDialect: will be later, possibly different implementation
///
/// Current focus: PostgreSQL + performance.
///
public interface ISqlDialect
{
///
/// Provider name (PostgreSQL, SqlServer, MySql)
///
string ProviderName { get; }
///
/// Pagination format: LIMIT/OFFSET for PostgreSQL, TOP/OFFSET for MSSQL
///
string FormatPagination(int? limit, int? offset);
///
/// Subquery wrapper: (subquery) AS alias
///
string WrapSubquery(string subquery, string alias);
///
/// PVT column for CASE WHEN approach.
/// PostgreSQL: MAX(CASE WHEN _id_structure = X THEN _Long END) AS "Age"
///
string FormatPvtColumn(long structureId, string dbColumn, string alias);
///
/// Array containment check: = ANY($1) for PostgreSQL, IN for MSSQL
///
string FormatArrayContains(string column, string paramName);
///
/// Mapping of redb types to SQL types
///
string GetDbTypeName(string redbType);
///
/// Parameter format: $1 for PostgreSQL, @p1 for MSSQL
///
string FormatParameter(int index);
///
/// Identifier escaping: "name" for PostgreSQL, [name] for MSSQL
///
string QuoteIdentifier(string name);
///
/// Case-insensitive LIKE: ILIKE for PostgreSQL, LIKE for MSSQL (CI collation)
///
string FormatCaseInsensitiveLike(string column, string parameter);
///
/// Wraps a text expression so the database folds its case for ALL scripts, not just ASCII.
///
///
/// Every case-insensitive operation goes through here, so the three of them
/// (ILIKE/LIKE, LOWER, UPPER) can never drift apart: fixing one and
/// forgetting another is exactly how a search finds a row that an equality check then rejects.
///
///
///
/// The mechanism differs per provider and that is deliberate, because the providers differ in
/// kind and not merely in syntax. PostgreSQL attaches a COLLATE clause to the operand.
/// MSSQL needs nothing: its default collation already folds every script. SQLite has no
/// collation that could help (its only case-insensitive one, NOCASE, is ASCII-only, and
/// LIKE is a function that ignores collations entirely), so its provider fixes the
/// problem one level down by overriding the built-in functions on the connection and returns
/// the expression untouched here.
///
///
/// Returns unchanged when the feature is off, so generated SQL is
/// byte-for-byte what it was.
///
/// A SQL text expression, already quoted or parenthesised as needed.
string FoldCase(string expression);
///
/// Format DateTime as SQL literal. PostgreSQL: '...'::timestamptz, MSSQL: '...' (parsed natively)
///
string FormatDateTimeLiteral(DateTime dt);
///
/// Format DateTimeOffset as SQL literal. PostgreSQL: '...'::timestamptz, MSSQL: '...' (parsed natively)
///
string FormatDateTimeOffsetLiteral(DateTimeOffset dto);
///
/// Format a bool as SQL literal for the _Boolean column. TRUE/FALSE by default (PostgreSQL); MSSQL (bit) and SQLite
/// (INTEGER) write 1/0.
///
string FormatBooleanLiteral(bool value) => value ? "TRUE" : "FALSE";
///
/// Format a string as SQL literal for the _String column: single quotes, a quote inside doubled. SQL Server
/// prefixes N, or every character outside the database code page is stored as '?'.
///
string FormatStringLiteral(string value) => "'" + value.Replace("'", "''") + "'";
/// Format a Guid as SQL literal for the _Guid column: the quoted 'D' form by default.
string FormatGuidLiteral(Guid value) => "'" + value.ToString("D") + "'";
///
/// Format bytes as SQL literal for the _ByteArray column: X'..' by default (SQLite); PostgreSQL '\x..'::bytea,
/// SQL Server 0x...
///
string FormatBinaryLiteral(byte[] value) => "X'" + Convert.ToHexString(value) + "'";
///
/// The longest dictionary key the _array_index column holds, in UTF-16 code units, or null when
/// the column has no bound. SQL Server declares it NVARCHAR(430) (index key width); PostgreSQL and SQLite
/// use unbounded text. The save checks a serialized key against it before any row is written.
///
int? DictionaryKeyMaxLength => null;
// ============================================================
// === ROLES SQL ===
// ============================================================
///
/// SELECT role by ID. Returns: Id, Name, IdConfiguration
///
string Roles_SelectById();
///
/// SELECT role by name. Returns: Id, Name, IdConfiguration
///
string Roles_SelectByName();
///
/// SELECT all roles ordered by name. Returns: Id, Name, IdConfiguration
///
string Roles_SelectAll();
///
/// INSERT new role. Params: $1=id, $2=name
///
string Roles_Insert();
///
/// UPDATE role name. Params: $1=newName, $2=roleId
///
string Roles_UpdateName();
///
/// DELETE role by ID. Params: $1=roleId
///
string Roles_Delete();
///
/// Check if role name exists (excluding role). Params: $1=name, $2=excludeId (optional)
///
string Roles_ExistsByName();
///
/// Check if role name exists excluding specific role. Params: $1=name, $2=excludeId
///
string Roles_ExistsByNameExcluding();
///
/// SELECT COUNT of all roles
///
string Roles_Count();
///
/// UPDATE role configuration. Params: $1=configId, $2=roleId
///
string Roles_UpdateConfiguration();
///
/// SELECT role configuration ID. Params: $1=roleId
///
string Roles_SelectConfigurationId();
// ============================================================
// === USERS_ROLES SQL ===
// ============================================================
///
/// INSERT user-role assignment. Params: $1=id, $2=userId, $3=roleId
///
string UsersRoles_Insert();
///
/// DELETE user-role assignment. Params: $1=userId, $2=roleId
///
string UsersRoles_Delete();
///
/// DELETE all user-role assignments for user. Params: $1=userId
///
string UsersRoles_DeleteByUser();
///
/// DELETE all user-role assignments for role. Params: $1=roleId
///
string UsersRoles_DeleteByRole();
///
/// Check if user-role assignment exists. Params: $1=userId, $2=roleId
///
string UsersRoles_Exists();
///
/// SELECT roles for user. Params: $1=userId. Returns: Id, Name, IdConfiguration
///
string UsersRoles_SelectRolesByUser();
///
/// SELECT users for role. Params: $1=roleId. Returns user fields
///
string UsersRoles_SelectUsersByRole();
///
/// SELECT COUNT of users for role. Params: $1=roleId
///
string UsersRoles_CountByRole();
// ============================================================
// === USERS SQL (for role operations) ===
// ============================================================
///
/// Check if user exists by ID. Params: $1=userId
///
string Users_ExistsById();
///
/// SELECT user by login. Params: $1=login. Returns: Id
///
string Users_SelectIdByLogin();
// ============================================================
// === PERMISSIONS SQL ===
// ============================================================
///
/// SELECT all permission columns FROM _permissions (no WHERE). Used for dynamic queries.
///
string Permissions_SelectAllColumns();
///
/// SELECT COUNT(*) FROM _permissions (no WHERE). Used for dynamic count queries.
///
string Permissions_CountFrom();
///
/// DELETE permissions by role. Params: $1=roleId
///
string Permissions_DeleteByRole();
///
/// Get user permissions for object via SQL function or query.
/// CRITICAL: PostgreSQL uses get_user_permissions_for_object() function!
/// MSSQL: Must be expanded to CTE/JOIN query.
/// Params: $1=objectId, $2=userId
///
string Permissions_GetEffectiveForObject();
///
/// The rows of for many objects in one statement, by the same rule
/// (the same function or view), with object_id the requested id. An object may have no row, as with the single
/// query. Params: $1=objectIds (array), $2=userId
///
string Permissions_GetEffectiveForObjects();
///
/// SELECT readable object IDs for user. Params: $1=userId
///
string Permissions_SelectReadableObjectIds();
///
/// INSERT new permission. Params: $1=id, $2=userId, $3=roleId, $4=refId, $5=select, $6=insert, $7=update, $8=delete
///
string Permissions_Insert();
///
/// UPDATE permission flags. Params: $1=select, $2=insert, $3=update, $4=delete, $5=permissionId
///
string Permissions_Update();
///
/// DELETE permission by ID. Params: $1=permissionId
///
string Permissions_Delete();
///
/// SELECT permission by ID. Params: $1=permissionId
///
string Permissions_SelectById();
///
/// SELECT permissions by user. Params: $1=userId
///
string Permissions_SelectByUser();
///
/// SELECT permissions by role. Params: $1=roleId
///
string Permissions_SelectByRole();
///
/// SELECT permissions by object. Params: $1=objectId
///
string Permissions_SelectByObject();
///
/// SELECT permission by user/role/object. Params: $1=userId, $2=roleId, $3=objectId
///
string Permissions_SelectByUserRoleObject();
///
/// DELETE permission by user/role/object. Params: $1=userId, $2=roleId, $3=objectId
///
string Permissions_DeleteByUserRoleObject();
///
/// DELETE all permissions by user. Params: $1=userId
///
string Permissions_DeleteByUser();
///
/// SELECT COUNT of all permissions
///
string Permissions_Count();
///
/// SELECT COUNT of permissions by user. Params: $1=userId
///
string Permissions_CountByUser();
///
/// SELECT COUNT of permissions by role. Params: $1=roleId
///
string Permissions_CountByRole();
///
/// SELECT user's role IDs. Params: $1=userId
///
string Permissions_SelectUserRoleIds();
// ============================================================
// === USERS SQL (full) ===
// ============================================================
///
/// SELECT all user columns FROM _users (no WHERE). Used for dynamic search queries.
///
string Users_SelectAllColumns();
///
/// SELECT COUNT(*) FROM _users (no WHERE). Used for dynamic count queries.
///
string Users_CountFrom();
///
/// SELECT all user fields by ID. Params: $1=userId
///
string Users_SelectById();
///
/// SELECT all user fields by IDs (batch). Params: $1=userIds (array/csv)
///
string Users_SelectByIds();
///
/// SELECT all user fields by login. Params: $1=login
///
string Users_SelectByLogin();
///
/// SELECT all user fields by email (case-insensitive, first match, active only).
/// Params: $1=email. Used by .
///
string Users_SelectByEmail();
///
/// INSERT new user with all fields.
/// Params: $1=id, $2=login, $3=password, $4=name, $5=phone, $6=email, $7=enabled,
/// $8=dateRegister, $9=dateDismiss, $10=key, $11=codeInt, $12=codeString,
/// $13=codeGuid, $14=note, $15=hash
///
string Users_Insert();
///
/// UPDATE user fields.
/// Params: $1=login, $2=name, $3=phone, $4=email, $5=enabled, $6=dateDismiss,
/// $7=key, $8=codeInt, $9=codeString, $10=codeGuid, $11=note, $12=hash, $13=userId
///
string Users_Update();
///
/// UPDATE user for soft delete. Params: $1=newLogin, $2=newName, $3=enabled, $4=dateDismiss, $5=userId
///
string Users_SoftDelete();
///
/// UPDATE user password. Params: $1=hashedPassword, $2=userId
///
string Users_UpdatePassword();
///
/// UPDATE user enabled status. Params: $1=enabled, $2=dateDismiss, $3=userId
///
string Users_UpdateStatus();
///
/// Check login exists. Params: $1=login
///
string Users_ExistsByLogin();
///
/// Check login exists excluding user. Params: $1=login, $2=excludeUserId
///
string Users_ExistsByLoginExcluding();
///
/// Check email exists. Params: $1=email
///
string Users_ExistsByEmail();
///
/// SELECT COUNT of all users
///
string Users_Count();
///
/// SELECT COUNT of enabled users
///
string Users_CountEnabled();
///
/// SELECT user configuration ID. Params: $1=userId
///
string Users_SelectConfigurationId();
///
/// UPDATE user configuration. Params: $1=configId, $2=userId
///
string Users_UpdateConfiguration();
///
/// SELECT role by name. Params: $1=roleName
///
string Roles_SelectIdByName();
///
/// Check role exists by ID. Params: $1=roleId
///
string Roles_ExistsById();
// ============================================================
// === SCHEMES SQL ===
// ============================================================
///
/// SELECT scheme by name. Params: $1=name
/// Returns: _id, _name, _alias, _name_space, _structure_hash, _type
///
string Schemes_SelectByName();
///
/// SELECT scheme by ID. Params: $1=schemeId
/// Returns: _id, _name, _alias, _name_space, _structure_hash, _type
///
string Schemes_SelectById();
///
/// SELECT all schemes.
/// Returns: _id, _name, _alias, _name_space, _structure_hash, _type
///
string Schemes_SelectAll();
///
/// INSERT new scheme. Params: $1=id, $2=name, $3=alias, $4=type
///
string Schemes_Insert();
///
/// INSERT a new scheme, doing nothing when the name is already taken.
/// Params: $1=id, $2=name, $3=alias, $4=type, $5=nameSpace (nullable). Returns 0 affected rows on conflict.
///
/// Exists because several nodes starting simultaneously all miss the lookup and all try to create
/// the same scheme. The conflict must be suppressed by the statement itself rather than caught:
/// on PostgreSQL a failed INSERT inside a transaction poisons that transaction, so a catch-and-retry
/// cannot re-read the winner's row.
///
///
string Schemes_InsertIfAbsent();
///
/// UPDATE scheme alias by ID. Params: $1=alias (nullable), $2=schemeId
///
string Schemes_UpdateAlias();
///
/// UPDATE scheme namespace by ID (V4, К7 — the ownership mark that gates short-name adoption).
/// Params: $1=nameSpace (nullable), $2=schemeId
///
string Schemes_UpdateNameSpace();
///
/// UPDATE scheme structure hash. Params: $1=hash, $2=schemeId
///
string Schemes_UpdateHash();
///
/// UPDATE the version of the Props class the scheme was synchronised with (_schemes._version), never lower
/// than the stored one. Params: $1=version, $2=schemeId
///
string Schemes_UpdateVersion();
///
/// Rename a scheme in place: the name and the list of its previous names. Used for every scheme rename of the sync
/// (short name or FullName to the explicit name, RedbScheme.RenamedFrom).
/// Params: $1=new name, $2=renamed_from (JSON array text), $3=schemeId
///
string Schemes_Rename();
///
/// SELECT the schemes that were renamed: _id, _name, _renamed_from where _renamed_from is set. Read only when the
/// sync is about to create a scheme, to stop a class older than a rename. No params.
///
string Schemes_SelectRenamed();
///
/// SELECT scheme hash by ID. Params: $1=schemeId
///
string Schemes_SelectHashById();
///
/// Check scheme exists by name. Params: $1=name
///
string Schemes_ExistsByName();
///
/// SELECT Object scheme by name and type. Params: $1=name, $2=type
///
string Schemes_SelectObjectByName();
///
/// INSERT Object scheme. Params: $1=id, $2=name, $3=type
///
string Schemes_InsertObject();
///
/// INSERT an Object scheme, doing nothing when the name is already taken.
/// Params: $1=id, $2=name, $3=type. Returns 0 affected rows on conflict.
/// Same race as , on the untyped path.
///
string Schemes_InsertObjectIfAbsent();
// ============================================================
// === STRUCTURES SQL ===
// ============================================================
///
/// SELECT full structures by scheme. Params: $1=schemeId
/// Returns all structure fields
///
string Structures_SelectByScheme();
///
/// SELECT structures short fields by scheme. Params: $1=schemeId
/// Returns: _id, _id_parent, _id_scheme, _id_type, _name, _order
///
string Structures_SelectBySchemeShort();
///
/// SELECT structures with cache fields by scheme. Params: $1=schemeId
/// Returns fields needed for caching
///
string Structures_SelectBySchemeCacheable();
///
/// INSERT new structure.
/// Params: $1=id, $2=schemeId, $3=parentId, $4=name, $5=alias, $6=typeId, $7=allowNotNull, $8=collectionType, $9=keyType, $10=order
///
string Structures_Insert();
///
/// UPDATE structure type. Params: $1=typeId, $2=structureId
///
string Structures_UpdateType();
///
/// UPDATE structure collection type. Params: $1=collectionType, $2=structureId
///
string Structures_UpdateCollectionType();
///
/// UPDATE structure key type. Params: $1=keyType, $2=structureId
///
string Structures_UpdateKeyType();
///
/// UPDATE structure alias. Params: $1=alias, $2=structureId
///
string Structures_UpdateAlias();
///
/// UPDATE structure allow_not_null. Params: $1=allowNotNull, $2=structureId
///
string Structures_UpdateAllowNotNull();
///
/// UPDATE the lazy-reference marker (V4, LAZY Л2). Params: $1=lazy, $2=structureId
///
string Structures_UpdateLazy();
///
/// Set the session lazy-references flag the JSON builders read (V4, LAZY L2).
/// Params: $1 = 1|0
///
string Session_SetLazyRefs();
///
/// DELETE structures by IDs. Params: dynamic IN clause
///
string Structures_DeleteByIds(IEnumerable ids);
// ============================================================
// === ROOT STRUCTURE KEY (Data.RootStructureKey) ===
// One root field name once per scheme: a partial unique index over the root rows on engines whose structure key
// counts two NULL parents as distinct (PostgreSQL, SQLite). SQL Server counts NULLs as equal, so its structure
// key holds for root rows already: there Structures_RootKeyExists returns null and the other members of this
// group are not called (they throw NotSupportedException).
// ============================================================
///
/// SELECT returning a row when the unique key of root structures exists. No params. null: the engine needs
/// no such key (SQL Server), and none of the members below applies.
///
string? Structures_RootKeyExists();
/// CREATE the unique key of root structures. No params.
string Structures_CreateRootKey();
///
/// SELECT the root structures whose (_id_scheme, _name) occurs more than once, as structure rows
/// (_id, _id_parent, _id_scheme, _name), ordered by scheme, name and id. No params.
///
string Structures_SelectRootDuplicates();
///
/// Locks a structure and every structure below it against writers until the transaction ends, so that a value
/// inserted into it meanwhile waits and then fails on the foreign key instead of being cascaded away by a delete.
/// Params: $1 = structure id. null: the engine has one writer at a time and the schema lock is that writer
/// (SQLite).
///
string? Structures_LockSubtree();
///
/// SELECT 1 when anything points to a structure or a structure below it (a value, an overriding structure and, with
/// , a record of _migrations), else 0. Params: $1 = structure id.
///
string Structures_SubtreeIsReferenced(bool withMigrations);
/// DELETE the metadata cache rows of a structure and every structure below it. Params: $1 = structure id.
string Structures_DeleteSubtreeMetadataCache();
/// DELETE a structure; its children go by the cascade of _id_parent. Params: $1 = structure id.
string Structures_DeleteById();
/// SELECT the number of metadata cache rows of a scheme as BIGINT. Params: $1 = scheme id.
string Schemes_CountMetadataCache();
///
/// UPDATE the unique-key flag, encoder version and element-key scope of a structure.
/// Params: $1=unique (bool), $2=unique_version (long, nullable),
/// $3=unique_scope (long, nullable; S3), $4=id
///
string Structures_UpdateUnique();
/// UPDATE the free-form _tags marker of a structure. Params: $1=tags, $2=id
string Structures_UpdateTags();
///
/// Rename a structure in place ([RedbRename]): the name and the list of its previous names.
/// Params: $1=new name, $2=renamed_from (JSON array text), $3=id
///
string Structures_Rename();
/// UPDATE the free-form _tags marker of a scheme. Params: $1=tags, $2=id
string Schemes_UpdateTags();
///
/// SELECT one structure by id (same columns as Structures_SelectByScheme). Params: $1=id
///
string Structures_SelectById();
// ============================================================
// === UNIQUE KEYS (_values._unique) SQL ===
// ============================================================
///
/// SELECT the root scalar rows of a structure — no array parent, no array index — with their
/// typed columns, for recomputing keys. Params: $1=structureId.
/// Returns RedbValue columns: Id, IdStructure, IdObject, String, Long, Guid, Double,
/// DateTimeOffset, Boolean, ByteArray, Numeric, Unique.
///
string Values_SelectRootScalarsByStructure();
///
/// SELECT the ELEMENT rows of a collection structure — array index present — with their
/// typed columns, reference targets and the owning collection id, for recomputing
/// element-scoped keys (S3). Params: $1=structureId.
/// Returns RedbValue columns: Id, IdStructure, IdObject, String, Long, Guid, Double,
/// DateTimeOffset, Boolean, ByteArray, Numeric, ListItem, Object, ArrayParentId, Unique.
///
string Values_SelectElementRowsByStructure();
/// UPDATE one row's key. Params: $1=unique (Guid, nullable), $2=id
string Values_UpdateUnique();
/// UPDATE every row of a structure to _unique = NULL. Params: $1=structureId
string Values_ClearUniqueByStructure();
///
/// 1 when the structure has any value row, else 0: the sync refuses a change of the collection kind of a structure that
/// holds values. Params: $1=structureId (SQL Server: @p0).
///
string Values_ExistsByStructure()
=> "SELECT CASE WHEN EXISTS (SELECT 1 FROM _values WHERE _id_structure = $1) THEN 1 ELSE 0 END";
///
/// SELECT _id_object of the root scalar row holding a key. Params: $1=structureId, $2=unique (Guid).
/// At most one row can match: the unique index guarantees it.
///
string Values_SelectObjectIdByUnique();
///
/// SELECT 1 if the structure has a root scalar row with a value in
/// but no key — the trace of a SQL-side writer. Params: $1=structureId. Column name is one of the
/// _values typed columns and is interpolated, never user input.
///
string Values_ExistsUnhashedByStructure(string typedColumn);
///
/// SELECT every row of a structure (base and array-element rows alike) with RedbValue aliases.
/// Params: $1=structureId. Used by the byte[]-storage conversion (V4, work Б1).
///
string Values_SelectByStructure();
///
/// UPDATE one row into the scalar byte[] shape: _ByteArray = payload, _Guid and _Long cleared.
/// Params: $1=bytes, $2=id.
///
string Values_SetByteArrayScalar();
///
/// DELETE the per-byte element rows of a legacy Array-of-Byte structure: rows of the structure
/// whose _array_parent_id points at another row OF THE SAME structure (the base row). A base row
/// nested in a class points at the class row, another structure, and is left alone. Set-based on
/// purpose: a megabyte payload is a million element rows. Params: $1=structureId (used twice).
///
string Values_DeleteByteArrayElements();
///
/// SELECT _id of the object holding a unique key in a scheme. Params: $1=schemeId, $2=valueUnique.
/// At most one row: the partial unique index over (_id_scheme, _value_unique) guarantees it.
///
string ObjectStorage_SelectIdBySchemeValueUnique();
///
/// UPDATE the listed objects to _value_unique = NULL (P7: release before take inside the batch
/// transaction, so an in-batch key exchange passes). Ids are inlined like Structures_DeleteByIds.
///
string ObjectStorage_ClearValueUniqueByIds(IEnumerable ids);
///
/// P7-аналог для ПОЛЕВЫХ ключей (Э2): освободить _values._unique у обновляемых строк перед
/// bulk-UPDATE - иначе обмен [RedbUnique]-значений двух объектов в одном батче бьётся об
/// частичный уникальный индекс (проверка немедленная; на SQLite bulk идёт построчно и своп
/// падал всегда, на PG/MSSQL исход зависел от порядка строк). Та же транзакция - снаружи
/// разрыв не виден. CT-1/CT-выяснение 2026-09-04.
///
string Values_ClearUniqueByValueIds(IEnumerable ids);
// ============================================================
// === TYPES SQL ===
// ============================================================
///
/// SELECT type by name. Params: $1=name
/// Returns: _id, _name
///
string Types_SelectByName();
///
/// SELECT all types. Returns: _id, _name, _db_type, _type
///
string Types_SelectAll();
// ============================================================
// === SCHEME FUNCTIONS (PostgreSQL-specific, MSSQL: stored procs or queries) ===
// ============================================================
///
/// Sync metadata cache for scheme. Params: $1=schemeId
/// PostgreSQL: SELECT sync_metadata_cache_for_scheme($1)
/// MSSQL: EXEC sp_sync_metadata_cache @schemeId
///
string Schemes_SyncMetadataCache();
///
/// Migrate structure type. Params: $1=structureId, $2=oldType, $3=newType, $4=dryRun
/// PostgreSQL: SELECT * FROM migrate_structure_type($1, $2, $3, $4)
///
string Schemes_MigrateStructureType();
///
/// Get structure tree JSON. Params: $1=schemeId
/// PostgreSQL: SELECT get_scheme_structure_tree($1)
///
string Schemes_GetStructureTree();
// ============================================================
// === TREE SQL ===
// ============================================================
///
/// SELECT children with JSON by parent and scheme. Params: $1=parentId, $2=schemeId
/// Returns: json_data column
///
string Tree_SelectChildrenJson();
///
/// SELECT polymorphic children with scheme. Params: $1=parentId
/// Returns: ObjectId, SchemeId, JsonData columns
///
string Tree_SelectPolymorphicChildren();
///
/// SELECT scheme and JSON for object. Params: $1=objectId
/// Returns: SchemeId, JsonData columns
///
string Tree_SelectSchemeAndJson();
///
/// SELECT children base fields by parent and scheme (Pro PVT mode).
/// Params: $1=parentId, $2=schemeId
/// Returns: RedbObjectRow columns
///
string Tree_SelectChildrenBySchemeBase();
///
/// SELECT all children base fields by parent (Pro PVT polymorphic mode).
/// Params: $1=parentId
/// Returns: RedbObjectRow columns
///
string Tree_SelectChildrenBase();
///
/// Check if object exists. Params: $1=objectId
///
string Tree_ObjectExists();
///
/// UPDATE object parent (move). Params: $1=newParentId, $2=dateModify, $3=whoChangeId, $4=objectId
///
string Tree_UpdateParent();
///
/// DELETE values by object IDs. Params: $1=objectIds (array)
///
string Tree_DeleteValuesByObjectIds();
///
/// DELETE objects by IDs. Params: $1=objectIds (array). Its rows-affected is the number of the given objects this
/// statement deleted, unless gives the count instead.
///
string Tree_DeleteObjectsByIds();
///
/// The count of a delete by ids (, )
/// where the rows-affected of the delete is not it. SQLite: the _id_parent cascade removes a child before the
/// statement reaches it, and the child is not counted. Run in the delete's transaction, which holds the write lock,
/// so no other writer changes the rows between the count and the delete. Params: $1=objectIds (array). Null: the
/// rows-affected of the delete is the count.
///
string? ObjectStorage_CountObjectsByIds() => null;
///
/// The subtree under an object in one statement: every descendant down to a depth, as rows
/// (Id, IdParent, IdScheme, Depth; the children of the object have depth 1), ordered by _name, _id as the children
/// queries order them, so that the children of each parent come in that order. With a scheme, the walk keeps to
/// objects of that scheme (a child of another scheme and what hangs below it are not reached).
/// Params: $1=objectId, $2=schemeId or NULL for any scheme, $3=maxDepth. A cycle in _id_parent repeats rows up to
/// the depth; the caller detects it.
///
string Tree_SelectSubtreeRows();
///
/// An object and its ancestors in one statement, as rows (Id, IdParent, IdScheme, Depth; the object itself has
/// depth 0, its parent 1), ordered by depth. Params: $1=objectId, $2=maxDepth. A cycle repeats rows up to the
/// depth; the caller detects it.
///
string Tree_SelectAncestorRows();
///
/// The ids of the given objects and of all their ancestors, each once, in one statement (ToTreeListAsync,
/// ToRootListAsync, LoadWithParentsAsync). Params: $1=object ids (long[]), $2=maxDepth: how far up a chain is read.
///
string Tree_SelectIdsWithAncestors();
// ============================================================
// === OBJECT STORAGE SQL ===
// ============================================================
///
/// SELECT all base fields for object by ID. Params: $1=objectId
/// Returns: Id, IdScheme, Hash, Name, IdParent, IdOwner, IdWhoChange, DateCreate, DateModify, DateBegin, DateComplete, Key, ValueLong, ValueString, ValueGuid, ValueBool, ValueDouble, ValueNumeric, ValueDatetime, ValueBytes, Note
///
string ObjectStorage_SelectObjectById();
///
/// SELECT only Id and Hash for object. Params: $1=objectId
///
string ObjectStorage_SelectIdHash();
///
/// SELECT Id, Hash, IdScheme for cache check. Params: $1=objectId
///
string ObjectStorage_SelectIdHashScheme();
///
/// SELECT all base fields for objects by IDs. Params: $1=objectIds (array)
///
string ObjectStorage_SelectObjectsByIds();
///
/// DELETE object by ID. Params: $1=objectId
///
string ObjectStorage_DeleteById();
///
/// DELETE objects by IDs (bulk). Params: $1=objectIds (array)
///
string ObjectStorage_DeleteByIds();
///
/// INSERT new object with all fields.
/// Params: $1=id, $2=schemeId, $3=name, $4=note, $5=dateCreate, $6=dateModify,
/// $7=ownerId, $8=whoChangeId, $9=parentId, $10=hash,
/// $11=valueString, $12=valueLong, $13=valueGuid, $14=valueBool,
/// $15=valueDouble, $16=valueNumeric, $17=valueDatetime, $18=valueBytes,
/// $19=key, $20=dateBegin, $21=dateComplete
///
string ObjectStorage_InsertObject();
///
/// UPDATE object with all fields.
/// Params: $1=name, $2=note, $3=dateModify, $4=whoChangeId, $5=hash,
/// $6=valueString, $7=valueLong, $8=valueGuid, $9=valueBool,
/// $10=valueDouble, $11=valueNumeric, $12=valueDatetime, $13=valueBytes,
/// $14=key, $15=dateBegin, $16=dateComplete, $17=objectId
///
string ObjectStorage_UpdateObject();
///
/// DELETE all values for object. Params: $1=objectId
///
string ObjectStorage_DeleteValuesByObjectId();
///
/// SELECT object as JSON. Params: $1=objectId, $2=depth
/// PostgreSQL: SELECT get_object_json($1, $2)::text
/// MSSQL: Stored procedure or CTE
///
string ObjectStorage_GetObjectJson();
///
/// SELECT objects as JSON (bulk). Params: $1=objectIds (array), $2=depth
/// PostgreSQL: SELECT get_object_json(id, $2)::text FROM unnest($1::bigint[]) AS id
/// MSSQL: Cursor or table-valued function
///
string ObjectStorage_GetObjectsJsonBulk();
///
/// SELECT structure metadata by scheme ID. Params: $1=schemeId
/// Returns: Id, IdParent, Name, DbType, CollectionType, KeyType, StoreNull, Lazy, TypeSemantic
///
string ObjectStorage_SelectStructuresWithMetadata();
///
/// SELECT type info by ID. Params: $1=typeId
/// Returns: Id, Name, DbType, Type1
///
string ObjectStorage_SelectTypeById();
///
/// Check if object exists by ID. Params: $1=objectId
/// Returns: _id or NULL
///
string ObjectStorage_CheckObjectExists();
///
/// SELECT scheme by ID. Params: $1=schemeId
/// Returns: Id, Name
///
string ObjectStorage_SelectSchemeById();
///
/// SELECT all values for object IDs (ChangeTracking). Params: $1=objectIds (array)
/// Returns: Id, IdStructure, IdObject, String, Long, Guid, Double, DateTimeOffset, Boolean, ByteArray, Numeric, ListItem, Object, ArrayParentId, ArrayIndex
///
string ObjectStorage_SelectValuesForObjects();
///
/// SELECT scheme IDs for objects. Params: $1=objectIds (array)
/// Returns: ObjectId, SchemeId
///
string ObjectStorage_SelectSchemeIdsForObjects();
///
/// SELECT single value by ID. Params: $1=valueId
/// Returns: all value fields
///
string ObjectStorage_SelectValueById();
///
/// SELECT all types (for cache preload). No params.
/// Returns: Id, Name, DbType, Type1
///
string ObjectStorage_SelectAllTypes();
///
/// SELECT existing object IDs from array. Params: $1=objectIds (array)
/// Returns: Id only
///
string ObjectStorage_SelectExistingIds();
///
/// SELECT id + stored creation date of existing objects, then one row per listed scheme.
/// Params: $1=objectIds (array), $2=schemeIds (array).
/// Returns: Id, DateCreate, SchemeHash, SchemeId. An object row carries its scheme's structure hash; a scheme row
/// has Id 0 and DateCreate NULL, so a save of new objects only still learns the hash of every scheme it writes.
/// The save strategies take the existing ids from it and hand the stored creation date back to the saved object:
/// an update never rewrites _date_create.
///
string ObjectStorage_SelectExistingCreateDates();
///
/// SELECT id + persisted content hash of existing objects. Params: $1=objectIds (array).
/// Returns: Id, Hash. F1 (CT hash shortcut): an existing object whose recomputed hash
/// equals the persisted one skips the value pipeline under ChangeTracking.
///
string ObjectStorage_SelectIdHashPairs();
///
/// SELECT schemes by IDs. Params: $1=schemeIds (array)
/// Returns: Id, Name, Alias, NameSpace, StructureHash, Type
///
string ObjectStorage_SelectSchemesByIds();
///
/// Lock objects for update (row locking) and RETURN THE LOCKED IDS. Params: $1=objectIds (array)
/// Contract (BR-9, 2026-09-02): SELECT _id (not SELECT 1) - the returned rows are the ids that
/// exist and are now locked; the caller counts them, a missing id is simply not in the result.
/// Rows are taken in ascending _id order so concurrent lockers cannot deadlock on each other.
/// PostgreSQL: SELECT _id ... FOR UPDATE. MSSQL: WITH (UPDLOCK, ROWLOCK). SQLite: existence
/// check only - writers are serialized database-wide, there is no row lock to take.
///
string ObjectStorage_LockObjectsForUpdate();
///
/// SELECT scheme ID for object. Params: $1=objectId
/// Returns: _id_scheme (long)
///
string ObjectStorage_SelectSchemeIdByObjectId();
// ============================================================
// === LIST SQL ===
// ============================================================
///
/// SELECT list by ID. Params: $1=listId
///
string Lists_SelectById();
///
/// SELECT list by name. Params: $1=name
///
string Lists_SelectByName();
///
/// SELECT all lists ordered by name.
///
string Lists_SelectAll();
///
/// INSERT new list. Params: $1=id, $2=name, $3=alias
///
string Lists_Insert();
///
/// UPDATE list. Params: $1=name, $2=alias, $3=id
///
string Lists_Update();
///
/// DELETE list by ID. Params: $1=listId
///
string Lists_Delete();
///
/// Check if list is used in structures. Params: $1=listId
///
string Lists_IsUsedInStructures();
// ============================================================
// === LIST ITEMS SQL ===
// ============================================================
///
/// SELECT list item by ID. Params: $1=itemId
///
string ListItems_SelectById();
///
/// SELECT list items by their ids. Params: $1=itemIds (long[])
///
string ListItems_SelectByIds();
///
/// SELECT list items by list ID. Params: $1=listId
///
string ListItems_SelectByListId();
///
/// SELECT list item by list ID and value. Params: $1=listId, $2=value
///
string ListItems_SelectByListIdAndValue();
///
/// INSERT list item. Params: $1=id, $2=idList, $3=value, $4=alias, $5=idObject
///
string ListItems_Insert();
///
/// UPDATE list item alias and idObject. Params: $1=alias, $2=idObject, $3=id
///
string ListItems_UpdateAliasAndObject();
///
/// UPDATE list item. Params: $1=value, $2=alias, $3=idObject, $4=id
///
string ListItems_Update();
///
/// DELETE list item by ID. Params: $1=itemId
///
string ListItems_Delete();
///
/// SELECT list items by object reference. Params: $1=objectId
///
string ListItems_SelectByObjectId();
// ============================================================
// === MAINTENANCE SQL ===
// ============================================================
// All provider variability of IMaintenanceProvider lives in these three texts; the base
// provider holds the only logic and the only mapping. Index-stats SQL must normalize the
// engine's catalogs to EXACTLY these column aliases: Table, Name, IsUnique, SizeBytes,
// EstimatedRows, Seeks, Scans, Updates, LastUsed - NULL where the engine cannot say.
///
/// Refresh planner statistics. bounds SQLite's ANALYZE
/// (PRAGMA analysis_limit; 0 = unbounded); PostgreSQL and MSSQL ignore it.
///
string Maintenance_Analyze(int analysisLimit);
///
/// Refresh planner statistics of ONE table. The identifier arrives already checked against
/// the catalogs by the base provider, and the dialect quotes it itself: an identifier cannot
/// be a query parameter, and this one comes from a dashboard.
///
string Maintenance_AnalyzeTable(string? schema, string table, int analysisLimit);
/// Does the table exist? Params: table name, then schema (null = the engine's default).
string Maintenance_SelectTableExists();
/// Index statistics of user tables, normalized to the alias contract above.
string Maintenance_SelectIndexStats();
///
/// Table statistics, normalized to the TableStatistics alias contract: Schema, Table,
/// EstimatedRows, DataSizeBytes, IndexesSizeBytes, DeadRows, LastAnalyze, LastAutoAnalyze,
/// LastVacuum, HasStatistics.
///
string Maintenance_SelectTableStats();
///
/// The table-stats forms in decreasing capability, tried in order until one runs. SQLite needs
/// three: the optional dbstat module may be missing, and sqlite_stat1 does not
/// exist at all until the first ANALYZE - the state every fresh database starts in, where a
/// storage page must report "no statistics" rather than fail (redb.Tsak BR-13, 2026-09-21).
/// Engines that can always answer return a single text.
///
System.Collections.Generic.IReadOnlyList Maintenance_SelectTableStatsForms();
///
/// The window the usage counters cover: aliases CountersSince and IsReplica, both null where
/// the engine keeps no counters.
///
string Maintenance_SelectStatisticsWindow();
///
/// Fallback form for engines where the full form may be unavailable: SQLite without the dbstat
/// virtual table (no sizes), SQL Server without VIEW SERVER STATE (no usage counters). Engines
/// with no such failure mode return the same text as ,
/// and the base provider then never falls back.
///
string Maintenance_SelectIndexStatsNoSize();
///
/// The index check (CheckBaseIndexesAsync): every index of the tables of the redb schema, cheaply, one row each with
/// the columns Name, Table, IsUnique, KeyColumnsCsv (key columns in index order),
/// IncludedColumnsCsv and IsValid (false only for a PostgreSQL index left INVALID). No sizes and no
/// counters: it runs at every start. Null where the provider does not check its indexes.
///
string? Schema_SelectIndexShapes() => null;
///
/// The repair's look before it builds a unique index of _values keyed on the place of a value
/// (RepairBaseIndexesAsync): the groups of rows the index would refuse, at most 100, one row each with the columns
/// ObjectId, StructureId and Rows. are the key columns of the
/// index, its filter in this provider's own text, null for none. Null where the provider
/// does not look.
///
string? Schema_SelectValueIndexDuplicates(IReadOnlyList keyColumns, string? predicate) => null;
// ============================================================
// === VALIDATION SQL ===
// ============================================================
///
/// SELECT all types for validation.
///
string Validation_SelectAllTypes();
///
/// SELECT scheme by name. Params: $1=schemeName
///
string Validation_SelectSchemeByName();
///
/// SELECT structures by scheme ID. Params: $1=schemeId
///
string Validation_SelectStructuresBySchemeId();
// ============================================================
// === LAZY LOADER SQL ===
// ============================================================
///
/// Get object base fields (without Props). Params: $1=objectId
///
string LazyLoader_SelectObjectBase();
///
/// Get object as JSON via get_object_json. Params: $1=objectId, $2=maxDepth
///
string LazyLoader_GetObjectJson();
///
/// Get multiple objects as JSON via get_object_json batch. Params: $1=objectIds array, $2=depth
/// (V4: a stub reload passes 1, query pages their PropsDepth, otherwise 10).
/// Returns: (Id, JsonData) tuples
///
string LazyLoader_GetObjectJsonBatch();
///
/// Get object hash for cache validation. Params: $1=objectId
///
string LazyLoader_SelectObjectHash();
///
/// Savepoint trio for a save running inside the CALLER's transaction (bug report п.2,
/// 2026-09-02): a unique violation must not leave that transaction aborted (PostgreSQL 25P02),
/// so the batch runs under a savepoint and rolls back TO it before the typed exception leaves.
/// Release is null where the engine has nothing to release (MSSQL savepoints dissolve on their
/// own). MSSQL note: SAVE TRANSACTION does not work in a distributed transaction.
///
string Transaction_SavepointBegin();
/// RELEASE of the savepoint above; null when the engine needs none.
string? Transaction_SavepointRelease();
/// ROLLBACK TO the savepoint above - the caller's transaction stays alive.
string Transaction_SavepointRollback();
// ============================================================
// === QUERY PROVIDER SQL ===
// ============================================================
///
/// SQL for checking user permission on object.
///
string Query_CheckPermissionSql();
///
/// SQL for SQL preview function.
///
string Query_SqlPreviewTemplate();
///
/// SQL for getting parent IDs from descendant IDs using recursive CTE.
/// PostgreSQL: WITH RECURSIVE ancestors AS (...)
/// MSSQL: WITH ancestors AS (...)
///
string Query_GetParentIdsFromDescendantsSql(string idsString, int depthLimit);
///
/// SQL for the ids of the descendants of the given objects, down to levels below them
/// (1 = their children); the objects themselves are not among them. WhereHasAncestor uses it with its maxDepth.
///
string Query_GetDescendantIdsFromAncestorsSql(string idsString, int depthLimit);
///
/// SQL for loading objects by IDs as JSON.
/// PostgreSQL: SELECT get_object_json(id, 10)::text FROM unnest(ARRAY[...])
/// MSSQL: SELECT dbo.get_object_json(_id, 10) FROM _objects WHERE _id IN (...)
///
string Query_LoadObjectsByIdsSql(string idsString, int maxDepth);
///
/// SQL for tree SQL preview.
///
string Query_TreeSqlPreviewTemplate(string functionName);
// ============================================================
// === SQL PREVIEW FUNCTION NAMES ===
// ============================================================
///
/// SQL preview function name for regular search.
/// PostgreSQL: "get_search_sql_preview"
/// MSSQL: "dbo.get_search_sql_preview"
///
string Query_SqlPreviewFunction();
///
/// SQL preview function name for tree base (lazy loading) search.
/// PostgreSQL: "get_search_tree_sql_preview_base"
/// MSSQL: "dbo.get_search_tree_sql_preview_base"
///
string Query_TreeSqlPreviewBaseFunction();
// ============================================================
// === v2-pvt MODULE (free Postgres only, phase 1) ===
// ------------------------------------------------------------
// Two-step search pipeline:
// 1. BUILD: ask the database to generate an _id-list SQL via
// pvt_build_query_sql(...) — returned as plain text.
// 2. EXECUTE: the client (C#/Python/Go) wraps that text with
// a materializer (get_object_json), COUNT(*), EXISTS(...) or
// a projection JOIN and executes the wrapped SQL.
//
// Dialects that don't support v2-pvt MUST return null from all
// methods in this block. A null return is the explicit "no PVT"
// signal — there is no fallback flag, no try/catch on the hot
// path. The dispatch happens once per query call.
// ============================================================
///
/// Bare SQL function name returning the inner _id-list SQL string.
/// PostgreSQL: "pvt_build_query_sql". Return null when the dialect
/// has no v2-pvt module deployed (e.g. MSSql phase 1).
///
string? Query_BuildPvtSqlFunction();
///
/// Builds the full SELECT statement that invokes pvt_build_query_sql.
/// Scalar arguments are inlined safely (no user-controlled strings);
/// only the three jsonb arguments are exposed as binding placeholders:
/// $1 = filter (jsonb)
/// $2 = order (jsonb)
/// $3 = distinct_on (jsonb) — array of {field|$expr} entries; NULL when absent.
/// All may be NULL — the caller should pass DBNull when absent.
/// Returns null when v2-pvt is not supported.
///
string? Query_BuildPvtSqlInvocation(
long schemeId,
int? limit,
int offset,
int maxDepth,
bool distinct,
string sourceMode,
long[]? treeIds,
bool hasDistinctOn = false);
///
/// Wraps the inner _id-list SQL so that it returns the _objects row of every id, in the order of the
/// inner list, with the columns of . Props are not read here: the
/// query provider loads them once, through the lazy loader and the Props cache. Returns null when v2-pvt is not
/// supported.
///
string? Query_WrapPvtWithObjectRows(string innerSql);
///
/// Wraps the inner _id-list SQL with COUNT(*).
/// Returns null when v2-pvt is not supported.
///
string? Query_WrapPvtWithCount(string innerSql);
///
/// Wraps the inner _id-list SQL with EXISTS(...).
/// Returns null when v2-pvt is not supported.
///
string? Query_WrapPvtWithExists(string innerSql);
///
/// Wraps the inner _id-list SQL so that it returns the ids alone, one column, in no particular order: a query delete
/// reads them before it deletes them through .
/// Returns null when v2-pvt is not supported.
///
string? Query_WrapPvtWithIds(string innerSql);
///
/// Bare SQL function name returning the deployed v2-pvt module
/// semver string (e.g. "0.1.0"). Used by RedbServiceBase.InitializeAsync
/// to enforce major-match + minor-compatibility. Returns null when
/// the dialect does not require a v2-pvt deployment check.
///
string? Query_PvtModuleVersionFunction();
///
/// Semver string the shipped v2-pvt bundle for this dialect declares.
/// Compared against the value returned by
/// at startup: an older or
/// missing module is replaced by 's embedded
/// bundle, a newer one is never replaced (see
/// ). Bump this string whenever
/// any *.sql file under the dialect's v2-pvt folder changes (together with
/// the `pvt_module_version()` literal inside `99_module_version.sql`).
/// Returns null for dialects that do not ship a v2-pvt module.
///
string? Query_PvtRequiredVersion();
///
/// Bare SQL function name returning what a deployed module still serves: '<oldest package module version>|<redb
/// package version that first shipped it>', e.g. '0.7.24|4.8.0'. A package whose module is older than the deployed
/// one leaves the module in place and starts when its own version is not below the first part; otherwise it stops
/// with . Returns null when the dialect has no such function.
///
string? Query_PvtModuleCompatFunction();
// ------------------------------------------------------------
// Native PVT projection orchestrator (pvt_build_projection_sql).
// Drives the .Select(...)/Distinct() shape directly in SQL: the
// outer SELECT yields the requested scalar columns (one per
// projection entry) instead of materializing full objects.
//
// Dialects that have no v2-pvt projection support MUST throw
// NotSupportedException from these methods. The caller dispatches
// via Query_BuildPvtProjectionSqlFunction() returning non-null.
// ------------------------------------------------------------
///
/// Bare SQL function name returning the projection SELECT string.
/// PostgreSQL: "pvt_build_projection_sql". Return null when the
/// dialect has no native PVT projection (projection then falls
/// back to the standard PVT full-object path or to legacy SQL).
///
string? Query_BuildPvtProjectionSqlFunction();
///
/// Builds the full SELECT statement that invokes
/// pvt_build_projection_sql. Scalar arguments are inlined safely;
/// jsonb arguments are exposed as bound placeholders:
/// $1 = projection (jsonb) — non-empty array, required
/// $2 = filter (jsonb) — nullable
/// $3 = order (jsonb) — nullable
/// $4 = distinct_on (jsonb) — nullable; required when hasDistinctOn
/// Returns null when native PVT projection is not supported.
///
string? Query_BuildPvtProjectionSqlInvocation(
long schemeId,
int? limit,
int offset,
int maxDepth,
bool distinct,
string sourceMode,
long[]? treeIds,
bool hasDistinctOn = false);
///
/// Wraps the projection inner SQL into a result-set of JSON rows
/// shaped as {"id": <_id>, "properties": { ...projected columns... }}.
/// The inner SQL MUST contain an _id column (the caller adds
/// it explicitly to the projection JSON unless DISTINCT collapses it).
/// When is false the wrapper synthesizes
/// id=0 and treats every inner column as a projected property.
/// Returns null when native PVT projection is not supported.
///
string? Query_WrapPvtProjectionRowsAsJson(string innerSql, bool includeId);
// =====================================================
// SOFT DELETE METHODS
// =====================================================
///
/// SQL to mark objects for soft-deletion.
/// Creates trash container and moves objects under it.
/// Params: $1=objectIds (array/comma-separated), $2=userId, $3=trashParentId (nullable)
/// Returns: trash_id, marked_count
/// PostgreSQL: SELECT * FROM mark_for_deletion($1, $2, $3)
/// MSSQL: EXEC sp_mark_for_deletion @p0, @p1, @p2 (with OUTPUT params)
///
string SoftDelete_MarkForDeletion();
///
/// SQL to purge (physically delete) objects from trash container.
/// Deletes in batches, removes trash container when empty.
/// Params: $1=trashId, $2=batchSize
/// Returns: deleted_count, remaining_count
/// PostgreSQL: SELECT * FROM purge_trash($1, $2)
/// MSSQL: EXEC sp_purge_trash @p0, @p1 (with OUTPUT params)
///
string SoftDelete_PurgeTrash();
///
/// SQL that removes a trash container once it holds no objects, for a dialect whose
/// cannot do it itself - SQLite, where the result row must be
/// the last statement of the batch and there is no variable to keep it in. Null when the purge
/// statement removes the container (PostgreSQL, MSSQL). Runs after the last batch.
/// Params: $1=trashId
///
string? SoftDelete_DeleteCompletedTrashContainer() => null;
///
/// SQL query listing the objects of a trash container that live objects (scheme other than -10)
/// still reference through a _values._Object row, paired with the referencing objects.
/// Used to report a purge that ended 'failed'.
/// Params: $1=trashId
/// Returns: referenced_id, referencing_id (at most 100 pairs, ordered)
///
string SoftDelete_SelectLiveReferrersOfTrash();
///
/// SQL query to get deletion progress for a specific trash container.
/// Reads progress from trash object fields: _value_long=total, _key=deleted, _value_string=status.
/// Params: $1=trashId
/// Returns: trash_id, total, deleted, status, started_at, owner_id
///
string SoftDelete_GetDeletionProgress();
///
/// SQL query to get all active deletions for a user.
/// Returns trash containers with status='pending' or 'running' owned by user.
/// Params: $1=userId
/// Returns: trash_id, total, deleted, status, started_at, owner_id
///
string SoftDelete_GetUserActiveDeletions();
///
/// SQL query to get orphaned deletion tasks (for recovery at startup).
/// Returns 'pending' tasks OR 'running' tasks where _date_modify older than timeout.
/// CLUSTER-SAFE: Only returns tasks that are likely abandoned.
/// Params: $1=timeoutMinutes (int)
/// Returns: trash_id, total, deleted, status, owner_id
///
string SoftDelete_GetOrphanedTasks();
///
/// SQL to atomically claim an orphaned task (prevent race condition in cluster).
/// Updates status to 'running' and _date_modify to NOW() only if conditions still match.
/// CLUSTER-SAFE: Uses atomic UPDATE with condition check.
/// Params: $1=trashId, $2=timeoutMinutes
/// Returns: claimed (1 = success, 0 = task already taken by another instance)
///
string SoftDelete_ClaimOrphanedTask();
// ============================================================
// === METADATA CACHE WARMUP ===
// ============================================================
///
/// SQL to warmup all metadata caches.
/// PostgreSQL: SELECT scheme_id, structures_count, scheme_name FROM warmup_all_metadata_caches()
/// MSSQL: EXEC warmup_all_metadata_caches (returns same columns)
/// Returns: scheme_id, structures_count, scheme_name
///
string Warmup_AllMetadataCaches();
}