Bundle: redb / redb.SQLite (redb.SQLite.txt), 72 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb/_index.txt ==== Path: redb/redb.SQLite/Data/SqliteBulkOperations.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/Data/SqliteBulkOperations.cs ---- using redb.Core.Data; using redb.Core.Models.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace redb.SQLite.Data { /// /// SQLite implementation of IBulkOperations. /// SQLite has no COPY/binary-import protocol — the fast path is a single /// transaction wrapping chunked multi-row INSERTs (one prepared statement /// per chunk). The big win versus N individual statements is the single /// transaction (one fsync instead of one per row). Parameter count per /// statement is chunked under SQLite's limit. /// public class SqliteBulkOperations : IBulkOperations { private readonly IRedbConnection _db; // Conservative cap on bound parameters per statement (SQLite default // SQLITE_MAX_VARIABLE_NUMBER is 999 on older builds, 32766 on 3.32+). private const int MaxParamsPerStatement = 900; public SqliteBulkOperations(IRedbConnection db) { _db = db ?? throw new ArgumentNullException(nameof(db)); } // ===== INSERTS ===== private static readonly string[] ObjectColumns = { "_id", "_id_parent", "_id_scheme", "_name", "_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", "_hash", "_value_unique" }; private static object?[] ObjectRowValues(RedbObjectRow o) => new object?[] { o.Id, o.IdParent, o.IdScheme, o.Name, o.IdOwner, o.IdWhoChange, o.DateCreate, o.DateModify, o.DateBegin, o.DateComplete, o.Key, o.ValueLong, o.ValueString, o.ValueGuid, o.ValueBool, o.ValueDouble, o.ValueNumeric, o.ValueDatetime, o.ValueBytes, o.Note, o.Hash, o.ValueUnique }; private static readonly string[] ValueColumns = { "_id", "_id_structure", "_id_object", "_String", "_Long", "_Guid", "_Double", "_DateTimeOffset", "_Boolean", "_ByteArray", "_Numeric", "_ListItem", "_Object", "_unique", "_array_parent_id", "_array_index" }; private static object?[] ValueRowValues(RedbValue v) => new object?[] { v.Id, v.IdStructure, v.IdObject, v.String, v.Long, v.Guid, v.Double, v.DateTimeOffset, v.Boolean, v.ByteArray, v.Numeric, v.ListItem, v.Object, v.Unique, v.ArrayParentId, v.ArrayIndex }; public async Task BulkInsertObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var rows = objects.Select(ObjectRowValues).ToList(); await BulkInsertAsync("_objects", ObjectColumns, rows, cancellationToken); } public async Task BulkInsertValuesAsync(IEnumerable values, CancellationToken cancellationToken = default) { var rows = values.Select(ValueRowValues).ToList(); await BulkInsertAsync("_values", ValueColumns, rows, cancellationToken); } /// /// Insert into using chunked /// multi-row INSERTs inside one transaction. /// private async Task BulkInsertAsync(string table, string[] columns, List rows, CancellationToken cancellationToken) { if (rows.Count == 0) return; int colCount = columns.Length; int rowsPerChunk = Math.Max(1, MaxParamsPerStatement / colCount); string columnList = string.Join(", ", columns); await _db.ExecuteAtomicAsync(async () => { foreach (var chunk in Chunk(rows, rowsPerChunk)) { var sb = new StringBuilder(); sb.Append("INSERT INTO ").Append(table).Append(" (").Append(columnList).Append(") VALUES "); var parameters = new List(chunk.Count * colCount); int p = 0; for (int r = 0; r < chunk.Count; r++) { if (r > 0) sb.Append(", "); sb.Append('('); for (int c = 0; c < colCount; c++) { if (c > 0) sb.Append(", "); // _hash is BLOB(16) written from the uuid TEXT parameter (SqliteHash). var placeholder = "$" + (++p); sb.Append(columns[c] is "_hash" or "_unique" ? SqliteHash.FromText(placeholder) : placeholder); parameters.Add(chunk[r][c]); } sb.Append(')'); } cancellationToken.ThrowIfCancellationRequested(); await _db.ExecuteAsync(sb.ToString(), parameters.ToArray()!, cancellationToken); } }); } // ===== UPDATES (per-row inside one transaction — simple and reliable) ===== public async Task BulkUpdateObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var list = objects.ToList(); if (list.Count == 0) return; // All columns except _id and _date_create (creation time is immutable). const string setSql = "_id_parent=$1, _id_scheme=$2, _name=$3, _id_owner=$4, _id_who_change=$5, " + "_date_modify=$6, _date_begin=$7, _date_complete=$8, _key=$9, _value_long=$10, " + "_value_string=$11, _value_guid=$12, _value_bool=$13, _value_double=$14, " + "_value_numeric=$15, _value_datetime=$16, _value_bytes=$17, _note=$18, _hash=unhex(replace($19,'-','')), _value_unique=$20"; const string sql = "UPDATE _objects SET " + setSql + " WHERE _id=$21"; await _db.ExecuteAtomicAsync(async () => { foreach (var o in list) { await _db.ExecuteAsync(sql, new object[] { o.IdParent, o.IdScheme, o.Name!, o.IdOwner, o.IdWhoChange, o.DateModify, o.DateBegin!, o.DateComplete!, o.Key!, o.ValueLong!, o.ValueString!, o.ValueGuid!, o.ValueBool!, o.ValueDouble!, o.ValueNumeric!, o.ValueDatetime!, o.ValueBytes!, o.Note!, o.Hash!, o.ValueUnique!, o.Id }, cancellationToken); } }); } public async Task BulkUpdateValuesAsync(IEnumerable values, CancellationToken cancellationToken = default) { var list = values.ToList(); if (list.Count == 0) return; // F6 (perf wave 6): chunked UPDATE ... FROM (VALUES ...) instead of one statement per // row (each row was its own command through P/Invoke). SQLite names bare VALUES // columns column1..columnN; _unique keeps its uuid-text -> BLOB(16) conversion, same // as the old per-row form did with unhex(replace($11,'-','')). const int colCount = 14; // 13 data columns + _id int rowsPerChunk = Math.Max(1, MaxParamsPerStatement / colCount); const string head = "UPDATE _values SET " + "_String=u.column1, _Long=u.column2, _Guid=u.column3, _Double=u.column4, " + "_DateTimeOffset=u.column5, _Boolean=u.column6, _ByteArray=u.column7, " + "_Numeric=u.column8, _ListItem=u.column9, _Object=u.column10, " + "_unique=unhex(replace(u.column11,'-','')), _array_parent_id=u.column12, _array_index=u.column13 " + "FROM (VALUES "; const string tail = ") AS u WHERE _values._id = u.column14"; await _db.ExecuteAtomicAsync(async () => { foreach (var chunk in Chunk(list, rowsPerChunk)) { var sb = new StringBuilder(head); var parameters = new List(chunk.Count * colCount); int p = 0; for (int r = 0; r < chunk.Count; r++) { var v = chunk[r]; if (r > 0) sb.Append(", "); sb.Append('('); for (int c = 0; c < colCount; c++) { if (c > 0) sb.Append(", "); sb.Append('$').Append(++p); } sb.Append(')'); parameters.AddRange(new object?[] { v.String, v.Long, v.Guid, v.Double, v.DateTimeOffset, v.Boolean, v.ByteArray, v.Numeric, v.ListItem, v.Object, v.Unique, v.ArrayParentId, v.ArrayIndex, v.Id }); } sb.Append(tail); cancellationToken.ThrowIfCancellationRequested(); await _db.ExecuteAsync(sb.ToString(), parameters.ToArray()!, cancellationToken); } }); } // ===== DELETES (chunked IN(...) — no PG ANY(array)) ===== public Task BulkDeleteObjectsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) => DeleteByIdsAsync("DELETE FROM _objects WHERE _id IN ", objectIds, cancellationToken); public Task BulkDeleteValuesAsync(IEnumerable valueIds, CancellationToken cancellationToken = default) => DeleteByIdsAsync("DELETE FROM _values WHERE _id IN ", valueIds, cancellationToken); public Task BulkDeleteValuesByObjectIdsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) => DeleteByIdsAsync("DELETE FROM _values WHERE _id_object IN ", objectIds, cancellationToken); public Task BulkDeleteValuesByListItemIdsAsync(IEnumerable listItemIds, CancellationToken cancellationToken = default) => DeleteByIdsAsync("DELETE FROM _values WHERE _ListItem IN ", listItemIds, cancellationToken); private async Task DeleteByIdsAsync(string head, IEnumerable ids, CancellationToken cancellationToken) { var idList = ids.ToList(); if (idList.Count == 0) return; await _db.ExecuteAtomicAsync(async () => { foreach (var chunk in Chunk(idList, MaxParamsPerStatement)) { var sb = new StringBuilder(head).Append('('); var parameters = new object?[chunk.Count]; for (int i = 0; i < chunk.Count; i++) { if (i > 0) sb.Append(", "); sb.Append('$').Append(i + 1); parameters[i] = chunk[i]; } sb.Append(')'); await _db.ExecuteAsync(sb.ToString(), parameters!); } }); } // ===== helpers ===== private static IEnumerable> Chunk(IReadOnlyList source, int size) { for (int i = 0; i < source.Count; i += size) { int n = Math.Min(size, source.Count - i); var bucket = new List(n); for (int j = 0; j < n; j++) bucket.Add(source[i + j]); yield return bucket; } } } } Path: redb/redb.SQLite/Data/SqliteCaseFolding.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/Data/SqliteCaseFolding.cs ---- using System; using System.Globalization; using Microsoft.Data.Sqlite; namespace redb.SQLite.Data { /// /// Replaces SQLite's built-in like, lower and upper with Unicode-aware /// implementations, on one connection. /// /// /// Why this is a connection concern and not a SQL one. On PostgreSQL the fix is a /// COLLATE clause in the generated SQL. SQLite has no equivalent to attach: its only /// case-insensitive collation, NOCASE, folds ASCII and nothing else, and LIKE is /// implemented as a function, so collations never reach it. Measured on the build redb ships /// with (3.46.1, no ICU compiled in): 'Привет' LIKE '%привет%' is 0, /// lower('Привет') returns the string unchanged, and 'Привет' = 'привет' COLLATE /// NOCASE is 0. Unlike PostgreSQL, where this depends on how the database was created, in /// SQLite it is unconditional. /// /// /// /// Overriding a built-in is the supported mechanism, and it is exactly what SQLite's own ICU /// extension does. Doing it from managed code keeps the whole fix inside the provider: no ICU /// build, no change to the native extension, no per-platform rebuild. /// /// /// /// Cost. A managed callback runs per row instead of the C implementation. That matters /// less than it sounds for the case this exists to serve: LIKE '%x%' cannot use an index /// in SQLite anyway, so both versions scan, and the difference is call overhead rather than /// algorithmic. It is opt-in regardless. /// /// internal static class SqliteCaseFolding { /// /// Installs the overrides when ; otherwise does nothing at all, so /// a connection is byte-for-byte what it was before this type existed. /// internal static void Install(SqliteConnection connection, bool enabled) { if (!enabled) return; // ToLowerInvariant rather than ToUpperInvariant on purpose. Upper-casing is the // length-changing direction in several languages (German ß becomes SS), which would make // lower(upper(x)) disagree with x and make the folded comparison disagree with itself. // Lower-casing is length-preserving for every mapping we care about here. connection.CreateFunction( "lower", s => s?.ToLowerInvariant(), isDeterministic: true); connection.CreateFunction( "upper", s => s?.ToUpperInvariant(), isDeterministic: true); // Both arities. SQLite exposes LIKE as like(pattern, value) and, for the // "LIKE ... ESCAPE c" form, like(pattern, value, escape). Registering only the first // would leave every ESCAPE query silently on the ASCII-only built-in — and redb emits // ESCAPE on its user-search path, so that is not a hypothetical. connection.CreateFunction( "like", (pattern, value) => Like(pattern, value, null), isDeterministic: true); connection.CreateFunction( "like", (pattern, value, escape) => Like(pattern, value, escape), isDeterministic: true); } /// /// SQLite's LIKE semantics, folded for all scripts: % matches any sequence including /// empty, _ matches exactly one character, and a character preceded by the escape /// character is literal. NULL in, NULL out, matching the built-in. /// private static long? Like(string? pattern, string? value, string? escape) { if (pattern is null || value is null) return null; char? esc = null; if (!string.IsNullOrEmpty(escape)) { // SQLite raises "ESCAPE expression must be a single character"; mirror that rather // than silently matching nothing. if (escape!.Length != 1) throw new ArgumentException("ESCAPE expression must be a single character.", nameof(escape)); esc = char.ToLowerInvariant(escape[0]); } // Fold once, then match on the folded forms. Case folding a pattern is safe: '%' and '_' // have no case, and the escape character is folded with it so the two stay in step. return IsMatch(pattern.ToLowerInvariant(), value.ToLowerInvariant(), esc) ? 1L : 0L; } /// /// Iterative wildcard match with backtracking. Iterative rather than recursive so a /// pathological pattern cannot exhaust the stack, and hand-written rather than translated to /// a regular expression so a user-supplied pattern cannot become a catastrophic-backtracking /// weapon. /// private static bool IsMatch(string pattern, string value, char? escape) { int p = 0, v = 0; int starP = -1, starV = 0; while (v < value.Length) { if (p < pattern.Length) { var pc = pattern[p]; if (escape.HasValue && pc == escape.Value) { // A pattern that ends with the escape character matches nothing at all, // which is what SQLite's own like() does. Verified against the built-in // rather than assumed. if (p + 1 >= pattern.Length) return false; // Escaped: the next pattern character is literal, wildcards included. var escLen = RuneLength(pattern, p + 1); var valLen = RuneLength(value, v); if (escLen == valLen && string.CompareOrdinal(pattern, p + 1, value, v, escLen) == 0) { p += 1 + escLen; v += valLen; continue; } } else if (pc == '%') { // Remember where the wildcard was so we can extend it on a later mismatch. starP = p; starV = v; p++; continue; } else if (pc == '_') { // Exactly one CHARACTER, and in SQLite a character is a code point, not a // UTF-16 code unit. Counting units would make '_' fail to match an emoji // or any other astral character, where the built-in matches it. v += RuneLength(value, v); p++; continue; } else { var patLen = RuneLength(pattern, p); var valLen = RuneLength(value, v); if (patLen == valLen && string.CompareOrdinal(pattern, p, value, v, patLen) == 0) { p += patLen; v += valLen; continue; } } } if (starP >= 0) { // Let the last '%' swallow one more code point and retry from just after it. starV += RuneLength(value, starV); p = starP + 1; v = starV; continue; } return false; } // Trailing '%' are allowed to match nothing; anything else left over is a mismatch. while (p < pattern.Length && pattern[p] == '%') p++; // ... including a lone trailing escape character, per the built-in. if (escape.HasValue && p == pattern.Length - 1 && pattern[p] == escape.Value) return false; return p == pattern.Length; } /// /// Length in UTF-16 units of the code point starting at : 2 for a /// well-formed surrogate pair, 1 otherwise. A lone surrogate counts as 1, so malformed /// input degrades instead of throwing. /// private static int RuneLength(string s, int i) => char.IsHighSurrogate(s[i]) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1]) ? 2 : 1; } } Path: redb/redb.SQLite/Data/SqliteDataSource.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/Data/SqliteDataSource.cs ---- using System; using System.IO; using System.Threading.Tasks; using Microsoft.Data.Sqlite; namespace redb.SQLite.Data { /// /// Lightweight stand-in for Npgsql's NpgsqlDataSource concept. /// Microsoft.Data.Sqlite has no DataSource type — it pools connections /// internally, keyed by connection string. This wrapper centralizes /// connection creation and applies the per-connection PRAGMAs that SQLite /// requires on EVERY connection (they are not persistent): /// - foreign_keys=ON (so ON DELETE CASCADE / SET NULL fire) /// - busy_timeout (so a second writer waits instead of failing with /// SQLITE_BUSY — SQLite is single-writer) /// public sealed class SqliteDataSource : IDisposable { private const int BusyTimeoutMs = 5000; static SqliteDataSource() { // SQLite stores datetimes as REAL Julian day (UTC). Object reads go through // get_object_json (already ISO), but analytics paths (Min/Max, AggregateRedbAsync, // Window, GroupBy) select the raw column and hand the bare NUMBER to core's // converters. Register the numeric→temporal decoder so core can turn it back into a // DateTime/DateTimeOffset/DateOnly — without core knowing anything about Julian days. // Runs once whenever SQLite is configured (Free and Pro both create a SqliteDataSource); // no-op for PostgreSQL/SQL Server, which never return a number for a temporal column. Core.Query.Utils.TemporalDecoder.NumericDecoder = static (julian, targetType) => { var dto = SqliteJulian.FromJulian(julian); if (targetType == typeof(DateTimeOffset)) return dto; if (targetType == typeof(DateOnly)) return DateOnly.FromDateTime(dto.UtcDateTime); return dto.UtcDateTime; // DateTime }; } /// /// Path to the REDB native loadable extension (redbsqlite.dll/.so/.dylib, WITHOUT /// the file suffix — SQLite appends it). When set, every connection loads it /// after PRAGMAs, so the FREE tier's in-DB functions (get_object_json, /// save_object_json, pvt_build_query_sql, ...) become callable. REQUIRED for /// the Free tier; harmless for Pro (which never calls those functions). /// Defaults to the REDB_SQLITE_EXTENSION env var. Load is per-connection /// (SQLite extensions are not persistent across connections). /// public static string? NativeExtensionPath { get; set; } = Environment.GetEnvironmentVariable("REDB_SQLITE_EXTENSION"); /// /// Size, in bytes, of the part of the database file every connection maps into memory /// (PRAGMA mmap_size). 0, the default, leaves SQLite as it is: pages are read through /// its own page cache, which is 2 MB per connection. On a database of several gigabytes that /// cache is the cost of every query that reads more than a few thousand rows: measured on /// 2.5 GB, the same statements ran 2-4 times faster with the file mapped. A mapping takes /// address space, not memory of its own - the pages live in the file cache of the operating /// system and are shared by all connections. SQLite caps the value at its compile-time limit /// (about 2 GB in the bundled build); what lies beyond the mapped part is read as before. /// public static long MmapSizeBytes { get; set; } /// /// Size, in bytes, of the page cache of every connection (PRAGMA cache_size). 0, the /// default, leaves SQLite's own 2 MB. Unlike this is memory of /// the process and it is per connection: the pool holds as many caches as it holds /// connections. Next to a mapped file a moderate cache is enough - measured on 2.5 GB, /// 64 MB on top of the mapping took another quarter to a third off the same statements, /// and 256 MB added nothing to that. /// public static long CacheSizeBytes { get; set; } /// Connection string this data source opens. public string ConnectionString { get; } private SqliteDataSource(string connectionString) { ConnectionString = connectionString; } /// Create a data source for the given connection string. public static SqliteDataSource Create(string connectionString) => new SqliteDataSource(connectionString); /// /// Create a data source that additionally installs Unicode-aware case folding on every /// connection it opens. See for why this is a connection /// concern in SQLite rather than a SQL one. /// public static SqliteDataSource Create(string connectionString, bool unicodeCaseFolding) => new SqliteDataSource(connectionString) { UnicodeCaseFolding = unicodeCaseFolding }; /// V4 (LAZY Л2): also arms the lazy-references connection flag of the native extension. public static SqliteDataSource Create(string connectionString, bool unicodeCaseFolding, bool lazyReferences) => new SqliteDataSource(connectionString) { UnicodeCaseFolding = unicodeCaseFolding, LazyReferences = lazyReferences }; /// /// When true, every opened connection gets like, lower and upper /// replaced by Unicode-aware implementations. Off by default: generated SQL and stock /// behaviour stay exactly as they were. /// public bool UnicodeCaseFolding { get; private init; } /// V4 (LAZY Л2): arm redb_lazy_refs(1) on every open (the native extension keeps the flag per connection). public bool LazyReferences { get; private init; } // V4 (LAZY Л2): the SQLite counterpart of the PostgreSQL GUC - the extension keeps the // flag in per-connection clientdata; unset means off, so old extensions and the off state // are byte-for-byte the previous behaviour. private void InstallLazyRefs(SqliteConnection conn) { if (!LazyReferences) return; using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT redb_lazy_refs(1)"; cmd.ExecuteNonQuery(); } /// /// Releases the connection pool of this data source's connection string. The pools of /// Microsoft.Data.Sqlite are static, keyed by connection string, and a pooled handle keeps /// the database FILE open (locked, on Windows) - so without this, a container that dies /// (test host teardown, a hot-reloaded module) leaves the file locked until process exit. /// The DI registrations are factories, so the container disposes the data source it /// created. ClearPool touches only this connection string; another live container on the /// same string is unaffected beyond refilling the pool on its next open. /// public void Dispose() { using var probe = new SqliteConnection(ConnectionString); SqliteConnection.ClearPool(probe); } /// Open a new pooled connection with REDB pragmas applied. public SqliteConnection OpenConnection() { var conn = new SqliteConnection(ConnectionString); conn.Open(); LoadNativeExtension(conn); ApplyPragmas(conn); SqliteCaseFolding.Install(conn, UnicodeCaseFolding); SqliteRegexFunctions.Install(conn); EnsureCleanTransactionState(conn); InstallLazyRefs(conn); return conn; } /// Open a new pooled connection with REDB pragmas applied. public async Task OpenConnectionAsync() { var conn = new SqliteConnection(ConnectionString); await conn.OpenAsync(); LoadNativeExtension(conn); await ApplyPragmasAsync(conn); SqliteCaseFolding.Install(conn, UnicodeCaseFolding); SqliteRegexFunctions.Install(conn); await EnsureCleanTransactionStateAsync(conn); InstallLazyRefs(conn); return conn; } /// Load the REDB native extension on this connection (Free tier). No-op /// when NativeExtensionPath is unset; both registrations locate the packaged one (object JSON). private static void LoadNativeExtension(SqliteConnection conn) { var path = NativeExtensionPath; if (string.IsNullOrEmpty(path)) return; conn.EnableExtensions(true); try { // Explicit entry point: the file is redbsqlite. but the C init symbol is // sqlite3_redb_init, so we can't rely on SQLite's basename derivation. conn.LoadExtension(path, "sqlite3_redb_init"); } finally { // Loading is done, so turn the loader back off. Leaving it enabled turned any SQL // injection on this connection into load_extension(), i.e. arbitrary code // (SQLI-PoC: load_extension amplifier). conn.EnableExtensions(false); } } /// /// Locate the REDB native extension shipped inside the NuGet package, relative to /// the running application (). Returns the full /// path (suffix included) or null if not found. /// /// Probes the runtimes/<rid>/native layout, then a flattened copy next to the /// app. Note the package does NOT ship that layout: the binaries live under /// buildTransitive/native/<rid>/ so platform SDKs (notably .NET Android, which /// harvests every runtimes/*/native/*.so into the APK) cannot pick them up. The /// package's .targets reproduces this layout in consumer output instead. Used by the /// Free DI registration to auto-configure without /// an explicit REDB_SQLITE_EXTENSION env var. As a dev fallback it also walks /// up the source tree to the CMake build output, so a ProjectReference run straight /// from the repo (a worker, tests) loads the extension with no manual setup. /// public static string? LocatePackagedExtension() { var lib = OperatingSystem.IsWindows() ? "redbsqlite.dll" : OperatingSystem.IsMacOS() ? "redbsqlite.dylib" : "redbsqlite.so"; var baseDir = AppContext.BaseDirectory; var rid = System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier; // 1. Exact RID path, then flattened next to the app (RID publish / manual copy). foreach (var candidate in new[] { Path.Combine(baseDir, "runtimes", rid, "native", lib), Path.Combine(baseDir, lib), }) { if (File.Exists(candidate)) return candidate; } // 2. RID-agnostic scan: any runtimes//native/ under the app base. var runtimesRoot = Path.Combine(baseDir, "runtimes"); if (Directory.Exists(runtimesRoot)) { foreach (var ridDir in Directory.EnumerateDirectories(runtimesRoot)) { var candidate = Path.Combine(ridDir, "native", lib); if (File.Exists(candidate)) return candidate; } } // 3. Dev fallback: walk up the source tree to the CMake build output // (redb.SQLite/native/build/redbsqlite.). Lets a ProjectReference run // straight from the repo (worker, tests, console) load the extension // without REDB_SQLITE_EXTENSION — mirrors redb.Examples' resolver. for (var dir = new DirectoryInfo(baseDir); dir != null; dir = dir.Parent) { // Public mirror layout first (redb.SQLite at the top level), then the development repository layout (redb.DB/src). var devCandidate = Path.Combine(dir.FullName, "redb.SQLite", "native", "build", lib); if (!File.Exists(devCandidate)) devCandidate = Path.Combine(dir.FullName, "redb.DB", "src", "redb.SQLite", "native", "build", lib); if (File.Exists(devCandidate)) return devCandidate; } return null; } private static void ApplyPragmas(SqliteConnection conn) { using var cmd = conn.CreateCommand(); // journal_mode=WAL → writers don't block readers (concurrent reads // during an open write tx are crucial for redb's check-then-save // patterns and for any visibility-of-uncommitted-writes probe). // synchronous=NORMAL is the WAL-recommended balance; matches what // most production SQLite deployments use under Microsoft.Data.Sqlite. cmd.CommandText = $"PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMs}; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;{MmapPragma()}"; cmd.ExecuteNonQuery(); } private static async Task ApplyPragmasAsync(SqliteConnection conn) { await using var cmd = conn.CreateCommand(); // journal_mode=WAL → writers don't block readers (concurrent reads // during an open write tx are crucial for redb's check-then-save // patterns and for any visibility-of-uncommitted-writes probe). // synchronous=NORMAL is the WAL-recommended balance; matches what // most production SQLite deployments use under Microsoft.Data.Sqlite. cmd.CommandText = $"PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMs}; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;{MmapPragma()}"; await cmd.ExecuteNonQueryAsync(); } // Nothing is added while both sizes are 0, so the statement stays what it was. // A negative cache_size is a size in KiB; a positive one would be a number of pages. private static string MmapPragma() => (MmapSizeBytes > 0 ? $" PRAGMA mmap_size={MmapSizeBytes};" : "") + (CacheSizeBytes > 0 ? $" PRAGMA cache_size=-{Math.Max(1, CacheSizeBytes / 1024)};" : ""); // Defensive pool-poisoning guard. Microsoft.Data.Sqlite's pool returns // SqliteConnection wrappers without inspecting the underlying sqlite3 // handle's autocommit state, so a prior caller that failed to COMMIT or // ROLLBACK (e.g. swallowed rollback in a dispose path) hands us a handle // with autocommit=0 — the next conn.BeginTransaction(...) then fails // with SQLITE_ERROR(1) "cannot start a transaction within a transaction". // A speculative ROLLBACK clears any leaked tx; the "no tx active" error // is the normal/clean case and is silently caught. // // Same idiom as Npgsql's DISCARD ALL / RESET ALL on connection acquire. private static void EnsureCleanTransactionState(SqliteConnection conn) { try { using var cmd = conn.CreateCommand(); cmd.CommandText = "ROLLBACK"; cmd.ExecuteNonQuery(); // Reached only when the pooled connection HAD a leaked tx — log // so the source of the leak surfaces in operator logs. // Console.WriteLine("[Diag-TXLOCK] POOL-CLEANUP: rolled back leaked tx on pooled connection acquire (sync path)."); } catch (SqliteException ex) when (ex.SqliteErrorCode == 1) { // SQLITE_ERROR(1): "cannot rollback - no transaction is active" — clean handle, expected. } } private static async Task EnsureCleanTransactionStateAsync(SqliteConnection conn) { try { await using var cmd = conn.CreateCommand(); cmd.CommandText = "ROLLBACK"; await cmd.ExecuteNonQueryAsync(); // Console.WriteLine("[Diag-TXLOCK] POOL-CLEANUP: rolled back leaked tx on pooled connection acquire (async path)."); } catch (SqliteException ex) when (ex.SqliteErrorCode == 1) { // SQLITE_ERROR(1): "cannot rollback - no transaction is active" — clean handle, expected. } } } } Path: redb/redb.SQLite/Data/SqliteHash.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/Data/SqliteHash.cs ---- using System; namespace redb.SQLite.Data; /// /// The stored form of a 128-bit hash in SQLite — _objects._hash, _schemes._structure_hash, /// _users._hash: BLOB(16) in RFC 4122 byte order, i.e. the bytes of the canonical text /// form read left to right (00112233-4455-6677-8899-aabbccddeeff is 00 11 22 33 44 55 …). /// /// /// One place for the byte order, because several code paths write it and several read it. Writes go /// through the Guid's TEXT parameter and the SQL wrapper — unhex() of the /// text without dashes is by construction the order the text shows; the native extension does the same /// in its own statements. Reads get a byte[] from the driver and use . /// The two must agree, and Guid.ToByteArray() without the big-endian flag does not: it puts the /// first three groups in little-endian order. /// /// /// /// Only hashes. _values._Guid, _objects._value_guid, _users._code_guid are data and /// stay TEXT — they are compared with values users write and read as text. /// /// /// /// A database created before V4 holds the hashes as 36-character TEXT. SQLite keeps the storage class /// a value was written with regardless of the declared type, so no ALTER is needed: the values /// are converted in place on open (ApplySchemaUpgradesAsync), and a reader that meets a TEXT /// value anyway still understands it. /// /// public static class SqliteHash { /// /// SQL that turns a canonical uuid TEXT expression (a $n parameter, a column) into the /// 16-byte BLOB. NULL stays NULL. unhex() needs SQLite 3.41+; the bundled library is newer. /// public static string FromText(string sqlExpression) => $"unhex(replace({sqlExpression},'-',''))"; /// The 16 bytes of in RFC 4122 order. public static byte[] ToBlob(Guid value) { // Guid.ToByteArray() is little-endian in the first three groups; put them back in text order. var b = value.ToByteArray(); return new[] { b[3], b[2], b[1], b[0], b[5], b[4], b[7], b[6], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15], }; } /// The Guid whose canonical text form spells . public static Guid FromBlob(ReadOnlySpan bytes) { if (bytes.Length != 16) throw new FormatException($"A stored hash is 16 bytes, got {bytes.Length}."); return new Guid( (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], (short)((bytes[4] << 8) | bytes[5]), (short)((bytes[6] << 8) | bytes[7]), bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]); } /// /// A Guid from whatever the driver returned for a uuid-valued column: the BLOB of a hash, the /// TEXT of a data guid (or of a hash not yet converted), or a Guid already. /// public static Guid FromDbValue(object value) => value switch { Guid g => g, byte[] b => FromBlob(b), _ => Guid.Parse(value.ToString()!), }; } Path: redb/redb.SQLite/Data/SqliteJulian.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/Data/SqliteJulian.cs ---- using System; namespace redb.SQLite.Data { /// /// SQLite stores REDB datetimes as REAL Julian day numbers in UTC — the native /// SQLite datetime representation. SQLite's own date/time functions /// (datetime(), strftime(), julianday(), date()) consume a /// REAL Julian day directly, and because it is a plain number, range comparisons /// (</>) are numeric, correct, and index-friendly (sargable) — /// unlike the previous TEXT-ISO storage whose lexical comparison broke on format drift. /// /// Offset is normalized to UTC, matching REDB's contract (stored datetimes are UTC /// instants — see ) and how PostgreSQL /// keeps timestamptz in UTC. /// /// The day count is linear in the tick count, truncated to the millisecond - the precision the /// other providers keep and the hash canon assumes. It was computed through the OLE automation /// date (ToOADate), which is not linear: its zero stands for , /// so a default date came back as 1899-12-30, and a day before its epoch is encoded as sign and /// magnitude, so any time of day before 1899-12-30 moved by a day - while the native extension /// writes through SQLite's own julianday(), which is linear. /// internal static class SqliteJulian { // 1899-12-30 00:00 UTC, the same epoch the OLE date used: for every instant from it on the number // is bit for bit what was stored before, so existing rows and equality filters keep matching. private const double EpochJulianDay = 2415018.5; private const long EpochMillis = 599264352000000000L / TimeSpan.TicksPerMillisecond; private const double MillisPerDay = 86_400_000.0; /// DateTimeOffset → UTC Julian day (REAL). Uses the true UTC instant. public static double ToJulian(DateTimeOffset dto) => ToJulian(dto.UtcDateTime); /// /// DateTime → UTC Julian day (REAL). The clock value is treated as UTC (REDB's /// contract: /// specifies Kind=Utc without converting), so Kind is ignored here. /// public static double ToJulian(DateTime dt) { var millis = dt.Ticks / TimeSpan.TicksPerMillisecond - EpochMillis; return millis / MillisPerDay + EpochJulianDay; } /// UTC Julian day (REAL) → DateTimeOffset (+00:00), to the millisecond. public static DateTimeOffset FromJulian(double julian) { var millis = (long)Math.Round((julian - EpochJulianDay) * MillisPerDay, MidpointRounding.AwayFromZero); var ticks = (millis + EpochMillis) * TimeSpan.TicksPerMillisecond; return new DateTimeOffset(new DateTime(ticks, DateTimeKind.Utc), TimeSpan.Zero); } } } Path: redb/redb.SQLite/Data/SqliteKeyGenerator.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/Data/SqliteKeyGenerator.cs ---- using System; using Microsoft.Data.Sqlite; using redb.Core.Data; using System.Collections.Generic; using System.Threading.Tasks; namespace redb.SQLite.Data { /// /// SQLite implementation of key generator. Ids come from the native /// AUTOINCREMENT table _global_identity; its high-water mark lives in /// sqlite_sequence. A batch of N ids is reserved with one atomic statement: /// UPDATE sqlite_sequence SET seq = seq + @n WHERE name='_global_identity' /// RETURNING seq; /// which returns the new top; the reserved ids are [top-N+1 .. top]. /// No explicit locking is needed — SQLite serializes writers and the /// read-modify-write happens inside the single UPDATE (RETURNING: 3.35+). /// The same sequence is also advanced by the C extension (nextId) and by /// soft-delete (INSERT DEFAULT VALUES); all consumers only ever increase it, /// so ids are globally unique. Caching is static in the base class. /// public class SqliteKeyGenerator : RedbKeyGeneratorBase { private readonly SqliteDataSource _dataSource; // The scope's ambient (connection, transaction) accessor for the single-writer bypass; // null (the connection-string constructor, tests) keeps the plain pooled-refill path. private readonly Func<(Microsoft.Data.Sqlite.SqliteConnection Connection, Microsoft.Data.Sqlite.SqliteTransaction Transaction)?>? _ambientAccessor; // AUTOINCREMENT table whose sqlite_sequence row is the id high-water mark. private const string SEQUENCE_TABLE = "_global_identity"; /// /// The highest id stored in the tables that take their ids from the sequence. Every range starts above it, so /// the sequence never hands out an id a stored row already has, whatever left it behind: a row committed with an /// id the application kept from a rolled-back transaction (the sequence bump went back, the row did not), an id /// another process wrote, a row written with an explicit id. Each term is the last key of a rowid table, read /// from the end of its b-tree. /// internal const string IdSpaceTopSql = "coalesce((SELECT max(_id) FROM _objects), 0), coalesce((SELECT max(_id) FROM _values), 0), " + "coalesce((SELECT max(_id) FROM _schemes), 0), coalesce((SELECT max(_id) FROM _structures), 0), " + "coalesce((SELECT max(_id) FROM _users), 0), coalesce((SELECT max(_id) FROM _roles), 0), " + "coalesce((SELECT max(_id) FROM _users_roles), 0), coalesce((SELECT max(_id) FROM _permissions), 0), " + "coalesce((SELECT max(_id) FROM _lists), 0), coalesce((SELECT max(_id) FROM _list_items), 0)"; /// /// Create SQLite key generator. /// public SqliteKeyGenerator(SqliteDataSource dataSource, string? domain = null, Func<(Microsoft.Data.Sqlite.SqliteConnection Connection, Microsoft.Data.Sqlite.SqliteTransaction Transaction)?>? ambientTransactionAccessor = null) : base(domain) { _dataSource = dataSource; _ambientAccessor = ambientTransactionAccessor; } /// /// Create SQLite key generator from connection string. /// public SqliteKeyGenerator(string connectionString, string? domain = null) : base(domain) { _dataSource = SqliteDataSource.Create(connectionString); } // === DB-SPECIFIC IMPLEMENTATIONS === /// /// Reserve a contiguous batch of ids by bumping the /// AUTOINCREMENT high-water mark in sqlite_sequence via one atomic UPDATE ... RETURNING. /// protected override async Task> GenerateKeysAsync(int count) { var sw = System.Diagnostics.Stopwatch.StartNew(); var tid = System.Environment.CurrentManagedThreadId; // Console.WriteLine($"[Diag-KeyGen] ENTER count={count} thread={tid}"); await using var conn = await _dataSource.OpenConnectionAsync(); var tConn = sw.ElapsedMilliseconds; // Console.WriteLine($"[Diag-KeyGen] OpenConnectionAsync +{tConn}ms thread={tid}"); await using var cmd = conn.CreateCommand(); PrepareReserve(cmd, count); object? scalar; try { scalar = await cmd.ExecuteScalarAsync(); var tScalar = sw.ElapsedMilliseconds - tConn; // Console.WriteLine($"[Diag-KeyGen] UPDATE sqlite_sequence RETURNING +{tScalar}ms (total {sw.ElapsedMilliseconds}ms) thread={tid}"); } catch (Microsoft.Data.Sqlite.SqliteException ex) { // Console.WriteLine($"[Diag-KeyGen] UPDATE FAILED after {sw.ElapsedMilliseconds}ms thread={tid} errno={ex.SqliteErrorCode} msg='{ex.Message}'"); throw; } if (scalar is null || scalar == DBNull.Value) { throw new InvalidOperationException( $"sqlite_sequence row for '{SEQUENCE_TABLE}' not found. " + "Ensure the schema (redbSqlite.sql) was applied — it materializes the sequence row."); } long top = Convert.ToInt64(scalar); RecordIssued(top); var keys = new List(count); for (long id = top - count + 1; id <= top; id++) { keys.Add(id); } // Console.WriteLine($"[Diag-KeyGen] EXIT keys=[{(keys.Count > 0 ? keys[0] : -1)}..{(keys.Count > 0 ? keys[^1] : -1)}] total={sw.ElapsedMilliseconds}ms thread={tid}"); return keys; } /// /// The single-writer bypass: the same atomic sequence bump, but on the scope's own /// connection INSIDE its BEGIN IMMEDIATE - the write lock is already ours, so there is /// no waiting and no self-deadlock. The keys deliberately do NOT enter the shared /// cache. A rollback takes the sequence bump back together with the transaction, but /// the ids stay with whoever got them (an object the application saves again), so /// every later range starts above the highest id handed out (). /// protected override async Task?> TryGenerateKeysInAmbientTransactionAsync(int count) { if (_ambientAccessor?.Invoke() is not { } ambient) return null; await using var cmd = ambient.Connection.CreateCommand(); cmd.Transaction = ambient.Transaction; PrepareReserve(cmd, count); var scalar = await cmd.ExecuteScalarAsync(); if (scalar is null || scalar == DBNull.Value) { throw new InvalidOperationException( $"sqlite_sequence row for '{SEQUENCE_TABLE}' not found. " + "Ensure the schema (redbSqlite.sql) was applied - it materializes the sequence row."); } long top = Convert.ToInt64(scalar); RecordIssued(top); var keys = new List(count); for (long id = top - count + 1; id <= top; id++) keys.Add(id); return keys; } /// /// The reserving statement of both paths. The range starts above the sequence and above every id this process /// handed out before: a range taken inside a transaction that rolled back is gone from sqlite_sequence, yet the /// application may still hold its ids (since 4.0.0 the next range repeated them, and saving such an object again /// overwrote the row of the object that got the id second). One statement, no extra write. /// private void PrepareReserve(SqliteCommand cmd, int count) { cmd.CommandText = "UPDATE sqlite_sequence SET seq = max(seq, @floor, " + IdSpaceTopSql + ") + @n WHERE name = @name RETURNING seq"; cmd.Parameters.AddWithValue("@floor", IssuedHighWater); cmd.Parameters.AddWithValue("@n", count); cmd.Parameters.AddWithValue("@name", SEQUENCE_TABLE); } } } Path: redb/redb.SQLite/Data/SqliteNativeExtension.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/Data/SqliteNativeExtension.cs ---- using System; namespace redb.SQLite.Data { /// /// The version gate of the native extension: the loaded redbsqlite library must report the version the /// dialect requires (pvt_module_version()), as the PostgreSQL and SQL Server modules must. A stale build /// next to the application loaded silently and answered in an old shape - list item JSON in the old form, a regex /// filter failing with an unrelated error. /// public static class SqliteNativeExtension { /// /// Throws when - what the loaded extension reports, null when it has no /// pvt_module_version() - is not . /// public static void EnsureVersion(string path, string? deployed, string required) { if (string.Equals(deployed, required, StringComparison.Ordinal)) return; var found = deployed == null ? "has no pvt_module_version() function" : $"reports version {deployed}"; throw new InvalidOperationException( $"The redb native SQLite extension '{path}' {found}; this build of redb.SQLite requires version " + $"{required}. The library is built from redb.SQLite/native and ships with the package: update the " + "package, or rebuild the extension (redb.SQLite/native/README.md) and replace the file next to the " + "application."); } } } Path: redb/redb.SQLite/Data/SqliteRedbConnection.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/Data/SqliteRedbConnection.cs ---- using Microsoft.Data.Sqlite; using redb.Core.Data; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using System.Transactions; namespace redb.SQLite.Data { /// /// SQLite implementation of IRedbConnection using Sqlite. /// Provides pure ADO.NET database access with automatic transaction management. /// public class SqliteRedbConnection : IRedbConnection { private readonly SqliteDataSource _dataSource; private SqliteConnection? _connection; private SqliteRedbTransaction? _currentTransaction; // The current command's hold on the ambient transaction's connection; released with the command. private AmbientLease? _ambientLease; // Identity of the database in AmbientConnectionRegistry (computed on first use). private string? _databaseKey; private bool _disposed = false; public bool IsDisposed => _disposed; /// /// One command: this wrapper's gate and, inside an ambient transaction, the lease on the /// transaction's connection taken by - both released when the /// command ends. /// private readonly struct CommandScope : IDisposable { private readonly SqliteRedbConnection _owner; private readonly CommandGate.Releaser _releaser; public CommandScope(SqliteRedbConnection owner, CommandGate.Releaser releaser) { _owner = owner; _releaser = releaser; } public void Dispose() { var lease = _owner._ambientLease; _owner._ambientLease = null; try { lease?.Dispose(); } finally { _releaser.Dispose(); } } } /// The database file: two connection strings reaching the same file share one key. private string DatabaseKey => _databaseKey ??= DatabaseKeyOf(_dataSource.ConnectionString); private string? _sessionSignature; // This configuration in AmbientConnectionRegistry: the cache domain of the connection string plus the // per-connection settings. The file is the database key; the transaction's connection to it is shared only // when they match. private string SessionSignature => _sessionSignature ??= redb.Core.Models.Configuration.RedbServiceConfiguration.ComputeCacheDomain(_dataSource.ConnectionString) + $"|case_folding={(_dataSource.UnicodeCaseFolding ? 1 : 0)};lazy_refs={(_dataSource.LazyReferences ? 1 : 0)}"; private static string DatabaseKeyOf(string connectionString) { var dataSource = new SqliteConnectionStringBuilder(connectionString).DataSource; var isFile = !string.IsNullOrEmpty(dataSource) && dataSource != ":memory:" && !dataSource.StartsWith("file:", StringComparison.OrdinalIgnoreCase); return "sqlite|" + (isFile ? System.IO.Path.GetFullPath(dataSource) : connectionString); } /// Opens the connection an ambient transaction holds (pragmas and extension applied by the data source). private async Task OpenAmbientAsync(CancellationToken cancellationToken) => await _dataSource.OpenConnectionAsync(); /// Synchronous . private System.Data.Common.DbConnection OpenAmbient() => _dataSource.OpenConnection(); /// /// Microsoft.Data.Sqlite never takes part in System.Transactions, so redb begins the transaction the /// scope commits or rolls back. BEGIN IMMEDIATE takes the single write lock up front, as every /// explicit redb transaction on SQLite does; it is held until the scope ends (owner decision P4). /// private static System.Data.Common.DbTransaction BeginAmbientTransaction(System.Data.Common.DbConnection connection) => ((SqliteConnection)connection).BeginTransaction(deferred: false); // Fail-fast concurrency guard. This connection holds ONE persistent SqliteConnection reused for all // Commands and teardown share ONE exclusion (CommandGate, a production report // 2026-09-11): this connection is NOT thread-safe, and racing a native SQLite query // with a handle close is worse than an exception. Two concurrent commands fail fast; // a command after teardown began is refused with ObjectDisposedException (the lazy // loader falls back to a detached scope); DisposeAsync WAITS for the in-flight // command instead of closing under it. private readonly CommandGate _gate = new(nameof(SqliteRedbConnection)); private CommandScope EnterCommand() => new(this, _gate.Enter()); // ── [Diag-TXLOCK] process-wide BeginTransaction tracker ──────────── // // Every BeginTransactionAsync call registers an entry keyed by this // SqliteRedbConnection's HashCode and dumps the current registry // contents before attempting BEGIN IMMEDIATE. A SqliteException // (BUSY / locked) on the BEGIN call triggers a second dump so the // operator can see WHO else is holding a write tx when the failure // hit. Active entries are removed on Commit / Rollback / Dispose. // Set DiagEnabled=true to enable [Diag-TXLOCK] BEGIN tracking dump // (single-writer concurrency triage). Off by default — the instrumentation // stays in code so it can be flipped back on without a recompile when the // next live writer-conflict scenario needs to be investigated. private sealed record BeginEntry( int ConnHash, int ThreadId, DateTime BeginUtc, string AmbientTxId, string CallerStack); private static readonly ConcurrentDictionary _activeBegins = new(); public static bool DiagEnabled { get; set; } = false; /// /// Connection string. /// public string ConnectionString => _dataSource.ConnectionString; /// /// Current active transaction. /// public IRedbTransaction? CurrentTransaction => _currentTransaction; /// /// The connection and transaction that hold the write lock for this scope, for the key /// generator's bypass (see SqliteKeyGenerator): the scope's explicit transaction, or - inside a /// TransactionScope - the transaction redb began on the transaction's connection. Null when /// neither exists. A refill on a separate connection would wait for that very lock. /// internal (Microsoft.Data.Sqlite.SqliteConnection Connection, Microsoft.Data.Sqlite.SqliteTransaction Transaction)? TryGetAmbientTransaction() { var tx = _currentTransaction; if (_connection != null && tx is { IsActive: true }) return (_connection, tx.SqliteTransaction); if (Transaction.Current is { } ambient) { var entry = AmbientConnectionRegistry.GetOrOpen(ambient, DatabaseKey, SessionSignature, OpenAmbient, BeginAmbientTransaction); return ((SqliteConnection)entry.Connection, (Microsoft.Data.Sqlite.SqliteTransaction)entry.OwnTransaction!); } return null; } /// /// Whether any transaction is active — explicit or ambient TransactionScope. /// EF Core pattern: checks both CurrentTransaction and Transaction.Current. /// public bool IsInTransaction => (_currentTransaction != null && _currentTransaction.IsActive) || Transaction.Current != null; /// /// Create connection from data source. /// /// Sqlite data source (pooled). public SqliteRedbConnection(SqliteDataSource dataSource) { _dataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource)); } /// /// Create connection from connection string. /// /// SQLite connection string. public SqliteRedbConnection(string connectionString) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString)); _dataSource = SqliteDataSource.Create(connectionString); } // === CONNECTION MANAGEMENT === /// /// Get underlying connection (for bulk operations). /// This ensures all operations use the same connection and transaction. /// public async Task GetUnderlyingConnectionAsync(CancellationToken cancellationToken = default) { // Outside a command: no lease, which would hold the transaction connection's gate past the command // and stall the end of the transaction. if (!_disposed && _currentTransaction is not { IsActive: true } && Transaction.Current is { } ambient) return (await AmbientConnectionRegistry.GetOrOpenAsync(ambient, DatabaseKey, SessionSignature, OpenAmbientAsync, BeginAmbientTransaction, cancellationToken)).Connection; return await GetOpenConnectionAsync(cancellationToken); } /// public async Task LeaseAsync(CancellationToken cancellationToken = default) { // One command's hold, as every command of this wrapper takes it: this wrapper's gate, and inside an ambient // transaction the lease on the transaction's connection. Both are left when the lease is given back. var command = EnterCommand(); try { var connection = await GetOpenConnectionAsync(cancellationToken); // Microsoft.Data.Sqlite refuses a command without the transaction object on a connection with an open // transaction: this wrapper's explicit one, or the one redb began on the ambient transaction's connection. System.Data.Common.DbTransaction? transaction = _currentTransaction is { IsActive: true } explicitTransaction ? explicitTransaction.SqliteTransaction : _ambientLease?.Entry.OwnTransaction; return new RedbConnectionLease(connection, transaction, command.Dispose); } catch { command.Dispose(); throw; } } private async Task GetOpenConnectionAsync(CancellationToken cancellationToken = default) { // Dispose nulls _connection; without this check a call after Dispose would open a NEW // connection on a wrapper whose second Dispose is a no-op, and it would never be closed. if (_disposed) throw new ObjectDisposedException(nameof(SqliteRedbConnection), "The scope that owned this connection has ended. Resolve a fresh scoped IRedbService " + "instead of reusing one from a finished scope or exchange."); // Inside an ambient transaction the TRANSACTION holds the connection (AmbientConnectionRegistry) // and redb's own transaction on it: the driver cannot enlist, and a second connection would wait // for the write lock that transaction holds. An explicit transaction of this wrapper keeps its own. if (_currentTransaction is not { IsActive: true } && Transaction.Current is { } ambient) { _ambientLease ??= await AmbientConnectionRegistry.AcquireAsync(ambient, DatabaseKey, SessionSignature, OpenAmbientAsync, BeginAmbientTransaction, cancellationToken); return (SqliteConnection)_ambientLease.Entry.Connection; } if (_connection == null) { _connection = await _dataSource.OpenConnectionAsync(); } else if (_connection.State != System.Data.ConnectionState.Open) { await _connection.OpenAsync(); } return _connection; } private SqliteCommand CreateCommand(SqliteConnection connection, string sql, object[] parameters) { // Convert @p0, @p1 format to SQLite $1, $2 format for cross-platform compatibility var convertedSql = ConvertParameters(sql, parameters.Length); var cmd = new SqliteCommand(convertedSql, connection); // Set transaction if active. The `_currentTransaction` field is // cleared on Dispose, NOT on Commit/Rollback — so after the caller // commits but before they dispose, this would otherwise try to // bind the command to an already-closed SQLite transaction object // and throw "transaction is not associated with the same connection". // Gate on IsActive so queries that fire between commit-and-dispose // (e.g. visibility probes in transaction-integrity tests) bind to // no transaction and run against the autocommit connection. if (_currentTransaction != null && _currentTransaction.IsActive) { cmd.Transaction = _currentTransaction.SqliteTransaction; } else if (_ambientLease?.Entry.OwnTransaction is SqliteTransaction ambientTransaction) { // Inside a TransactionScope: bind to the transaction redb began on the transaction's connection. cmd.Transaction = ambientTransaction; } // Add parameters NAMED to match the converted $1,$2,... placeholders // (Microsoft.Data.Sqlite binds by name, not by position). for (int i = 0; i < parameters.Length; i++) { var param = parameters[i]; var sqliteParam = new SqliteParameter { ParameterName = "$" + (i + 1) }; switch (param) { case null: sqliteParam.Value = DBNull.Value; break; case DateTimeOffset dto: // Datetimes are stored as REAL Julian day (UTC) — the native SQLite // datetime format → numeric, correct, index-friendly comparisons and // datetime()/strftime()/julianday() work directly. Covers writes // (base _date_* + props _DateTimeOffset) AND parameterized query values. sqliteParam.Value = SqliteJulian.ToJulian(dto); break; case DateTime dt2: // e.g. a LINQ comparison value (DateTime) — same UTC Julian encoding. sqliteParam.Value = SqliteJulian.ToJulian(dt2); break; case decimal dec: // Microsoft.Data.Sqlite binds decimal as TEXT, but _Numeric/_value_numeric // are REAL — and in SQLite type-ordering a REAL is always < any TEXT, so // `Salary(REAL) > '80000'(TEXT)` is always false. Bind decimals as double. sqliteParam.Value = (double)dec; break; case long[]: case int[]: case string[]: // SQLite has no array parameters. Bind arrays as a JSON array // (TEXT); SQL that needs the elements uses // `IN (SELECT value FROM json_each($n))`. sqliteParam.Value = JsonSerializer.Serialize(param); break; case Array values when values is not byte[]: // The same JSON array for the other element types a list of values carries (Contains over a // list of dates, decimals, flags, Guids): each element spelled as the single value is bound, // a date as its Julian day, a decimal as a double, so json_each yields what the column holds. // A DateTime[] reached the driver as it was and failed: "No mapping exists from object type". sqliteParam.Value = JsonArrayOfStoredValues(values); break; default: sqliteParam.Value = param; break; } cmd.Parameters.Add(sqliteParam); } return cmd; } /// /// A list of values as the JSON array json_each reads, every element spelled as the column stores it: a /// date as its Julian day, a decimal as a double, a flag as 1/0, a Guid as the driver writes one (upper-case /// text). Nulls stay JSON null: IN never matches them. An element of any other type is refused here, /// before the statement runs, instead of reaching the driver. /// private static string JsonArrayOfStoredValues(Array values) { var items = new List(values.Length); foreach (var v in values) { items.Add(v switch { null => null, DateTimeOffset dto => SqliteJulian.ToJulian(dto), DateTime dt => SqliteJulian.ToJulian(dt), decimal dec => (double)dec, double or float or long or int or short or byte or sbyte or ushort or uint or string => v, bool flag => flag ? 1 : 0, Guid g => g.ToString().ToUpperInvariant(), char c => c.ToString(), _ => throw new NotSupportedException( $"SQLite cannot take a list of {v.GetType().Name} values as a parameter.") }); } return JsonSerializer.Serialize(items); } // === QUERY METHODS === /// /// Execute SQL query and map results to list of objects. /// Uses JsonPropertyName attribute for snake_case to PascalCase mapping. /// public Task> QueryAsync(string sql, params object[] parameters) where T : new() => QueryAsync(sql, parameters, CancellationToken.None); /// public async Task> QueryAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : new() { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await QueryCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task> QueryCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) where T : new() { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await cmd.ExecuteReaderAsync(cancellationToken); var results = new List(); var mapper = new RedbRowMapper(); while (await reader.ReadAsync(cancellationToken)) { results.Add(mapper.MapRow(reader)); } return results; } /// /// Execute SQL query and return first result. /// public Task QueryFirstOrDefaultAsync(string sql, params object[] parameters) where T : class, new() => QueryFirstOrDefaultAsync(sql, parameters, CancellationToken.None); /// public async Task QueryFirstOrDefaultAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new() { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await QueryFirstOrDefaultCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task QueryFirstOrDefaultCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new() { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await cmd.ExecuteReaderAsync(cancellationToken); if (await reader.ReadAsync(cancellationToken)) { var mapper = new RedbRowMapper(); return mapper.MapRow(reader); } return null; } /// /// Execute SQL query and return scalar value. /// public Task ExecuteScalarAsync(string sql, params object[] parameters) => ExecuteScalarAsync(sql, parameters, CancellationToken.None); /// public async Task ExecuteScalarAsync(string sql, object[] parameters, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await ExecuteScalarCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task ExecuteScalarCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); var result = await cmd.ExecuteScalarAsync(cancellationToken); if (result == null || result == DBNull.Value) return default; return ConvertScalar(result); } // === ORPHAN TRANSACTION HYGIENE === private const string OrphanRollbackFailureKey = "redb.OrphanTransactionRollbackFailure"; /// /// A command that failed can leave behind a transaction its own SQL text opened: a root /// SAVEPOINT or BEGIN, some writes, then an error before RELEASE or COMMIT. This wrapper does /// not own that transaction, and Microsoft.Data.Sqlite pools the handle as it is - the pool /// clears it only when that very handle is handed out again, so its write lock stalls every /// writer of the database meanwhile, and the scope itself cannot start a transaction. It is /// rolled back here before the failure leaves, unless a transaction of this wrapper or an /// ambient one owns the connection (its owner ends it). The original exception always /// propagates; a rollback that fails as well is attached to it instead of replacing it. /// private void RollbackOrphanTransaction(SqliteConnection conn, Exception failure) { if (_currentTransaction is { IsActive: true } || Transaction.Current != null) return; if (conn.State != System.Data.ConnectionState.Open || SQLitePCL.raw.sqlite3_get_autocommit(conn.Handle) != 0) return; try { using var cmd = conn.CreateCommand(); cmd.CommandText = "ROLLBACK"; cmd.ExecuteNonQuery(); } catch (Exception rollbackFailure) { failure.Data[OrphanRollbackFailureKey] = rollbackFailure.Message; } } /// /// The last line for a handle about to return to the pool inside a transaction nobody owns - /// a path that reached the physical connection without the per-command guard. Pooled as it is, /// its write lock would stall every writer until the pool happened to hand it out again. /// An ambient transaction still in flight owns the handle and ends it itself. A failing /// rollback propagates, like any other dispose fault here. /// private static void ReleaseOrphanTransactionBeforePooling(SqliteConnection conn) { // The connection's own state first: Transaction.Current throws between Complete() and Dispose() of // a TransactionScope, and disposing a scope's services in that window is legal. if (conn.State != System.Data.ConnectionState.Open || SQLitePCL.raw.sqlite3_get_autocommit(conn.Handle) != 0) return; if (Transaction.Current != null) return; using var cmd = conn.CreateCommand(); cmd.CommandText = "ROLLBACK"; cmd.ExecuteNonQuery(); } // === SYNCHRONOUS COUNTERPARTS (thread-pool-free lazy path) === // The sync getter of RedbListItem.Object runs the whole load on the calling thread; these // are true sync ADO calls - no thread-pool continuation anywhere, so a saturated pool // cannot slow or deadlock them. Same command shape and pragmas as the async twins above // (SqliteDataSource.OpenConnection applies them synchronously). private SqliteConnection GetOpenConnection() { if (_disposed) throw new ObjectDisposedException(nameof(SqliteRedbConnection), "The scope that owned this connection has ended. Resolve a fresh scoped IRedbService " + "instead of reusing one from a finished scope or exchange."); // Same ambient-transaction rule as the async twin. if (_currentTransaction is not { IsActive: true } && Transaction.Current is { } ambient) { _ambientLease ??= AmbientConnectionRegistry.Acquire(ambient, DatabaseKey, SessionSignature, OpenAmbient, BeginAmbientTransaction); return (SqliteConnection)_ambientLease.Entry.Connection; } if (_connection == null) { _connection = _dataSource.OpenConnection(); } else if (_connection.State != System.Data.ConnectionState.Open) { _connection.Open(); } return _connection; } /// public T? QueryFirstOrDefault(string sql, params object[] parameters) where T : class, new() { using var _guard = EnterCommand(); var conn = GetOpenConnection(); try { return QueryFirstOrDefaultCore(conn, sql, parameters); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private T? QueryFirstOrDefaultCore(SqliteConnection conn, string sql, object[] parameters) where T : class, new() { using var cmd = CreateCommand(conn, sql, parameters); using var reader = cmd.ExecuteReader(); return reader.Read() ? new RedbRowMapper().MapRow(reader) : null; } /// public List Query(string sql, params object[] parameters) where T : new() { using var _guard = EnterCommand(); var conn = GetOpenConnection(); try { return QueryCore(conn, sql, parameters); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private List QueryCore(SqliteConnection conn, string sql, object[] parameters) where T : new() { using var cmd = CreateCommand(conn, sql, parameters); using var reader = cmd.ExecuteReader(); var results = new List(); var mapper = new RedbRowMapper(); while (reader.Read()) results.Add(mapper.MapRow(reader)); return results; } /// public int Execute(string sql, params object[] parameters) { using var _guard = EnterCommand(); var conn = GetOpenConnection(); try { using var cmd = CreateCommand(conn, sql, parameters); return cmd.ExecuteNonQuery(); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } /// public T? ExecuteScalar(string sql, params object[] parameters) { using var _guard = EnterCommand(); var conn = GetOpenConnection(); try { return ExecuteScalarCore(conn, sql, parameters); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private T? ExecuteScalarCore(SqliteConnection conn, string sql, object[] parameters) { using var cmd = CreateCommand(conn, sql, parameters); var result = cmd.ExecuteScalar(); if (result == null || result == DBNull.Value) return default; return ConvertScalar(result); } /// public string? ExecuteJson(string sql, params object[] parameters) { using var _guard = EnterCommand(); var conn = GetOpenConnection(); try { return ExecuteJsonCore(conn, sql, parameters); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private string? ExecuteJsonCore(SqliteConnection conn, string sql, object[] parameters) { using var cmd = CreateCommand(conn, sql, parameters); var result = cmd.ExecuteScalar(); return result == null || result == DBNull.Value ? null : result.ToString(); } /// /// Convert a raw SQLite value to T, handling uuid->Guid (a hash BLOB or a TEXT guid), /// TEXT/ DateTime -> DateTimeOffset, and BLOB -> byte[] (which /// Convert.ChangeType cannot do), then falling back to ChangeType. /// private static T ConvertScalar(object value) { var targetType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); if (value.GetType() == targetType || targetType.IsAssignableFrom(value.GetType())) return (T)value; if (targetType == typeof(Guid)) return (T)(object)SqliteHash.FromDbValue(value); // Datetimes are stored as REAL Julian day (UTC) → value is a double. if (targetType == typeof(DateTimeOffset)) return (T)(object)(value is double jdo ? SqliteJulian.FromJulian(jdo) : value is DateTimeOffset d ? d : value is DateTime dt ? new DateTimeOffset(dt, TimeSpan.Zero) : DateTimeOffset.Parse(value.ToString()!, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind)); if (targetType == typeof(DateTime)) return (T)(object)(value is double jdt ? SqliteJulian.FromJulian(jdt).UtcDateTime : value is DateTime dt3 ? dt3 : value is DateTimeOffset dto3 ? dto3.UtcDateTime : DateTime.Parse(value.ToString()!, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind)); if (targetType == typeof(DateOnly)) return (T)(object)(value is double jod ? DateOnly.FromDateTime(SqliteJulian.FromJulian(jod).UtcDateTime) : value is DateTime dt4 ? DateOnly.FromDateTime(dt4) : DateOnly.Parse(value.ToString()!, System.Globalization.CultureInfo.InvariantCulture)); if (targetType == typeof(byte[])) return (T)(object)(byte[])value; return (T)redb.Core.Utils.RedbDecimal.ChangeType(value, targetType); } /// /// Execute SQL command (INSERT, UPDATE, DELETE). /// public Task ExecuteAsync(string sql, params object[] parameters) => ExecuteAsync(sql, parameters, CancellationToken.None); /// public async Task ExecuteAsync(string sql, object[] parameters, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await ExecuteCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task ExecuteCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); return await cmd.ExecuteNonQueryAsync(cancellationToken); } /// /// Execute SQL query and return list of scalar values (first column only). /// Use for simple queries like SELECT _id FROM ... that return single column. /// public Task> QueryScalarListAsync(string sql, params object[] parameters) => QueryScalarListAsync(sql, parameters, CancellationToken.None); /// public async Task> QueryScalarListAsync(string sql, object[] parameters, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await QueryScalarListCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task> QueryScalarListCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await cmd.ExecuteReaderAsync(cancellationToken); var results = new List(); while (await reader.ReadAsync(cancellationToken)) { if (reader.IsDBNull(0)) { results.Add(default!); } else { results.Add(ConvertScalar(reader.GetValue(0))); } } return results; } // === TRANSACTION METHODS === /// /// Begin new transaction. /// public async Task BeginTransactionAsync(System.Data.IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default) { // BR-1: the parameter is accepted for portability. SQLite is a single serial writer and // BEGIN IMMEDIATE below already takes the write lock at start - every transaction is // effectively serializable, whatever level the caller names. _ = isolationLevel; if (_currentTransaction != null && _currentTransaction.IsActive) throw new InvalidOperationException("Transaction already active. Commit or rollback first."); if (Transaction.Current != null) throw new InvalidOperationException( "Ambient TransactionScope detected. Cannot create explicit transaction inside TransactionScope. " + "Use ExecuteAtomicAsync() which respects ambient transactions."); using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); // [Diag-TXLOCK] — capture WHO is about to BEGIN IMMEDIATE and WHAT // else is currently holding write tx; on BUSY we dump again so the // operator can see who was racing. var connHash = GetHashCode(); var ambient = Transaction.Current?.TransactionInformation.LocalIdentifier ?? ""; var caller = DiagEnabled ? CaptureCallerStack(skipFrames: 1) : ""; if (DiagEnabled) { Console.WriteLine( $"[Diag-TXLOCK] BEGIN ENTRY conn=#{connHash} thread={Environment.CurrentManagedThreadId} " + $"ambientTx={ambient} activeCount={_activeBegins.Count}"); DumpActiveBegins("BEGIN ENTRY (pre-BeginImmediate)"); // Console.WriteLine($"[Diag-TXLOCK] BEGIN CALLER conn=#{connHash}\n{caller}"); } SqliteTransaction sqliteTx; try { // BEGIN IMMEDIATE (deferred:false) acquires SQLite's single write lock at // transaction start — the SQLite equivalent of pessimistic locking / the PG // `FOR UPDATE` intent. Atomicity here is critical and reused widely. sqliteTx = conn.BeginTransaction(deferred: false); } catch (SqliteException ex) { if (DiagEnabled) { Console.WriteLine( $"[Diag-TXLOCK] BEGIN FAILED conn=#{connHash} thread={Environment.CurrentManagedThreadId} " + $"errno={ex.SqliteErrorCode} msg='{ex.Message}'"); DumpActiveBegins("BEGIN FAILED — current holders"); } throw; } _currentTransaction = new SqliteRedbTransaction(sqliteTx, () => { _currentTransaction = null; if (DiagEnabled) { _activeBegins.TryRemove(connHash, out _); Console.WriteLine( $"[Diag-TXLOCK] BEGIN RELEASED conn=#{connHash} thread={Environment.CurrentManagedThreadId} " + $"activeCount={_activeBegins.Count}"); } }); if (DiagEnabled) { _activeBegins[connHash] = new BeginEntry( connHash, Environment.CurrentManagedThreadId, DateTime.UtcNow, ambient, caller); Console.WriteLine( $"[Diag-TXLOCK] BEGIN OK conn=#{connHash} thread={Environment.CurrentManagedThreadId} " + $"activeCount={_activeBegins.Count}"); } return _currentTransaction; } // ── [Diag-TXLOCK] helpers ────────────────────────────────────────── private static string CaptureCallerStack(int skipFrames) { try { var st = new StackTrace(skipFrames + 1, fNeedFileInfo: false); var frames = st.GetFrames(); if (frames is null) return ""; var top = frames.Take(8).Select(f => { var m = f.GetMethod(); return m is null ? "" : $" at {m.DeclaringType?.FullName}.{m.Name}"; }); return string.Join("\n", top); } catch { return ""; } } private static void DumpActiveBegins(string label) { if (_activeBegins.IsEmpty) { // Console.WriteLine($"[Diag-TXLOCK] {label}: "); return; } // Console.WriteLine($"[Diag-TXLOCK] {label}: count={_activeBegins.Count}"); foreach (var (key, e) in _activeBegins) { var heldFor = DateTime.UtcNow - e.BeginUtc; Console.WriteLine( $" conn=#{key} thread={e.ThreadId} heldFor={heldFor.TotalMilliseconds:N0}ms " + $"ambientAtBegin={e.AmbientTxId}"); foreach (var line in e.CallerStack.Split('\n').Take(5)) Console.WriteLine($" {line}"); } } // === ATOMIC OPERATIONS === /// /// Atomic execution under an explicit isolation level (BR-1). An active or ambient transaction /// wins: operations join it and its level is NOT changed. /// public async Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func operations, CancellationToken cancellationToken = default) { if (IsInTransaction) { await operations(); return; } await using var tx = await BeginTransactionAsync(isolationLevel, cancellationToken); try { await operations(); await tx.CommitAsync(); } catch { await tx.RollbackAsync(); throw; } } /// Result-returning form of the isolation-level overload (BR-1). public async Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func> operations, CancellationToken cancellationToken = default) { if (IsInTransaction) return await operations(); await using var tx = await BeginTransactionAsync(isolationLevel, cancellationToken); try { var result = await operations(); await tx.CommitAsync(); return result; } catch { await tx.RollbackAsync(); throw; } } /// /// Execute operations atomically (SaveChanges replacement). /// public async Task ExecuteAtomicAsync(Func operations, CancellationToken cancellationToken = default) { // EF pattern: if any transaction active (explicit or ambient TransactionScope) — just execute if (IsInTransaction) { await operations(); return; } // Otherwise create auto-transaction await using var tx = await BeginTransactionAsync(cancellationToken: cancellationToken); try { await operations(); await tx.CommitAsync(); } catch { await tx.RollbackAsync(); throw; } } /// /// Execute operations atomically and return result. /// public async Task ExecuteAtomicAsync(Func> operations, CancellationToken cancellationToken = default) { // EF pattern: if any transaction active (explicit or ambient TransactionScope) — just execute if (IsInTransaction) { return await operations(); } await using var tx = await BeginTransactionAsync(cancellationToken: cancellationToken); try { var result = await operations(); await tx.CommitAsync(); return result; } catch { await tx.RollbackAsync(); throw; } } // === JSON METHODS === /// /// Execute SQL returning JSON (for SQLite functions). /// public Task ExecuteJsonAsync(string sql, params object[] parameters) => ExecuteJsonAsync(sql, parameters, CancellationToken.None); /// public async Task ExecuteJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await ExecuteJsonCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task ExecuteJsonCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); var result = await cmd.ExecuteScalarAsync(cancellationToken); if (result == null || result == DBNull.Value) return null; return result.ToString(); } /// /// Execute SQL returning multiple JSON rows. /// public Task> ExecuteJsonListAsync(string sql, params object[] parameters) => ExecuteJsonListAsync(sql, parameters, CancellationToken.None); /// public async Task> ExecuteJsonListAsync(string sql, object[] parameters, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await ExecuteJsonListCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task> ExecuteJsonListCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await cmd.ExecuteReaderAsync(cancellationToken); var results = new List(); while (await reader.ReadAsync(cancellationToken)) { // Skip NULL values (e.g. get_object_json returns NULL for deleted objects) if (reader.IsDBNull(0)) continue; var json = reader.GetString(0); if (!string.IsNullOrEmpty(json)) results.Add(json); } return results; } /// /// Execute SQL and serialize the result rows to a JSON array string in C# /// (column names from the reader). SQLite has no row_to_json/json_agg, so the /// Pro analytics providers package dynamic-shaped results here instead of in SQL. /// Returns "[]" when there are no rows. /// public Task QueryRowsAsJsonAsync(string sql, params object[] parameters) => QueryRowsAsJsonAsync(sql, parameters, CancellationToken.None); /// Cancellable form. public async Task QueryRowsAsJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await QueryRowsAsJsonCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task QueryRowsAsJsonCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await cmd.ExecuteReaderAsync(cancellationToken); var rows = new List>(); while (await reader.ReadAsync(cancellationToken)) { var row = new Dictionary(reader.FieldCount); for (int i = 0; i < reader.FieldCount; i++) row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i); rows.Add(row); } return JsonSerializer.Serialize(rows); } /// /// Execute SQL and serialize the FIRST result row to a JSON object string in C#, /// or null if there are no rows. SQLite analog of "SELECT row_to_json(t) FROM (...) t". /// public Task QueryFirstRowAsJsonAsync(string sql, params object[] parameters) => QueryFirstRowAsJsonAsync(sql, parameters, CancellationToken.None); /// Cancellable form. public async Task QueryFirstRowAsJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { return await QueryFirstRowAsJsonCoreAsync(conn, sql, parameters, cancellationToken); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private async Task QueryFirstRowAsJsonCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await cmd.ExecuteReaderAsync(cancellationToken); if (!await reader.ReadAsync(cancellationToken)) return null; var row = new Dictionary(reader.FieldCount); for (int i = 0; i < reader.FieldCount; i++) row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i); return JsonSerializer.Serialize(row); } // === DISPOSE === public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; // Teardown takes the SAME exclusion as commands: wait for the in-flight one (new // entrants bounce with ObjectDisposedException the moment the gate flag is set). // The budget follows the connection's own Default Timeout (SQLite's command // timeout). The LIVE object is the source of truth (it can be changed // programmatically); the string is the fallback for a never-opened connection. int commandTimeout; try { commandTimeout = _connection?.DefaultTimeout ?? new Microsoft.Data.Sqlite.SqliteConnectionStringBuilder(_dataSource.ConnectionString).DefaultTimeout; } catch { commandTimeout = 0; } await _gate.DisposeAndWaitAsync(CommandGate.BudgetFrom(commandTimeout)); // The physical connection MUST return to the pool even if disposing a broken transaction // throws (e.g. after a mid-query failure): finally guarantees the return, and the exception // is NOT swallowed — it propagates so the fault stays observable. The route's ReleaseScopes // loop is throw-resilient, so a propagated dispose fault won't strand sibling scopes. try { if (_currentTransaction != null) await _currentTransaction.DisposeAsync(); } finally { _currentTransaction = null; var conn = _connection; _connection = null; if (conn != null) { try { ReleaseOrphanTransactionBeforePooling(conn); } finally { await conn.DisposeAsync(); } } } } /// /// Synchronous dispose for DI container compatibility. /// public void Dispose() { if (_disposed) return; _disposed = true; try { _currentTransaction?.DisposeAsync().AsTask().GetAwaiter().GetResult(); } finally { _currentTransaction = null; var conn = _connection; _connection = null; if (conn != null) { try { ReleaseOrphanTransactionBeforePooling(conn); } finally { conn.Dispose(); } } } } /// /// Convert @p0, @p1 parameter format to SQLite $1, $2 format. /// Enables cross-platform SQL compatibility. /// private static string ConvertParameters(string sql, int paramCount) { var result = sql; // Replace @p0, @p1 with $1, $2 (in reverse order to avoid index shifting) for (int i = paramCount - 1; i >= 0; i--) { result = result.Replace($"@p{i}", $"${i + 1}"); } return result; } } /// /// Row mapper for converting SqliteDataReader to objects. /// Supports multiple column name formats: /// - SQLite table columns: _id, _name, _id_scheme /// - JSON output: id, name, id_scheme /// - PascalCase: Id, Name, IdScheme /// /// Target type. internal class RedbRowMapper where T : new() { // Bound on the first row: one mapper reads one result set, whose columns do not change between rows. private RedbRowMapping.Slot?[]? _slots; public T MapRow(SqliteDataReader reader) { var obj = new T(); var slots = _slots ??= RedbRowMapping.Bind(reader); for (int i = 0; i < slots.Length; i++) { var slot = slots[i]; if (slot == null) continue; var property = slot.Property; var value = reader.IsDBNull(i) ? null : reader.GetValue(i); if (value != null) { try { var targetType = slot.TargetType; // Datetimes are stored as REAL Julian day (UTC) — value is a double. if (targetType == typeof(DateTimeOffset)) { if (value is double jd) slot.Assign(obj, SqliteJulian.FromJulian(jd)); else if (value is DateTime dt) slot.Assign(obj, new DateTimeOffset(dt, TimeSpan.Zero)); else if (value is DateTimeOffset dto) slot.Assign(obj, dto); else if (value is string sdt) slot.Assign(obj, DateTimeOffset.Parse(sdt, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind)); continue; } if (targetType == typeof(DateTime)) { if (value is double jd2) slot.Assign(obj, SqliteJulian.FromJulian(jd2).UtcDateTime); else if (value is DateTime dt2) slot.Assign(obj, dt2); else if (value is DateTimeOffset dto2) slot.Assign(obj, dto2.UtcDateTime); else if (value is string sdt2) slot.Assign(obj, DateTime.Parse(sdt2, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind)); continue; } if (targetType == typeof(DateOnly)) { if (value is double jd3) slot.Assign(obj, DateOnly.FromDateTime(SqliteJulian.FromJulian(jd3).UtcDateTime)); else if (value is DateTime dt3) slot.Assign(obj, DateOnly.FromDateTime(dt3)); else if (value is string sdt3) slot.Assign(obj, DateOnly.Parse(sdt3, System.Globalization.CultureInfo.InvariantCulture)); continue; } // A hash comes back as BLOB(16), a data guid as TEXT — SqliteHash reads both. if (targetType == typeof(Guid)) { slot.Assign(obj, SqliteHash.FromDbValue(value)); continue; } // A value already of the property's type is assigned as is (BLOB -> byte[] among them). if (property.PropertyType.IsInstanceOfType(value)) { slot.Assign(obj, value); continue; } var convertedValue = redb.Core.Utils.RedbDecimal.ChangeType(value, targetType, System.Globalization.CultureInfo.InvariantCulture); slot.Assign(obj, convertedValue); } catch (Exception ex) when (ex is InvalidCastException or FormatException or OverflowException) { // SL-57: two silent catches left the property at its default - the row read as if the // column were NULL. throw new InvalidOperationException( $"Column '{reader.GetName(i)}': the value '{value}' ({value.GetType().Name}) cannot be read as " + $"{property.PropertyType.Name} ({typeof(T).Name}.{property.Name}).", ex); } } } return obj; } } } Path: redb/redb.SQLite/Data/SqliteRedbContext.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/Data/SqliteRedbContext.cs ---- using System; using Microsoft.Data.Sqlite; using redb.Core.Data; namespace redb.SQLite.Data { /// /// SQLite implementation of REDB context. /// Assembles all Sqlite components into single facade. /// public class SqliteRedbContext : RedbContextBase { private readonly SqliteRedbConnection _connection; private readonly SqliteKeyGenerator _keyGenerator; private readonly SqliteBulkOperations _bulkOperations; /// /// Database connection. /// public override IRedbConnection Db => _connection; /// /// Key generator with caching. /// public override IKeyGenerator Keys => _keyGenerator; /// /// Bulk operations (COPY protocol). /// protected override IBulkOperations BulkOperations => _bulkOperations; /// protected override Task QueryRowsAsJsonCoreAsync(string sql, object[] parameters, System.Threading.CancellationToken cancellationToken) => _connection.QueryRowsAsJsonAsync(sql, parameters, cancellationToken); /// /// Sqlite data source (for direct access if needed). /// public SqliteDataSource DataSource { get; } /// /// Create SQLite context from data source. /// /// Sqlite data source (pooled connections). public SqliteRedbContext(SqliteDataSource dataSource) { DataSource = dataSource; _connection = new SqliteRedbConnection(dataSource); var domain = redb.Core.Models.Configuration.RedbServiceConfiguration.ComputeCacheDomain(dataSource.ConnectionString); _keyGenerator = new SqliteKeyGenerator(dataSource, domain, ambientTransactionAccessor: () => _connection.TryGetAmbientTransaction()); _bulkOperations = new SqliteBulkOperations(_connection); } /// /// Create SQLite context from connection string. /// /// SQLite connection string. public SqliteRedbContext(string connectionString) : this(SqliteDataSource.Create(connectionString)) { } /// /// Dispose context and all components. /// public override async ValueTask DisposeAsync() { await _connection.DisposeAsync(); // DataSource is shared, don't dispose it here } } } Path: redb/redb.SQLite/Data/SqliteRedbTransaction.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/Data/SqliteRedbTransaction.cs ---- using Microsoft.Data.Sqlite; using redb.Core.Data; using System; using System.Threading.Tasks; namespace redb.SQLite.Data { /// /// SQLite implementation of IRedbTransaction using Sqlite. /// Connection-scoped: parent connection automatically uses this transaction. /// public class SqliteRedbTransaction : IRedbTransaction { private readonly SqliteTransaction _transaction; private readonly Action _onDispose; private bool _completionReported; // Reports the outcome once to the callbacks registered for this transaction (cache publication after commit). private void Complete(bool committed) { if (_completionReported) return; _completionReported = true; redb.Core.Data.TransactionCompletion.Completed(this, committed); } private bool _disposed = false; /// /// Transaction unique identifier. /// public Guid TransactionId { get; } = Guid.NewGuid(); /// /// Whether transaction is still active. /// public bool IsActive { get; private set; } = true; /// /// Transaction start time. /// public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow; /// /// Internal Sqlite transaction (for command assignment). /// internal SqliteTransaction SqliteTransaction => _transaction; /// /// Create new transaction wrapper. /// /// Underlying Sqlite transaction. /// Callback when transaction is disposed. public SqliteRedbTransaction(SqliteTransaction transaction, Action onDispose) { _transaction = transaction ?? throw new ArgumentNullException(nameof(transaction)); _onDispose = onDispose ?? throw new ArgumentNullException(nameof(onDispose)); } /// /// Commit all changes. /// public async Task CommitAsync() { if (!IsActive) throw new InvalidOperationException("Transaction is not active. Already committed or rolled back."); try { await _transaction.CommitAsync(); } catch (Exception ex) { // Commit failed: the underlying sqlite3 handle may still have autocommit=0. // Speculatively rollback so the pooled SqliteConnection returns clean. // Both errors are visible via [Diag-TX-LIFECYCLE] so the source is traceable. // Console.WriteLine($"[Diag-TX-LIFECYCLE] CommitAsync FAILED: {ex.GetType().Name}: {ex.Message}. Attempting speculative rollback."); Complete(committed: false); try { await _transaction.RollbackAsync(); } catch (Exception rbEx) { // Console.WriteLine($"[Diag-TX-LIFECYCLE] Speculative rollback after failed commit ALSO FAILED: {rbEx.GetType().Name}: {rbEx.Message}. Pool may receive a dirty handle (mitigated by SqliteDataSource.EnsureCleanTransactionState on next acquire)."); } IsActive = false; _onDispose(); throw; } Complete(committed: true); IsActive = false; // Clear the connection's `_currentTransaction` slot now — any // command issued between commit and dispose must NOT bind to this // (now closed) SqliteTransaction. DisposeAsync is idempotent on // _onDispose (the callback just nulls a field). _onDispose(); } /// /// Rollback all changes. /// public async Task RollbackAsync() { if (!IsActive) throw new InvalidOperationException("Transaction is not active. Already committed or rolled back."); Complete(committed: false); try { await _transaction.RollbackAsync(); } catch (Exception ex) { // Console.WriteLine($"[Diag-TX-LIFECYCLE] RollbackAsync FAILED: {ex.GetType().Name}: {ex.Message}. Pool may receive a dirty handle (mitigated by SqliteDataSource.EnsureCleanTransactionState on next acquire)."); IsActive = false; _onDispose(); throw; } IsActive = false; _onDispose(); } /// /// Dispose transaction. /// If still active - rollback automatically. /// public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; Complete(committed: false); // Auto-rollback if still active. The catch CANNOT throw (Dispose contract), // so leaks here are mitigated by SqliteDataSource.EnsureCleanTransactionState // which runs a speculative ROLLBACK on every pooled connection acquire. if (IsActive) { try { await _transaction.RollbackAsync(); } catch (Exception ex) { // Console.WriteLine($"[Diag-TX-LIFECYCLE] DisposeAsync auto-rollback FAILED: {ex.GetType().Name}: {ex.Message}. Pool poisoning mitigated by SqliteDataSource.EnsureCleanTransactionState on next acquire."); } IsActive = false; } // Disposing a broken transaction must never block the connection's cleanup callback: // _onDispose() clears _currentTransaction on the connection so it can return to the pool. // finally guarantees that even if _transaction.DisposeAsync() throws — and the exception // is NOT swallowed, it propagates so the fault stays observable. try { await _transaction.DisposeAsync(); } finally { _onDispose(); } } } } Path: redb/redb.SQLite/Data/SqliteRegexFunctions.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/Data/SqliteRegexFunctions.cs ---- using System.Text.RegularExpressions; using Microsoft.Data.Sqlite; namespace redb.SQLite.Data { /// /// Regular expressions for queries, on one connection. SQLite has none of its own - X REGEXP Y calls a user /// function that nobody registers - so the query builder translates a LINQ Regex.IsMatch or /// Regex.Replace to these functions, and the expression runs with the .NET semantics it has in memory. /// /// /// NULL in, NULL out, like the built-ins: a NULL match is neither true nor false, so a row with a NULL value is not /// selected by the predicate or by its negation. The match timeout is the process default of /// (REGEX_DEFAULT_MATCH_TIMEOUT), the same an in-memory match uses. /// /// internal static class SqliteRegexFunctions { internal static void Install(SqliteConnection connection) { connection.CreateFunction( "redb_regexp", (input, pattern) => input is null || pattern is null ? (long?)null : Regex.IsMatch(input, pattern) ? 1L : 0L, isDeterministic: true); connection.CreateFunction( "redb_regexp_i", (input, pattern) => input is null || pattern is null ? (long?)null : Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) ? 1L : 0L, isDeterministic: true); connection.CreateFunction( "redb_regexp_replace", (input, pattern, replacement) => input is null || pattern is null || replacement is null ? null : Regex.Replace(input, pattern, replacement), isDeterministic: true); } } } Path: redb/redb.SQLite/Extensions/PropertyInfoExtensions.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/Extensions/PropertyInfoExtensions.cs ---- using System.Reflection; using System.Text.Json.Serialization; using redb.Core.Attributes; namespace redb.SQLite.Extensions { /// /// Extensions for working with PropertyInfo /// internal static class PropertyInfoExtensions { /// /// Checks if property should be ignored by REDB /// /// Property to check /// true if property should be ignored public static bool ShouldIgnoreForRedb(this PropertyInfo property) { return //property.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).Length > 0 || property.GetCustomAttributes(typeof(RedbIgnoreAttribute), false).Length > 0; } } } Path: redb/redb.SQLite/Extensions/RedbServiceExtensions.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/Extensions/RedbServiceExtensions.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Security; using redb.SQLite.Providers; using redb.Core.Providers; using redb.Core.Serialization; namespace redb.SQLite.Extensions { /// /// Extension methods for unified REDB registration following EF Core AddDbContext pattern /// public static class RedbServiceExtensions { /// /// Registers REDB with configuration via lambda (main method). /// Automatically registers all necessary providers and services. /// /// Service collection /// Delegate for configuration setup /// Service collection for method chaining /// /// services.AddRedb(options => { /// options.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; /// options.EnablePropsCache = true; /// options.PropsCacheMaxSize = 50000; /// }); /// [Obsolete("Use services.AddRedb(o => o.UseSqlite(connectionString)) from redb.Core.Extensions")] public static IServiceCollection AddRedbSqlite( this IServiceCollection services, Action? configure = null) { var config = new RedbServiceConfiguration(); configure?.Invoke(config); // Validation triggers in setters! services.AddSingleton(config); // Auto-register IRedbContext if ConnectionString is provided if (!string.IsNullOrEmpty(config.ConnectionString)) { // Factory registration: the container OWNS the data source it creates and // disposes it on shutdown, releasing the connection pool (an instance // registration is never disposed by MS DI - the pool would outlive the // container and keep the database file locked). services.AddSingleton(_ => Data.SqliteDataSource.Create(config.ConnectionString, config.StringCollation != null, config.EnableLazyReferences)); services.AddScoped(sp => new Data.SqliteRedbContext(sp.GetRequiredService())); } // Register SecurityContext (required for providers) services.AddScoped(sp => AmbientSecurityContext.GetOrCreateDefault()); // Register ALL providers automatically services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // The user configuration service takes its statements from the dialect services.AddSingleton(); // Register user configuration service services.AddScoped(); services.AddScoped(); return services; } /// /// Registers REDB with configuration from appsettings.json /// /// Service collection /// Application configuration /// Section name in appsettings.json (default "RedbService") /// Service collection for method chaining /// /// In appsettings.json: /// "RedbService": { "EnablePropsCache": true, "PropsCacheMaxSize": 50000 } /// services.AddRedb(Configuration); /// [Obsolete("Use services.AddRedb(o => o.UseSqlite(connectionString)) from redb.Core.Extensions")] public static IServiceCollection AddRedbSqliteFromConfig( this IServiceCollection services, IConfiguration configuration, string sectionName = "RedbService") { var config = configuration.GetSection(sectionName).Get() ?? new RedbServiceConfiguration(); services.AddSingleton(config); // Auto-register IRedbContext if ConnectionString is provided if (!string.IsNullOrEmpty(config.ConnectionString)) { // Factory registration: the container OWNS the data source it creates and // disposes it on shutdown, releasing the connection pool (an instance // registration is never disposed by MS DI - the pool would outlive the // container and keep the database file locked). services.AddSingleton(_ => Data.SqliteDataSource.Create(config.ConnectionString, config.StringCollation != null, config.EnableLazyReferences)); services.AddScoped(sp => new Data.SqliteRedbContext(sp.GetRequiredService())); } // Register SecurityContext (required for providers) services.AddScoped(sp => AmbientSecurityContext.GetOrCreateDefault()); // Register providers services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // The user configuration service takes its statements from the dialect services.AddSingleton(); // Register user configuration service services.AddScoped(); services.AddScoped(); return services; } /// /// Registers REDB with ready configuration instance /// /// Service collection /// Ready configuration instance /// Service collection for method chaining /// /// var config = PredefinedConfigurations.Production; /// services.AddRedb(config); /// public static IServiceCollection AddRedb( this IServiceCollection services, RedbServiceConfiguration configuration) { services.AddSingleton(configuration); // Auto-register IRedbContext if ConnectionString is provided if (!string.IsNullOrEmpty(configuration.ConnectionString)) { // Factory registration: the container OWNS the data source it creates and // disposes it on shutdown, releasing the connection pool (an instance // registration is never disposed by MS DI - the pool would outlive the // container and keep the database file locked). services.AddSingleton(_ => Data.SqliteDataSource.Create(configuration.ConnectionString, configuration.StringCollation != null, configuration.EnableLazyReferences)); services.AddScoped(sp => new Data.SqliteRedbContext(sp.GetRequiredService())); } // Register SecurityContext (required for providers) services.AddScoped(sp => AmbientSecurityContext.GetOrCreateDefault()); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); return services; } } } Path: redb/redb.SQLite/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Configuration; using System; using redb.Core.Models.Configuration; namespace redb.SQLite.Extensions { /// /// Extension methods for registering RedbService in DI container. /// public static class ServiceCollectionExtensions { /// /// Register RedbService with default configuration. /// [Obsolete("Use services.AddRedb() from redb.SQLite.Extensions.RedbServiceExtensions")] public static IServiceCollection AddRedbService(this IServiceCollection services) { services.AddScoped(); services.AddScoped(); return services; } /// /// Register RedbService with configuration from IConfiguration. /// [Obsolete("Use services.AddRedb(configuration) from redb.SQLite.Extensions.RedbServiceExtensions")] public static IServiceCollection AddRedbService( this IServiceCollection services, IConfiguration configuration, string sectionName = "RedbService") { // Register configuration from appsettings.json var config = configuration.GetSection(sectionName).Get() ?? new RedbServiceConfiguration(); services.AddSingleton(config); services.AddScoped(); return services; } /// /// Register RedbService with programmatic configuration via Action. /// [Obsolete("Use services.AddRedb(options => { ... }) from redb.SQLite.Extensions.RedbServiceExtensions")] public static IServiceCollection AddRedbService( this IServiceCollection services, Action configureOptions) { var config = new RedbServiceConfiguration(); configureOptions(config); services.AddSingleton(config); services.AddScoped(); return services; } /// /// Register RedbService with programmatic configuration via Builder. /// [Obsolete("Use services.AddRedb(options => { ... }) from redb.SQLite.Extensions.RedbServiceExtensions")] public static IServiceCollection AddRedbService( this IServiceCollection services, Action configureBuilder) { var builder = new RedbServiceConfigurationBuilder(); configureBuilder(builder); var config = builder.Build(); services.AddSingleton(config); services.AddScoped(); return services; } /// /// Register RedbService with predefined profile. /// [Obsolete("Use services.AddRedb(PredefinedConfigurations.GetByName(profile)) from redb.SQLite.Extensions.RedbServiceExtensions")] public static IServiceCollection AddRedbService( this IServiceCollection services, string profileName) { var config = profileName.ToLowerInvariant() switch { "development" => PredefinedConfigurations.Development, "production" => PredefinedConfigurations.Production, "highperformance" => PredefinedConfigurations.HighPerformance, "bulkoperations" => PredefinedConfigurations.BulkOperations, "debug" => PredefinedConfigurations.Debug, "integrationtesting" => PredefinedConfigurations.IntegrationTesting, "datamigration" => PredefinedConfigurations.DataMigration, _ => throw new ArgumentException($"Unknown profile: {profileName}") }; services.AddSingleton(config); services.AddScoped(); return services; } /// /// Register RedbService with combined configuration (profile + additional settings). /// [Obsolete("Use services.AddRedb(options => { ... }) from redb.SQLite.Extensions.RedbServiceExtensions")] public static IServiceCollection AddRedbService( this IServiceCollection services, string profileName, Action additionalConfiguration) { var baseConfig = profileName.ToLowerInvariant() switch { "development" => PredefinedConfigurations.Development, "production" => PredefinedConfigurations.Production, "highperformance" => PredefinedConfigurations.HighPerformance, "bulkoperations" => PredefinedConfigurations.BulkOperations, "debug" => PredefinedConfigurations.Debug, "integrationtesting" => PredefinedConfigurations.IntegrationTesting, "datamigration" => PredefinedConfigurations.DataMigration, _ => throw new ArgumentException($"Unknown profile: {profileName}") }; var builder = new RedbServiceConfigurationBuilder(baseConfig); additionalConfiguration(builder); var finalConfig = builder.Build(); services.AddSingleton(finalConfig); services.AddScoped(); return services; } /// /// Register RedbService with configuration validation. /// [Obsolete("Use services.AddRedb(configuration) - validation now built into configuration properties")] public static IServiceCollection AddValidatedRedbService( this IServiceCollection services, IConfiguration configuration, bool throwOnValidationError = false, string sectionName = "RedbService") { var config = configuration.GetSection(sectionName).Get() ?? new RedbServiceConfiguration(); // Validate configuration var validator = new RedbServiceConfigurationValidator(); var validationResult = validator.Validate(null, config); if (!validationResult.Succeeded && throwOnValidationError) { throw new InvalidOperationException($"Configuration validation failed: {validationResult.FailureMessage}"); } services.AddSingleton(config); services.AddScoped(); return services; } /// /// Register RedbService with configuration change monitoring (hot-reload). /// [Obsolete("Use services.AddRedb(configuration) from redb.SQLite.Extensions.RedbServiceExtensions")] public static IServiceCollection AddRedbServiceWithHotReload( this IServiceCollection services, IConfiguration configuration, string sectionName = "RedbService") { // For hot-reload use IOptionsMonitor services.Configure(configuration.GetSection(sectionName)); // Register change monitoring (if available) // Configuration monitoring is deferred // services.AddRedbServiceConfigurationMonitoring(configuration); // Register RedbService with hot-reload support services.AddScoped(provider => { try { var configMonitor = provider.GetService>(); if (configMonitor != null) { // TODO: Implement hot-reload support in RedbService var config = configMonitor.CurrentValue; return new RedbService(provider); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Config monitor setup failed: {ex.Message}"); } // Fallback to regular configuration return new RedbService(provider); }); return services; } } } Path: redb/redb.SQLite/Extensions/SqliteOptionsExtensions.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/Extensions/SqliteOptionsExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using redb.Core; using redb.Core.Data; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Security; using redb.Core.Providers; using redb.Core.Query; using redb.Core.Serialization; using redb.Core.Services; using redb.SQLite.Data; using redb.SQLite.Providers; using redb.SQLite.Sql; namespace redb.SQLite.Extensions; /// /// SQLite provider extensions for RedbOptionsBuilder. /// public static class SqliteOptionsExtensions { /// /// Configures REDB to use SQLite as the database provider. /// For Pro version, use AddRedbPro() from redb.SQLite.Pro package. /// /// The options builder. /// SQLite connection string. If null, must be set in Configure(). /// The options builder for chaining. /// /// services.AddRedb(options => options /// .UseSqlite("Host=localhost;Database=mydb;Username=user;Password=pass") /// .Configure(c => c.EnablePropsCache = true)); /// public static RedbOptionsBuilder UseSqlite( this RedbOptionsBuilder builder, string? connectionString = null) { var infrastructure = (IRedbOptionsBuilderInfrastructure)builder; if (!string.IsNullOrEmpty(connectionString)) infrastructure.Configuration.ConnectionString = connectionString; infrastructure.SetProviderRegistration((services, config, isPro) => { if (isPro) throw new InvalidOperationException( "Pro version requires redb.SQLite.Pro package. Use AddRedbPro() from redb.SQLite.Pro.Extensions."); RegisterOpenSourceServices(services, config); }); return builder; } /// /// Registers OpenSource SQLite services. /// Called by UseSqlite() and can be used by Pro version as fallback. /// public static void RegisterOpenSourceServices(IServiceCollection services, RedbServiceConfiguration config) { // Free tier loads the native SQLite extension that hosts the server-side SQL // functions (get_object_json, pvt_build_*_sql, ...). Honour an explicit override // (REDB_SQLITE_EXTENSION env / manual NativeExtensionPath) first; otherwise // auto-locate the binary shipped in this package next to the running app. // Pro locates it too: it reads objects in C#, but the JSON of an object is get_object_json. Data.SqliteDataSource.NativeExtensionPath ??= Data.SqliteDataSource.LocatePackagedExtension(); // DataSource and Context if (!string.IsNullOrEmpty(config.ConnectionString)) { // Factory registration: the container OWNS the data source it creates and disposes it // on shutdown, releasing the connection pool (an instance registration is never // disposed by MS DI - the pool would outlive the container and keep the file locked). services.AddSingleton(_ => Data.SqliteDataSource.Create(config.ConnectionString, config.StringCollation != null, config.EnableLazyReferences)); services.AddScoped(sp => new SqliteRedbContext(sp.GetRequiredService())); } // Security services.AddScoped(sp => AmbientSecurityContext.GetOrCreateDefault()); // SQL Dialect services.AddSingleton(); // Core providers services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // Query providers services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(sp => sp.GetRequiredService().ListProvider); // one per scope: the service's own services.AddScoped(); // Background deletion service (singleton + hosted service) services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); services.AddHostedService(sp => sp.GetRequiredService()); // Main service services.AddScoped(); } } Path: redb/redb.SQLite/Providers/LazyPropsLoader.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/Providers/LazyPropsLoader.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using redb.Core.Caching; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Exceptions; using redb.Core.Models.Configuration; using redb.Core.Providers; using redb.Core.Query; using redb.Core.Serialization; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers { /// /// OpenSource implementation of lazy Props loading for SQLite. /// Uses get_object_json SQL function for simple and efficient loading. /// Pro version uses PropsMaterializer with PVT optimizations. /// public class LazyPropsLoader : ILazyPropsLoader { // get_object_json depth the batch uses when the caller names none (query pages, tree loads). private const int DefaultBatchDepth = 10; private readonly ConcurrentDictionary _loadingInProgress = new(); private readonly IRedbContext _context; private readonly IRedbObjectSerializer _serializer; private readonly RedbServiceConfiguration _config; private readonly ISqlDialect _sql; private readonly GlobalPropsCache _propsCache; /// public string? CacheDomain => _propsCache.Domain; /// public redb.Core.Data.IRedbContext? ScopeContext => _context; private readonly ILogger? _logger; public LazyPropsLoader( IRedbContext context, ISchemeSyncProvider schemeSync, IRedbObjectSerializer serializer, RedbServiceConfiguration config, IListProvider? listProvider = null, ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _config = config ?? throw new ArgumentNullException(nameof(config)); _propsCache = schemeSync?.PropsCache ?? throw new ArgumentNullException(nameof(schemeSync)); _sql = new Sql.SqliteDialect(); _logger = logger; } /// /// Synchronous Props loading (for getter). /// public TProps? LoadProps(long objectId, long schemeId) where TProps : class, new() { if (_config.LazyReferenceAccess == LazyReferenceAccessMode.Throw) throw new RedbSynchronousLazyLoadException(objectId, schemeId); // Blocking by design (the getter is synchronous), but never on the caller's context: the load // runs on the thread pool, so a host with a SynchronizationContext (Blazor Server, WPF, MAUI) // waits instead of deadlocking on its own continuations (review). The caller blocks meanwhile, // so the context stays single-threaded; ExecutionContext (the AsyncLocal scope) flows in. return Task.Run(() => LoadPropsAsync(objectId, schemeId)).GetAwaiter().GetResult(); } /// /// Async Props loading for single object via get_object_json. /// Simple and efficient for OpenSource version. /// public async Task LoadPropsAsync(long objectId, long schemeId, CancellationToken cancellationToken = default) where TProps : class, new() { if (_context.IsDisposed) throw new RedbLazyLoadScopeEndedException(objectId, schemeId); // 1. Check cache first if (_config.EnablePropsCache && _propsCache.Instance != null) { var hashes = await _context.QueryScalarListAsync( _sql.LazyLoader_SelectObjectHash(), new object[] { objectId }, cancellationToken); if (hashes.Count > 0) { var hash = hashes[0]; var cached = _propsCache.Get(objectId, hash); if (cached != null) { var propsFromCache = cached.GetPropsDirectly(); if (propsFromCache != null) return propsFromCache; } } } // 2. Load via get_object_json — ONE query, simple! var jsonResults = await _context.QueryScalarListAsync( _sql.LazyLoader_GetObjectJson(), new object[] { objectId, 1 }, cancellationToken); // V4 (L.3): the reloaded object's own references are stubs again (L.3): the reloaded object's own references are stubs again var json = jsonResults.FirstOrDefault(); if (string.IsNullOrEmpty(json)) return null; // V4 (L.3): a reference whose target left for the trash reloads as null Props, not an exception // 3. Deserialize var obj = _serializer.Deserialize(json); redb.Core.Utils.LazyReferenceInstaller.Install(obj, this); // V4 (L.3): nested stubs get their loader // 4. Cache the result if (_config.EnablePropsCache && obj.hash.HasValue) { redb.Core.Caching.CachePublication.AfterCommit(_context, () => _propsCache.Set(obj)); } // Raw access instead of the getter: for an object with properties:null (values wiped by a // race, or a bare object) Install has attached the loader to the root itself, so the Props // getter would start a new load - endless recursion eating a pool thread per turn. return obj.GetPropsDirectly(); } /// /// BULK Props loading for multiple objects via get_object_json batch. /// Uses unnest for efficient batch loading. /// public async Task LoadPropsForManyAsync(List> objects, int? propsDepth, CancellationToken cancellationToken = default) where TProps : class, new() { var depth = propsDepth ?? DefaultBatchDepth; if (objects.Count == 0) return; var requested = objects; // Protection from infinite recursion var uniqueIds = objects.Select(o => o.id).Distinct().ToList(); var alreadyLoading = uniqueIds.Where(id => _loadingInProgress.ContainsKey(id)).ToList(); if (alreadyLoading.Any()) { objects = objects.Where(o => !alreadyLoading.Contains(o.id)).ToList(); uniqueIds = uniqueIds.Except(alreadyLoading).ToList(); if (objects.Count == 0) return; } foreach (var id in uniqueIds) _loadingInProgress.TryAdd(id, 0); try { HashSet needToLoad; Dictionary> fromCache; // 1. Check cache if (_config.EnablePropsCache && _propsCache.Instance != null) { var objectsData = objects .Where(o => o.hash.HasValue) .Select(o => (o.id, o.hash!.Value)) .ToList(); needToLoad = _propsCache.FilterNeedToLoad(objectsData, out fromCache); // An object without a hash cannot be matched by the cache: it loads from the database, never dropped. foreach (var obj in objects) if (!obj.hash.HasValue) needToLoad.Add(obj.id); foreach (var obj in objects) { if (fromCache.TryGetValue(obj.id, out var cachedObj)) { obj.Props = cachedObj.Props; obj._propsLoaded = true; obj._lazyLoader = null; } } } else { needToLoad = objects.Select(o => o.id).ToHashSet(); fromCache = new Dictionary>(); } // 2. Load from DB via get_object_json batch if (needToLoad.Count > 0) { var idsToLoad = needToLoad.ToArray(); // Batch query via unnest + get_object_json var results = await _context.QueryAsync( _sql.LazyLoader_GetObjectJsonBatch(), new object[] { idsToLoad, depth }, cancellationToken); var jsonById = results.ToDictionary(r => r.Id, r => r.JsonData); foreach (var obj in objects.Where(o => needToLoad.Contains(o.id))) { if (jsonById.TryGetValue(obj.id, out var json) && !string.IsNullOrEmpty(json)) { try { var loaded = _serializer.Deserialize(json); // Copy Props from loaded object obj.Props = loaded.Props; obj._propsLoaded = true; obj._lazyLoader = null; redb.Core.Utils.LazyReferenceInstaller.Install(obj, this); // V4 (L.3) // Cache if (_config.EnablePropsCache && obj.hash.HasValue) { redb.Core.Caching.CachePublication.AfterCommit(_context, () => _propsCache.Set(obj)); } } catch (Exception) { // Skip failed deserialization, leave Props as default } } } // get_object_json is null only for an object that is gone: deleted after the query found it. It // leaves the list instead of being handed out without Props; the page is shorter by it. requested.RemoveAll(o => needToLoad.Contains(o.id) && !(jsonById.TryGetValue(o.id, out var j) && !string.IsNullOrEmpty(j))); } } finally { foreach (var id in uniqueIds) _loadingInProgress.TryRemove(id, out _); } } /// /// BULK Props loading with projection filter (for Select projections). /// In OpenSource version, projection is ignored — full objects loaded via get_object_json. /// public Task LoadPropsForManyAsync( List> objects, HashSet? projectedStructureIds, CancellationToken cancellationToken = default) where TProps : class, new() { // OpenSource: ignore projection, load full objects return LoadPropsForManyAsync(objects, propsDepth: null); } /// /// BULK Props loading at the default batch depth; the depth form above is the core. /// A stub reload passes 1 (transitive laziness), query pages their PropsDepth. /// public Task LoadPropsForManyAsync(List> objects, CancellationToken cancellationToken = default) where TProps : class, new() => LoadPropsForManyAsync(objects, propsDepth: null); /// /// BULK Props loading with projection filter and custom depth. /// In OpenSource version the projection is ignored (full objects); the depth is honoured. /// public Task LoadPropsForManyAsync( List> objects, HashSet? projectedStructureIds, int? propsDepth, CancellationToken cancellationToken = default) where TProps : class, new() { // OpenSource: ignore projection; the depth is honoured return LoadPropsForManyAsync(objects, propsDepth); } /// /// BULK loading for polymorphic objects (different schemes). /// Each object is deserialized to its own type based on scheme_id. /// public async Task LoadPropsForManyPolymorphicAsync(List objects, CancellationToken cancellationToken = default) { if (objects.Count == 0) return; var uniqueIds = objects.Select(o => o.Id).Distinct().ToList(); var alreadyLoading = uniqueIds.Where(id => _loadingInProgress.ContainsKey(id)).ToList(); if (alreadyLoading.Any()) { objects = objects.Where(o => !alreadyLoading.Contains(o.Id)).ToList(); uniqueIds = uniqueIds.Except(alreadyLoading).ToList(); if (objects.Count == 0) return; } foreach (var id in uniqueIds) _loadingInProgress.TryAdd(id, 0); try { var idsToLoad = uniqueIds.ToArray(); var depth = DefaultBatchDepth; // Batch query var results = await _context.QueryAsync( _sql.LazyLoader_GetObjectJsonBatch(), new object[] { idsToLoad, depth }, cancellationToken); var jsonById = results.ToDictionary(r => r.Id, r => r.JsonData); foreach (var obj in objects) { if (jsonById.TryGetValue(obj.Id, out var json) && !string.IsNullOrEmpty(json)) { try { // Get Props type from object's generic parameter (the type or its RedbObject base) var objType = obj.GetType(); var genericObjType = redb.Core.Utils.RedbObjectTypes.GenericOf(objType); if (genericObjType != null) { var propsType = genericObjType.GetGenericArguments()[0]; var loaded = _serializer.DeserializeDynamic(json, propsType); // Copy Props via reflection var propsProperty = objType.GetProperty("Props"); var loadedProps = loaded.GetType().GetProperty("Props")?.GetValue(loaded); propsProperty?.SetValue(obj, loadedProps); // Mark as loaded var loadedField = objType.GetField("_propsLoaded"); loadedField?.SetValue(obj, true); var loaderField = objType.GetField("_lazyLoader"); loaderField?.SetValue(obj, null); } } catch (Exception) { // Skip failed deserialization } } } } finally { foreach (var id in uniqueIds) _loadingInProgress.TryRemove(id, out _); } } } /// /// DTO for batch get_object_json results. /// internal class ObjectJsonResult { public long Id { get; set; } public string JsonData { get; set; } = string.Empty; } } Path: redb/redb.SQLite/Providers/SqliteListProvider.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/Providers/SqliteListProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Providers; using redb.Core.Providers.Base; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers { /// /// SQLite implementation of IListProvider. /// Inherits all logic from ListProviderBase, provides SQLite-specific SQL via SqliteDialect. /// public class SqliteListProvider : ListProviderBase { /// /// Creates SQLite list provider with default SqliteDialect. /// /// Database context for executing queries /// Service configuration /// Scheme sync provider (for accessing domain-bound caches) /// Optional logger for diagnostics public SqliteListProvider( IRedbContext context, RedbServiceConfiguration configuration, ISchemeSyncProvider schemeSync, ILogger? logger = null) : base(context, configuration, new SqliteDialect(), schemeSync, logger) { } } } Path: redb/redb.SQLite/Providers/SqliteMaintenanceProvider.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/Providers/SqliteMaintenanceProvider.cs ---- using redb.Core.Data; using redb.Core.Providers.Base; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers { /// /// SQLite maintenance provider. All logic lives in the base; this class only wires the /// dialect in (same shape as SqliteValidationProvider). /// public class SqliteMaintenanceProvider : MaintenanceProviderBase { public SqliteMaintenanceProvider(IRedbContext context, int analysisLimit, ILogger? logger = null) : base(context, new SqliteDialect(), analysisLimit, logger) { } } } Path: redb/redb.SQLite/Providers/SqliteObjectStorageProvider.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/Providers/SqliteObjectStorageProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Providers; using redb.Core.Providers.Base; using redb.Core.Query; using redb.Core.Serialization; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers { /// /// SQLite implementation of ObjectStorageProvider. /// Inherits all business logic from ObjectStorageProviderBase, provides SQLite-specific LazyPropsLoader. /// public class SqliteObjectStorageProvider : ObjectStorageProviderBase { /// /// Creates a new SqliteObjectStorageProvider instance. /// public SqliteObjectStorageProvider( IRedbContext context, IRedbObjectSerializer serializer, IPermissionProvider permissionProvider, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration configuration, IListProvider? listProvider = null, ILogger? logger = null, redb.Core.Interception.RedbSaveInterceptorPipeline? saveInterceptors = null) : base(context, serializer, permissionProvider, securityContext, schemeSync, configuration, new SqliteDialect(), listProvider, logger, saveInterceptors) { } /// /// Creates SQLite-specific LazyPropsLoader for lazy property loading. /// protected override ILazyPropsLoader CreateLazyPropsLoader() { return new LazyPropsLoader(Context, SchemeSyncProvider, Serializer, Configuration, ListProvider, Logger); } } } Path: redb/redb.SQLite/Providers/SqlitePermissionProvider.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/Providers/SqlitePermissionProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers; /// /// SQLite implementation of permission provider. /// Inherits all business logic from PermissionProviderBase. /// Only provides SQLite-specific SQL dialect. /// /// IMPORTANT: Uses SQLite function get_user_permissions_for_object() /// for efficient recursive permission calculation. /// /// Usage: /// services.AddScoped<IPermissionProvider, SqlitePermissionProvider>(); /// public class SqlitePermissionProvider : PermissionProviderBase { /// /// Creates a new SQLite permission provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics public SqlitePermissionProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null) : base(context, securityContext, new SqliteDialect(), logger) { } // All business logic is inherited from PermissionProviderBase. // SQLite-specific SQL is provided by SqliteDialect. // The critical method Permissions_GetEffectiveForObject() uses // SQLite function get_user_permissions_for_object() for efficient // recursive permission calculation with inheritance. } Path: redb/redb.SQLite/Providers/SqliteQueryableProvider.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/Providers/SqliteQueryableProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Security; using redb.Core.Providers; using redb.Core.Providers.Base; using redb.Core.Query; using redb.Core.Query.Base; using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; using redb.SQLite.Query; using redb.Core.Query.Parsing; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; namespace redb.SQLite.Providers { /// /// SQLite implementation of IQueryableProvider. /// Inherits all logic from QueryableProviderBase, provides SQLite-specific query providers. /// public class SqliteQueryableProvider : QueryableProviderBase { public SqliteQueryableProvider( IRedbContext context, IRedbObjectSerializer serializer, ISchemeSyncProvider schemeSync, IRedbSecurityContext securityContext, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, string? cacheDomain = null, ILogger? logger = null) : base(context, serializer, schemeSync, securityContext, lazyPropsLoader, configuration, cacheDomain, logger) { } protected override IRedbQueryable CreateQuery(long schemeId, long? userId, bool checkPermissions) { var queryProvider = new SqliteQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, SchemeSync); return queryProvider.CreateQuery(schemeId, userId, checkPermissions); } protected override IRedbQueryable CreateTreeQuery( long schemeId, long? userId, bool checkPermissions, long? rootObjectId, int? maxDepth) { var treeQueryProvider = new SqliteTreeQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, cacheDomain: CacheDomain, schemeSync: SchemeSync); return treeQueryProvider.CreateTreeQuery(schemeId, userId, checkPermissions, rootObjectId, maxDepth); } protected override IRedbQueryable CreateEmptyTreeQuery(long schemeId, long? userId, bool checkPermissions) { var treeQueryProvider = new SqliteTreeQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, cacheDomain: CacheDomain, schemeSync: SchemeSync); var emptyTreeQuery = treeQueryProvider.CreateTreeQuery(schemeId, userId, checkPermissions); return emptyTreeQuery.Where(x => false); } protected override IRedbQueryable CreateMultiRootTreeQuery( long schemeId, long? userId, bool checkPermissions, List rootObjects, int? maxDepth) { var treeQueryProvider = new SqliteTreeQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, cacheDomain: CacheDomain, schemeSync: SchemeSync); var parentIds = rootObjects.Select(obj => obj.Id).ToArray(); var multiRootContext = new TreeQueryContext(schemeId, userId, checkPermissions, null, maxDepth) { ParentIds = parentIds }; var filterParser = new FilterExpressionParser(); var orderingParser = new OrderingExpressionParser(); return new SqliteTreeQueryable(treeQueryProvider, multiRootContext, filterParser, orderingParser); } protected override IRedbQueryable CreateMultiRootTreeQueryByIds( long schemeId, long? userId, bool checkPermissions, IEnumerable rootObjectIds, int? maxDepth) { var treeQueryProvider = new SqliteTreeQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, cacheDomain: CacheDomain, schemeSync: SchemeSync); var parentIds = rootObjectIds.ToArray(); var multiRootContext = new TreeQueryContext(schemeId, userId, checkPermissions, null, maxDepth) { ParentIds = parentIds }; var filterParser = new FilterExpressionParser(); var orderingParser = new OrderingExpressionParser(); return new SqliteTreeQueryable(treeQueryProvider, multiRootContext, filterParser, orderingParser); } } } Path: redb/redb.SQLite/Providers/SqliteRoleProvider.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/Providers/SqliteRoleProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers; /// /// SQLite implementation of role provider. /// Inherits all business logic from RoleProviderBase. /// Only provides SQLite-specific SQL dialect. /// /// Usage: /// services.AddScoped<IRoleProvider, SqliteRoleProvider>(); /// public class SqliteRoleProvider : RoleProviderBase { /// /// Creates a new SQLite role provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics public SqliteRoleProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null) : base(context, securityContext, new SqliteDialect(), logger) { } // All business logic is inherited from RoleProviderBase. // SQLite-specific SQL is provided by SqliteDialect. // Override virtual methods here for SQLite-specific optimizations if needed. // For example, using RETURNING clause for insert operations. } Path: redb/redb.SQLite/Providers/SqliteSchemeSyncProvider.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/Providers/SqliteSchemeSyncProvider.cs ---- using System.Text.Json; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Providers; using redb.Core.Providers.Base; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers; /// /// SQLite implementation of scheme synchronization provider. /// Inherits all logic from SchemeSyncProviderBase, provides SQLite-specific SQL via SqliteDialect. /// public class SqliteSchemeSyncProvider : SchemeSyncProviderBase { /// /// Creates SQLite scheme sync provider with default SqliteDialect. /// public SqliteSchemeSyncProvider( IRedbContext context, RedbServiceConfiguration? configuration = null, string? cacheDomain = null, ILogger? logger = null) : base(context, new SqliteDialect(), configuration, cacheDomain, logger) { } /// /// Gets structure tree as JsonElement (for API compatibility). /// public new async Task GetStructureTreeJsonAsync(long schemeId) { var result = await base.GetStructureTreeJsonAsync(schemeId); if (string.IsNullOrEmpty(result)) return JsonSerializer.SerializeToElement("[]"); return JsonSerializer.SerializeToElement(result); } /// /// SQLite type migration for an existing structure whose property type changed. The Postgres/MSSQL /// path runs a stored function (migrate_structure_type); SQLite has no stored functions, so the /// equivalent runs here as plain SQL. Fixes GitHub #5, where the base path emitted /// SELECT * FROM migrate_structure_type(...) and failed with /// no such table: migrate_structure_type, so InitializeAsync never came up. /// public override async Task MigrateStructureTypeAsync( long structureId, string oldTypeName, string newTypeName, bool dryRun = false, CancellationToken cancellationToken = default) { var source = GetValueColumn(oldTypeName); var target = GetValueColumn(newTypeName); // No scalar value-column mapping on one side (e.g. a nested Class property): there is nothing to // move in _values here; let the caller update _id_type. Mirrors the PG function returning a benign // result rather than throwing. if (source == null || target == null) return new TypeMigrationResult { Errors = $"No value-column mapping for '{oldTypeName}' -> '{newTypeName}'" }; // Same storage column (Int -> Long both _Long; DateTime -> DateOnly both _DateTimeOffset; // String -> MimeType both _String): values already sit in the right column, only _id_type changes. if (string.Equals(source, target, StringComparison.OrdinalIgnoreCase)) return new TypeMigrationResult(); // Rows that actually hold a value under the old column for this structure. var affected = (int)(await Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = $1 AND {source} IS NOT NULL", new object[] { structureId }, cancellationToken) ?? 0); if (affected == 0 || dryRun) return new TypeMigrationResult { AffectedRows = affected }; // There IS data to move across storage columns. Which of those moves is safe is decided by an // explicit matrix, mirroring the pairs PostgreSQL's migrate_structure_type() supports. A blanket // refusal used to stand here; it was written when the alternative was a cryptic "no such table" // (GitHub #5) and it swept up conversions that are trivially safe — Boolean and Long are both // INTEGER columns, so bool -> int is a plain copy. var conversion = BuildConversion(source, target); if (conversion == null) { // Reported as a result rather than thrown, which is how PostgreSQL and MSSQL report the same // refusal. The scheme-sync path turns any failing result into RedbTypeMigrationException, so // the caller that matters still gets an exception — the same one on all three providers. return new TypeMigrationResult { AffectedRows = affected, SuccessCount = 0, ErrorCount = affected, Errors = $"SQLite: cannot auto-migrate structure {structureId} from '{oldTypeName}' to '{newTypeName}' — " + $"{affected} value(s) live in column {source} and moving them to {target} is not a safe automatic " + $"conversion. Remove and re-add the property (dropping its values), or migrate the data manually " + $"before changing the type." }; } // Rows the conversion can actually take. For text sources this is narrower than `affected`: // an unparseable string must stay where it is rather than become CAST's silent 0. var convertible = (int)(await Context.ExecuteScalarAsync( $"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_structure = $1 " + $"AND {source} IS NOT NULL AND {conversion.Guard}", new object[] { structureId }, cancellationToken) ?? 0); await Context.ExecuteAsync( $"UPDATE _values SET {target} = {conversion.Expression}, {source} = NULL, _unique = NULL " + $"WHERE _id_structure = $1 AND {source} IS NOT NULL AND {conversion.Guard}", new object[] { structureId }, cancellationToken); return new TypeMigrationResult { AffectedRows = affected, SuccessCount = convertible, ErrorCount = affected - convertible, Errors = convertible == affected ? null : $"SQLite: {affected - convertible} of {affected} value(s) in {source} could not be read as " + $"'{newTypeName}' and were left in place; {convertible} were moved to {target}." }; } /// A conversion: the value expression for the target column, and the rows it applies to. private sealed record Conversion(string Expression, string Guard); /// /// Cross-column conversions SQLite performs, keyed by storage column pair. Mirrors the matrix in /// PostgreSQL's migrate_structure_type() so a type change behaves the same on every provider. /// /// /// Guards are not optional. SQLite has affinity rather than types: CAST('abc' AS INTEGER) /// is 0, not an error, so an unguarded move would turn unreadable text into a plausible-looking /// number. Each text source therefore carries a predicate selecting only the rows that survive a /// round-trip, and the rest are left in place and reported — the same shape as PostgreSQL's regex. /// /// /// /// Known divergence from PostgreSQL, deliberate. PostgreSQL guards with ~ '^-?[0-9]+$', /// which accepts '007' and stores 7. The round-trip check here rejects it, because SQLite has /// no regex operator without registering one on every connection. The difference only ever moves a /// row into the "left behind and reported" group, never into the "silently changed" one, so the /// stricter side is the safe side; registering a regexp function for exact parity was judged /// not worth a per-connection callback for leading zeros. /// /// /// /// Dates need no special handling: _DateTimeOffset holds a UTC Julian day as REAL precisely so /// that SQLite's own strftime / julianday read it directly (see SqliteJulian). /// /// private static Conversion? BuildConversion(string source, string target) => (source, target) switch { // --- numeric and boolean: same storage domain, nothing can fail --- ("_Boolean", "_Long") => new("_Boolean", "1=1"), ("_Long", "_Boolean") => new("CASE WHEN _Long <> 0 THEN 1 ELSE 0 END", "1=1"), ("_Long", "_Double") => new("CAST(_Long AS REAL)", "1=1"), ("_Long", "_Numeric") => new("CAST(_Long AS REAL)", "1=1"), ("_Double", "_Long") => new("CAST(_Double AS INTEGER)", "1=1"), ("_Double", "_Numeric") => new("_Double", "1=1"), ("_Numeric", "_Long") => new("CAST(_Numeric AS INTEGER)", "1=1"), ("_Numeric", "_Double") => new("_Numeric", "1=1"), // --- to text: always representable --- ("_Boolean", "_String") => new("CASE WHEN _Boolean <> 0 THEN 'true' ELSE 'false' END", "1=1"), ("_Long", "_String") => new("CAST(_Long AS TEXT)", "1=1"), ("_Double", "_String") => new("CAST(_Double AS TEXT)", "1=1"), ("_Numeric", "_String") => new("CAST(_Numeric AS TEXT)", "1=1"), ("_Guid", "_String") => new("_Guid", "1=1"), // --- temporal: Julian REAL is what SQLite's own date functions consume --- ("_DateTimeOffset", "_String") => new("strftime('%Y-%m-%dT%H:%M:%fZ', _DateTimeOffset)", "1=1"), ("_DateTimeOffset", "_Long") => new("CAST(strftime('%s', _DateTimeOffset) AS INTEGER)", "1=1"), ("_Long", "_DateTimeOffset") => new("julianday(_Long, 'unixepoch')", "1=1"), // --- from text: only rows that read back unchanged --- ("_String", "_Long") => new( "CAST(_String AS INTEGER)", "CAST(CAST(_String AS INTEGER) AS TEXT) = _String"), ("_String", "_Double") => new( "CAST(_String AS REAL)", "CAST(CAST(_String AS REAL) AS TEXT) = _String OR CAST(CAST(_String AS INTEGER) AS TEXT) = _String"), ("_String", "_Numeric") => new( "CAST(_String AS REAL)", "CAST(CAST(_String AS REAL) AS TEXT) = _String OR CAST(CAST(_String AS INTEGER) AS TEXT) = _String"), ("_String", "_Boolean") => new( "CASE WHEN lower(_String) IN ('true','t','1','yes','y') THEN 1 ELSE 0 END", "lower(_String) IN ('true','t','1','yes','y','false','f','0','no','n')"), ("_String", "_Guid") => new( "_String", "_String GLOB '[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-" + "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-" + "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]" + "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]'"), ("_String", "_DateTimeOffset") => new( "julianday(_String)", "julianday(_String) IS NOT NULL"), _ => null }; /// Maps a REDB type name to its _values storage column (SQLite), or null for non-scalar types. private static string? GetValueColumn(string? typeName) => typeName?.Trim().ToLowerInvariant() switch { "string" or "text" or "mimetype" or "filepath" or "filename" => "_String", "long" or "int" or "short" or "byte" or "timespan" => "_Long", "double" or "float" => "_Double", "boolean" => "_Boolean", "datetime" or "datetimeoffset" or "dateonly" or "timeonly" => "_DateTimeOffset", "guid" => "_Guid", "bytearray" => "_ByteArray", "numeric" => "_Numeric", "listitem" => "_ListItem", "object" => "_Object", _ => null }; } Path: redb/redb.SQLite/Providers/SqliteTreeProvider.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/Providers/SqliteTreeProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Providers; using redb.Core.Providers.Base; using redb.Core.Serialization; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers; /// /// SQLite implementation of tree provider. /// Inherits all logic from TreeProviderBase, provides SQLite-specific SQL via SqliteDialect. /// public class SqliteTreeProvider : TreeProviderBase { /// /// Creates SQLite tree provider with default SqliteDialect. /// public SqliteTreeProvider( IRedbContext context, IObjectStorageProvider objectStorage, IPermissionProvider permissionProvider, IRedbObjectSerializer serializer, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSyncProvider, RedbServiceConfiguration? configuration = null, ILogger? logger = null, redb.Core.Interception.RedbSaveInterceptorPipeline? saveInterceptors = null) : base( context, objectStorage, permissionProvider, serializer, securityContext, schemeSyncProvider, new SqliteDialect(), configuration, logger, saveInterceptors) { } } Path: redb/redb.SQLite/Providers/SqliteUserProvider.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/Providers/SqliteUserProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.Core.Security; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers; /// /// SQLite implementation of user provider. /// Inherits all business logic from UserProviderBase. /// Only provides SQLite-specific SQL dialect and password hasher. /// /// Usage: /// services.AddScoped<IUserProvider, SqliteUserProvider>(); /// public class SqliteUserProvider : UserProviderBase { /// /// Creates a new SQLite user provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics public SqliteUserProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null) : base(context, securityContext, new SqliteDialect(), new BcryptPasswordHasher(), logger) { } /// /// Creates a new SQLite user provider with custom password hasher. /// /// Database context for executing queries /// Security context for authorization /// Custom password hasher implementation /// Optional logger for diagnostics public SqliteUserProvider( IRedbContext context, IRedbSecurityContext securityContext, IPasswordHasher passwordHasher, ILogger? logger = null) : base(context, securityContext, new SqliteDialect(), passwordHasher, logger) { } // All business logic is inherited from UserProviderBase. // SQLite-specific SQL is provided by SqliteDialect. // Password hashing is provided by IPasswordHasher - bcrypt by default (SimplePasswordHasher is // only the legacy format, and BcryptPasswordHasher.VerifyPassword still accepts it). } Path: redb/redb.SQLite/Providers/SqliteValidationProvider.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/Providers/SqliteValidationProvider.cs ---- using redb.Core.Data; using redb.Core.Providers.Base; using redb.SQLite.Sql; using Microsoft.Extensions.Logging; namespace redb.SQLite.Providers { /// /// SQLite implementation of validation provider. /// Inherits common logic from ValidationProviderBase. /// public class SqliteValidationProvider : ValidationProviderBase { /// /// Creates SQLite validation provider. /// /// Database context for executing queries /// Optional logger for diagnostics public SqliteValidationProvider(IRedbContext context, ILogger? logger = null) : base(context, new SqliteDialect(), logger) { } } } Path: redb/redb.SQLite/Query/SqliteQueryProvider.Aggregation.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/Query/SqliteQueryProvider.Aggregation.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Core.Query.QueryExpressions; namespace redb.SQLite.Query; /// /// PVT-backed terminal aggregations for free SQLite. Generates the /// aggregate SQL via the server-side compiler pvt_build_aggregate_sql /// (free PVT v2 module) and executes the produced statement client-side, /// wrapping the single result row with row_to_json to materialize /// in a single round-trip after the build step. /// /// Overrides the FilterExpression-typed virtual methods on the base provider. /// Legacy facet-JSON overloads stay on the base type for dialects without /// the PVT module (e.g. MSSql). /// public partial class SqliteQueryProvider { /// /// Single-aggregate path. Delegates to /// with a one-element request list and extracts the scalar value. /// public override async Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, FilterExpression? filter, CancellationToken cancellationToken = default) { var request = new AggregateRequest { FieldPath = fieldPath ?? string.Empty, Function = function, Alias = "value" }; var batch = await ExecuteAggregateBatchAsync(schemeId, new[] { request }, filter); if (!batch.Values.TryGetValue("value", out var raw) || raw is null) return null; return raw switch { decimal d => d, double dbl => redb.Core.Utils.RedbDecimal.FromDouble(dbl), long l => l, int i => i, _ => Convert.ToDecimal(raw, CultureInfo.InvariantCulture) }; } /// /// Batch aggregate path: builds aggregations JSON, asks /// pvt_build_aggregate_sql to compile the inner SQL, then executes /// it through row_to_json to capture every alias in one row. /// public override Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, FilterExpression? filter, CancellationToken cancellationToken = default) { var facetFilters = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return ExecuteAggregateBatchInternalAsync(schemeId, requests, facetFilters); } /// /// Batch aggregate path with pre-built facet-JSON filter. Same PVT pipeline /// as the overload — overriding the base /// virtual ensures custom-projection callers (RedbQueryable.AggregateAsync) /// hit the v2-pvt module instead of the deprecated aggregate_batch /// SQL function (now removed from PG dialect). /// public override Task ExecuteAggregateBatchAsync( long schemeId, IEnumerable requests, string? filterJson = null, CancellationToken cancellationToken = default) { return ExecuteAggregateBatchInternalAsync(schemeId, requests, filterJson); } internal async Task ExecuteAggregateBatchInternalAsync( long schemeId, IEnumerable requests, string? filterJson, CancellationToken cancellationToken = default) { var list = requests?.ToList() ?? throw new ArgumentNullException(nameof(requests)); if (list.Count == 0) return new AggregateResult(); var innerSql = await BuildAggregateSqlAsync(schemeId, list, filterJson, cancellationToken); // SQLite has no row_to_json: execute the (fully-literal) inner SQL and // serialize its single result row to a JSON object in C#. var jsonRow = await FirstRowAsJsonAsync(innerSql); var result = new AggregateResult(); if (!string.IsNullOrEmpty(jsonRow)) { using var doc = JsonDocument.Parse(jsonRow); foreach (var prop in doc.RootElement.EnumerateObject()) { result.Values[prop.Name] = ConvertJsonValue(prop.Value); } } return result; } /// /// SQL preview of an AggregateAsync selector: the aggregate statement pvt_build_aggregate_sql compiles for the /// same requests and filter as the execution, which runs it as it is. The base implementation asked for /// aggregate_batch_preview, a function of the removed legacy module. /// public override async Task GetAggregateSqlPreviewAsync( QueryContext context, Expression, TResult>> selector, CancellationToken cancellationToken = default) { var requests = ParseAggregateRequests(selector); if (requests.Count == 0) return "-- No aggregations specified"; var facetFilters = context.Filter is null ? null : _facetBuilder.BuildFacetFilters(context.Filter); return await BuildAggregateSqlAsync(context.SchemeId, requests, facetFilters, cancellationToken); } /// The aggregate statement pvt_build_aggregate_sql compiles for the requests; it binds no parameters. private async Task BuildAggregateSqlAsync( long schemeId, IList requests, string? filterJson, CancellationToken cancellationToken) { var aggregationsJson = BuildPvtAggregationsJson(requests); object filterParam = string.IsNullOrEmpty(filterJson) || filterJson == "{}" || filterJson == "null" ? DBNull.Value : (object)filterJson!; // SQLite arg list mirrors PG positionally but without ::type casts (SQLite // chokes on "::") and with 1/1 for the include_seed/polymorphic booleans. var invocation = "SELECT pvt_build_aggregate_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, 'flat', NULL, NULL, 1, 1) AS \"Value\""; _logger?.LogDebug("PVT Aggregate Build: SchemeId={SchemeId}, Aggs={Aggs}, Filter={Filter}", schemeId, aggregationsJson, filterJson ?? "null"); var innerSql = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, aggregationsJson }, cancellationToken); if (string.IsNullOrWhiteSpace(innerSql)) throw new InvalidOperationException( "pvt_build_aggregate_sql returned an empty SQL string for scheme " + schemeId + "."); return innerSql; } /// /// Serializes an aggregate request list to the JSON shape consumed by /// pvt_build_aggregate_sql: /// [{"alias":"x","$sum":{"$field":"Price"}}, {"alias":"y","$count":"*"}]. /// Count with empty FieldPath becomes $count: "*". /// private static string BuildPvtAggregationsJson(IList requests) { var auto = 0; var entries = new List>(requests.Count); foreach (var r in requests) { auto++; var alias = string.IsNullOrEmpty(r.Alias) ? "_agg_" + auto : r.Alias!; var opKey = r.Function switch { AggregateFunction.Sum => "$sum", AggregateFunction.Average => "$avg", AggregateFunction.Min => "$min", AggregateFunction.Max => "$max", AggregateFunction.Count => "$count", _ => throw new NotSupportedException( "Aggregation function " + r.Function + " is not supported by pvt_build_aggregate_sql.") }; var entry = new Dictionary { ["alias"] = alias }; // RedbQueryable / RedbGroupedQueryable encode COUNT(*) as FieldPath "*"; // PVT expects the literal star as the operand string, not as a field reference. var isCountStar = r.Function == AggregateFunction.Count && (string.IsNullOrEmpty(r.FieldPath) || r.FieldPath == "*"); if (isCountStar) { entry[opKey] = "*"; } else { FieldPathRefusal.EnsureModuleAggregateCanRead(r.FieldPath); entry[opKey] = new Dictionary { ["$field"] = NormalizePvtFieldName(r.FieldPath, r.IsBaseField) }; } // Agg.Count(g, x => condition): the module compiles it as a per-aggregate filter. if (r.ConditionJson != null) entry["filter"] = JsonDocument.Parse(r.ConditionJson).RootElement.Clone(); entries.Add(entry); } return JsonSerializer.Serialize(entries); } private static object? ConvertJsonValue(JsonElement el) => el.ValueKind switch { JsonValueKind.Number => el.TryGetDecimal(out var d) ? d : (object)el.GetDouble(), JsonValueKind.String => el.GetString(), JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Null => null, _ => el.GetRawText() }; } Path: redb/redb.SQLite/Query/SqliteQueryProvider.GroupedWindow.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/Query/SqliteQueryProvider.GroupedWindow.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Query.Aggregation; using redb.Core.Query.Grouping; using redb.Core.Query.QueryExpressions; using redb.Core.Query.Window; namespace redb.SQLite.Query; /// /// PVT-backed GroupBy + Window Functions for free SQLite. Builds the /// inner grouped SQL via pvt_build_groupby_sql, then wraps it in an /// outer SELECT that applies the requested window functions over the /// already-grouped row set, finally wrapping the whole thing in /// json_agg(row_to_json(t)) for one-shot materialization. /// /// Window OVER clause refs: /// * partition_by: must reference a group alias. /// * order_by: either a group alias or the synthetic /// Agg_<func>_<field> pattern emitted by /// ; /// the latter is resolved against the aggregations list /// to recover the actual aggregate alias. /// public partial class SqliteQueryProvider { /// public override Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) { return ExecuteGroupedWindowInternalAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson); } /// public override Task ExecuteGroupedWindowQueryAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return ExecuteGroupedWindowInternalAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson); } /// public override async Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) { return await BuildGroupedWindowSqlAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson); } /// public override async Task GetGroupedWindowSqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return await BuildGroupedWindowSqlAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson); } private async Task ExecuteGroupedWindowInternalAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson, string? havingJson) { var sql = await BuildGroupedWindowSqlAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson); // SQLite has no json_agg/row_to_json: run the windowed SELECT and serialize rows in C#. var jsonArray = await _context.QueryRowsAsJsonAsync(sql, System.Array.Empty()); if (string.IsNullOrEmpty(jsonArray)) return null; return JsonDocument.Parse(jsonArray); } private async Task BuildGroupedWindowSqlAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson, string? havingJson, CancellationToken cancellationToken = default) { var groupList = groupFields?.ToList() ?? new List(); var aggList = aggregations?.ToList() ?? new List(); var windowList = windowFuncs?.ToList() ?? new List(); var partitionList = partitionBy?.ToList() ?? new List(); var orderList = orderBy?.ToList() ?? new List(); if (groupList.Count == 0) throw new ArgumentException("groupFields must contain at least one entry.", nameof(groupFields)); if (windowList.Count == 0) throw new ArgumentException("windowFuncs must contain at least one entry.", nameof(windowFuncs)); // An aggregate the window sorts, partitions or reads by need not be in the selector: computed under a private alias. var shownAggregates = aggList.ToList(); aggList = GroupedWindowSelect.WithHiddenAggregates(shownAggregates, windowList, partitionList, orderList); var groupByJson = BuildPvtGroupByJson(groupList); var aggregationsJson = aggList.Count == 0 ? null : BuildPvtAggregationsJson(aggList); object filterParam = string.IsNullOrEmpty(filterJson) || filterJson == "{}" || filterJson == "null" ? DBNull.Value : (object)filterJson!; object aggParam = aggregationsJson is null ? DBNull.Value : (object)aggregationsJson; object havingParam = string.IsNullOrEmpty(havingJson) || havingJson == "{}" || havingJson == "null" ? DBNull.Value : (object)havingJson!; var invocation = "SELECT pvt_build_groupby_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, $3, $4, NULL, NULL, 0, 'flat', NULL, NULL, 1, 1) AS \"Value\""; _logger?.LogDebug("PVT GroupedWindow Build: SchemeId={SchemeId}, GroupBy={GroupBy}, Aggs={Aggs}, Filter={Filter}", schemeId, groupByJson, aggregationsJson ?? "null", filterJson ?? "null"); var innerSql = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, groupByJson, aggParam, havingParam }, cancellationToken); if (string.IsNullOrWhiteSpace(innerSql)) throw new InvalidOperationException( "pvt_build_groupby_sql returned an empty SQL string for scheme " + schemeId + "."); // Returns the windowed SELECT itself; the caller serializes rows to JSON in C# // (SQLite has no json_agg/row_to_json). Preview surfaces see the real SQL. return GroupedWindowSelect.Build( innerSql, groupList, aggList, shownAggregates, windowList, partitionList, orderList, QuoteIdent, rankingNeedsOrder: false); } private static string QuoteIdent(string identifier) { // Match SQLite's standard double-quote identifier escaping. return "\"" + identifier.Replace("\"", "\"\"") + "\""; } } Path: redb/redb.SQLite/Query/SqliteQueryProvider.Grouping.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/Query/SqliteQueryProvider.Grouping.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Query.Aggregation; using redb.Core.Query.Grouping; using redb.Core.Query.QueryExpressions; namespace redb.SQLite.Query; /// /// PVT-backed GROUP BY for free SQLite. Generates the projection SQL /// via the server-side compiler pvt_build_groupby_sql and wraps it /// with json_agg(row_to_json(t)) to materialize a JSON array of /// group rows in one round-trip after the build step. /// /// Overrides both string-based and FilterExpression-based virtual methods /// on so callers reach /// the PVT compiler regardless of which surface they use. /// public partial class SqliteQueryProvider { /// public override Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson = null, string? havingJson = null, CancellationToken cancellationToken = default) { return ExecuteGroupedAggregateInternalAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } /// public override Task ExecuteGroupedAggregateAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return ExecuteGroupedAggregateInternalAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } private async Task ExecuteGroupedAggregateInternalAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson, string? havingJson = null) { var groupList = groupFields?.ToList() ?? new List(); var aggList = aggregations?.ToList() ?? new List(); // Empty group-by => degenerate to a flat batch aggregate; *RedbAsync helpers // (SumRedbAsync, AverageRedbAsync, ...) intentionally pass zero group keys to // request a single-row aggregate over base IRedbObject columns. if (groupList.Count == 0) { if (!string.IsNullOrEmpty(havingJson)) throw new NotSupportedException( "HAVING requires GROUP BY keys; cannot be combined with a flat aggregate batch."); if (aggList.Count == 0) return null; var aggResult = await ExecuteAggregateBatchInternalAsync(schemeId, aggList, filterJson); var rowJson = JsonSerializer.Serialize(new[] { aggResult.Values }); return JsonDocument.Parse(rowJson); } var innerSql = await BuildGroupByInnerSqlAsync(schemeId, groupList, aggList, filterJson, havingJson); // SQLite has no json_agg/row_to_json: run the inner SQL and serialize rows in C#. var jsonArray = await _context.QueryRowsAsJsonAsync(innerSql, System.Array.Empty()); if (string.IsNullOrEmpty(jsonArray)) return null; return JsonDocument.Parse(jsonArray); } /// /// Returns the inner SELECT compiled by pvt_build_groupby_sql for the /// requested grouping. This is the same first-pass SQL that /// later wraps with /// json_agg(row_to_json(t)); exposed so ToSqlStringAsync and /// other diagnostics surfaces can see the actual SQL. /// public override async Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default) { var groupList = groupFields?.ToList() ?? new List(); var aggList = aggregations?.ToList() ?? new List(); if (groupList.Count == 0) throw new ArgumentException("A GroupBy SQL preview needs at least one key.", nameof(groupFields)); return await BuildGroupByInnerSqlAsync(schemeId, groupList, aggList, filterJson, havingJson); } /// /// FilterExpression overload of . /// public override Task GetGroupBySqlPreviewAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, FilterExpression? filter, string? havingJson = null, CancellationToken cancellationToken = default) { var filterJson = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return GetGroupBySqlPreviewAsync(schemeId, groupFields, aggregations, filterJson, havingJson); } private async Task BuildGroupByInnerSqlAsync( long schemeId, IList groupList, IList aggList, string? filterJson, string? havingJson = null, CancellationToken cancellationToken = default) { var groupByJson = BuildPvtGroupByJson(groupList); var aggregationsJson = aggList.Count == 0 ? null : BuildPvtAggregationsJson(aggList); object filterParam = string.IsNullOrEmpty(filterJson) || filterJson == "{}" || filterJson == "null" ? DBNull.Value : (object)filterJson!; object aggParam = aggregationsJson is null ? DBNull.Value : (object)aggregationsJson; object havingParam = string.IsNullOrEmpty(havingJson) || havingJson == "null" ? DBNull.Value : (object)havingJson!; var invocation = "SELECT pvt_build_groupby_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, $3, $4, NULL, NULL, 0, 'flat', NULL, NULL, 1, 1) AS \"Value\""; _logger?.LogDebug("PVT GroupBy Build: SchemeId={SchemeId}, GroupBy={GroupBy}, Aggs={Aggs}, Filter={Filter}, Having={Having}", schemeId, groupByJson, aggregationsJson ?? "null", filterJson ?? "null", havingJson ?? "null"); var innerSql = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, groupByJson, aggParam, havingParam }, cancellationToken); if (string.IsNullOrWhiteSpace(innerSql)) throw new InvalidOperationException( "pvt_build_groupby_sql returned an empty SQL string for scheme " + schemeId + "."); return innerSql!; } /// /// Serializes group fields to the JSON shape consumed by /// pvt_build_groupby_sql: [{"field":"Department","alias":"d"}]. /// Base fields () get the 0$: /// prefix so PVT's pvt_normalize_base_field_name resolves them to the /// underlying _objects column. Underscore-prefixed names and inputs /// that already carry 0$: are passed through. /// private static string BuildPvtGroupByJson(IList groupFields) { var entries = new List>(groupFields.Count); foreach (var g in groupFields) { var entry = new Dictionary { ["field"] = NormalizePvtFieldName(g.FieldPath, g.IsBaseField) }; if (!string.IsNullOrEmpty(g.Alias)) entry["alias"] = g.Alias!; entries.Add(entry); } return JsonSerializer.Serialize(entries); } /// /// Returns with the 0$: base-field prefix /// applied when is true and the path is not /// already prefixed / underscore-prefixed. Used by GROUP BY, ORDER BY and /// window partition / order entries that flow through PVT. /// internal static string NormalizePvtFieldName(string? fieldPath, bool isBaseField) { var path = fieldPath ?? string.Empty; if (!isBaseField) return path; if (path.Length == 0 || path.StartsWith("0$:", StringComparison.Ordinal) || path[0] == '_') return path; return "0$:" + path; } /// /// GroupByArray on the free SQLite provider: pvt_build_array_groupby_sql of the extension builds the /// grouping (and its HAVING); a window over the groups is written around it by . /// SQLite has no json_agg, so the rows are packed into JSON in C#, NULL values included. /// public override async Task ExecuteArrayGroupQueryAsync(ArrayGroupQuery query, CancellationToken cancellationToken = default) { var sql = await BuildArrayGroupSqlAsync(query, cancellationToken); var json = await _context.QueryRowsAsJsonAsync(sql, System.Array.Empty(), cancellationToken); if (string.IsNullOrEmpty(json)) throw new InvalidOperationException("GroupByArray: the grouping returned no rows document for scheme " + query.SchemeId + "."); return JsonDocument.Parse(json); } /// public override Task GetArrayGroupQuerySqlAsync(ArrayGroupQuery query, CancellationToken cancellationToken = default) => BuildArrayGroupSqlAsync(query, cancellationToken); private async Task BuildArrayGroupSqlAsync(ArrayGroupQuery query, CancellationToken cancellationToken) { query.EnsureValid(); var filterJson = query.Filter != null ? _facetBuilder.BuildFacetFilters(query.Filter) : query.FilterJson; var shown = query.Aggregations.ToList(); var aggregations = query.Window == null ? shown : GroupedWindowSelect.WithHiddenAggregates(shown, query.Window.Functions, query.Window.PartitionBy, query.Window.OrderBy); var invocation = "SELECT pvt_build_array_groupby_sql(" + query.SchemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, $3, $4, $5, NULL, NULL, 0) AS \"Value\""; var innerSql = await _context.ExecuteScalarAsync(invocation, new object[] { query.ArrayPath, ArrayGroupModuleJson.Param(filterJson), ArrayGroupModuleJson.GroupBy(query.GroupFields), ArrayGroupModuleJson.Param(ArrayGroupModuleJson.Aggregations(aggregations)), ArrayGroupModuleJson.Param(query.HavingJson) }, cancellationToken); if (string.IsNullOrWhiteSpace(innerSql)) throw new InvalidOperationException( "pvt_build_array_groupby_sql returned an empty SQL string for scheme " + query.SchemeId + "."); return query.Window == null ? innerSql : GroupedWindowSelect.Build(innerSql, query.GroupFields, aggregations, shown, query.Window.Functions, query.Window.PartitionBy, query.Window.OrderBy, QuoteIdent, rankingNeedsOrder: false); } } Path: redb/redb.SQLite/Query/SqliteQueryProvider.Window.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/Query/SqliteQueryProvider.Window.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Query.QueryExpressions; using redb.Core.Query.Window; namespace redb.SQLite.Query; /// /// PVT-backed window functions for free SQLite. Generates the SELECT /// SQL via the server-side compiler pvt_build_window_sql and wraps /// it with json_agg(row_to_json(t)) to materialize a JSON array in /// one round-trip. /// /// Window calls are expressed as scalar $over nodes inside the /// p_select array; all funcs share the same partition_by / order_by /// / frame supplied through the public API. /// public partial class SqliteQueryProvider { /// public override Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { return ExecuteWindowQueryInternalAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); } /// public override Task ExecuteWindowQueryAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, FilterExpression? filter, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { var filterJson = filter is null ? null : _facetBuilder.BuildFacetFilters(filter); return ExecuteWindowQueryInternalAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); } private async Task ExecuteWindowQueryInternalAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson, string? frameJson, int? take, int? skip) { var innerSql = await BuildWindowInnerSqlAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); // SQLite has no json_agg/row_to_json: run the inner SQL and serialize rows in C#. var jsonArray = await _context.QueryRowsAsJsonAsync(innerSql, System.Array.Empty()); if (string.IsNullOrEmpty(jsonArray)) return null; return JsonDocument.Parse(jsonArray); } /// public override Task GetWindowSqlPreviewAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson = null, string? frameJson = null, int? take = null, int? skip = null, CancellationToken cancellationToken = default) { return BuildWindowInnerSqlAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); } private async Task BuildWindowInnerSqlAsync( long schemeId, IEnumerable selectFields, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson, string? frameJson, int? take, int? skip, CancellationToken cancellationToken = default) { var selectList = selectFields?.ToList() ?? new List(); var funcList = windowFuncs?.ToList() ?? new List(); if (funcList.Count == 0) throw new ArgumentException("windowFuncs must contain at least one entry.", nameof(windowFuncs)); var partitionList = partitionBy?.ToList() ?? new List(); var orderList = orderBy?.ToList() ?? new List(); JsonElement? frameNode = null; if (!string.IsNullOrWhiteSpace(frameJson) && frameJson != "null") { using var frameDoc = JsonDocument.Parse(frameJson); frameNode = ConvertLegacyFrameJson(frameDoc.RootElement); } var selectJson = BuildPvtWindowSelectJson(selectList, funcList, partitionList, orderList, frameNode); object filterParam = string.IsNullOrEmpty(filterJson) || filterJson == "{}" || filterJson == "null" ? DBNull.Value : (object)filterJson!; object limitParam = take.HasValue ? (object)take.Value : DBNull.Value; object offsetParam = skip ?? 0; var invocation = "SELECT pvt_build_window_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, NULL, $3, $4, 'flat', NULL, NULL, 1, 1) AS \"Value\""; _logger?.LogDebug("PVT Window Build: SchemeId={SchemeId}, Select={Select}, Filter={Filter}, Take={Take}, Skip={Skip}", schemeId, selectJson, filterJson ?? "null", take, skip); var innerSql = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, selectJson, limitParam, offsetParam }, cancellationToken); if (string.IsNullOrWhiteSpace(innerSql)) throw new InvalidOperationException( "pvt_build_window_sql returned an empty SQL string for scheme " + schemeId + "."); return innerSql!; } /// /// Builds the p_select JSON: plain field projections followed by /// one $over entry per window function. partition_by / order_by / /// frame from the API are replicated into every $over node since /// SQLite has no native WINDOW-clause sharing at this layer. /// private static string BuildPvtWindowSelectJson( IList selectFields, IList windowFuncs, IList partitionBy, IList orderBy, JsonElement? frameNode) { var entries = new List>(selectFields.Count + windowFuncs.Count); foreach (var f in selectFields) { var entry = new Dictionary { ["field"] = SqliteQueryProvider.NormalizePvtFieldName(f.FieldPath, f.IsBaseField) }; if (!string.IsNullOrEmpty(f.Alias)) entry["alias"] = f.Alias!; entries.Add(entry); } var partitionEntries = partitionBy .Select(p => new Dictionary { ["field"] = SqliteQueryProvider.NormalizePvtFieldName(p.FieldPath, p.IsBaseField) }) .ToList(); var orderEntries = orderBy .Select(o => new Dictionary { ["field"] = SqliteQueryProvider.NormalizePvtFieldName(o.FieldPath, o.IsBaseField), ["dir"] = o.Descending ? "desc" : "asc" }) .ToList(); foreach (var f in windowFuncs) { var over = new Dictionary { ["func"] = (f.Func ?? string.Empty).ToLowerInvariant() }; var args = BuildWindowArgs(f); if (args is not null) over["args"] = args; if (partitionEntries.Count > 0) over["partition_by"] = partitionEntries; if (orderEntries.Count > 0) over["order_by"] = orderEntries; if (frameNode.HasValue) over["frame"] = frameNode.Value; var entry = new Dictionary { ["alias"] = string.IsNullOrEmpty(f.Alias) ? (f.Func ?? string.Empty).ToLowerInvariant() : f.Alias!, ["$expr"] = new Dictionary { ["$over"] = over } }; entries.Add(entry); } var options = new JsonSerializerOptions { Converters = { new JsonElementPassThroughConverter() } }; return JsonSerializer.Serialize(entries, options); } /// /// Builds the args array for a PVT $over node. Returns /// List<object> so we can mix scalar dicts /// ({"$field":...}, {"$const":...}) with the bare string /// "*" that pvt_build_window_expr recognizes as the /// COUNT(*) shorthand. /// private static List? BuildWindowArgs(WindowFuncRequest f) { var func = (f.Func ?? string.Empty).ToUpperInvariant(); if (func == "NTILE" && f.Buckets.HasValue) { return new List { new Dictionary { ["$const"] = f.Buckets.Value } }; } if (!string.IsNullOrEmpty(f.FieldPath)) { return new List { new Dictionary { ["$field"] = SqliteQueryProvider.NormalizePvtFieldName(f.FieldPath, f.IsBaseField) } }; } // COUNT() over the whole partition: emit COUNT(*) shorthand. // All other aggregate / value functions without an argument are // rejected by PVT later, which surfaces a clearer error there. if (func == "COUNT") return new List { "*" }; return null; } /// /// Converts the legacy SerializeFrame() JSON shape /// ({"type":"ROWS","start":{"kind":"PRECEDING","offset":3},"end":{"kind":"CURRENT_ROW","offset":null}}) /// to the PVT frame shape consumed by _pvt_compile_frame_bound /// ({"type":"rows","start":{"preceding":3},"end":"current_row"}). /// Inputs already in PVT shape pass through unchanged. /// private static JsonElement ConvertLegacyFrameJson(JsonElement frame) { if (frame.ValueKind != JsonValueKind.Object) return frame.Clone(); var node = new Dictionary(); if (frame.TryGetProperty("type", out var typeEl) && typeEl.ValueKind == JsonValueKind.String) node["type"] = typeEl.GetString()!.ToLowerInvariant(); if (frame.TryGetProperty("start", out var startEl)) node["start"] = ConvertLegacyFrameBound(startEl); if (frame.TryGetProperty("end", out var endEl)) node["end"] = ConvertLegacyFrameBound(endEl); if (frame.TryGetProperty("exclude", out var excEl) && excEl.ValueKind == JsonValueKind.String) node["exclude"] = excEl.GetString()!.ToLowerInvariant(); var json = JsonSerializer.Serialize(node); using var doc = JsonDocument.Parse(json); return doc.RootElement.Clone(); } private static object ConvertLegacyFrameBound(JsonElement bound) { if (bound.ValueKind == JsonValueKind.String) return bound.GetString()!.ToLowerInvariant(); if (bound.ValueKind != JsonValueKind.Object) return bound.Clone(); if (bound.TryGetProperty("preceding", out _) || bound.TryGetProperty("following", out _)) return bound.Clone(); if (!bound.TryGetProperty("kind", out var kindEl) || kindEl.ValueKind != JsonValueKind.String) return bound.Clone(); var kind = (kindEl.GetString() ?? string.Empty).ToUpperInvariant(); int? offset = null; if (bound.TryGetProperty("offset", out var offEl) && offEl.ValueKind == JsonValueKind.Number) offset = offEl.GetInt32(); return kind switch { "UNBOUNDEDPRECEDING" or "UNBOUNDED_PRECEDING" => "unbounded_preceding", "CURRENTROW" or "CURRENT_ROW" => "current_row", "UNBOUNDEDFOLLOWING" or "UNBOUNDED_FOLLOWING" => "unbounded_following", "PRECEDING" => new Dictionary { ["preceding"] = offset ?? 0 }, "FOLLOWING" => new Dictionary { ["following"] = offset ?? 0 }, _ => (object)bound.Clone() }; } /// /// Converter that emits already-parsed values /// verbatim instead of re-wrapping them. Used so the embedded /// frame sub-tree survives serialization intact. /// private sealed class JsonElementPassThroughConverter : System.Text.Json.Serialization.JsonConverter { public override JsonElement Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => JsonDocument.ParseValue(ref reader).RootElement.Clone(); public override void Write(Utf8JsonWriter writer, JsonElement value, JsonSerializerOptions options) => value.WriteTo(writer); } } Path: redb/redb.SQLite/Query/SqliteQueryProvider.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/Query/SqliteQueryProvider.cs ---- using Microsoft.Extensions.Logging; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Providers; using redb.Core.Query; using redb.Core.Query.Base; using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; using redb.SQLite.Data; using redb.SQLite.Sql; namespace redb.SQLite.Query; /// /// SQLite query provider implementation. /// Inherits from QueryProviderBase and provides SQLite-specific components. /// public partial class SqliteQueryProvider : QueryProviderBase { /// /// The first row of as a JSON object, or null when there is none. SQLite has no /// row_to_json, so the analytics read their rows through IRedbContext.QueryRowsAsJsonAsync (one command and one /// telemetry span, as on the other providers); they used to read on the raw connection, which opened no span. /// private async Task FirstRowAsJsonAsync(string sql) { var json = await _context.QueryRowsAsJsonAsync(sql, System.Array.Empty()); using var rows = System.Text.Json.JsonDocument.Parse(json); return rows.RootElement.GetArrayLength() == 0 ? null : rows.RootElement[0].GetRawText(); } public SqliteQueryProvider( IRedbContext context, IRedbObjectSerializer serializer, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, ILogger? logger = null, ISchemeSyncProvider? schemeSync = null, ISqlDialect? dialect = null) : base(context, serializer, dialect ?? new SqliteDialect(), lazyPropsLoader, configuration, logger, schemeSync) { } } Path: redb/redb.SQLite/Query/SqliteTreeQueryProvider.Pvt.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/Query/SqliteTreeQueryProvider.Pvt.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Models.Entities; using redb.Core.Query.Base; using redb.Core.Query.QueryExpressions; #pragma warning disable CS0672 // Member overrides obsolete member (legacy fallback retained for HasAncestor/HasDescendant + flat search) #pragma warning disable CS0618 // Type or member is obsolete namespace redb.SQLite.Query; /// /// Routes tree-subtree LINQ queries through the v2-pvt engine when the /// generated filter contains expression-form predicates ($expr) that /// the legacy search_tree_objects_with_facets_base SQL function does /// not understand. For all other tree filters we keep the legacy path /// (faster index plans, no behavioural change). /// public partial class SqliteTreeQueryProvider { /// /// Describes how a tree LINQ query is mapped onto the v2-pvt /// pvt_build_query_sql orchestrator: which source mode to use, /// which seed ids (if any) feed the recursive walks, whether to keep /// the seed rows in the output, and which filter JSON to bind. /// private readonly struct PvtTreeRoute { public PvtTreeRoute(string sourceMode, long[] treeIds, bool includeSeed, string filterJson) { SourceMode = sourceMode; TreeIds = treeIds; IncludeSeed = includeSeed; FilterJson = filterJson; } public string SourceMode { get; } public long[] TreeIds { get; } public bool IncludeSeed { get; } public string FilterJson { get; } } /// protected override async Task ExecuteTreeToListAsync(TreeQueryContext context, CancellationToken cancellationToken = default) { // Free PG: HasAncestor / HasDescendant are routed through PVT here // because the legacy search_*_base SQL functions are gone. var hasAncestorFilter = GetOptimizableHasAncestorFilter(context); if (hasAncestorFilter != null) return await ExecutePvtHasAncestorToListAsync(context, hasAncestorFilter); var hasDescendantFilter = GetOptimizableHasDescendantFilter(context); if (hasDescendantFilter != null) return await ExecutePvtHasDescendantToListAsync(context, hasDescendantFilter); if (!ShouldRoutePvtTree(context, out var route)) throw UnresolvedTreeFilter(); try { var rows = await ExecutePvtTreeAsync(context, route, cancellationToken); var result = rows.Select(MapRowToTreeObject).ToList(); if (result.Count > 0 && _lazyPropsLoader != null) { var sw = System.Diagnostics.Stopwatch.StartNew(); var baseObjects = result.Cast>().ToList(); await _lazyPropsLoader.LoadPropsForManyAsync(baseObjects, context.PropsDepth); sw.Stop(); _logger?.LogInformation("Props loaded via batch (PVT tree) in {ElapsedMs} ms", sw.ElapsedMilliseconds); } return (object)result; } catch (Exception ex) { _logger?.LogError(ex, "Error executing PVT tree ToList query"); throw; } } /// protected override async Task ExecuteTreeCountAsync(TreeQueryContext context, CancellationToken cancellationToken = default) { // Free PG: HasAncestor / HasDescendant — execute list path and count. // The two operators rewrite the context via recursive ExecuteTreeToListAsync, // so the count cannot be issued as a single SQL aggregate at this layer. var hasAncestorFilter = GetOptimizableHasAncestorFilter(context); if (hasAncestorFilter != null) { var list = await ExecutePvtHasAncestorToListAsync(context, hasAncestorFilter); return ((IList>)list).Count; } var hasDescendantFilter = GetOptimizableHasDescendantFilter(context); if (hasDescendantFilter != null) { var list = await ExecutePvtHasDescendantToListAsync(context, hasDescendantFilter); return ((IList>)list).Count; } if (!ShouldRoutePvtTree(context, out var route)) throw UnresolvedTreeFilter(); var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: true); var sql = "SELECT COUNT(*) AS \"Value\" FROM (" + inner + ") t"; object filterParam = string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson; // A count reads no order: the inner SQL is built without one (forCount), so nothing is sorted. long? count = await _context.ExecuteScalarAsync(sql, new object[] { filterParam }, cancellationToken); return checked((int)(count ?? 0)); } /// /// Is there at least one node: the inner statement of the count under EXISTS, which stops at the first node the /// walk and the filter let through. It used to count every node. WhereHasAncestor / WhereHasDescendant resolve /// into object ids first, as the count does, and answer by that count. /// protected override async Task ExecuteTreeAnyAsync(TreeQueryContext context, CancellationToken cancellationToken = default) { if (GetOptimizableHasAncestorFilter(context) != null || GetOptimizableHasDescendantFilter(context) != null) return await ExecuteTreeCountAsync(context, cancellationToken) > 0; if (!ShouldRoutePvtTree(context, out var route)) throw UnresolvedTreeFilter(); var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: true); var sql = _sql.Query_WrapPvtWithExists(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithExists returned null for a PVT-enabled dialect."); object filterParam = string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson; return ExistsResult(await _context.ExecuteScalarAsync(sql, new object[] { filterParam }, cancellationToken)); } /// /// Returns true when the request can be served by the v2-pvt /// orchestrator. Picks the appropriate p_source_mode and seed /// id array based on the tree filters present in the context. /// /// /// Routes covered: /// /// WhereRoots() → tree_roots /// WhereLeaves() → tree_leaves /// WhereChildrenOf(id) → tree_children + tree_ids=[id] /// WhereDescendantsOf(id) → tree_descendants + tree_ids=[id] /// RootObjectId / ParentIds set → tree_descendants /// Whole-scheme (no root, no special filter) → flat /// WhereLevel(...) is attached as a $level facet /// filter and combined with any of the above modes. /// /// WhereHasAncestor / WhereHasDescendant are NOT served /// here — they use their own optimized base-class path that builds /// SQL out of two flat queries with logic inversion. /// private bool ShouldRoutePvtTree(TreeQueryContext context, out PvtTreeRoute route) where TProps : class, new() { route = new PvtTreeRoute("flat", Array.Empty(), false, "{}"); if (context.TreeFilters != null && context.TreeFilters.Any(f => f.Operator == TreeFilterOperator.HasAncestor || f.Operator == TreeFilterOperator.HasDescendant)) return false; if (GetOptimizableHasAncestorFilter(context) != null) return false; if (GetOptimizableHasDescendantFilter(context) != null) return false; var treeFilters = context.TreeFilters ?? new List(); // Determine source_mode / tree_ids / include_seed. var sourceMode = "flat"; long[] treeIds = Array.Empty(); var includeSeed = false; var childrenOf = treeFilters.FirstOrDefault(f => f.Operator == TreeFilterOperator.ChildrenOf); var descendantsOf = treeFilters.FirstOrDefault(f => f.Operator == TreeFilterOperator.DescendantsOf); var isRoot = treeFilters.Any(f => f.Operator == TreeFilterOperator.IsRoot); var isLeaf = treeFilters.Any(f => f.Operator == TreeFilterOperator.IsLeaf); if (descendantsOf != null) { sourceMode = "tree_descendants"; treeIds = new[] { Convert.ToInt64(descendantsOf.Value, CultureInfo.InvariantCulture) }; includeSeed = false; } else if (childrenOf != null) { sourceMode = "tree_children"; treeIds = new[] { Convert.ToInt64(childrenOf.Value, CultureInfo.InvariantCulture) }; } else if (isRoot) { sourceMode = "tree_roots"; // Respect root scoping: TreeQuery(rootObj).WhereRoots() means "the root of THIS tree", // not every root in the scheme. Seed with the scoped root so the SQL restricts to it; // an empty seed keeps the whole-scheme "all roots" behavior. if (context.ParentIds != null && context.ParentIds.Length > 0) treeIds = context.ParentIds; else if (context.RootObjectId.HasValue) treeIds = new[] { context.RootObjectId.Value }; } else if (isLeaf) { sourceMode = "tree_leaves"; // Respect root scoping: TreeQuery(rootObj).WhereLeaves() means "leaves of THIS subtree", // not every leaf in the scheme (the cross-tree leak). Seed with the scoped root so the SQL // descends from it and applies the leaf predicate over its subtree; an empty seed keeps the // whole-scheme "all leaves" behavior. if (context.ParentIds != null && context.ParentIds.Length > 0) treeIds = context.ParentIds; else if (context.RootObjectId.HasValue) treeIds = new[] { context.RootObjectId.Value }; } else if (context.RootObjectId.HasValue || (context.ParentIds != null && context.ParentIds.Length > 0)) { sourceMode = "tree_descendants"; treeIds = (context.ParentIds != null && context.ParentIds.Length > 0) ? context.ParentIds : new[] { context.RootObjectId!.Value }; includeSeed = false; } // Build the filter JSON by combining the user .Where() predicates // and any tree-level filters PVT understands natively ($level). var merged = new Dictionary(); if (context.Filter != null) { var userJson = _facetBuilder.BuildFacetFilters(context.Filter); if (!string.IsNullOrEmpty(userJson) && userJson != "{}") { using var doc = JsonDocument.Parse(userJson); foreach (var prop in doc.RootElement.EnumerateObject()) merged[prop.Name] = prop.Value.Clone(); } } foreach (var tf in treeFilters) { if (tf.Operator != TreeFilterOperator.Level) continue; if (tf.Value is int lvl) merged["$level"] = lvl; else if (tf.FilterConditions != null) merged["$level"] = tf.FilterConditions; } // The tree filters after the one that gave the source narrow it, as conditions of the filter // (WhereDescendantsOf(x).WhereLeaves(): the leaves under x). Only the first one used to be read. var source = descendantsOf != null ? TreeFilterOperator.DescendantsOf : childrenOf != null ? TreeFilterOperator.ChildrenOf : isRoot ? TreeFilterOperator.IsRoot : isLeaf ? TreeFilterOperator.IsLeaf : (TreeFilterOperator?)null; foreach (var tf in treeFilters) { if (tf.Operator == source) continue; if (tf.Operator == TreeFilterOperator.ChildrenOf) merged["$childrenOf"] = Convert.ToInt64(tf.Value, CultureInfo.InvariantCulture); else if (tf.Operator == TreeFilterOperator.IsRoot) merged["$isRoot"] = true; else if (tf.Operator == TreeFilterOperator.IsLeaf) merged["$isLeaf"] = true; } var filterJson = merged.Count == 0 ? "{}" : JsonSerializer.Serialize(merged, new JsonSerializerOptions { WriteIndented = false, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); route = new PvtTreeRoute(sourceMode, treeIds, includeSeed, filterJson); return true; } /// /// Builds the inner SELECT _id ... SQL via /// pvt_build_query_sql. The resulting SQL binds /// $1::jsonb = filter, and (when present) $2::jsonb = order. /// private async Task BuildPvtTreeInnerSqlAsync( TreeQueryContext context, PvtTreeRoute route, bool forCount, CancellationToken cancellationToken = default) where TProps : class, new() { var orderByJson = context.Orderings.Count > 0 ? _facetBuilder.BuildOrderBy(context.Orderings) : null; var hasOrder = !forCount && !string.IsNullOrEmpty(orderByJson) && orderByJson != "null" && orderByJson != "[]"; // The depth of the tree walk (TreeQuery(root, maxDepth)); none: the whole subtree. This passed MaxRecursionDepth, the // depth of nested props, so maxDepth was ignored and every subtree stopped at 10 levels. // WhereDescendantsOf(node, maxDepth) walks from that node, to its own depth when it has one. var walkDepth = context.TreeFilters?.FirstOrDefault(f => f.Operator == TreeFilterOperator.DescendantsOf)?.MaxDepth ?? context.MaxDepth; var maxDepth = walkDepth?.ToString(CultureInfo.InvariantCulture) ?? "NULL"; var limitArg = forCount || !context.Limit.HasValue ? "NULL" : context.Limit.Value.ToString(CultureInfo.InvariantCulture); var offsetArg = forCount ? "0" : (context.Offset ?? 0).ToString(CultureInfo.InvariantCulture); // SQLite: p_tree_ids is a JSON array text (parsed by pvtInListFromJsonArray), not a PG bigint[]. var treeIdsLiteral = route.TreeIds.Length == 0 ? "NULL" : "'[" + string.Join(",", route.TreeIds.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]'"; // pvt_build_query_sql signature: // p_scheme_id, p_filter, p_limit, p_offset, p_order, p_max_depth, // p_distinct, p_source_mode, p_tree_ids, p_include_seed, // p_polymorphic, p_distinct_on // SQLite has no ::type casts; booleans pass as 1/0. // A distinct key binds $3; the order then always binds $2, NULL when there is none. var distinctOnJson = BuildPvtDistinctOnJson(context); var orderArg = hasOrder || distinctOnJson != null ? "$2" : "NULL"; var invocation = "SELECT pvt_build_query_sql(" + context.SchemeId.ToString(CultureInfo.InvariantCulture) + ", $1, " + limitArg + ", " + offsetArg + ", " + orderArg + ", " + maxDepth + ", " + (context.IsDistinct ? "1" : "0") + ", '" + route.SourceMode + "'" + ", " + treeIdsLiteral + ", " + (route.IncludeSeed ? "1" : "0") + ", 1" // p_polymorphic=1 matches Pro default + (distinctOnJson != null ? ", json($3)" : "") + ") AS \"Value\""; object filterParam = string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson; string? inner; if (distinctOnJson != null) inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, hasOrder ? (object)orderByJson! : DBNull.Value, distinctOnJson }, cancellationToken); else if (hasOrder) inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam, orderByJson! }, cancellationToken); else inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam }, cancellationToken); if (string.IsNullOrWhiteSpace(inner)) throw new InvalidOperationException( "pvt_build_query_sql returned an empty SQL string for tree query (scheme " + context.SchemeId + ")."); return inner; } /// /// SQL preview of a tree query: the statement pvt_build_query_sql compiles for it, with the /// values it binds listed above it. The base implementation asks the database for /// get_search_tree_sql_preview_base, a function of the retired search module that the native /// SQLite extension does not host, so ToSqlStringAsync on a tree query failed with /// "no such function: get_search_tree_sql_preview_base" (E204). /// public override async Task GetSqlPreviewAsync( TreeQueryContext context, CancellationToken cancellationToken = default) { if (!ShouldRoutePvtTree(context, out var route)) return await base.GetSqlPreviewAsync(context, cancellationToken); var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: false, cancellationToken); var orderByJson = context.Orderings.Count > 0 ? _facetBuilder.BuildOrderBy(context.Orderings) : null; var sb = new StringBuilder(); sb.Append("-- $1 (filter) = ") .AppendLine(string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson); if (!string.IsNullOrEmpty(orderByJson) && orderByJson != "null" && orderByJson != "[]") sb.Append("-- $2 (order) = ").AppendLine(orderByJson); sb.Append(inner); return sb.ToString(); } /// /// Reads the _objects rows of the inner _id list, in its order. Props are not read here: the /// caller loads them once through the lazy loader (this wrapper used to build each object's JSON with /// get_object_json, and the loader built it again). /// private async Task> ExecutePvtTreeAsync( TreeQueryContext context, PvtTreeRoute route, CancellationToken cancellationToken = default) where TProps : class, new() { var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: false); var sql = _sql.Query_WrapPvtWithObjectRows(inner) ?? throw new InvalidOperationException("Query_WrapPvtWithObjectRows returned null for the SQLite dialect."); object filterParam = string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson; var orderByJson = context.Orderings.Count > 0 ? _facetBuilder.BuildOrderBy(context.Orderings) : null; var hasOrder = !string.IsNullOrEmpty(orderByJson) && orderByJson != "null" && orderByJson != "[]"; if (hasOrder) return await _context.QueryAsync(sql, new object[] { filterParam, orderByJson! }, cancellationToken); return await _context.QueryAsync(sql, new object[] { filterParam }, cancellationToken); } } Path: redb/redb.SQLite/Query/SqliteTreeQueryProvider.PvtHasFilter.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/Query/SqliteTreeQueryProvider.PvtHasFilter.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Models.Entities; using redb.Core.Query.Base; using redb.Core.Query.QueryExpressions; #pragma warning disable CS0618 // ExecuteTreeToListAsync base is [Obsolete] (provider overrides it). namespace redb.SQLite.Query; /// /// Free PG: implements WhereHasAncestor / WhereHasDescendant /// via the v2-pvt orchestrator (the legacy search_*_with_facets_base /// SQL helpers were removed). Mirrors the inversion logic used by the Pro /// CTE+PVT path: find the target ids first, then recurse back into /// with a /// rewritten . /// public partial class SqliteTreeQueryProvider { /// /// WhereHasAncestor by inversion: /// * the ids of the objects of hasAncestorFilter.TargetSchemeId that match the inner condition, looked for /// below the start of the query as deep as the query reaches; /// * their descendants down to the filter's maxDepth (counted up from the returned object: 1 = the parent); /// * the query itself, with the filter replaced by a condition on those ids, so its start, depth, Where and /// paging apply as to any other query. /// private async Task ExecutePvtHasAncestorToListAsync( TreeQueryContext context, TreeFilter hasAncestorFilter, CancellationToken cancellationToken = default) where TProps : class, new() { var ancestorIds = await FindIdsViaPvtAsync(hasAncestorFilter, QueryStart(context), context.MaxDepth ?? 50, cancellationToken); if (ancestorIds.Length == 0) return new List>(); var idsString = string.Join(",", ancestorIds.Select(id => id.ToString(CultureInfo.InvariantCulture))); var sql = _sql.Query_GetDescendantIdsFromAncestorsSql(idsString, hasAncestorFilter.MaxDepth ?? 50); var ids = await _context.QueryScalarListAsync(sql, System.Array.Empty(), cancellationToken); if (ids.Count == 0) return new List>(); return await ExecuteTreeToListAsync(WithIdsInstead(context, hasAncestorFilter, ids)); } /// The nodes the query starts from: its root, or its parents; null for the whole scheme. private static long[]? QueryStart(TreeQueryContext context) where TProps : class, new() => context.RootObjectId.HasValue ? new[] { context.RootObjectId.Value } : context.ParentIds is { Length: > 0 } ? context.ParentIds : null; /// The query without , its object id confined to . protected static TreeQueryContext WithIdsInstead( TreeQueryContext context, TreeFilter treeFilter, IReadOnlyCollection ids) where TProps : class, new() { var idsFilter = new InExpression( new redb.Core.Query.QueryExpressions.PropertyInfo("_id", typeof(long), true), ids.Cast().ToList()); var rewritten = context.Clone(); rewritten.TreeFilters = new List(context.TreeFilters.Where(f => f != treeFilter)); rewritten.Filter = rewritten.Filter != null ? new LogicalExpression(LogicalOperator.And, new FilterExpression[] { rewritten.Filter, idsFilter }) : idsFilter; return rewritten; } /// /// Step 1+2+3 of WhereHasDescendant inversion: /// * find descendant ids of hasDescendantFilter.TargetSchemeId matching the inner condition; /// * walk up via Query_GetParentIdsFromDescendantsSql to collect every ancestor id; /// * rewrite the context (drop HasDescendant filter, AND-merge an /// on _id) and recurse. /// private async Task ExecutePvtHasDescendantToListAsync( TreeQueryContext context, TreeFilter hasDescendantFilter, CancellationToken cancellationToken = default) where TProps : class, new() { var descendantIds = await FindIdsViaPvtAsync(hasDescendantFilter, scopeRootIds: null, searchDepth: hasDescendantFilter.MaxDepth ?? 50, cancellationToken); if (descendantIds.Length == 0) return new List>(); // Walk up the parent chain to collect every potential matching object id. var depthLimit = hasDescendantFilter.MaxDepth ?? 50; var idsString = string.Join(",", descendantIds.Select(id => id.ToString(CultureInfo.InvariantCulture))); var sql = _sql.Query_GetParentIdsFromDescendantsSql(idsString, depthLimit); var parentIdList = await _context.QueryScalarListAsync(sql, System.Array.Empty(), cancellationToken); var parentIds = parentIdList.ToArray(); if (parentIds.Length == 0) return new List>(); var idsFilter = new InExpression( new redb.Core.Query.QueryExpressions.PropertyInfo("_id", typeof(long), true), parentIds.Cast().ToList()); var optimizedContext = context.Clone(); optimizedContext.TreeFilters = new List( context.TreeFilters.Where(f => f != hasDescendantFilter)); optimizedContext.Filter = optimizedContext.Filter != null ? new LogicalExpression(LogicalOperator.And, new FilterExpression[] { optimizedContext.Filter, idsFilter }) : (FilterExpression)idsFilter; return await ExecuteTreeToListAsync(optimizedContext); } /// /// Compiles the inner SELECT _id ... SQL for the given tree filter /// (HasAncestor / HasDescendant — both use the same flat or /// tree_descendants route depending on ) /// via pvt_build_query_sql, then executes it and returns the /// matching object ids. /// private async Task FindIdsViaPvtAsync(TreeFilter filter, long[]? scopeRootIds, int searchDepth, CancellationToken cancellationToken = default) { if (filter.TargetSchemeId is null || filter.TargetSchemeId.Value == 0) return Array.Empty(); var conditionJson = JsonSerializer.Serialize( filter.FilterConditions, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); var sourceMode = scopeRootIds != null && scopeRootIds.Length > 0 ? "tree_descendants" : "flat"; // SQLite: p_tree_ids is a JSON array text (parsed by pvtInListFromJsonArray), not a PG bigint[]. var treeIdsLiteral = scopeRootIds == null || scopeRootIds.Length == 0 ? "NULL" : "'[" + string.Join(",", scopeRootIds.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]'"; var maxDepth = searchDepth; var invocation = "SELECT pvt_build_query_sql(" + filter.TargetSchemeId.Value.ToString(CultureInfo.InvariantCulture) + ", $1, NULL, 0, NULL, " + maxDepth.ToString(CultureInfo.InvariantCulture) + ", 0, '" + sourceMode + "', " + treeIdsLiteral + ", 0, 1) AS \"Value\""; object filterParam = string.IsNullOrEmpty(conditionJson) || conditionJson == "null" ? (object)"{}" : (object)conditionJson; _logger?.LogDebug( "PVT HasAncestor/Descendant Build: TargetSchemeId={SchemeId}, Mode={Mode}, Scope={Scope}, Cond={Cond}", filter.TargetSchemeId.Value, sourceMode, treeIdsLiteral, conditionJson); var inner = await _context.ExecuteScalarAsync(invocation, new object[] { filterParam }, cancellationToken); if (string.IsNullOrWhiteSpace(inner)) return Array.Empty(); var idSql = "SELECT _id AS \"Value\" FROM (" + inner + ") sub"; var ids = await _context.QueryScalarListAsync(idSql, System.Array.Empty(), cancellationToken); return ids.ToArray(); } } Path: redb/redb.SQLite/Query/SqliteTreeQueryProvider.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/Query/SqliteTreeQueryProvider.cs ---- using Microsoft.Extensions.Logging; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Providers; using redb.Core.Query; using redb.Core.Query.Base; using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; using redb.SQLite.Sql; namespace redb.SQLite.Query; /// /// SQLite tree query provider implementation. /// Inherits from TreeQueryProviderBase and provides SQLite-specific components. /// public partial class SqliteTreeQueryProvider : TreeQueryProviderBase { public SqliteTreeQueryProvider( IRedbContext context, IRedbObjectSerializer serializer, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, ILogger? logger = null, ISqlDialect? dialect = null, string? cacheDomain = null, ISchemeSyncProvider? schemeSync = null) : base(context, serializer, dialect ?? new SqliteDialect(), cacheDomain, lazyPropsLoader, configuration, logger, schemeSync) { } /// /// Creates query provider for delegation. /// protected override IRedbQueryProvider CreateQueryProvider() { return new SqliteQueryProvider(_context, _serializer, _lazyPropsLoader, _configuration, _logger, _schemeSync); } /// /// Creates tree queryable instance. /// protected override IRedbQueryable CreateTreeQueryable(TreeQueryContext context) { return new SqliteTreeQueryable(this, context, _filterParser, _orderingParser); } } Path: redb/redb.SQLite/Query/SqliteTreeQueryable.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/Query/SqliteTreeQueryable.cs ---- using redb.Core.Query; using redb.Core.Query.Base; using redb.Core.Query.FacetFilters; using redb.Core.Query.QueryExpressions; namespace redb.SQLite.Query; /// /// SQLite tree queryable implementation. /// Inherits from TreeQueryableBase and provides SQLite-specific components. /// public class SqliteTreeQueryable : TreeQueryableBase where TProps : class, new() { public SqliteTreeQueryable( ITreeQueryProvider provider, TreeQueryContext context, IFilterExpressionParser filterParser, IOrderingExpressionParser orderingParser) : base(provider, context, filterParser, orderingParser, new FacetFilterBuilder()) { } /// /// Creates a new instance with the specified context. /// protected override TreeQueryableBase CreateInstance(TreeQueryContext context) { return new SqliteTreeQueryable(_treeProvider, context, _filterParser, _orderingParser); } } Path: redb/redb.SQLite/README.md 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/README.md ---- # redb.SQLite SQLite provider for **RedBase (REDB)** — Entity Database for .NET. [![NuGet](https://img.shields.io/nuget/v/redb.SQLite?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.SQLite) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../LICENSE) ## What's inside - SQLite-optimized SQL generation - Tree queries with recursive CTEs - Schema initialization (`redbPostgre.sql`) - Full LINQ-to-SQL translation - Depends on `redb.Core` and `Sqlite` ## Installation ```bash dotnet add package redb.SQLite ``` ## Setup ```csharp using redb.Core.Extensions; using redb.SQLite.Extensions; builder.Services.AddRedb(options => options .UseSqlite("Host=localhost;Port=5432;Database=mydb;Username=sqlite;Password=pass")); ``` ## Page cache and file mapping By default the provider leaves SQLite's own settings: a 2 MB page cache per connection and no memory-mapped file (`SqliteDataSource.MmapSizeBytes` and `SqliteDataSource.CacheSizeBytes` are 0). On a database of a few gigabytes that small cache is what most of a query's time goes into. The examples set both before the provider is registered: ```csharp using redb.SQLite.Data; SqliteDataSource.MmapSizeBytes = 4L * 1024 * 1024 * 1024; // PRAGMA mmap_size SqliteDataSource.CacheSizeBytes = 64L * 1024 * 1024; // PRAGMA cache_size, per connection ``` Measured on the examples database (2.5 GB, about 100 000 employees), one grouping over a nested array with a window took 940-1060 ms with the defaults and 430-600 ms with these two settings. The trade-off: a mapping takes address space, not memory of its own; the pages live in the operating system's file cache and all connections share them. SQLite caps the mapping at its compile-time limit, and what lies beyond the mapped part is read as before. The page cache is process memory, and every pooled connection has its own, so 64 MB times the number of open connections. For a small database, or where memory is tight, keep the defaults. ## Planner statistics SQLite keeps no statistics of its own until `ANALYZE` runs, and without them it may start a query from a large table where a small page should drive it. At start-up the provider analyzes a file that has none and holds at least 10 000 value rows (sampled by `MaintenanceAnalysisLimit`, 1 000 rows per index by default), and runs `PRAGMA optimize` on a file that has them, which refreshes only tables that grew a lot. A file filled by a bulk import gets its statistics at the next start; `IMaintenanceProvider.AnalyzeAsync` gathers them on demand. `KeepSqlitePlannerStatistics = false` turns the start-up step off. ## Several processes on one file Several processes may open the same database file; SQLite runs their writes one at a time, and redb never hands out an object id twice. One case stays with the application: an id it takes itself (`NextObjectIdBatchAsync`) inside a transaction that then rolls back may go to another process before it is used, so take such ids again after a rollback. ## Links - Documentation (EN): [redbase.app](https://redbase.app) - Documentation (RU): [redb.ru](https://redb.ru) - API Reference: [redbase-app.github.io/redb](https://redbase-app.github.io/redb/) - GitHub: [github.com/redbase-app/redb](https://github.com/redbase-app/redb) ## License Apache License 2.0 — see [LICENSE](https://github.com/redbase-app/redb/blob/main/LICENSE). Path: redb/redb.SQLite/RedbService.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.SQLite/RedbService.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Data; using redb.Core.Providers; using redb.Core.Query; using redb.Core.Serialization; using redb.Core.Utils; using redb.Core.Security; using redb.Core.Models.Contracts; using redb.Core.Models.Configuration; using redb.SQLite.Data; using redb.SQLite.Providers; using redb.SQLite.Sql; namespace redb.SQLite; /// /// SQLite implementation of IRedbService. /// Inherits all common logic from RedbServiceBase. /// Only provides SQLite-specific provider factories. /// public class RedbService : RedbServiceBase { private static readonly SqliteDialect _dialect = new(); /// /// Creates a new SQLite RedbService instance. /// public RedbService(IServiceProvider serviceProvider) : base(serviceProvider) { } // === SQLITE-SPECIFIC IMPLEMENTATIONS === protected override string DatabaseTypeName => "SQLite"; protected override ISqlDialect SqlDialect => _dialect; /// The indexes of a fresh SQLite database of this build (SqliteIndexCatalog, generated and pinned by a test). protected override IReadOnlyList ExpectedIndexes => SqliteIndexCatalog.Base; protected override string GetVersionSql => "SELECT sqlite_version()"; // Bytes, like pg_database_size on PostgreSQL: the pages the database file holds. protected override string GetDatabaseSizeSql => "SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()"; protected override string ContextNotRegisteredError => "IRedbContext is not registered in DI container. Add SqliteRedbContext to configuration."; // === PROVIDER FACTORIES === protected override ISchemeSyncProvider CreateSchemeSyncProvider( IRedbContext context, RedbServiceConfiguration config, string cacheDomain, ILogger? logger) => new SqliteSchemeSyncProvider(context, config, cacheDomain, logger); protected override IPermissionProvider CreatePermissionProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new SqlitePermissionProvider(context, securityContext, logger); protected override IUserProvider CreateUserProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new SqliteUserProvider(context, securityContext, ResolvePasswordHasher(), logger); protected override IRoleProvider CreateRoleProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new SqliteRoleProvider(context, securityContext, logger); protected override IListProvider CreateListProvider( IRedbContext context, RedbServiceConfiguration config, ISchemeSyncProvider schemeSync, ILogger? logger) => new SqliteListProvider(context, config, schemeSync, logger); protected override IObjectStorageProvider CreateObjectStorageProvider( IRedbContext context, IRedbObjectSerializer serializer, IPermissionProvider permissionProvider, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration config, IListProvider listProvider, ILogger? logger, redb.Core.Interception.RedbSaveInterceptorPipeline? saveInterceptors) => new SqliteObjectStorageProvider(context, serializer, permissionProvider, securityContext, schemeSync, config, listProvider, logger, saveInterceptors); protected override ITreeProvider CreateTreeProvider( IRedbContext context, IObjectStorageProvider objectStorage, IPermissionProvider permissionProvider, IRedbObjectSerializer serializer, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration config, ILogger? logger, redb.Core.Interception.RedbSaveInterceptorPipeline? saveInterceptors) => new SqliteTreeProvider(context, objectStorage, permissionProvider, serializer, securityContext, schemeSync, config, logger, saveInterceptors); protected override ILazyPropsLoader CreateLazyPropsLoader( IRedbContext context, ISchemeSyncProvider schemeSync, IRedbObjectSerializer serializer, RedbServiceConfiguration config, string cacheDomain, IListProvider listProvider, ILogger? logger) => new LazyPropsLoader(context, schemeSync, serializer, config, listProvider, logger); protected override IQueryableProvider CreateQueryableProvider( IRedbContext context, IRedbObjectSerializer serializer, ISchemeSyncProvider schemeSync, IRedbSecurityContext securityContext, ILazyPropsLoader lazyPropsLoader, RedbServiceConfiguration config, string cacheDomain, ILogger? logger) => new SqliteQueryableProvider(context, serializer, schemeSync, securityContext, lazyPropsLoader, config, cacheDomain, logger); protected override IValidationProvider CreateValidationProvider( IRedbContext context, ILogger? logger) => new SqliteValidationProvider(context, logger); protected override Core.Providers.IMaintenanceProvider CreateMaintenanceProvider( IRedbContext context, int analysisLimit, ILogger? logger) => new Providers.SqliteMaintenanceProvider(context, analysisLimit, logger); // === DATABASE SCHEMA MANAGEMENT === /// protected override async Task TableExistsAsync(string tableName) { var sql = "SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = @p0)"; return await Context.ExecuteScalarAsync(sql, tableName); } /// protected override string ReadEmbeddedSql() { var assembly = typeof(RedbService).Assembly; var resourceName = "redb.SQLite.sql.redbSqlite.sql"; using var stream = assembly.GetManifestResourceStream(resourceName) ?? throw new InvalidOperationException( $"Embedded resource '{resourceName}' not found. Ensure the project was built correctly."); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } /// protected override string? ReadEmbeddedPvtBundleSql() { // SQLite has no server-side v2-pvt module (no stored functions). The Pro // tier generates query SQL in C# (ProSqlBuilder); the Free tier will host // equivalents in the native extension. Either way, nothing to deploy here. return null; } /// /// /// The script runs under a savepoint and is rolled back as a whole when a statement fails: the schema lock commits /// its transaction when it is released, so the statements before the failure stayed in the file, and the next start /// took the file with _schemes for an existing schema and ran the upgrade steps over the half of it. /// protected override async Task ExecuteSchemaScriptAsync(string sql) { await Context.ExecuteAsync("SAVEPOINT redb_schema_create"); try { await Context.ExecuteAsync(sql); } catch (Exception failure) { try { await Context.ExecuteAsync("ROLLBACK TO redb_schema_create"); await Context.ExecuteAsync("RELEASE redb_schema_create"); } catch (Exception rollbackFailure) { // SQLite may have ended the transaction itself (a full disk): the creation error is the one to report. failure.Data["redb.SchemaCreateRollbackFailure"] = rollbackFailure.Message; } throw; } await Context.ExecuteAsync("RELEASE redb_schema_create"); } /// /// The schema version this build writes into PRAGMA user_version — the SQLite counterpart of /// pvt_module_version(): the one number that says which upgrades a database file has had. /// Bump it when gains a step; a database stamped with an /// older number gets every step (they are idempotent), a current one skips the pass entirely. /// /// /// 1 — V4: hashes as BLOB(16) (). /// 2 — V4 (UNIQUE Э2): _structures._unique, _structures._unique_version, _values._unique BLOB(16), /// the partial unique index, and the same two columns on _scheme_metadata_cache. /// 3 — V4 (UNIQUE Э1): _objects._value_unique and its partial unique index. /// 4 — V4 (LAZY Л2): _structures._lazy and _scheme_metadata_cache._lazy (the virtual marker). /// 5 — V4 (LAZY Л2): resync _scheme_metadata_cache._lazy from _structures (repairs caches /// synced between the column upgrade and the marker write). /// 6 — V4 (LAZY Л2): stamp bump only. The SQLite metadata-cache WARMUP (`Warmup_AllMetadataCaches`) /// carried a stale column list and re-nulled the marker after step 5 on files stamped 5; /// the list is fixed and the resync of step 5 runs again for them. /// 7 — FK-column indexes IX__values__ListItem_not_null / IX__values__Object_not_null (partial): /// without them every DELETE of a referenced object or list item scans the whole _values /// for the FK check (perf finding, 2026-09-10). /// 10 — the indexes another index of the same table fully replaces are dropped, the set PostgreSQL /// dropped in its module 0.7.13 (2026-10-14). /// 11 — value-leading indexes IX__values__structure_<value>_object for every value column, the set /// PostgreSQL got in its module 0.7.16; the object-leading *_not_null, ix__values__array_null_structure /// and the IX__values__scalar_*_object of SQLite Pro dropped (2026-10-17). /// 12 — IX__values__structure_object_string (partial, text values only): which objects hold a text value of a /// field, without reading the text. A filter Field == null over a text field reads it (2026-10-21). /// 13 — the table _schema_compat: which builds a file still serves (). A build /// whose schema version is below the file's leaves the file as it is and opens it when that row allows, /// otherwise it stops with RedbSchemaNewerException (2026-11-14). /// 14 — _structures._renamed_from and _schemes._renamed_from: the previous names the sync records when it applies a /// rename ([RedbRename], RedbScheme.RenamedFrom), read to stop a class older than the rename (2026-11-18). /// 15 — TimeOnly and TimeSpan as Ticks in _Long: _types._db_type and _scheme_metadata_cache.db_type say Long for /// them. Older builds read and write them as text, so the file refuses them ( /// 15, 2026-11-21). /// 16 — _schemes._version: the version of the Props class the scheme was last synchronised with /// (RedbScheme.Version); the sync deletes a structure or changes its type only for a class of a higher version /// (2026-11-29). Older builds ignore the column, so the oldest reader stays as it was. /// 17 — IX__values__array_parent_id is dropped where a non-partial index led by _array_parent_id remains /// (IX__values__array_parent_index), the step PostgreSQL module 0.7.33 makes (2026-11-30). /// public static int SchemaVersion { get; } = 17; /// /// The oldest schema version that may open a file of this build: written into _schema_compat with every /// stamp. Raise it only when a step breaks the C# of older builds (a dropped or renamed column or table they read); /// never lower it. is the redb package version that first shipped that schema /// version, named to the operator of an older build that may not open the file. /// // 15: an older build would write TimeOnly/TimeSpan as text into a file whose readers take ticks (step 15). private const int SchemaCompatMinReader = 15; private const string SchemaCompatPackage = "4.8.0"; /// /// The schema upgrades of under the schema lock, the version asked again /// under it: two processes opening one old file (a panel and a worker of one host) ran the same steps at once, and /// a step that checks and then acts (a column, an index rebuilt under its name) failed in the second. /// /// False when the file belongs to a newer build: then nothing was changed, and nothing else may be. private async Task ApplySchemaUpgradesAsync() { var fileVersion = await Context.ExecuteScalarAsync("PRAGMA user_version"); if (fileVersion > SchemaVersion) { await AcceptNewerFileAsync(fileVersion); return false; } // The unique key of root structures is not a numbered step: a file with duplicates holding values goes on // without it, and every start tries again until they are resolved. if (fileVersion >= SchemaVersion && !await IsRootStructureKeyMissingAsync()) return true; await using (await AcquireSchemaLockAsync()) { // A newer build may have opened the file while this one waited. fileVersion = await Context.ExecuteScalarAsync("PRAGMA user_version"); if (fileVersion > SchemaVersion) { await AcceptNewerFileAsync(fileVersion); return false; } if (fileVersion < SchemaVersion) await ApplySchemaUpgradeStepsAsync(); await EnsureRootStructureKeyAsync(); } return true; } /// /// The file was written by a newer build: never taken back. Opened, with one warning per process, when its /// _schema_compat row allows this build; otherwise start-up stops with /// . A newer file without the row states nothing and is /// treated as not allowing. /// private async Task AcceptNewerFileAsync(long fileVersion) { long? minReader = null; string? package = null; if (await TableExistsAsync("_schema_compat")) { var rows = await Context.QueryAsync( "SELECT _min_reader AS MinReader, _package AS Package FROM _schema_compat LIMIT 1"); if (rows.Count > 0) { minReader = rows[0].MinReader; package = rows[0].Package; } } var deployed = fileVersion.ToString(System.Globalization.CultureInfo.InvariantCulture); var own = SchemaVersion.ToString(System.Globalization.CultureInfo.InvariantCulture); if (minReader is null || minReader > SchemaVersion) throw new redb.Core.Exceptions.RedbSchemaNewerException(DatabaseTypeName, deployed, own, package); WarnNewerOnce(DatabaseTypeName, deployed, own, Logger); } private sealed class SchemaCompatRow { public long MinReader { get; set; } public string? Package { get; set; } } /// protected override Task OpenSchemaLockAsync(CancellationToken cancellationToken) // Inside a transaction of this service the write lock of the file is already ours. => Task.FromResult(Context.IsInTransaction ? SchemaLockHandle.None : new WriteLock(Context)); /// /// The schema lock of SQLite: the single write lock of the file, taken by an immediate transaction of the /// service's own connection, and every statement of the work runs in it. A lock on a connection of its own would /// make the service wait for itself. An attempt that finds the file locked past the busy time-out of the /// connection gives way; disposing commits what was done, as each statement committed on its own before. /// private sealed class WriteLock(IRedbContext context) : SchemaLockHandle { private IRedbTransaction? _transaction; public override string Name => "BEGIN IMMEDIATE"; public override async Task TryAcquireAsync(CancellationToken cancellationToken) { // Microsoft.Data.Sqlite retries a busy BEGIN until the command time-out of the connection (Default Timeout, // 30 s unless the connection string says otherwise), so one attempt lasts up to that; the wait of the // service overshoots its time-out by at most as much. try { _transaction = await context.BeginTransactionAsync(cancellationToken: cancellationToken); return true; } catch (Microsoft.Data.Sqlite.SqliteException ex) when (ex.SqliteErrorCode is 5 or 6) { // SQLITE_BUSY / SQLITE_LOCKED: another process writes. return false; } } public override async ValueTask DisposeAsync() { if (_transaction == null) return; try { if (_transaction.IsActive) await _transaction.CommitAsync(); } finally { await _transaction.DisposeAsync(); } } } /// /// Schema upgrades for a database created by an older build — the SQLite counterpart of the /// "0. Schema upgrades" step of the PostgreSQL/MSSQL module bundle. Every statement is idempotent, /// and the pass as a whole is gated by PRAGMA user_version: without the gate the /// typeof() checks below would scan _objects on every start. Runs before /// . /// private async Task ApplySchemaUpgradeStepsAsync() { var deployed = await Context.ExecuteScalarAsync("PRAGMA user_version"); if (deployed >= SchemaVersion) return; // 1 — V4: hashes are BLOB(16) in RFC 4122 byte order (SqliteHash). Databases created before V4 // hold them as 36-character TEXT. SQLite keeps the storage class a value was written with, // whatever the column declares, so a declared-TEXT column takes the BLOB and no ALTER is // needed: convert the values in place; typeof() tells the two apart. foreach (var (table, column) in new[] { ("_objects", "_hash"), ("_schemes", "_structure_hash"), ("_users", "_hash") }) { await Context.ExecuteAsync( $"UPDATE {table} SET {column} = {SqliteHash.FromText(column)} WHERE typeof({column}) = 'text'"); } // 2 - V4 (UNIQUE stage 2): [RedbUnique] key metadata and the key hash column - the SQLite // delivery of the module block "0. Schema upgrades" (PG/MSSQL 00_module_init.sql). SQLite // ALTER TABLE ADD COLUMN has no IF NOT EXISTS, so each is guarded by pragma_table_info. foreach (var (table, column, type) in new[] { ("_structures", "_unique", "INTEGER"), ("_structures", "_unique_version", "INTEGER"), ("_values", "_unique", "BLOB"), ("_scheme_metadata_cache", "_unique", "INTEGER"), ("_scheme_metadata_cache", "_unique_version", "INTEGER"), }) { if (!await ColumnExistsAsync(table, column)) await Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN {column} {type} NULL"); } await Context.ExecuteAsync( "CREATE UNIQUE INDEX IF NOT EXISTS \"UIX__values__structure_unique\" " + "ON _values (_id_structure, _unique) " + "WHERE _unique IS NOT NULL"); // 3 - V4 (UNIQUE stage 1): the object key column and its unique index (length 440 is // enforced in C# - SQLite does not check VARCHAR lengths). if (!await ColumnExistsAsync("_objects", "_value_unique")) await Context.ExecuteAsync("ALTER TABLE _objects ADD COLUMN _value_unique TEXT NULL"); await Context.ExecuteAsync( "CREATE UNIQUE INDEX IF NOT EXISTS \"UIX__objects__scheme_unique\" " + "ON _objects (_id_scheme, _value_unique) WHERE _value_unique IS NOT NULL"); // 4 - V4 (LAZY L2): the lazy-reference marker, read from `virtual` at synchronisation. foreach (var (table, column) in new[] { ("_structures", "_lazy"), ("_scheme_metadata_cache", "_lazy") }) { if (!await ColumnExistsAsync(table, column)) await Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN {column} INTEGER NULL"); } // 5 - V4 (LAZY L2): repair caches that were synced before the marker landed. await Context.ExecuteAsync( "UPDATE _scheme_metadata_cache SET _lazy = (SELECT s._lazy FROM _structures s WHERE s._id = _structure_id)"); // 7 - FK-column indexes of _values (perf, 2026-09-10): _Object and _ListItem carry // foreign keys, and without a leading index every DELETE of a referenced object or // list item scans the whole table for the FK check (measured: seconds per check on // ~8.4M rows, milliseconds with the index). Partial form keeps them nearly empty - // reference fields are a small fraction of rows - so writes barely pay. await Context.ExecuteAsync( "CREATE INDEX IF NOT EXISTS \"IX__values__ListItem_not_null\" " + "ON _values (_ListItem) WHERE _ListItem IS NOT NULL"); await Context.ExecuteAsync( "CREATE INDEX IF NOT EXISTS \"IX__values__Object_not_null\" " + "ON _values (_Object) WHERE _Object IS NOT NULL"); // 8 - S2 (subtree-unique plan): the key index covers keyed rows at ANY position now - // nested scalar keys carry _array_parent_id, and the old positional filter kept them // OUT of the index, so their "uniqueness" silently never fired. Recreate on the old // predicate; fresh databases get the final form from redbSqlite.sql. var oldKeyIndexForm = await Context.ExecuteScalarAsync( "SELECT 1 FROM sqlite_master WHERE type = 'index' " + "AND name = 'UIX__values__structure_unique' AND sql LIKE '%_array_parent_id%'"); if (oldKeyIndexForm.HasValue) { await Context.ExecuteAsync("DROP INDEX \"UIX__values__structure_unique\""); await Context.ExecuteAsync( "CREATE UNIQUE INDEX \"UIX__values__structure_unique\" " + "ON _values (_id_structure, _unique) WHERE _unique IS NOT NULL"); } // 9 - S3 (subtree-unique plan): element-key scope of collection keys, and the // free-form _tags marker on schemes, structures and the metadata cache. foreach (var (table, column, type) in new[] { ("_structures", "_unique_scope", "INTEGER"), ("_structures", "_tags", "TEXT"), ("_schemes", "_tags", "TEXT"), ("_scheme_metadata_cache", "_unique_scope", "INTEGER"), ("_scheme_metadata_cache", "_tags", "TEXT"), }) { if (!await ColumnExistsAsync(table, column)) await Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN {column} {type} NULL"); } await Context.ExecuteAsync( "CREATE INDEX IF NOT EXISTS \"IX__structures__tags\" " + "ON _structures (_tags) WHERE _tags IS NOT NULL"); await Context.ExecuteAsync( "UPDATE _scheme_metadata_cache SET " + "_unique_scope = (SELECT s._unique_scope FROM _structures s WHERE s._id = _structure_id), " + "_tags = (SELECT s._tags FROM _structures s WHERE s._id = _structure_id)"); // 10 - index cleanup (2026-10-14): indexes another index of the same table fully replaces, // the set PostgreSQL dropped in its module 0.7.13. Runs once, on the stamp: an index put back // by hand stays. The statements that put them back: // CREATE INDEX "IX__values__object_structure_array_index" ON _values (_id_object, _id_structure, _array_index) WHERE _array_index IS NOT NULL; // CREATE INDEX "IX__structures__not_collection" ON _structures (_id, _name, _id_scheme) WHERE _collection_type IS NULL; // CREATE INDEX "IX__functions__schemes" ON _functions (_id_scheme); // CREATE INDEX "IX__permissions__roles" ON _permissions (_id_role); // CREATE INDEX "IX__dependencies__schemes_1" ON _dependencies (_id_scheme_1); // CREATE INDEX "IX__users_roles__roles" ON _users_roles (_id_role); // IX__values__structure_object_lookup stays, unlike PostgreSQL: the streams form reads // string fields through it. foreach (var index in new[] { "IX__values__object_structure_array_index", "IX__structures__not_collection", "IX__functions__schemes", "IX__permissions__roles", "IX__dependencies__schemes_1", "IX__users_roles__roles", }) { await Context.ExecuteAsync($"DROP INDEX IF EXISTS \"{index}\""); } // 11 - value-leading indexes (2026-10-17), see redbSqlite.sql. Built before the old ones are // dropped. An index of one of these names with any other definition is rebuilt: CREATE INDEX IF // NOT EXISTS alone would keep it. sqlite_master keeps the statement as written, so it is compared // with whitespace collapsed and IF NOT EXISTS taken out. An index built here gets planner // statistics at once, bounded as the maintenance ANALYZE is: without them SQLite costs it blind. var built = new List(); foreach (var column in ValueColumns) { var name = $"IX__values__structure_{column.ToLowerInvariant()}_object"; var definition = $"CREATE INDEX \"{name}\" ON _values (_id_structure, _{column}, _id_object, _array_index) WHERE _{column} IS NOT NULL"; var existing = await Context.ExecuteScalarAsync( $"SELECT sql FROM sqlite_master WHERE type = 'index' AND name = '{name}'"); if (existing != null && NormalizeIndexSql(existing) != definition) { await Context.ExecuteAsync($"DROP INDEX \"{name}\""); existing = null; } if (existing == null) { await Context.ExecuteAsync(definition); built.Add(name); } } if (built.Count > 0) { var limit = Configuration.MaintenanceAnalysisLimit; await Context.ExecuteAsync($"PRAGMA analysis_limit = {(limit > 0 ? limit : 0)}"); foreach (var name in built) await Context.ExecuteAsync($"ANALYZE \"{name}\""); } foreach (var index in new[] { "IX__values__String_not_null", "IX__values__Long_not_null", "IX__values__DateTimeOffset_not_null", "IX__values__Numeric_not_null", "ix__values__array_null_structure", "IX__values__scalar_String_object", "IX__values__scalar_Long_object", "IX__values__scalar_Numeric_object", "IX__values__scalar_DateTimeOffset_object", }) { await Context.ExecuteAsync($"DROP INDEX IF EXISTS \"{index}\""); } // 12 - which objects hold a text value of a field (2026-10-21), see redbSqlite.sql. The text column is // in no other index by object, so a check that a text field is absent read every row from the table. // Statistics at once, as in step 11. var stringIndexExists = await Context.ExecuteScalarAsync( "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'IX__values__structure_object_string'"); if (!stringIndexExists.HasValue) { await Context.ExecuteAsync( "CREATE INDEX \"IX__values__structure_object_string\" ON _values (_id_structure, _id_object) WHERE _String IS NOT NULL"); var limit = Configuration.MaintenanceAnalysisLimit; await Context.ExecuteAsync($"PRAGMA analysis_limit = {(limit > 0 ? limit : 0)}"); await Context.ExecuteAsync("ANALYZE \"IX__values__structure_object_string\""); } // 13 - _schema_compat: which builds the file still serves. Written by the stamp below, with every stamp. // 14 - the previous names of renamed structures and schemes ([RedbRename], RedbScheme.RenamedFrom). foreach (var table in new[] { "_structures", "_schemes" }) { if (!await ColumnExistsAsync(table, "_renamed_from")) await Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN _renamed_from TEXT NULL"); } // 15 - TimeOnly and TimeSpan are stored as Ticks in _Long: the type rows and their copy in the metadata cache // say Long. Values already stored as text are not converted (UPGRADING.md gives the statement). await Context.ExecuteAsync( "UPDATE _types SET _db_type = 'Long' WHERE _id IN (-9223372036854775685, -9223372036854775684) AND _db_type <> 'Long'"); await Context.ExecuteAsync( "UPDATE _scheme_metadata_cache SET db_type = 'Long' WHERE _type_id IN (-9223372036854775685, -9223372036854775684) AND db_type <> 'Long'"); // 16 - the version of the Props class a scheme was last synchronised with (RedbScheme.Version). if (!await ColumnExistsAsync("_schemes", "_version")) await Context.ExecuteAsync("ALTER TABLE _schemes ADD COLUMN _version INTEGER NULL"); // 17 - IX__values__array_parent_id (_array_parent_id) is the leading column of IX__values__array_parent_index, // which serves its lookups and the ON DELETE CASCADE of FK__values__array_parent. Dropped only where another // non-partial index led by _array_parent_id remains: a file created by an old version may lack the wide one, and // the cascade must keep an index. Put back by hand: // CREATE INDEX "IX__values__array_parent_id" ON _values (_array_parent_id); var wideParentIndexes = await Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM pragma_index_list('_values') l " + "WHERE l.name <> 'IX__values__array_parent_id' AND l.partial = 0 " + "AND EXISTS (SELECT 1 FROM pragma_index_info(l.name) i WHERE i.seqno = 0 AND i.name = '_array_parent_id')"); if (wideParentIndexes > 0) await Context.ExecuteAsync("DROP INDEX IF EXISTS \"IX__values__array_parent_id\""); await StampSchemaVersionAsync(); } /// Value columns of _values that get a value-leading index (schema step 11). private static readonly string[] ValueColumns = ["String", "Long", "Numeric", "Double", "DateTimeOffset", "Boolean", "Guid", "ListItem", "Object"]; /// A CREATE INDEX statement as sqlite_master keeps it, reduced to one spelling. private static string NormalizeIndexSql(string sql) => System.Text.RegularExpressions.Regex.Replace(sql, @"\s+", " ").Trim() .Replace("CREATE INDEX IF NOT EXISTS ", "CREATE INDEX ", StringComparison.OrdinalIgnoreCase); /// /// The version of this build into PRAGMA user_version, and into _schema_compat which builds the file /// still serves (step 13; written with every stamp, so a file created from the schema script has it too). /// private async Task StampSchemaVersionAsync() { await Context.ExecuteAsync( "CREATE TABLE IF NOT EXISTS _schema_compat(_min_reader INTEGER NOT NULL, _package TEXT NOT NULL)"); await Context.ExecuteAsync("DELETE FROM _schema_compat"); await Context.ExecuteAsync( $"INSERT INTO _schema_compat(_min_reader, _package) VALUES ({SchemaCompatMinReader}, '{SchemaCompatPackage}')"); await Context.ExecuteAsync($"PRAGMA user_version = {SchemaVersion}"); } private async Task ColumnExistsAsync(string table, string column) => (await Context.ExecuteScalarAsync( $"SELECT 1 FROM pragma_table_info('{table}') WHERE name = '{column}' LIMIT 1")).HasValue; /// /// Applies corrections to seeded metadata on a database that already exists. /// /// /// PostgreSQL and MSSQL get this for free: a corrected seed rides /// sql/v2-pvt/*.sql, and EnsurePvtModuleDeployedAsync reapplies the bundle whenever /// pvt_module_version() disagrees with the dialect. SQLite has no such channel — it has no /// stored functions, so it has no module and no version to compare, and /// returns null on purpose. redbSqlite.sql is applied /// only when the tables are absent. Without the step below, a fix to seeded data would reach new /// databases and no existing one, however many times the package is upgraded. /// /// /// /// Every statement here must be idempotent: this runs on every start, not once. /// /// private async Task ApplySeedCorrectionsAsync() { // DateOnly was seeded with _db_type = 'DateTime', a value no JSON projection branches on, so // every DateOnly property materialised as 0001-01-01. Retyping it to 'DateTimeOffset' routes it // through the branch that already exists; the stored value is untouched, it has always been // midnight of that date in _values._DateTimeOffset. var fixedRows = await Context.ExecuteAsync( "UPDATE _types SET _db_type = 'DateTimeOffset' " + "WHERE _id = " + RedbTypeIds.DateOnly + " AND _db_type <> 'DateTimeOffset'"); if (fixedRows <= 0) return; // The scheme metadata cache copies _db_type, so readers would keep answering from the stale // copy. Dropping the affected rows is enough — the cache is rebuilt on demand. await Context.ExecuteAsync( "DELETE FROM _scheme_metadata_cache WHERE _scheme_id IN " + "(SELECT DISTINCT _id_scheme FROM _structures WHERE _id_type = " + RedbTypeIds.DateOnly + ")"); } /// /// SQLite ships no v2-pvt bundle, so the base version check is a no-op; the schema-upgrade pass /// is the SQLite delivery of the same contract and must reach an existing file through /// InitializeAsync() exactly as the module block "0. Schema upgrades" reaches PostgreSQL /// and MSSQL, not only through . A file without the schema is /// left to (or the first synchronisation) to report; /// itself runs the pass after creation, so the base call made /// from there is skipped. AutoApplyDatabaseUpgrades is ignored on SQLite by contract. /// protected override async Task EnsurePvtModuleDeployedAsync() { await EnsureNativeExtensionVersionAsync(); if (_ensuringDatabase) return; if (!await TableExistsAsync("_schemes")) return; await ApplySchemaUpgradesAsync(); await KeepPlannerStatisticsAsync(); } /// Value rows from which a file without planner statistics is analyzed at start-up. internal const int PlannerStatisticsThreshold = 10_000; /// /// Planner statistics of the file (KeepSqlitePlannerStatistics). Without sqlite_stat1 SQLite costs an /// index lookup at a few rows whatever the table holds, and may put the scheme's index of _objects on the outer /// loop of a statement that a page of a hundred rows should drive. A file an application filled has none: SQLite /// gathers them only on ANALYZE. So a file with no statistics for _objects and _values and at least /// value rows is analyzed here, sampled by MaintenanceAnalysisLimit; /// a smaller file is left alone, because statistics of a nearly empty file stay behind as it grows and mislead more /// than none. A file that has statistics gets PRAGMA optimize, which analyzes again, sampled the same way, only /// the tables whose row count changed tenfold since. A file that cannot be written is left as it is. /// private async Task KeepPlannerStatisticsAsync() { if (!Configuration.KeepSqlitePlannerStatistics) return; try { var limit = Configuration.MaintenanceAnalysisLimit; await Context.ExecuteAsync($"PRAGMA analysis_limit = {(limit > 0 ? limit : 0)}"); var haveStatistics = await Context.ExecuteScalarAsync( "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'") != null && await Context.ExecuteScalarAsync( "SELECT 1 FROM sqlite_stat1 WHERE tbl IN ('_objects', '_values') LIMIT 1") != null; if (haveStatistics) { // 0x10002: analyze where it pays (0x02), over every table, not only those this connection has read (0x10000). await Context.ExecuteAsync("PRAGMA optimize = 0x10002"); return; } var rows = await Context.ExecuteScalarAsync( $"SELECT count(*) FROM (SELECT 1 FROM _values LIMIT {PlannerStatisticsThreshold})") ?? 0; if (rows < PlannerStatisticsThreshold) return; var started = System.Diagnostics.Stopwatch.StartNew(); await Context.ExecuteAsync("ANALYZE"); Logger?.LogInformation("Planner statistics gathered for the SQLite file in {Elapsed} ms (sample limit {Limit}).", started.ElapsedMilliseconds, limit); } catch (Microsoft.Data.Sqlite.SqliteException ex) when (ex.SqliteErrorCode is 5 or 6 or 8) { // SQLITE_BUSY, SQLITE_LOCKED, SQLITE_READONLY: another process holds the file, or it is opened read-only. Logger?.LogWarning(ex, "Planner statistics of the SQLite file were not refreshed: the file cannot be written now. " + "IMaintenanceProvider.AnalyzeAsync gathers them on demand."); } } /// /// The SQLite delivery of the module version gate: the loaded native extension must report the version the /// dialect requires. Nothing to apply on a mismatch - the library ships with the package - so it is refused, /// naming the file. Skipped when no extension is configured (the Pro tier compiles its queries in C#). /// private async Task EnsureNativeExtensionVersionAsync() { var path = SqliteDataSource.NativeExtensionPath; var versionFn = SqlDialect.Query_PvtModuleVersionFunction(); var required = SqlDialect.Query_PvtRequiredVersion(); if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(versionFn) || string.IsNullOrEmpty(required)) return; string? deployed; try { deployed = await Context.ExecuteScalarAsync($"SELECT {versionFn}()"); } catch (Microsoft.Data.Sqlite.SqliteException ex) when (ex.Message.Contains("no such function", StringComparison.Ordinal)) { // An extension from before the version function: refused below by name. deployed = null; } SqliteNativeExtension.EnsureVersion(path, deployed, required); } private bool _ensuringDatabase; /// public override async Task EnsureDatabaseAsync() { // Asked before the base call, which creates the tables when they are missing: a freshly created // database is already correct and needs no correction pass. var existedBefore = await TableExistsAsync("_schemes"); _ensuringDatabase = true; try { await base.EnsureDatabaseAsync(); } finally { _ensuringDatabase = false; } if (!existedBefore) { // Created by this build: every upgrade is already in the schema script. await StampSchemaVersionAsync(); return; } // A file of a newer build is left as it is, seed corrections included. if (await ApplySchemaUpgradesAsync()) await ApplySeedCorrectionsAsync(); } } Path: redb/redb.SQLite/Utils/ValuesTopologicalSort.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/Utils/ValuesTopologicalSort.cs ---- using System.Collections.Generic; using System.Linq; using redb.Core.Data; using redb.Core.Models.Entities; namespace redb.SQLite.Utils { /// /// Topological sorting of _values to maintain FK constraint on _array_parent_id. /// Parent records must be inserted BEFORE children in BulkInsert. /// public static class ValuesTopologicalSort { /// /// Sort values by ArrayParentId dependencies (single-threaded). /// BFS algorithm: first records without parent, then their children, etc. /// public static List SortByFkDependency(List values) { if (values.Count <= 1) return values; var valueIds = values.Select(v => v.Id).ToHashSet(); // BFS sorting var byParent = values .Where(v => v.ArrayParentId.HasValue) .ToLookup(v => v.ArrayParentId!.Value); var result = new List(values.Count); var added = new HashSet(); var queue = new Queue(); // Start with records WITHOUT parent OR with EXTERNAL parent (parent in DB, not in batch) foreach (var v in values.Where(v => !v.ArrayParentId.HasValue || !valueIds.Contains(v.ArrayParentId.Value))) { queue.Enqueue(v); added.Add(v.Id); } while (queue.Count > 0) { var current = queue.Dequeue(); result.Add(current); foreach (var child in byParent[current.Id]) { if (!added.Contains(child.Id)) { queue.Enqueue(child); added.Add(child.Id); } } } // If records remain (cyclic dependencies?), add to end if (result.Count < values.Count) { var remaining = values.Where(v => !added.Contains(v.Id)).ToList(); result.AddRange(remaining); } return result; } } } Path: redb/redb.SQLite/build/redb.SQLite.targets 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/build/redb.SQLite.targets ---- runtimes\win-x64\native\redbsqlite.dll PreserveNewest false runtimes\linux-x64\native\redbsqlite.so PreserveNewest false runtimes\linux-arm64\native\redbsqlite.so PreserveNewest false runtimes\osx-x64\native\redbsqlite.dylib PreserveNewest false runtimes\osx-arm64\native\redbsqlite.dylib PreserveNewest false Path: redb/redb.SQLite/native/CMakeLists.txt 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/native/CMakeLists.txt ---- cmake_minimum_required(VERSION 3.16) project(redb_sqlite_ext C) # REDB SQLite Free loadable extension. # Hosts the server-side SQL functions (get_object_json, pvt_*, permissions, # soft-delete) inside the SQLite engine — the SQLite analog of PostgreSQL Free. # Works in ANY SQLite host (Microsoft.Data.Sqlite, Python sqlite3, sqlite3 CLI), # because the extension is loaded by the host process and resolves the sqlite3 # API symbols from it at load time — we do NOT link against libsqlite3. set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) # ---------------------------------------------------------------------------- # SQLite amalgamation headers (sqlite3.h + sqlite3ext.h). # A loadable extension only needs the HEADERS to compile against the public # API + the SQLITE_EXTENSION_INIT machinery. We fetch a pinned amalgamation # zip at configure time so the repo stays clean (no vendored 13k-line header). # Override SQLITE_AMALGAMATION_URL to bump or to point at a local mirror. # ---------------------------------------------------------------------------- include(FetchContent) set(SQLITE_AMALGAMATION_URL "https://www.sqlite.org/2024/sqlite-amalgamation-3460100.zip" CACHE STRING "URL of the SQLite amalgamation zip (provides sqlite3.h + sqlite3ext.h)") FetchContent_Declare(sqlite_amalgamation URL "${SQLITE_AMALGAMATION_URL}" DOWNLOAD_EXTRACT_TIMESTAMP TRUE) FetchContent_MakeAvailable(sqlite_amalgamation) # ---------------------------------------------------------------------------- # The extension itself — built as a shared MODULE (dlopen/LoadLibrary target). # Output base name is "redbsqlite" on every platform (a specific name, not the # generic/dangerous "redb", which collides with the managed redb.* assemblies and # the host's redb.* prune globs): # Windows : redbsqlite.dll # Linux : redbsqlite.so (PREFIX "" → not libredbsqlite.so) # macOS : redbsqlite.dylib # The C init symbol stays sqlite3_redb_init (see src/redb_extension.c); because the # file base name no longer derives it, consumers load with an EXPLICIT entry point: # conn.LoadExtension(path, "sqlite3_redb_init") (SqliteDataSource.LoadNativeExtension) # ---------------------------------------------------------------------------- add_library(redb MODULE src/redb_extension.c src/redb_pvt.c src/redb_pvt_analytics.c ) target_include_directories(redb PRIVATE "${sqlite_amalgamation_SOURCE_DIR}") set_target_properties(redb PROPERTIES PREFIX "" OUTPUT_NAME "redbsqlite") if(APPLE) set_target_properties(redb PROPERTIES SUFFIX ".dylib") endif() # Warnings as a quality gate (extension code must be clean). if(MSVC) target_compile_options(redb PRIVATE /W3) else() target_compile_options(redb PRIVATE -Wall -Wextra) endif() Path: redb/redb.SQLite/native/Dockerfile 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/native/Dockerfile ---- # Toolchain image for the REDB SQLite loadable extension: native x64 + arm64 cross-compile. # # Why an image at all: the recipe used to be `docker run --rm debian:12` + apt-get install on every # build, so each rebuild re-downloaded ~190 MB of toolchain and the container took it away again. # Built once, this image makes a rebuild take seconds and work offline — which also means a release # does not depend on a Debian mirror answering at that moment. # # docker build -t redb-sqlite-native native/ # once (or after changing this file) # # crossbuild-essential-arm64, not a bare gcc-aarch64-linux-gnu: the cross compiler alone has no # arm64 C runtime and fails at link with "cannot find Scrt1.o / crti.o". FROM debian:12 ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update -qq && \ apt-get install -y --no-install-recommends \ build-essential \ cmake \ crossbuild-essential-arm64 \ ca-certificates \ curl \ unzip \ file && \ rm -rf /var/lib/apt/lists/* # The sqlite3 CLI of the verification step, built from the SAME amalgamation the extension compiles # against (keep in step with SQLITE_AMALGAMATION_URL in CMakeLists.txt). Debian 12 ships 3.40.1, and # the extension refuses to load below 3.44 (it needs sqlite3_get_clientdata), so the packaged CLI # cannot run the check at all. Building it here also keeps the check offline. ARG SQLITE_AMALGAMATION_URL=https://www.sqlite.org/2024/sqlite-amalgamation-3460100.zip RUN curl -sSL "$SQLITE_AMALGAMATION_URL" -o /tmp/sqlite.zip && \ unzip -q /tmp/sqlite.zip -d /tmp && \ cd /tmp/sqlite-amalgamation-* && \ gcc -O2 -DSQLITE_ENABLE_LOAD_EXTENSION=1 shell.c sqlite3.c -o /usr/local/bin/sqlite3 -ldl -lm -lpthread && \ rm -rf /tmp/sqlite.zip /tmp/sqlite-amalgamation-* && \ sqlite3 --version WORKDIR /src Path: redb/redb.SQLite/native/README.md 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/native/README.md ---- # REDB SQLite Free — native extension A SQLite **loadable extension** that hosts the REDB server-side SQL functions (`get_object_json`, `pvt_*`, permissions, soft-delete) inside the SQLite engine. This is the SQLite analog of the PostgreSQL **Free** edition (where those live as PL/pgSQL functions). Because it is loaded by the host process and resolves the `sqlite3` API at load time, **the same binary works in any SQLite host**: Microsoft.Data.Sqlite (.NET), Python's `sqlite3`, the `sqlite3` CLI, etc. > Pure-C# **Pro** (`redb.SQLite.Pro`) needs none of this — it materializes in > managed code and runs in Blazor WASM. This extension is the **Free** path and > the foundation for non-.NET bindings (e.g. Python). ## Status | Milestone | Scope | State | |-----------|-------|-------| | M1 | Build/load pipeline + `redb_version()` canary | **current** | | M2 | `get_object_json` recursive materializer | pending | | M3 | `pvt_*` SQL generators + `search_objects_with_facets` | pending | | M4 | permissions (`get_user_permissions_for_object`, `v_user_permissions`) | pending | | M5 | soft-delete (`mark_for_deletion`, `purge_trash`) | pending | ## Output One file, base name `redbsqlite`, per platform/arch: | Platform | File | |----------|------| | Windows x64 | `redbsqlite.dll` | | Linux x64 / arm64 (glibc) | `redbsqlite.so` | | macOS x64 / arm64 | `redbsqlite.dylib` | > The base name is **`redbsqlite`** (specific), NOT the generic `redb` — the latter > collides with the managed `redb.*` assemblies and the host's `redb.*` prune globs. > The C init symbol stays **`sqlite3_redb_init`** (SQLite would otherwise derive > `sqlite3_redbsqlite_init` from the file name), so hosts must load with an **explicit > entry point**: `sqlite3_redb_init`. ## Toolchain - **CMake ≥ 3.16** and a **C99 compiler**. - Windows: Visual Studio Build Tools (Desktop C++ workload) **or** MSYS2 / MinGW-w64. Plus CMake. - Linux: `gcc` or `clang` + `cmake` (e.g. `apt install build-essential cmake`). From a Windows host nothing is needed beyond Docker: the toolchain ships in the image built from [Dockerfile](Dockerfile). - macOS: Xcode Command Line Tools + `cmake` (`brew install cmake`). - Internet access on the **first** configure (CMake fetches the pinned SQLite amalgamation for `sqlite3.h` / `sqlite3ext.h`). Override the source with `-DSQLITE_AMALGAMATION_URL=...` to use a local mirror. ## Build One `redb_pvt.c` (and siblings) → one loadable module per platform/arch. There is **no CI for the native extension** — it is rebuilt by hand whenever the C sources change, and the artifacts are git-ignored (packed at publish time from the `build*/` directories below). The recipes below are the verified ones. ### Windows x64 → `build/redbsqlite.dll` Uses the compiler + CMake + Ninja bundled with Visual Studio (no separate CMake install needed). Run from **PowerShell** — piping a `vcvarsXX.bat` through Git Bash mangles the quoting. ```powershell $vs = "C:\Program Files\Microsoft Visual Studio\18\Insiders" # adjust edition/year $vcvars = "$vs\VC\Auxiliary\Build\vcvars64.bat" $cmake = "$vs\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" $nat = "C:\Work\redb_code\csharp\redb\redb.SQLite\native" cmd /c "`"$vcvars`" && `"$cmake`" -S `"$nat`" -B `"$nat\build`" -G Ninja -DCMAKE_BUILD_TYPE=Release" cmd /c "`"$vcvars`" && `"$cmake`" --build `"$nat\build`" --clean-first" ``` Artifact: `build/redbsqlite.dll`. ### Linux x64 + arm64 → `build-linux-x64/` and `build-linux-arm64/` (Docker, from a Windows/any host) x64 builds natively; arm64 cross-compiles. The toolchain lives in an image built from [Dockerfile](Dockerfile) — build it once: ```sh docker build -t redb-sqlite-native native/ ``` Then every rebuild is seconds and needs no network: ```sh docker run --rm -v "/abs/path/to/redb.SQLite/native":/src redb-sqlite-native bash -c ' set -e cmake -S /src -B /src/build-linux-x64 -DCMAKE_BUILD_TYPE=Release && cmake --build /src/build-linux-x64 cmake -S /src -B /src/build-linux-arm64 -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=aarch64-linux-gnu-gcc cmake --build /src/build-linux-arm64' ``` > On Windows Git Bash, prefix with `MSYS_NO_PATHCONV=1` and use a forward-slash absolute path for `-v` > (`"C:/Work/.../redb.SQLite/native":/src`) so the mount path is not rewritten. The recipe this replaced ran `debian:12` and `apt-get install` inside every build, then threw the container away: ~190 MB of toolchain re-downloaded per rebuild, and a release that could not be built while a Debian mirror was unreachable. It also configured into `/tmp` inside the container, so the fetched SQLite amalgamation went with the container too. **Mount at `/src` and keep the build dirs.** CMake records in `CMakeCache.txt` the path the cache was created under; mounting the same folder elsewhere makes it refuse the cache outright (*"The current CMakeCache.txt directory ... is different"*), and stale stamps under `_deps/` then fail the amalgamation fetch. Caches made before 2026-09-17 came from a `/work/...` mount and had to be deleted once — after that the dirs are reusable and hold the amalgamation, so nothing is downloaded again. When a cache does have to be reset: `rm -rf build-linux-*/CMakeCache.txt build-linux-*/CMakeFiles build-linux-*/_deps`. ### macOS x64/arm64 → `.dylib` Xcode Command Line Tools + `cmake` (`brew install cmake`), same `cmake -S . -B build && cmake --build build` on a macOS host (no cross-build from Windows/Linux). ## Verify a rebuilt artifact ```sh # 1. Right arch: file build-linux-arm64/redbsqlite.so # → ELF ... ARM aarch64 # 2. Carries the current SQL (spot-check a literal that only the new code emits): grep -a "depth > 0) AND NOT EXISTS" build-linux-x64/redbsqlite.so # 3. Loads + reports version (native-arch host only): sqlite3 ":memory:" ".load ./build-linux-x64/redbsqlite.so sqlite3_redb_init" "SELECT redb_version();" ``` Run step 3 inside the build image — its `sqlite3` is compiled from the same pinned amalgamation as the extension. The Debian package is 3.40.1 and the extension refuses to load below 3.44 (it needs `sqlite3_get_clientdata`), so the distro CLI answers with the version guard, not with a verdict on the artifact: ```sh docker run --rm -v "/abs/path/to/redb.SQLite/native":/src redb-sqlite-native bash -c ' file -b /src/build-linux-arm64/redbsqlite.so sqlite3 ":memory:" ".load /src/build-linux-x64/redbsqlite.so sqlite3_redb_init" "SELECT redb_version();"' ``` Also worth a look after a rebuild: `PVT_MODULE_VERSION` in `src/redb_pvt.c` must equal `SqliteDialect.Query_PvtRequiredVersion()` — `RedbService` compares them at initialization, so a stale artifact fails the Free path outright rather than misbehaving quietly. The full functional check is the .NET Free-path integration suite (`redb.Tests.Integration`, the `Sqlite*` fixtures), which loads the platform artifact. ## Quick check ```sh sqlite3 sqlite> .load ./build/redbsqlite sqlite3_redb_init sqlite> SELECT redb_version(); 0.1.0-m1 ``` (`.load` requires a `sqlite3` CLI built with extension loading enabled, which is the default.) ## Loading from .NET (Microsoft.Data.Sqlite) ```csharp connection.EnableExtensions(true); connection.LoadExtension("/path/to/redbsqlite", "sqlite3_redb_init"); ``` Wiring this into `SqliteRedbConnection` (Free path only, behind config) is done once the extension exposes real functions (M2+). Path: redb/redb.SQLite/redb.SQLite.csproj 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/redb.SQLite.csproj ---- net10.0;net11.0 enable enable true $(NoWarn);CS1591 redb.SQLite REDB - Entity Database for .NET SQLite provider for REDB. Includes optimized SQL generation, tree queries with CTEs, and full LINQ support. https://github.com/redbase-app/redb database;orm;redb;redbase;sqlite;linq;dotnet;typed-storage;cte;tree-query README.md 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; """; } Path: redb/redb.SQLite/sql/maintenance/free_value_indexes.sql 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/maintenance/free_value_indexes.sql ---- -- ===================================================================== -- REDB (SQLite): value indexes for the FREE provider -- ===================================================================== -- Schema step 11 (2026-10-17) replaced the object-leading value indexes (_id_structure, _id_object, -- ) with value-leading ones (_id_structure, , _id_object, _array_index). The new ones -- serve a filter on a field; the old ones served reading the value of a known object. -- -- This file brings them back under names of their own (IX__values__free_*). Schema steps drop the old -- names again whenever the schema version of the file goes up; they neither drop nor check these, so -- they survive upgrades. Pro with the planner on (the default) does not need them, do not run the file -- there. Pro with EnablePvtPrefilter = false reads the same forms as the free provider and may gain from -- them as well. -- -- Left out on purpose: -- IX__values__scalar_* - built by Pro only, never part of the free schema; -- the six indexes schema step 10 dropped as duplicates: the leading columns of each are the leading -- columns of an index or UNIQUE constraint of the same table that stays. -- IX__values__structure_object_lookup was never dropped on SQLite and stays in the schema. -- -- Price: every index here is updated on each save of a value. SQLite has no length limit on an index -- entry, so the string index holds every string in full: on a file with long texts it is large. Run the -- file only if free queries got slower. -- -- Nothing runs this file automatically. Run it yourself, once per database file, with the application -- stopped or idle: -- sqlite3 < free_value_indexes.sql -- The file is locked for writing while the indexes are built. Running it again is safe: an existing -- index is kept. -- -- To remove them: -- DROP INDEX IF EXISTS "IX__values__free_string_by_object"; (and so on for each name below) -- ===================================================================== BEGIN IMMEDIATE; -- 1. String, number, date and decimal value of a field by object (were IX__values__*_not_null) CREATE INDEX IF NOT EXISTS "IX__values__free_string_by_object" ON _values (_id_structure, _id_object, _String) WHERE _String IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__free_long_by_object" ON _values (_id_structure, _id_object, _Long) WHERE _Long IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__free_datetimeoffset_by_object" ON _values (_id_structure, _id_object, _DateTimeOffset) WHERE _DateTimeOffset IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__free_numeric_by_object" ON _values (_id_structure, _id_object, _Numeric) WHERE _Numeric IS NOT NULL; -- 2. Scalar (non-array) values of a field by object (was ix__values__array_null_structure) CREATE INDEX IF NOT EXISTS "IX__values__free_array_null_structure" ON _values (_id_structure, _id_object, _Long) WHERE _array_index IS NULL; COMMIT; ANALYZE _values; Path: redb/redb.SQLite/sql/maintenance/rebuild_objects_indexes_without_date_modify.sql 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/maintenance/rebuild_objects_indexes_without_date_modify.sql ---- -- ===================================================================== -- REDB (SQLite): bring three _objects indexes of an EXISTING file to the current schema -- ===================================================================== -- redbSqlite.sql no longer puts _date_modify into these indexes. That file creates indexes with -- CREATE INDEX IF NOT EXISTS, which does not change an index that already exists, so an existing -- file keeps the old definitions until this file is run. -- -- Why it matters: _date_modify changes on every save, so an index that carries it is rewritten for -- every saved object. On PostgreSQL, with frequent saves, these three had grown to 700-1400 bytes per -- entry and shrank 10-20 times when rebuilt without the column. -- -- Nothing runs this file automatically. Run it yourself, once per database file, with the application -- stopped or idle: -- sqlite3 < rebuild_objects_indexes_without_date_modify.sql -- -- SQLite cannot rename an index, so each one is dropped and created again under its name, all in one -- transaction: the file is locked for writing meanwhile, and a failure leaves the old indexes in place. -- Running the file again only pays for one more rebuild. -- ===================================================================== BEGIN IMMEDIATE; -- 1. Descendants of an object DROP INDEX IF EXISTS "IX__objects__parent_id_descendant_lookup"; CREATE INDEX "IX__objects__parent_id_descendant_lookup" ON _objects (_id_parent, _id_scheme, _id, _id_owner, _date_create) WHERE _id_parent IS NOT NULL; -- 2. Tree queries sorted by creation date DROP INDEX IF EXISTS "IX__objects__scheme_parent_date_create"; CREATE INDEX "IX__objects__scheme_parent_date_create" ON _objects (_id_scheme, _id_parent, _date_create DESC, _id, _id_owner); -- 3. Tree queries filtered by owner or name DROP INDEX IF EXISTS "IX__objects__scheme_parent_owner"; CREATE INDEX "IX__objects__scheme_parent_owner" ON _objects (_id_scheme, _id_parent, _id, _id_owner, _date_create, _name) WHERE _id_parent IS NOT NULL; COMMIT; ANALYZE _objects; Path: redb/redb.SQLite/sql/redbSqlite.sql 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/redbSqlite.sql ---- -- ============================================================================ -- REDB SQLite schema (DDL). Ported from redb.Postgres/sql/redbPostgre.sql. -- Target: SQLite 3.44.0+ (Microsoft.Data.Sqlite). -- Contains schema ONLY (tables + indexes + identity). The PL/pgSQL functions -- and views from the PG file are NOT here — for SQLite they live in the native -- C extension (Free) or in C# (Pro). -- ---------------------------------------------------------------------------- -- Type mapping: bigint->INTEGER, text/varchar->TEXT, boolean->INTEGER(0/1), -- uuid->TEXT, bytea->BLOB, float->REAL, timestamptz->TEXT(ISO-8601), -- NUMERIC(38,18)->TEXT (exact; configurable to REAL for speed). -- NOTE: PRAGMA foreign_keys=ON must be set per-connection (in C#); it is not -- persistent. WAL is set by every connection of the service (SqliteDataSource); -- by hand, run PRAGMA journal_mode = WAL; on its own before this script. -- The script holds no top-level statement that returns rows: after such a statement -- Microsoft.Data.Sqlite does not report the error of a later statement of the same -- command, and a failed creation looked like a successful one. -- ============================================================================ -- ============================================================================ -- ID generation. SQLite has no sequences; we use a native AUTOINCREMENT table. -- The high-water mark lives in sqlite_sequence._global_identity and is advanced -- monotonically by every id consumer, so ids are globally unique and never reused: -- * C# keygen (hi-lo block): UPDATE sqlite_sequence SET seq = seq + :n -- WHERE name='_global_identity' RETURNING seq; -- ids=[seq-n+1 .. seq] -- * C ext nextId (single): same with +1. -- * soft-delete (single, in a multi-statement dialect script): INSERT INTO -- _global_identity DEFAULT VALUES + last_insert_rowid() — last_insert_rowid() -- is per-connection, so it is stable across statements regardless of other -- writers (no counter re-read race). -- (RETURNING requires SQLite 3.35+, AUTOINCREMENT is native; we target 3.44+.) -- ============================================================================ CREATE TABLE IF NOT EXISTS _global_identity( _id INTEGER PRIMARY KEY AUTOINCREMENT ); -- Reserve ids 1..1000 for system/seed rows; runtime ids start at 1001. -- Forcing one explicit insert materializes the sqlite_sequence row at seq=1000, -- then we clear the table (the sequence persists and only ever increases). INSERT INTO _global_identity(_id) VALUES (1000000); DELETE FROM _global_identity WHERE _id = 1000000; -- ============================================================================ -- Core tables. `_id INTEGER PRIMARY KEY` aliases the SQLite rowid; the app -- supplies explicit ids from SqliteKeyGenerator (no AUTOINCREMENT). -- ============================================================================ CREATE TABLE _types( _id INTEGER NOT NULL PRIMARY KEY, _name TEXT NOT NULL UNIQUE, _db_type TEXT NULL, _type TEXT NULL ); CREATE TABLE _links( _id INTEGER NOT NULL PRIMARY KEY, _id_1 INTEGER NOT NULL, _id_2 INTEGER NOT NULL, CONSTRAINT IX__links UNIQUE (_id_1, _id_2), CONSTRAINT CK__links CHECK (_id_1 <> _id_2) ); CREATE TABLE _lists( _id INTEGER NOT NULL PRIMARY KEY, _name TEXT NOT NULL, _alias TEXT NULL, CONSTRAINT IX__lists_name UNIQUE (_name) ); CREATE TABLE _roles( _id INTEGER NOT NULL PRIMARY KEY, _name TEXT NOT NULL, -- forward FK to _objects (created later); SQLite resolves FKs at DML time _id_configuration INTEGER NULL REFERENCES _objects(_id) ON DELETE SET NULL, CONSTRAINT IX__roles UNIQUE (_name) ); CREATE TABLE _users( _id INTEGER NOT NULL PRIMARY KEY, _login TEXT NOT NULL UNIQUE, _password TEXT NOT NULL, _name TEXT NOT NULL, _phone TEXT NULL, _email TEXT NULL, _date_register REAL NOT NULL DEFAULT (julianday('now')), -- UTC Julian day (REAL); native datetime()/strftime()/julianday() consume directly _date_dismiss REAL NULL, _enabled INTEGER NOT NULL DEFAULT 1, _key INTEGER NULL, _code_int INTEGER NULL, _code_string TEXT NULL, _code_guid TEXT NULL, _note TEXT NULL, _hash BLOB NULL, -- 16 bytes, RFC 4122 order (SqliteHash); pre-V4 TEXT is converted on open _id_configuration INTEGER NULL REFERENCES _objects(_id) ON DELETE SET NULL ); CREATE TABLE _users_roles( _id INTEGER NOT NULL PRIMARY KEY, _id_role INTEGER NOT NULL, _id_user INTEGER NOT NULL, CONSTRAINT IX__users_roles UNIQUE (_id_role, _id_user), CONSTRAINT FK__users_roles__roles FOREIGN KEY (_id_role) REFERENCES _roles (_id) ON DELETE CASCADE, CONSTRAINT FK__users_roles__users FOREIGN KEY (_id_user) REFERENCES _users (_id) ON DELETE CASCADE ); CREATE TABLE _schemes( _id INTEGER NOT NULL PRIMARY KEY, _id_parent INTEGER NULL, _name TEXT NOT NULL, _alias TEXT NULL, _name_space TEXT NULL, _structure_hash BLOB NULL, -- 16 bytes, RFC 4122 order (SqliteHash); pre-V4 TEXT is converted on open _tags TEXT NULL, -- V4: free-form marker for future / custom extensions (450 chars, enforced in C#; sync never wipes it) _renamed_from TEXT NULL, -- previous names, oldest first, as a JSON array (RedbRename / RedbScheme.RenamedFrom); NULL = never renamed _version INTEGER NULL, -- version of the Props class last synchronised (RedbScheme.Version); NULL = 0; never lowered _type INTEGER NOT NULL DEFAULT -9223372036854775675, -- Class (default), Array, Dictionary, JsonDocument, XDocument CONSTRAINT IX__schemes UNIQUE (_name), CONSTRAINT FK__schemes__schemes FOREIGN KEY (_id_parent) REFERENCES _schemes (_id), CONSTRAINT FK__schemes__types FOREIGN KEY (_type) REFERENCES _types (_id) ); -- Scheme name validation. Mirrors the PostgreSQL validate_scheme_name() trigger rule for rule so -- that a name accepted by one provider is accepted by all three. -- -- This is a BACKSTOP against writes that bypass the library. The library validates explicit names -- in C# first (redb.Core/Attributes/SchemeNameValidator.cs), which is what reports the offending -- type instead of a bare constraint error, and which also covers databases created before this -- trigger existed -- EnsureDatabaseAsync skips initialisation entirely when _schemes is already -- present, so older databases never receive it. -- -- Two triggers because SQLite has no combined INSERT OR UPDATE form. The UPDATE one fires only -- when _name is written, so touching the hash or alias costs nothing and cannot fail on a legacy -- name that predates these rules. CREATE TRIGGER tr_validate_scheme_name_insert BEFORE INSERT ON _schemes FOR EACH ROW WHEN NEW._name NOT GLOB '@@*' -- system schemes (e.g. @@__deleted) bypass validation BEGIN SELECT RAISE(ABORT, 'Scheme name cannot be empty') WHERE length(trim(NEW._name)) = 0; SELECT RAISE(ABORT, 'Scheme name cannot start with a digit') WHERE NEW._name GLOB '[0-9]*'; SELECT RAISE(ABORT, 'Scheme name contains characters outside [a-zA-Z0-9_.+] or does not start with a letter/underscore') WHERE NEW._name GLOB '*[^a-zA-Z0-9_.+]*' OR NEW._name NOT GLOB '[a-zA-Z_]*'; SELECT RAISE(ABORT, 'Scheme name cannot end with a dot') WHERE NEW._name GLOB '*.'; SELECT RAISE(ABORT, 'Scheme name cannot contain two consecutive dots') WHERE instr(NEW._name, '..') > 0; SELECT RAISE(ABORT, 'Scheme name is longer than 128 characters') WHERE length(NEW._name) > 128; -- Rules 7 and 8: split on '.' and '+', then check every part. The seed row carries an empty -- part and is filtered out; genuinely empty parts are already rejected by the '..' rule above. SELECT RAISE(ABORT, 'Scheme name has a part that is not a valid identifier or is a C# reserved word') WHERE EXISTS ( WITH RECURSIVE parts(part, rest) AS ( SELECT '', replace(NEW._name, '+', '.') || '.' UNION ALL SELECT substr(rest, 1, instr(rest, '.') - 1), substr(rest, instr(rest, '.') + 1) FROM parts WHERE rest <> '' ) SELECT 1 FROM parts WHERE part <> '' AND (part GLOB '*[^a-zA-Z0-9_]*' OR part GLOB '[0-9]*' OR lower(part) IN ( 'abstract','as','bool','break','byte','case','catch','char','checked', 'class','const','continue','decimal','default','delegate','do','double','else', 'enum','event','explicit','extern','false','finally','fixed','float','for', 'foreach','goto','if','implicit','in','int','interface','internal','is','lock', 'long','namespace','new','null','object','operator','out','override','params', 'private','protected','public','readonly','ref','return','sbyte','sealed', 'short','sizeof','stackalloc','static','string','struct','switch','this', 'throw','true','try','typeof','uint','ulong','unchecked','unsafe','ushort', 'using','virtual','void','volatile','while')) ); END; CREATE TRIGGER tr_validate_scheme_name_update BEFORE UPDATE OF _name ON _schemes FOR EACH ROW WHEN NEW._name <> OLD._name AND NEW._name NOT GLOB '@@*' BEGIN SELECT RAISE(ABORT, 'Scheme name cannot be empty') WHERE length(trim(NEW._name)) = 0; SELECT RAISE(ABORT, 'Scheme name cannot start with a digit') WHERE NEW._name GLOB '[0-9]*'; SELECT RAISE(ABORT, 'Scheme name contains characters outside [a-zA-Z0-9_.+] or does not start with a letter/underscore') WHERE NEW._name GLOB '*[^a-zA-Z0-9_.+]*' OR NEW._name NOT GLOB '[a-zA-Z_]*'; SELECT RAISE(ABORT, 'Scheme name cannot end with a dot') WHERE NEW._name GLOB '*.'; SELECT RAISE(ABORT, 'Scheme name cannot contain two consecutive dots') WHERE instr(NEW._name, '..') > 0; SELECT RAISE(ABORT, 'Scheme name is longer than 128 characters') WHERE length(NEW._name) > 128; SELECT RAISE(ABORT, 'Scheme name has a part that is not a valid identifier or is a C# reserved word') WHERE EXISTS ( WITH RECURSIVE parts(part, rest) AS ( SELECT '', replace(NEW._name, '+', '.') || '.' UNION ALL SELECT substr(rest, 1, instr(rest, '.') - 1), substr(rest, instr(rest, '.') + 1) FROM parts WHERE rest <> '' ) SELECT 1 FROM parts WHERE part <> '' AND (part GLOB '*[^a-zA-Z0-9_]*' OR part GLOB '[0-9]*' OR lower(part) IN ( 'abstract','as','bool','break','byte','case','catch','char','checked', 'class','const','continue','decimal','default','delegate','do','double','else', 'enum','event','explicit','extern','false','finally','fixed','float','for', 'foreach','goto','if','implicit','in','int','interface','internal','is','lock', 'long','namespace','new','null','object','operator','out','override','params', 'private','protected','public','readonly','ref','return','sbyte','sealed', 'short','sizeof','stackalloc','static','string','struct','switch','this', 'throw','true','try','typeof','uint','ulong','unchecked','unsafe','ushort', 'using','virtual','void','volatile','while')) ); END; CREATE TABLE _structures( _id INTEGER NOT NULL PRIMARY KEY, _id_parent INTEGER NULL, _id_scheme INTEGER NOT NULL, _id_override INTEGER NULL, _id_type INTEGER NOT NULL, _id_list INTEGER NULL, _name TEXT NOT NULL, _alias TEXT NULL, _order INTEGER NULL, _readonly INTEGER NULL, _allow_not_null INTEGER NULL, _collection_type INTEGER NULL, -- Array/Dictionary type ID or NULL for non-collections _key_type INTEGER NULL, -- Key type for Dictionary fields _is_compress INTEGER NULL, _store_null INTEGER NULL, _unique INTEGER NULL, -- V4: field is a unique key within its scheme ([RedbUnique]) _unique_version INTEGER NULL, -- V4: UniqueKeyEncoder.Version the stored keys were computed with _unique_scope INTEGER NULL, -- S3: element-key scope of a collection key (NULL = default; 1 = Scheme elements; 2 = Collection elements) _lazy INTEGER NULL, -- V4 (LAZY Л2): lazy reference marker (virtual) _tags TEXT NULL, -- V4: free-form marker for future / custom extensions (sync never wipes it) _renamed_from TEXT NULL, -- previous names, oldest first, as a JSON array (RedbRename); NULL = never renamed _default_value BLOB NULL, _default_editor TEXT NULL, CONSTRAINT IX__structures UNIQUE (_id_scheme, _name, _id_parent), CONSTRAINT FK__structures__structures FOREIGN KEY (_id_parent) REFERENCES _structures (_id) ON DELETE CASCADE, CONSTRAINT FK__structures__schemes FOREIGN KEY (_id_scheme) REFERENCES _schemes (_id), CONSTRAINT FK__structures__types FOREIGN KEY (_id_type) REFERENCES _types (_id), CONSTRAINT FK__structures__lists FOREIGN KEY (_id_list) REFERENCES _lists (_id), CONSTRAINT FK__structures__collection_type FOREIGN KEY (_collection_type) REFERENCES _types (_id), CONSTRAINT FK__structures__key_type FOREIGN KEY (_key_type) REFERENCES _types (_id) ); CREATE TABLE _dependencies( _id INTEGER NOT NULL PRIMARY KEY, _id_scheme_1 INTEGER NULL, _id_scheme_2 INTEGER NOT NULL, CONSTRAINT IX__dependencies UNIQUE (_id_scheme_1, _id_scheme_2), CONSTRAINT FK__dependencies__schemes_1 FOREIGN KEY (_id_scheme_1) REFERENCES _schemes (_id), CONSTRAINT FK__dependencies__schemes_2 FOREIGN KEY (_id_scheme_2) REFERENCES _schemes (_id) ON DELETE CASCADE ); CREATE TABLE _objects( _id INTEGER NOT NULL PRIMARY KEY, _id_parent INTEGER NULL, _id_scheme INTEGER NOT NULL, _id_owner INTEGER NOT NULL, _id_who_change INTEGER NOT NULL, _date_create REAL NOT NULL DEFAULT (julianday('now')), -- UTC Julian day (REAL) _date_modify REAL NOT NULL DEFAULT (julianday('now')), -- UTC Julian day (REAL) _date_begin REAL NULL, _date_complete REAL NULL, _key INTEGER NULL, _name TEXT NULL, _note TEXT NULL, _hash BLOB NULL, -- 16 bytes, RFC 4122 order (SqliteHash); pre-V4 TEXT is converted on open -- Value columns for RedbPrimitive (Props = primitive value stored directly) _value_long INTEGER NULL, _value_string TEXT NULL, -- identifiers/external keys; contract limit 450 (C#-enforced), long text belongs in _note _value_guid TEXT NULL, _value_bool INTEGER NULL, _value_double REAL NULL, _value_numeric REAL NULL, -- NUMERIC(38,18): REAL default (numeric ops/JSON); TEXT = exact (config) _value_datetime REAL NULL, -- UTC Julian day (REAL) _value_bytes BLOB NULL, _value_unique TEXT NULL, -- V4: unique key within the scheme (440 chars, enforced in C#) CONSTRAINT FK__objects__objects FOREIGN KEY (_id_parent) REFERENCES _objects (_id) ON DELETE CASCADE, CONSTRAINT FK__objects__schemes FOREIGN KEY (_id_scheme) REFERENCES _schemes (_id) ON DELETE CASCADE, CONSTRAINT FK__objects__users1 FOREIGN KEY (_id_owner) REFERENCES _users (_id), CONSTRAINT FK__objects__users2 FOREIGN KEY (_id_who_change) REFERENCES _users (_id) ); CREATE TABLE _list_items( _id INTEGER NOT NULL PRIMARY KEY, _id_list INTEGER NOT NULL, _value TEXT NULL, _alias TEXT NULL, _id_object INTEGER NULL, CONSTRAINT FK__list_items__id_list FOREIGN KEY (_id_list) REFERENCES _lists (_id) ON DELETE CASCADE, CONSTRAINT FK__list_items__objects FOREIGN KEY (_id_object) REFERENCES _objects (_id) ON DELETE SET NULL ); -- PG used `NULLS NOT DISTINCT` (one NULL per list). SQLite treats NULLs as -- distinct in UNIQUE, so we emulate via an expression index with a sentinel. -- Sentinel char(1) (SOH) is not expected as a real dictionary value. CREATE UNIQUE INDEX IX__list_items_unique ON _list_items (_id_list, IFNULL(_value, char(1))); CREATE TABLE _values( _id INTEGER NOT NULL PRIMARY KEY, _id_structure INTEGER NOT NULL, _id_object INTEGER NOT NULL, _String TEXT NULL, _Long INTEGER NULL, _Guid TEXT NULL, _Double REAL NULL, _DateTimeOffset REAL NULL, -- DateTime/DateTimeOffset/DateOnly as UTC Julian day (REAL) _Boolean INTEGER NULL, _ByteArray BLOB NULL, _Numeric REAL NULL, -- NUMERIC(38,18): REAL default (numeric ops/JSON); TEXT = exact (config) _ListItem INTEGER NULL, _Object INTEGER NULL, _unique BLOB NULL, -- V4: unique-key hash (16 bytes, RFC 4122 order, SqliteHash) for [RedbUnique] root scalars -- Relational storage of collections (arrays, dictionaries) _array_parent_id INTEGER NULL, -- parent element (nested structures) _array_index TEXT NULL, -- '0','1',... for arrays; string key for dictionaries CONSTRAINT FK__values__objects FOREIGN KEY (_id_object) REFERENCES _objects (_id) ON DELETE CASCADE, CONSTRAINT FK__values__structures FOREIGN KEY (_id_structure) REFERENCES _structures (_id) ON DELETE CASCADE, CONSTRAINT FK__values__array_parent FOREIGN KEY (_array_parent_id) REFERENCES _values (_id) ON DELETE CASCADE, CONSTRAINT FK__values__list_items FOREIGN KEY (_ListItem) REFERENCES _list_items (_id), CONSTRAINT FK__values__objects_ref FOREIGN KEY (_Object) REFERENCES _objects (_id) ); CREATE TABLE _permissions( _id INTEGER NOT NULL PRIMARY KEY, _id_role INTEGER NULL, _id_user INTEGER NULL, _id_ref INTEGER NOT NULL, _select INTEGER NULL, _insert INTEGER NULL, _update INTEGER NULL, _delete INTEGER NULL, CONSTRAINT CK__permissions_users_roles CHECK (_id_role IS NOT NULL AND _id_user IS NULL OR _id_role IS NULL AND _id_user IS NOT NULL), CONSTRAINT IX__permissions UNIQUE (_id_role, _id_user, _id_ref, _select, _insert, _update, _delete), CONSTRAINT FK__permissions__roles FOREIGN KEY (_id_role) REFERENCES _roles (_id) ON DELETE CASCADE, CONSTRAINT FK__permissions__users FOREIGN KEY (_id_user) REFERENCES _users (_id) ON DELETE CASCADE ); CREATE TABLE _functions( _id INTEGER NOT NULL PRIMARY KEY, _id_scheme INTEGER NOT NULL, _language TEXT NOT NULL, _name TEXT NOT NULL, _body TEXT NOT NULL, CONSTRAINT IX__functions_scheme_name UNIQUE (_id_scheme, _name), CONSTRAINT FK__functions__schemes FOREIGN KEY (_id_scheme) REFERENCES _schemes (_id) ); -- Pro data-migration history (ported 1:1 from redb_migrations.sql, PG types mapped: -- BIGSERIAL->INTEGER PK (the id is supplied explicitly by NextObjectIdAsync), -- TIMESTAMPTZ->REAL UTC Julian day like every other date column here, -- BOOLEAN->INTEGER 0/1). -- -- Unlike PG/MSSql, SQLite has no redb_init.sql concatenation step, so the shared -- redb_migrations.sql never reached this provider and the table was missing entirely — -- MigrationExecutor's very first statement (the idempotency probe in -- ProSqliteDialect.Migration_SelectExisting) failed with "no such table: _migrations", -- making Pro data migrations unusable on SQLite. CREATE TABLE _migrations( _id INTEGER NOT NULL PRIMARY KEY, _migration_id TEXT NOT NULL, -- "OrderProps_TotalPrice_v1" _scheme_id INTEGER NOT NULL, _structure_id INTEGER NULL, -- NULL = whole scheme _property_name TEXT NULL, _expression_hash TEXT NULL, -- MD5 of the Expression, to detect changes _migration_type TEXT NOT NULL, -- ComputedFrom, TypeChange, DefaultValue, Transform _applied_at REAL NOT NULL DEFAULT (julianday('now')), -- UTC Julian day (REAL) _applied_by TEXT NULL, _sql_executed TEXT NULL, -- executed SQL, kept for audit _affected_rows INTEGER NULL, _duration_ms INTEGER NULL, _dry_run INTEGER NOT NULL DEFAULT 0, CONSTRAINT uq_migration_scheme UNIQUE (_scheme_id, _migration_id), CONSTRAINT FK__migrations__schemes FOREIGN KEY (_scheme_id) REFERENCES _schemes (_id) ON DELETE CASCADE, CONSTRAINT FK__migrations__structures FOREIGN KEY (_structure_id) REFERENCES _structures (_id) ON DELETE SET NULL ); CREATE INDEX idx_migrations_scheme ON _migrations(_scheme_id); CREATE INDEX idx_migrations_applied ON _migrations(_applied_at DESC); -- ============================================================================ -- Metadata cache (ported 1:1 from redb_metadata_cache.sql). Denormalized -- _structures ⋈ _types (+ scheme/collection/key type names) per scheme, to avoid -- repeated JOINs. Maintained by SqliteDialect.Schemes_SyncMetadataCache (called -- by SchemeSyncProviderBase after each scheme sync) and Warmup_AllMetadataCaches -- (InitializeAsync). bytea->BLOB, boolean->INTEGER. -- ============================================================================ CREATE TABLE _scheme_metadata_cache ( _scheme_id INTEGER NOT NULL, _structure_id INTEGER NOT NULL, _parent_structure_id INTEGER, _id_override INTEGER, _name TEXT NOT NULL, _alias TEXT, _type_id INTEGER NOT NULL, _list_id INTEGER, type_name TEXT NOT NULL, db_type TEXT NOT NULL, type_semantic TEXT NOT NULL, _scheme_type INTEGER, scheme_type_name TEXT, _order INTEGER, _collection_type INTEGER, collection_type_name TEXT, _key_type INTEGER, key_type_name TEXT, _readonly INTEGER, _allow_not_null INTEGER, _is_compress INTEGER, _store_null INTEGER, _lazy INTEGER, _unique INTEGER, _unique_version INTEGER, _unique_scope INTEGER, -- S3: element-key scope of a collection key _tags TEXT, -- V4: free-form marker mirrored from _structures _default_value BLOB, _default_editor TEXT ); CREATE INDEX idx_metadata_cache_lookup ON _scheme_metadata_cache (_scheme_id, _parent_structure_id, _order); CREATE INDEX idx_metadata_cache_structure ON _scheme_metadata_cache (_structure_id); CREATE INDEX idx_metadata_cache_scheme ON _scheme_metadata_cache (_scheme_id); CREATE INDEX idx_metadata_cache_name ON _scheme_metadata_cache (_scheme_id, _name); CREATE INDEX idx_metadata_cache_collection ON _scheme_metadata_cache (_scheme_id, _collection_type) WHERE _collection_type IS NOT NULL; CREATE INDEX idx_metadata_cache_scheme_type ON _scheme_metadata_cache (_scheme_id, _scheme_type); CREATE INDEX idx_metadata_cache_key_type ON _scheme_metadata_cache (_scheme_id, _key_type) WHERE _key_type IS NOT NULL; -- ============================================================================ -- Indexes. PG `WITH (deduplicate_items=True)` dropped. PG covering `INCLUDE(...)` -- columns are appended to the index key (SQLite has no INCLUDE; trailing key -- columns give the same covering-scan benefit). Partial `WHERE` and `DESC` -- columns are supported as-is. The pg_trgm GIN index is dropped (no SQLite -- equivalent; text pattern search to be revisited via FTS5). -- ============================================================================ -- REMOVED (2026-10-14): "IX__functions__schemes" (_id_scheme) is the leading column of the UNIQUE constraint -- IX__functions_scheme_name (_id_scheme, _name); the constraint's index serves the same lookups. -- REMOVED (2026-10-14): "IX__permissions__roles" (_id_role) is the leading column of the UNIQUE constraint -- IX__permissions (_id_role, _id_user, ...). CREATE INDEX IF NOT EXISTS "IX__permissions__users" ON _permissions (_id_user); CREATE INDEX IF NOT EXISTS "IX__permissions__ref" ON _permissions (_id_ref); CREATE INDEX IF NOT EXISTS "IX__values__objects" ON _values (_id_object); CREATE INDEX IF NOT EXISTS "IX__values__structures" ON _values (_id_structure); -- FK-column indexes: _Object/_ListItem carry foreign keys, and without a leading index every -- DELETE of a referenced object or list item scans the whole table for the FK check. Partial: -- reference fields are a small fraction of rows, so the indexes stay nearly empty. CREATE INDEX IF NOT EXISTS "IX__values__ListItem_not_null" ON _values (_ListItem) WHERE _ListItem IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__Object_not_null" ON _values (_Object) WHERE _Object IS NOT NULL; -- REMOVED (schema step 17): "IX__values__array_parent_id" (_array_parent_id), the leading column of the index below, -- which serves its lookups and the cascade of FK__values__array_parent. CREATE INDEX IF NOT EXISTS "IX__values__array_parent_index" ON _values (_array_parent_id, _array_index); CREATE INDEX IF NOT EXISTS "IX__values__array_key" ON _values (_id_structure, _array_index) WHERE _array_index IS NOT NULL; -- V4: uniqueness of [RedbUnique] fields. Covers keyed rows at ANY position (root and S2 nested -- scalars; element keys join in S3). No INCLUDE in SQLite: the _id_object lookup goes through -- the rowid, which is cheap. CREATE UNIQUE INDEX IF NOT EXISTS "UIX__values__structure_unique" ON _values (_id_structure, _unique) WHERE _unique IS NOT NULL; -- One value per place, as on PostgreSQL and SQL Server: a root field once per object, the base row of a nested -- collection once per parent, an element once per position or key. Missing here before 4.8.1; an existing file is told -- by the index check at start-up, and RepairBaseIndexesAsync ('redb indexes repair') builds them after looking for -- duplicate rows. NULLs are distinct in a SQLite unique index, as in a PostgreSQL one. CREATE UNIQUE INDEX IF NOT EXISTS "UIX__values__structure_object" ON _values (_id_structure, _id_object) WHERE _array_index IS NULL AND _array_parent_id IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS "UIX__values__structure_object_parent" ON _values (_id_structure, _id_object, _array_parent_id) WHERE _array_index IS NULL AND _array_parent_id IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS "UIX__values__structure_object_array_index" ON _values (_id_structure, _id_object, _array_parent_id, _array_index) WHERE _array_index IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__list_items__id_list" ON _list_items (_id_list); CREATE INDEX IF NOT EXISTS "IX__list_items__objects" ON _list_items (_id_object); CREATE INDEX IF NOT EXISTS "IX__objects__objects" ON _objects (_id_parent); CREATE INDEX IF NOT EXISTS "IX__objects__schemes" ON _objects (_id_scheme); CREATE INDEX IF NOT EXISTS "IX__objects__users1" ON _objects (_id_owner); CREATE INDEX IF NOT EXISTS "IX__objects__users2" ON _objects (_id_who_change); CREATE INDEX IF NOT EXISTS "IX__objects__date_create" ON _objects (_date_create); CREATE INDEX IF NOT EXISTS "IX__objects__date_modify" ON _objects (_date_modify); CREATE INDEX IF NOT EXISTS "IX__objects__name" ON _objects (_name); CREATE INDEX IF NOT EXISTS "IX__users__name" ON _users (_name); CREATE INDEX IF NOT EXISTS "IX__objects__hash" ON _objects (_hash); CREATE INDEX IF NOT EXISTS "IX__objects__value_long" ON _objects (_value_long) WHERE _value_long IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__objects__value_string" ON _objects (_value_string) WHERE _value_string IS NOT NULL; -- V4: application-defined object key, unique per scheme (length 440 enforced in C# - SQLite does -- not check VARCHAR lengths). CREATE UNIQUE INDEX IF NOT EXISTS "UIX__objects__scheme_unique" ON _objects (_id_scheme, _value_unique) WHERE _value_unique IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__objects__value_guid" ON _objects (_value_guid) WHERE _value_guid IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__objects__value_datetime" ON _objects (_value_datetime) WHERE _value_datetime IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__objects__value_numeric" ON _objects (_value_numeric) WHERE _value_numeric IS NOT NULL; -- REMOVED (2026-10-14): "IX__dependencies__schemes_1" (_id_scheme_1) is the leading column of the UNIQUE -- constraint IX__dependencies (_id_scheme_1, _id_scheme_2). The index on _id_scheme_2 below stays. CREATE INDEX IF NOT EXISTS "IX__dependencies__schemes_2" ON _dependencies (_id_scheme_2); CREATE INDEX IF NOT EXISTS "IX__structures__structures" ON _structures (_id_parent); -- One root field name once per scheme: IX__structures counts two NULL parents as distinct. Existing files get it from -- RootStructureKey (redb.Core) in the upgrade pass at start-up. CREATE UNIQUE INDEX IF NOT EXISTS "UX__structures__root" ON _structures (_id_scheme, _name) WHERE _id_parent IS NULL; CREATE INDEX IF NOT EXISTS "IX__structures__schemes" ON _structures (_id_scheme); CREATE INDEX IF NOT EXISTS "IX__structures__types" ON _structures (_id_type); CREATE INDEX IF NOT EXISTS "IX__structures__lists" ON _structures (_id_list); CREATE INDEX IF NOT EXISTS "IX__schemes__schemes" ON _schemes (_id_parent); CREATE INDEX IF NOT EXISTS "IX__schemes__structure_hash" ON _schemes (_structure_hash); CREATE INDEX IF NOT EXISTS "IX__schemes__type" ON _schemes (_type); -- REMOVED (2026-10-14): "IX__users_roles__roles" (_id_role) is the leading column of the UNIQUE constraint -- IX__users_roles (_id_role, _id_user). CREATE INDEX IF NOT EXISTS "IX__users_roles__users" ON _users_roles (_id_user); CREATE INDEX IF NOT EXISTS "IX__users__id_configuration" ON _users (_id_configuration) WHERE _id_configuration IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__roles__id_configuration" ON _roles (_id_configuration) WHERE _id_configuration IS NOT NULL; -- REMOVED (2026-10-17): "ix__values__array_null_structure" (_id_structure, _id_object, _Long) WHERE _array_index IS NULL. -- Its predicate matches the term every stream states, so SQLite drove pages from it, from a boolean field -- of 390 thousand rows instead of a value range of 410 (1.4 s against 26-38 ms). Reading a value by object -- is covered by IX__values__structure_object_lookup. Removed by schema step 11 of RedbService. -- Nested fields by structure_id (INCLUDE cols folded into key) CREATE INDEX IF NOT EXISTS "IX__values__structure_parent_batch" ON _values (_id_structure, _array_parent_id, _Long, _Double, _Boolean, _Guid) WHERE _array_parent_id IS NOT NULL; -- Structure lookups (INCLUDE folded into key) CREATE INDEX IF NOT EXISTS "IX__structures__name" ON _structures (_name, _id, _id_type, _collection_type, _id_scheme); CREATE INDEX IF NOT EXISTS "IX__structures__id_lookup" ON _structures (_id, _id_type, _name, _collection_type, _id_scheme); -- REMOVED (2026-10-14): "IX__structures__not_collection" (_id, _name, _id_scheme) WHERE _collection_type IS NULL -- is a prefix of IX__structures__not_collection_enhanced below, same predicate. CREATE INDEX IF NOT EXISTS "IX__structures__not_collection_enhanced" ON _structures (_id, _name, _id_scheme, _id_type) WHERE _collection_type IS NULL; CREATE INDEX IF NOT EXISTS "IX__structures__collection" ON _structures (_id, _id_scheme, _collection_type) WHERE _collection_type IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__structures__key_type" ON _structures (_id, _id_scheme, _key_type) WHERE _key_type IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__structures__collection_type" ON _structures (_collection_type) WHERE _collection_type IS NOT NULL; -- Covering value lookups (INCLUDE folded into key) CREATE INDEX IF NOT EXISTS "IX__values__object_structure_lookup" ON _values (_id_object, _id_structure, _array_index, _Long, _Double, _DateTimeOffset, _Boolean, _Guid, _Numeric, _ListItem, _Object); CREATE INDEX IF NOT EXISTS "IX__values__object_array_null" ON _values (_id_object, _id_structure, _Long, _Double, _DateTimeOffset, _Boolean, _Guid, _Numeric, _ListItem, _Object) WHERE _array_index IS NULL; -- Faceted search core CREATE INDEX IF NOT EXISTS "IX__values__structure_object_lookup" ON _values (_id_structure, _id_object, _Long, _DateTimeOffset, _Boolean, _Double, _Guid, _Numeric, _ListItem, _Object); CREATE INDEX IF NOT EXISTS "IX__objects__scheme_parent" ON _objects (_id_scheme, _id_parent, _id); -- REMOVED (2026-10-14): "IX__values__object_structure_array_index" (_id_object, _id_structure, _array_index) -- WHERE _array_index IS NOT NULL is a prefix of IX__values__object_structure_lookup above, which has no predicate. -- Value-leading indexes (2026-10-17), the set PostgreSQL and SQL Server have: a filter on a field reads -- one range of its index, and the objects come out of it. SQLite has no INCLUDE, so _array_index is the -- last key column: a query that states _array_index IS NULL checks it inside the index. -- The predicate names the value only. SQLite does not prove implications between a query and a partial -- index predicate, it looks for a matching term: "_array_index IS NULL" there kept a prefilter that does -- not state it off the index, and PostgreSQL lost a prefilter the same way (7 ms -> 1.2 s). It derives -- "IS NOT NULL" from a comparison but never from LIKE, so the prefilter spells it out for LIKE branches. -- Unlike PostgreSQL there is NO length guard on the string: an SQLite index entry has no size limit, and -- "length(_String) < 2000" is a term no query states (a LIKE prefilter 294 ms without it, 1230 ms with it). -- They replace IX__values__{String,Long,DateTimeOffset,Numeric}_not_null, (_id_structure, _id_object, -- ), which only served reading the value of a known object. Schema step 11 of RedbService builds -- these and drops those on an existing file. To bring the old ones back: -- CREATE INDEX "IX__values__String_not_null" ON _values (_id_structure, _id_object, _String) WHERE _String IS NOT NULL; -- CREATE INDEX "IX__values__Long_not_null" ON _values (_id_structure, _id_object, _Long) WHERE _Long IS NOT NULL; -- CREATE INDEX "IX__values__DateTimeOffset_not_null" ON _values (_id_structure, _id_object, _DateTimeOffset) WHERE _DateTimeOffset IS NOT NULL; -- CREATE INDEX "IX__values__Numeric_not_null" ON _values (_id_structure, _id_object, _Numeric) WHERE _Numeric IS NOT NULL; -- CREATE INDEX "ix__values__array_null_structure" ON _values (_id_structure, _id_object, _Long) WHERE _array_index IS NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_string_object" ON _values (_id_structure, _String, _id_object, _array_index) WHERE _String IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_long_object" ON _values (_id_structure, _Long, _id_object, _array_index) WHERE _Long IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_numeric_object" ON _values (_id_structure, _Numeric, _id_object, _array_index) WHERE _Numeric IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_double_object" ON _values (_id_structure, _Double, _id_object, _array_index) WHERE _Double IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_datetimeoffset_object" ON _values (_id_structure, _DateTimeOffset, _id_object, _array_index) WHERE _DateTimeOffset IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_boolean_object" ON _values (_id_structure, _Boolean, _id_object, _array_index) WHERE _Boolean IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_guid_object" ON _values (_id_structure, _Guid, _id_object, _array_index) WHERE _Guid IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_listitem_object" ON _values (_id_structure, _ListItem, _id_object, _array_index) WHERE _ListItem IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_object_object" ON _values (_id_structure, _Object, _id_object, _array_index) WHERE _Object IS NOT NULL; -- Which objects hold a text value of a field, without the text: the text column is in no other index by object. -- A filter Field == null over a text field checks it with NOT EXISTS (SQLite Pro names it, INDEXED BY: the planner -- prefers IX__values__structure_object_lookup and reads the text from the table). Schema step 12 of RedbService. CREATE INDEX IF NOT EXISTS "IX__values__structure_object_string" ON _values (_id_structure, _id_object) WHERE _String IS NOT NULL; -- Hierarchy / tree CREATE INDEX IF NOT EXISTS "IX__objects__parent_scheme_id" ON _objects (_id_parent, _id_scheme, _id) WHERE _id_parent IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__objects__root_objects" ON _objects (_id_scheme, _id) WHERE _id_parent IS NULL; CREATE INDEX IF NOT EXISTS "IX__objects__scheme_date_create" ON _objects (_id_scheme, _date_create DESC, _id); CREATE INDEX IF NOT EXISTS "IX__objects__scheme_date_modify" ON _objects (_id_scheme, _date_modify DESC, _id); CREATE INDEX IF NOT EXISTS "IX__objects__scheme_name" ON _objects (_id_scheme, _name, _id); -- Ancestor/descendant (INCLUDE folded into key) -- _date_modify is deliberately NOT in these three covering _objects indexes (as in PostgreSQL, 2026-10-12). It -- changes on every save, so an index that carries it is rewritten for every saved object. Queries that go through -- them read the object row anyway. An existing file keeps the old definitions: -- sql/maintenance/rebuild_objects_indexes_without_date_modify.sql. CREATE INDEX IF NOT EXISTS "IX__objects__parent_id_descendant_lookup" ON _objects (_id_parent, _id_scheme, _id, _id_owner, _date_create) WHERE _id_parent IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__objects__scheme_parent_date_create" ON _objects (_id_scheme, _id_parent, _date_create DESC, _id, _id_owner); CREATE INDEX IF NOT EXISTS "IX__objects__id_parent_scheme" ON _objects (_id, _id_parent, _id_scheme) WHERE _id_parent IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__objects__scheme_parent_owner" ON _objects (_id_scheme, _id_parent, _id, _id_owner, _date_create, _name) WHERE _id_parent IS NOT NULL; -- Tree walk that needs the object hash (transparent cache). Analogue of -- IX__objects__id_parent in redbMSSQL.sql, whose INCLUDE (_id, _hash, _id_scheme) is -- folded into the key here — SQLite has no INCLUDE. IX__objects__parent_scheme_id above -- stops at (_id_parent, _id_scheme, _id) and does NOT carry _hash, so a walk that reads -- the hash falls back to the table on every row. Filtered on _id_parent IS NOT NULL: a lookup -- by parent never matches NULL, so root objects would sit in the index as dead weight. -- Verified on SQLite 3.46.1: SELECT _id, _hash, _id_scheme WHERE _id_parent = ? plans as -- SEARCH ... USING COVERING INDEX. (_id is the rowid alias and is therefore already in -- every index; it is listed to keep the column set identical to the MSSQL analogue.) CREATE INDEX IF NOT EXISTS "IX__objects__id_parent" ON _objects (_id_parent, _id, _hash, _id_scheme) WHERE _id_parent IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__parent_structure" ON _values (_array_parent_id, _id_structure) WHERE _array_parent_id IS NOT NULL; -- ============================================================================ -- SEED DATA (ported from redbPostgre.sql, lines 710-801, 1346-1364). -- Required by the C# layer: _types are referenced by _schemes._type / -- _structures._id_type; system _users (-1/0/1) are referenced by _objects' -- owner/who_change FKs; the soft-delete scheme (-10); and default permissions. -- Booleans -> 0/1, timestamptz -> ISO-8601 TEXT. (PG validation triggers on -- _structures/_schemes are intentionally NOT ported — they are PL/pgSQL.) -- ============================================================================ INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775709, 'Boolean', 'Boolean', 'boolean'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775708, 'DateTime', 'DateTimeOffset', 'DateTime'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775707, 'Double', 'Double', 'double'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775706, 'ListItem', 'ListItem', '_RListItem'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775705, 'Guid', 'Guid', 'Guid'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775673, 'DateTimeOffset', 'DateTimeOffset', 'DateTimeOffset'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775674, 'Numeric', 'Numeric', 'decimal'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775704, 'Long', 'Long', 'long'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775703, 'Object', 'Object', '_RObject'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775701, 'ByteArray', 'ByteArray', 'byte[]'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775700, 'String', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775699, 'Int', 'Long', 'int'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775698, 'Short', 'Long', 'short'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775697, 'Byte', 'Long', 'byte'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775696, 'Float', 'Double', 'float'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775695, 'Decimal', 'Numeric', 'decimal'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775694, 'Char', 'String', 'char'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775693, 'Url', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775692, 'Email', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775691, 'Phone', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775690, 'Json', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775689, 'Xml', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775688, 'Base64', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775687, 'Color', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775686, 'DateOnly', 'DateTimeOffset', 'DateOnly'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775685, 'TimeOnly', 'Long', 'TimeOnly'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775684, 'TimeSpan', 'Long', 'TimeSpan'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775683, 'Enum', 'String', 'Enum'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775682, 'EnumInt', 'Long', 'Enum'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775681, 'Latitude', 'Double', 'double'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775680, 'Longitude', 'Double', 'double'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775679, 'GeoPoint', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775678, 'FilePath', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775677, 'FileName', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775676, 'MimeType', 'String', 'string'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775675, 'Class', 'Guid', 'Object'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775668, 'Array', 'Guid', 'Array'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775667, 'Dictionary', 'Guid', 'Dictionary'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775666, 'JsonDocument', 'Guid', 'JsonDocument'); INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775665, 'XDocument', 'Guid', 'XDocument'); INSERT INTO _users (_id, _login, _password, _name, _phone, _email, _date_register, _date_dismiss, _enabled) VALUES (-1, 'default', '', 'default', NULL, NULL, julianday('2023-12-26T01:14:34.410'), NULL, 1); INSERT INTO _users (_id, _login, _password, _name, _phone, _email, _date_register, _date_dismiss, _enabled) VALUES (0, 'sys', '', 'sys', NULL, NULL, julianday('2023-12-26T01:14:34.410'), NULL, 1); INSERT INTO _users (_id, _login, _password, _name, _phone, _email, _date_register, _date_dismiss, _enabled) VALUES (1, 'admin', '', 'admin', NULL, NULL, julianday('2023-12-26T01:14:34.410'), NULL, 1); -- Soft-delete reserved scheme (objects marked for deletion get _id_scheme = -10) INSERT INTO _schemes (_id, _name, _alias, _type) VALUES (-10, '@@__deleted', 'Deleted Objects', -9223372036854775703) ON CONFLICT (_id) DO NOTHING; -- Default permissions for sys (0) and admin (1): all rights on all objects (_id_ref=0). -- System rows use explicit ids in the reserved 1..1000 range, so they never collide -- with runtime ids handed out from sqlite_sequence (which start at 1001). INSERT INTO _permissions (_id, _id_user, _id_ref, _select, _insert, _update, _delete) VALUES (1, 0, 0, 1, 1, 1, 1); INSERT INTO _permissions (_id, _id_user, _id_ref, _select, _insert, _update, _delete) VALUES (2, 1, 0, 1, 1, 1, 1); -- ============================================================================ -- v_user_permissions — effective permissions per (object, user), with tree -- inheritance + global (_id_ref=0) fallback. Port of the PG view (redbPostgre.sql). -- PG `DISTINCT ON (object_id) ... ORDER BY object_id, level` -> SQLite -- ROW_NUMBER() OVER (PARTITION BY object_id ORDER BY level) = 1. Booleans are 0/1. -- Columns match UserPermissionResult (permission_source_id, _id_user, ...). -- NOTE: per-object permission checks scan the full view (O(N)); the optimized -- per-object get_user_permissions_for_object() stays a Free C-function task (Python surface). -- System user (id=0) is short-circuited to full rights in C# before any query here. -- ============================================================================ CREATE VIEW IF NOT EXISTS v_user_permissions AS WITH RECURSIVE permission_search AS ( -- Step 1: each object searches for its own permission SELECT o._id AS object_id, o._id AS current_search_id, o._id_parent, 0 AS level, EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = o._id) AS has_permission FROM _objects o UNION ALL -- Step 2: if NO permission - walk up to the parent SELECT ps.object_id, o._id AS current_search_id, o._id_parent, ps.level + 1, EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = o._id) AS has_permission FROM _objects o JOIN permission_search ps ON o._id = ps._id_parent WHERE ps.level < 50 AND ps.has_permission = 0 ), -- closest permission per (object, grantee). NOTE: deviation from the literal PG view, -- which partitions by object_id ONLY (DISTINCT ON object_id) and is therefore lossy when -- one node carries permissions for several users/roles (e.g. the global _id_ref=0 row for -- both sys and admin) — it would keep just one, shadowing the others. We partition by -- (object_id, _id_user, _id_role) so every grantee keeps its own closest-level permission. object_permissions AS ( SELECT object_id, permission_id, _id_user, _id_role, _select, _insert, _update, _delete, level FROM ( SELECT ps.object_id, p._id AS permission_id, p._id_user, p._id_role, p._select, p._insert, p._update, p._delete, ps.level, ROW_NUMBER() OVER (PARTITION BY ps.object_id, p._id_user, p._id_role ORDER BY ps.level) AS rn FROM permission_search ps JOIN _permissions p ON p._id_ref = ps.current_search_id WHERE ps.has_permission = 1 ) WHERE rn = 1 ), -- global rights as virtual records with object_id = 0 global_permissions AS ( SELECT 0 AS object_id, p._id AS permission_id, p._id_user, p._id_role, p._select, p._insert, p._update, p._delete, 999 AS level FROM _permissions p WHERE p._id_ref = 0 ), all_permissions AS ( SELECT * FROM object_permissions UNION ALL SELECT * FROM global_permissions ), -- specific (object) beats global (object_id=0) per grantee: lower level wins. final_permissions AS ( SELECT object_id, permission_id, _id_user, _id_role, _select, _insert, _update, _delete, level FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY object_id, _id_user, _id_role ORDER BY level) AS rn FROM all_permissions ) WHERE rn = 1 ) SELECT fp.object_id, CASE WHEN fp._id_user IS NOT NULL THEN fp._id_user ELSE ur._id_user END AS user_id, fp.permission_id AS permission_source_id, CASE WHEN fp._id_user IS NOT NULL THEN 'user' ELSE 'role' END AS permission_type, fp._id_role, fp._id_user, fp._select AS can_select, fp._insert AS can_insert, fp._update AS can_update, fp._delete AS can_delete FROM final_permissions fp LEFT JOIN _users_roles ur ON ur._id_role = fp._id_role WHERE fp._id_user IS NOT NULL OR ur._id_user IS NOT NULL; Path: redb/redb.SQLite/sql/v2-pvt/00_module_init.sql 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/v2-pvt/00_module_init.sql ---- -- ===================================================================== -- v2-pvt module init -- ===================================================================== -- Purpose: PVT-based search engine for REDB free (PostgreSQL). -- Owner : redb core team. Forked helpers in 01..07 mirror legacy -- redb_facets_search.sql / redb_lazy_loading_search.sql. -- Version: see pvt_module_version() at the bottom of this file. -- -- This file must be applied FIRST. It performs three things: -- 1. Verifies that system infrastructure of REDB is in place -- (core tables and two system functions). -- 2. Drops every function this module owns (CASCADE) so the module -- can be redeployed cleanly. -- 3. Creates pvt_module_version() — used by the C# client to verify -- compatibility on InitializeAsync(). No runtime fallback. -- ===================================================================== -- ---------- 1. System infrastructure check ------------------------------ DO $$ BEGIN -- Required system function: scheme metadata reader. Source lives in -- redbPostgre.sql; ships in the generated bundle redb_init.sql. IF NOT EXISTS ( SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE p.proname = 'get_scheme_definition' AND n.nspname = 'public' ) THEN RAISE EXCEPTION 'v2-pvt: required system function public.get_scheme_definition(bigint) is missing. Deploy the REDB core schema first (redbPostgre.sql / generated redb_init.sql).'; END IF; -- Required system function: object JSON materializer. IF NOT EXISTS ( SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE p.proname = 'get_object_json' AND n.nspname = 'public' ) THEN RAISE EXCEPTION 'v2-pvt: required system function public.get_object_json(bigint, integer) is missing. Deploy the REDB core schema first (redbPostgre.sql / generated redb_init.sql).'; END IF; -- Required core tables. IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '_objects') THEN RAISE EXCEPTION 'v2-pvt: required table public._objects is missing.'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '_values') THEN RAISE EXCEPTION 'v2-pvt: required table public._values is missing.'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '_structures') THEN RAISE EXCEPTION 'v2-pvt: required table public._structures is missing.'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '_list_items') THEN RAISE EXCEPTION 'v2-pvt: required table public._list_items is missing.'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '_scheme_metadata_cache') THEN RAISE EXCEPTION 'v2-pvt: required cache table public._scheme_metadata_cache is missing. Deploy redb_metadata_cache.sql first.'; END IF; END $$; -- ---------- 2. DROP every pvt_* function this module owns --------------- -- Universal drop: enumerate all functions in the public schema whose name -- starts with `pvt_` and drop them with their actual signatures. This -- protects the module against signature drift between releases. DO $$ DECLARE r record; BEGIN FOR r IN SELECT p.oid::regprocedure::text AS sig FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname LIKE 'pvt\_%' ESCAPE '\' LOOP EXECUTE 'DROP FUNCTION IF EXISTS ' || r.sig || ' CASCADE'; END LOOP; END $$; -- ---------- 3. Module version function --------------------------------- -- semver: bump MAJOR on breaking changes to entry-point signatures or -- result shape; bump MINOR on additive features; bump PATCH on bug fixes. CREATE OR REPLACE FUNCTION pvt_module_version() RETURNS text LANGUAGE plpgsql IMMUTABLE AS $BODY$ BEGIN -- 0.6.2 — Nested-dict object-set pushdown (mixed scalar+nested): -- * 12_pvt_cte_builder.sql now folds the object-set restriction -- (scheme + base pushdown + tree filter) into every -- nested_dict_N CTE's WHERE, not just the nested-only path. -- Mixed scalar+nested queries were previously scanning the -- full parent_sid partition of _values and gating via the -- outer JOIN; with this change PG prunes dp rows by -- _id_scheme BEFORE the LEFT JOIN nv expansion. -- 0.6.1 — ListItem.Value/.Alias Pro-parity perf: -- * pvt_build_cte_sql and the inline GROUP BY path in -- pvt_build_groupby_sql now emit a single -- `LEFT JOIN _list_items li ON li._id = v._ListItem` on the -- pivot source whenever any field projects `list_item_prop` -- in (Value, Alias). Per-column expressions reference bare -- `li._value` / `li._alias` and aggregate via -- `array_agg(li.) FILTER (...)`. -- * Replaces N per-column correlated subselects -- `(SELECT li._value FROM _list_items li WHERE li._id = v._ListItem)` -- with one JOIN per pivot — matches Pro PivotSqlGenerator. -- * Scalar Value/Alias pivot column still holds resolved text -- (Free LINQ passes string literals; comparison is `= '...'::text`). -- 0.6.0 — Pro-parity perf rewrite (large-scale ops): -- * #1 Filter pushdown: pvt_split_filter detects narrow filter sets -- that contain no base refs and inlines the residual WHERE -- inside _pvt_cte with an explicit `SELECT pvt._id_object, pvt."col", ...` -- wrapper (pvt_filter_has_base_refs gate + explicit-cols -- projection in pvt_build_cte_sql). Outer WHERE collapses to TRUE. -- * #2 GROUP BY inline subquery: pvt_build_groupby_sql now skips -- the CTE for pure-scalar narrow shapes and emits -- `SELECT pvt., agg(...) FROM () pvt`. -- `v._array_index IS NULL` is lifted from per-column FILTER into -- the inline subquery's outer WHERE — index-friendly at 100M+ rows. -- pvt_build_column_expr gained p_array_index_in_outer for this. -- * #3 Nested-dict side CTE: a single LEFT JOIN _values + per-field -- `array_agg(...) FILTER (...)` replaces N correlated subselects. -- SID list collapses to `IN (...)` (or `= sid`) with dedup. -- 0.5.0 — Expression engine (Pro parity, capability): -- * 17_pvt_expr.sql introduces pvt_build_scalar_expr (recursive -- compiler for $field/$const/arithmetic/Math/String/Concat/ -- Coalesce/Cast) and pvt_build_expr_predicate (full predicate -- family $eq..$gte / $like / $ilike / $in / $nin / $between / -- $null / $notNull / $contains[IgnoreCase] / $startsWith / $endsWith). -- * pvt_build_where_from_json and pvt_split_filter route -- filter-level expression-form predicates through the new engine. -- * pvt_extract_field_pairs harvests $field references from -- expression subtrees so pvt_collect_fields resolves them. -- * Pushdown: expression predicates are pushed iff every $field -- reference inside resolves to kind=base (pvt_expr_is_base_only). -- 0.4.0 — Base-field pushdown (Pro parity, perf): -- * pvt_split_filter walks the filter and peels off base/hierarchical -- predicates into a SQL fragment over `_objects o.*`. -- * pvt_build_cte_sql accepts p_extra_where and ANDs it into the -- inner WHERE so PG can use system-column indexes BEFORE the -- JOIN with _values and the GROUP BY agg. -- * pvt_build_field_condition gained p_base_prefix; passed as 'o.' -- in pushdown context, '' (default) in the outer CTE WHERE. -- * $or/$not are pushed only when every leaf inside is base — -- mixed branches keep the original semantics. -- 0.3.0 — Pro parity rewrite: -- * `(array_agg(v.) FILTER (...))[1]` idiom (works for bool/uuid/etc). -- * `_array_index IS NULL` filter for scalars (NOT `_array_parent_id IS NULL`). -- * `0$:` base-field prefix stripping in pvt_normalize_base_field_name. -- * full collection / nested / dictionary / ListItem.Value/Alias / array-op support. RETURN '0.6.2'; END; $BODY$; COMMENT ON FUNCTION pvt_module_version() IS 'Returns the semver of the v2-pvt module. Used by the C# client on InitializeAsync to enforce compatibility (major must match, deployed minor >= required).'; -- ---------- 4. Shared legacy helpers used by pvt_* code ---------------- -- Forked verbatim from sql/deprecated/redb_facets_search.sql. They are -- referenced by pvt_build_inner_condition / pvt_build_single_facet_condition -- and were left in the legacy file before the PG free path was rewritten on -- top of v2-pvt. Kept here (not under deprecated/) so the module is fully -- self-contained — the bundled redb_init.sql no longer ships the legacy -- facets_search file. Names keep the underscore prefix to avoid touching -- every call site inside the pvt_* functions. DROP TYPE IF EXISTS structure_info_type CASCADE; CREATE TYPE structure_info_type AS ( root_structure_id bigint, nested_structure_id bigint, root_type_info jsonb, nested_type_info jsonb ); CREATE OR REPLACE FUNCTION _format_json_array_for_in( array_data jsonb ) RETURNS text LANGUAGE 'plpgsql' IMMUTABLE AS $BODY$ DECLARE in_values text := ''; json_element jsonb; first_item boolean := true; element_text text; BEGIN IF jsonb_typeof(array_data) != 'array' THEN RAISE EXCEPTION 'JSON array expected, got: %', jsonb_typeof(array_data); END IF; FOR json_element IN SELECT value FROM jsonb_array_elements(array_data) LOOP IF NOT first_item THEN in_values := in_values || ', '; END IF; first_item := false; CASE jsonb_typeof(json_element) WHEN 'string' THEN element_text := quote_literal(json_element #>> '{}'); WHEN 'number' THEN element_text := json_element::text; WHEN 'boolean' THEN element_text := CASE WHEN (json_element)::boolean THEN 'true' ELSE 'false' END; ELSE element_text := quote_literal(json_element #>> '{}'); END CASE; in_values := in_values || element_text; END LOOP; RETURN in_values; END; $BODY$; COMMENT ON FUNCTION _format_json_array_for_in(jsonb) IS 'Converts JSONB array to string of values for SQL IN clause. Forked from redb_facets_search.sql into the v2-pvt module bundle (00_module_init.sql).'; -- pvt_resolve_field_path_table: TABLE-returning resolver used by -- 26_pvt_array_groupby.sql. Forked verbatim from -- sql/deprecated/redb_aggregation.sql (resolve_field_path). The PVT module -- also ships pvt_resolve_field_path(bigint, text) RETURNS jsonb (see -- 01_pvt_field_path.sql) — that one mirrors C# SchemeFieldResolver and is -- used by the rest of pvt_*. Keep both: the table form is what the -- array_groupby builder consumes (structure_id / db_type / is_array / -- array_index / dict_key / is_dictionary). CREATE OR REPLACE FUNCTION pvt_resolve_field_path_table( p_scheme_id bigint, p_field_path text ) RETURNS TABLE(structure_id bigint, db_type text, is_array boolean, array_index int, dict_key text, is_dictionary boolean) LANGUAGE plpgsql AS $BODY$ DECLARE v_segments text[]; v_segment text; v_clean_segment text; v_current_parent_id bigint := NULL; v_structure_id bigint; v_db_type text; v_is_collection boolean := false; v_is_dictionary boolean := false; v_found_collection_type bigint; v_array_index int := NULL; v_dict_key text := NULL; v_index_match text[]; v_key_match text[]; v_collection_type_name text; BEGIN v_index_match := regexp_match(p_field_path, '\[(\d+)\]'); IF v_index_match IS NOT NULL THEN v_array_index := v_index_match[1]::int; END IF; v_key_match := regexp_match(p_field_path, '\[([A-Za-z_][A-Za-z0-9_-]*)\]'); IF v_key_match IS NOT NULL THEN v_dict_key := v_key_match[1]; END IF; v_segments := string_to_array(regexp_replace(p_field_path, '\[[^\]]*\]', '', 'g'), '.'); FOREACH v_segment IN ARRAY v_segments LOOP v_clean_segment := trim(v_segment); IF v_clean_segment = '' THEN CONTINUE; END IF; SELECT c._structure_id, c.db_type, c._collection_type INTO v_structure_id, v_db_type, v_found_collection_type FROM _scheme_metadata_cache c WHERE c._scheme_id = p_scheme_id AND c._name = v_clean_segment AND ( (v_current_parent_id IS NULL AND c._parent_structure_id IS NULL) OR c._parent_structure_id = v_current_parent_id ) LIMIT 1; IF v_structure_id IS NULL THEN RAISE EXCEPTION 'Field segment "%" not found in path "%" (scheme=%). Check cache: SELECT * FROM warmup_all_metadata_caches();', v_clean_segment, p_field_path, p_scheme_id; END IF; IF v_found_collection_type IS NOT NULL THEN v_is_collection := true; SELECT t._name INTO v_collection_type_name FROM _types t WHERE t._id = v_found_collection_type; IF v_collection_type_name = 'Dictionary' THEN v_is_dictionary := true; END IF; END IF; v_current_parent_id := v_structure_id; END LOOP; structure_id := v_structure_id; db_type := v_db_type; is_array := v_is_collection OR (p_field_path ~ '\[[^\]]*\]'); array_index := v_array_index; dict_key := v_dict_key; is_dictionary := v_is_dictionary; RETURN NEXT; END; $BODY$; COMMENT ON FUNCTION pvt_resolve_field_path_table(bigint, text) IS 'TABLE-returning field-path resolver forked from redb_aggregation.sql. Consumed by pvt_build_array_groupby_sql (26_pvt_array_groupby.sql).'; DO $$ BEGIN RAISE NOTICE 'v2-pvt module init OK, version: %', pvt_module_version(); END $$; Path: redb/redb.SQLite/sql/v2-pvt/01_pvt_field_path.sql 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/v2-pvt/01_pvt_field_path.sql ---- -- ===================================================================== -- pvt_normalize_base_field_name: map C# base field names to _objects columns -- --------------------------------------------------------------------- -- Forked from redb_facets_search.sql L51 on 2026-05-18. -- Legacy version stays untouched. Mirror legacy bug fixes here. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_normalize_base_field_name(field_name text) RETURNS text LANGUAGE 'plpgsql' IMMUTABLE AS $BODY$ DECLARE v_had_prefix boolean := false; v_result text; BEGIN -- FacetFilterBuilder marks base fields by prepending '0$:' to the raw name. -- Strip it before the lookup so '0$:Id', '0$:Name' resolve to base columns. IF field_name LIKE '0$:%' THEN v_had_prefix := true; field_name := substring(field_name from 4); END IF; v_result := CASE field_name -- ID fields WHEN 'id' THEN '_id' WHEN 'Id' THEN '_id' WHEN '_id' THEN '_id' WHEN 'parent_id' THEN '_id_parent' WHEN 'ParentId' THEN '_id_parent' WHEN 'id_parent' THEN '_id_parent' WHEN '_id_parent' THEN '_id_parent' WHEN 'scheme_id' THEN '_id_scheme' WHEN 'SchemeId' THEN '_id_scheme' WHEN 'id_scheme' THEN '_id_scheme' WHEN '_id_scheme' THEN '_id_scheme' WHEN 'owner_id' THEN '_id_owner' WHEN 'OwnerId' THEN '_id_owner' WHEN '_id_owner' THEN '_id_owner' WHEN 'who_change_id' THEN '_id_who_change' WHEN 'WhoChangeId' THEN '_id_who_change' WHEN '_id_who_change' THEN '_id_who_change' -- Value fields (RedbPrimitive support) WHEN 'value_long' THEN '_value_long' WHEN 'ValueLong' THEN '_value_long' WHEN '_value_long' THEN '_value_long' WHEN 'value_string' THEN '_value_string' WHEN 'ValueString' THEN '_value_string' WHEN '_value_string' THEN '_value_string' WHEN 'value_guid' THEN '_value_guid' WHEN 'ValueGuid' THEN '_value_guid' WHEN '_value_guid' THEN '_value_guid' -- Other base fields WHEN 'key' THEN '_key' WHEN 'Key' THEN '_key' WHEN '_key' THEN '_key' WHEN 'name' THEN '_name' WHEN 'Name' THEN '_name' WHEN '_name' THEN '_name' WHEN 'note' THEN '_note' WHEN 'Note' THEN '_note' WHEN '_note' THEN '_note' WHEN 'value_bool' THEN '_value_bool' WHEN 'ValueBool' THEN '_value_bool' WHEN '_value_bool' THEN '_value_bool' -- New RedbPrimitive value fields WHEN 'value_double' THEN '_value_double' WHEN 'ValueDouble' THEN '_value_double' WHEN '_value_double' THEN '_value_double' WHEN 'value_numeric' THEN '_value_numeric' WHEN 'ValueNumeric' THEN '_value_numeric' WHEN '_value_numeric' THEN '_value_numeric' WHEN 'value_datetime' THEN '_value_datetime' WHEN 'ValueDatetime' THEN '_value_datetime' WHEN '_value_datetime' THEN '_value_datetime' WHEN 'value_bytes' THEN '_value_bytes' WHEN 'ValueBytes' THEN '_value_bytes' WHEN '_value_bytes' THEN '_value_bytes' WHEN 'hash' THEN '_hash' WHEN 'Hash' THEN '_hash' WHEN '_hash' THEN '_hash' -- DateTime fields WHEN 'date_create' THEN '_date_create' WHEN 'DateCreate' THEN '_date_create' WHEN '_date_create' THEN '_date_create' WHEN 'date_modify' THEN '_date_modify' WHEN 'DateModify' THEN '_date_modify' WHEN '_date_modify' THEN '_date_modify' WHEN 'date_begin' THEN '_date_begin' WHEN 'DateBegin' THEN '_date_begin' WHEN '_date_begin' THEN '_date_begin' WHEN 'date_complete' THEN '_date_complete' WHEN 'DateComplete' THEN '_date_complete' WHEN '_date_complete' THEN '_date_complete' -- Not a base field - return NULL ELSE NULL END; -- Disambiguation: bare names like `Name`, `Id`, `Key` collide with -- legitimate user-defined Props fields of the same name. Only honor -- the base-column mapping when the caller explicitly opted in via -- the `0$:` prefix, OR the input already starts with an underscore -- (system column naming convention). IF v_result IS NOT NULL AND NOT v_had_prefix AND substring(field_name from 1 for 1) <> '_' THEN RETURN NULL; END IF; RETURN v_result; END; $BODY$; COMMENT ON FUNCTION pvt_normalize_base_field_name(text) IS 'Normalizes C# base field names to SQL column names in _objects. Returns NULL if field is not a base field.'; -- ===================================================================== -- pvt_parse_field_path: split dotted/bracketed field paths into components -- --------------------------------------------------------------------- -- Forked from redb_facets_search.sql L185 on 2026-05-18. -- Legacy version stays untouched. Mirror legacy bug fixes here. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_parse_field_path( field_path text ) RETURNS TABLE ( root_field text, nested_field text, is_array boolean, is_nested boolean, dict_key text -- NEW: Dictionary key for AddressBook[home] -> 'home' ) LANGUAGE 'plpgsql' IMMUTABLE AS $BODY$ DECLARE bracket_pos int; dot_after_bracket int; key_end int; BEGIN -- Initialize dict_key as NULL dict_key := NULL; -- Determine if field is array (contains [] WITHOUT key inside) is_array := field_path LIKE '%[]%'; -- Check for Dictionary path: AddressBook[home] or AddressBook[home].City -- Dictionary differs from array by having non-empty key in brackets IF field_path ~ '\[[^\]]+\]' AND NOT is_array THEN -- This is a Dictionary path: AddressBook[home] or AddressBook[home].City bracket_pos := position('[' in field_path); key_end := position(']' in field_path); -- Extract root field (before bracket) root_field := substring(field_path from 1 for bracket_pos - 1); -- Extract dict key (inside brackets) dict_key := substring(field_path from bracket_pos + 1 for key_end - bracket_pos - 1); -- Check for nested field after bracket: AddressBook[home].City dot_after_bracket := position('.' in substring(field_path from key_end + 1)); IF dot_after_bracket > 0 THEN nested_field := substring(field_path from key_end + 2); -- +2 to skip '].' is_nested := true; ELSE nested_field := NULL; is_nested := false; END IF; RETURN QUERY SELECT root_field, nested_field, false, is_nested, dict_key; RETURN; END IF; -- Determine if field is nested (contains dot) is_nested := field_path LIKE '%.%'; IF is_nested THEN IF is_array THEN -- Case: "Contacts[].Email" -> root="Contacts", nested="Email", is_array=true root_field := split_part(replace(field_path, '[]', ''), '.', 1); nested_field := split_part(replace(field_path, '[]', ''), '.', 2); ELSE -- Case: "Contact.Name" -> root="Contact", nested="Name", is_array=false root_field := split_part(field_path, '.', 1); nested_field := split_part(field_path, '.', 2); END IF; ELSE IF is_array THEN -- Case: "Tags[]" -> root="Tags", nested=NULL, is_array=true root_field := replace(field_path, '[]', ''); nested_field := NULL; ELSE -- Case: "Name" -> root="Name", nested=NULL, is_array=false root_field := field_path; nested_field := NULL; END IF; END IF; RETURN QUERY SELECT root_field, nested_field, is_array, is_nested, dict_key; END; $BODY$; COMMENT ON FUNCTION pvt_parse_field_path(text) IS 'Parses field path to support Class fields, arrays and Dictionary. Supports: "Name", "Contact.Name", "Tags[]", "Contacts[].Email", "PhoneBook[home]", "AddressBook[home].City". Returns path components for further processing.'; -- ===================================================================== -- pvt_normalize_field_name: rewrite `.ContainsKey` predicate paths -- --------------------------------------------------------------------- -- Mirrors redb.Core.Pro.Query.ProSqlBuilderBase.NormalizeDictionaryFieldName: -- when the C# predicate is `Dict.ContainsKey("home")`, the builder emits a -- field name of ".ContainsKey" with a string operand "home". The PVT -- layer rewrites that to "[home]" so the existing dictionary-pivot -- machinery handles it and the operator collapses to IS NOT NULL. -- -- Returns the rewritten path. When the conditions are not met, returns -- the input path unchanged. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_normalize_field_name( p_path text, p_op_value text ) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $BODY$ DECLARE v_base text; BEGIN IF p_path IS NULL THEN RETURN NULL; END IF; IF right(p_path, length('.ContainsKey')) <> '.ContainsKey' THEN RETURN p_path; END IF; IF p_op_value IS NULL OR p_op_value = '' THEN RETURN p_path; END IF; v_base := left(p_path, length(p_path) - length('.ContainsKey')); RETURN v_base || '[' || p_op_value || ']'; END; $BODY$; COMMENT ON FUNCTION pvt_normalize_field_name(text, text) IS 'If path ends with ".ContainsKey" and a string operand is provided, rewrites to "[]" so dictionary-pivot path resolution kicks in. Mirrors Pro.ProSqlBuilderBase.NormalizeDictionaryFieldName.'; -- ===================================================================== -- pvt_peek_contains_key_value: extract a string operand for ContainsKey -- --------------------------------------------------------------------- -- The operand of `Dict.ContainsKey(...)` can arrive either as a bare -- JSON string (shorthand $eq) or as an object `{ "$eq": "" }`. -- Returns the underlying text, or NULL if the operand is not a string. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_peek_contains_key_value(p_op jsonb) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $BODY$ DECLARE v jsonb; BEGIN IF p_op IS NULL THEN RETURN NULL; END IF; IF jsonb_typeof(p_op) = 'string' THEN RETURN p_op #>> '{}'; END IF; IF jsonb_typeof(p_op) = 'object' THEN v := p_op -> '$eq'; IF v IS NOT NULL AND jsonb_typeof(v) = 'string' THEN RETURN v #>> '{}'; END IF; END IF; RETURN NULL; END; $BODY$; COMMENT ON FUNCTION pvt_peek_contains_key_value(jsonb) IS 'Returns the string operand of a ContainsKey predicate (bare string or {"$eq": "..."}), else NULL.'; Path: redb/redb.SQLite/sql/v2-pvt/02_pvt_type_info.sql 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/v2-pvt/02_pvt_type_info.sql ---- -- ===================================================================== -- pvt_get_listitem_field_type_info: resolve type info for ListItem-typed fields -- --------------------------------------------------------------------- -- Forked from redb_facets_search.sql L268 on 2026-05-18. -- Legacy version stays untouched. Mirror legacy bug fixes here. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_get_listitem_field_type_info(field_name text) RETURNS jsonb LANGUAGE 'plpgsql' IMMUTABLE AS $BODY$ BEGIN CASE field_name WHEN 'Value' THEN RETURN jsonb_build_object('db_type', 'String', 'type_semantic', 'String', 'is_array', false); WHEN 'Alias' THEN RETURN jsonb_build_object('db_type', 'String', 'type_semantic', 'String', 'is_array', false); WHEN 'IdObject' THEN RETURN jsonb_build_object('db_type', 'Long', 'type_semantic', 'Long', 'is_array', false); WHEN 'IdList' THEN RETURN jsonb_build_object('db_type', 'Long', 'type_semantic', 'Long', 'is_array', false); WHEN 'Id' THEN RETURN jsonb_build_object('db_type', 'Long', 'type_semantic', 'Long', 'is_array', false); ELSE RETURN NULL; END CASE; END; $BODY$; Path: redb/redb.SQLite/sql/v2-pvt/03_pvt_structure_info.sql 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/v2-pvt/03_pvt_structure_info.sql ---- -- ===================================================================== -- pvt_find_structure_info: look up structure metadata by field path -- --------------------------------------------------------------------- -- Forked from redb_facets_search.sql L291 on 2026-05-18. -- Legacy version stays untouched. Mirror legacy bug fixes here. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_find_structure_info( scheme_id bigint, root_field text, nested_field text DEFAULT NULL ) RETURNS TABLE ( root_structure_id bigint, nested_structure_id bigint, root_type_info jsonb, nested_type_info jsonb ) LANGUAGE 'plpgsql' COST 50 VOLATILE NOT LEAKPROOF AS $BODY$ DECLARE scheme_def jsonb; BEGIN -- Get scheme definition using existing function SELECT get_scheme_definition(scheme_id) INTO scheme_def; -- Find root structure SELECT (struct->>'_id')::bigint, jsonb_build_object( 'type_name', struct->>'_type_name', 'db_type', struct->>'_type_db_type', 'type_semantic', struct->>'_type_dotnet_type', 'is_array', (struct->>'_collection_type')::bigint IS NOT NULL ) INTO root_structure_id, root_type_info FROM jsonb_array_elements(scheme_def->'structures') AS struct WHERE struct->>'_name' = root_field AND struct->>'_id_parent' IS NULL; -- If there is a nested field, find its structure IF nested_field IS NOT NULL AND root_structure_id IS NOT NULL THEN -- 🎯 NEW: Special handling for ListItem fields IF root_type_info->>'type_semantic' = '_RListItem' THEN -- For ListItem nested fields (Value, Alias, etc.) are not structures -- They are stored as columns in _list_items nested_structure_id := NULL; nested_type_info := pvt_get_listitem_field_type_info(nested_field); ELSE -- Normal logic for other types SELECT (struct->>'_id')::bigint, jsonb_build_object( 'type_name', struct->>'_type_name', 'db_type', struct->>'_type_db_type', 'type_semantic', struct->>'_type_dotnet_type', 'is_array', (struct->>'_collection_type')::bigint IS NOT NULL ) INTO nested_structure_id, nested_type_info FROM jsonb_array_elements(scheme_def->'structures') AS struct WHERE struct->>'_name' = nested_field AND (struct->>'_id_parent')::bigint = root_structure_id; END IF; ELSE nested_structure_id := NULL; nested_type_info := NULL; END IF; RETURN QUERY SELECT root_structure_id, nested_structure_id, root_type_info, nested_type_info; END; $BODY$; COMMENT ON FUNCTION pvt_find_structure_info(bigint, text, text) IS 'Finds structure information for Class fields using get_scheme_definition. Returns structure IDs and type metadata for root and nested fields.'; Path: redb/redb.SQLite/sql/v2-pvt/04_pvt_inner_condition.sql 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/v2-pvt/04_pvt_inner_condition.sql ---- -- ===================================================================== -- pvt_build_inner_condition: build SQL operator/value fragment for a typed value column -- --------------------------------------------------------------------- -- Forked from redb_facets_search.sql L362 on 2026-05-18. -- Legacy version stays untouched. Mirror legacy bug fixes here. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_build_inner_condition( operator_name text, operator_value text, type_info jsonb -- Type information from pvt_find_structure_info ) RETURNS text LANGUAGE 'plpgsql' IMMUTABLE AS $BODY$ DECLARE op_symbol text; pattern text; in_values_list text; db_type text := type_info->>'db_type'; is_array boolean := (type_info->>'is_array')::boolean; BEGIN -- Numeric and DateTime operators IF operator_name IN ('$gt', '$lt', '$gte', '$lte') THEN CASE operator_name WHEN '$gt' THEN op_symbol := '>'; WHEN '$lt' THEN op_symbol := '<'; WHEN '$gte' THEN op_symbol := '>='; WHEN '$lte' THEN op_symbol := '<='; END CASE; -- 🚀 OPTIMIZATION: removed fs.db_type checks - use db_type from type_info directly IF type_info->>'type_semantic' = 'TimeSpan' THEN -- TimeSpan: convert to INTERVAL for correct comparison RETURN format('fv._String::interval %s %L::interval', op_symbol, operator_value); ELSIF operator_value ~ '^\d{4}-\d{2}-\d{2}' OR db_type = 'DateTimeOffset' THEN RETURN format('fv._DateTimeOffset %s %L::timestamptz', op_symbol, operator_value); ELSIF db_type = 'Long' THEN -- Known Long type (int, long) RETURN format('fv._Long %s %L::bigint', op_symbol, operator_value); ELSIF db_type = 'Double' THEN -- Known Double type (float, double) RETURN format('fv._Double %s %L::double precision', op_symbol, operator_value); ELSIF db_type = 'Numeric' THEN -- Known Numeric type (decimal) RETURN format('fv._Numeric %s %L::numeric', op_symbol, operator_value); ELSE -- Type unknown - check all numeric types (fallback) RETURN format('((fv._Long %s %L::bigint) OR (fv._Double %s %L::double precision) OR (fv._Numeric %s %L::numeric))', op_symbol, operator_value, op_symbol, operator_value, op_symbol, operator_value); END IF; -- String operators (case-sensitive) -- 🚀 OPTIMIZATION: removed fs.db_type check - type already known for string operators ELSIF operator_name IN ('$startsWith', '$endsWith', '$contains') THEN CASE operator_name WHEN '$startsWith' THEN pattern := operator_value || '%'; WHEN '$endsWith' THEN pattern := '%' || operator_value; WHEN '$contains' THEN pattern := '%' || operator_value || '%'; END CASE; RETURN format('fv._String LIKE %L', pattern); -- String operators (case-insensitive) -- 🚀 OPTIMIZATION: removed fs.db_type check ELSIF operator_name IN ('$startsWithIgnoreCase', '$endsWithIgnoreCase', '$containsIgnoreCase') THEN CASE operator_name WHEN '$startsWithIgnoreCase' THEN pattern := operator_value || '%'; WHEN '$endsWithIgnoreCase' THEN pattern := '%' || operator_value; WHEN '$containsIgnoreCase' THEN pattern := '%' || operator_value || '%'; END CASE; RETURN format('fv._String ILIKE %L', pattern); -- IN operator -- 🚀 OPTIMIZATION: removed fs.db_type checks - use db_type from type_info directly ELSIF operator_name = '$in' THEN in_values_list := _format_json_array_for_in(operator_value::jsonb); IF type_info->>'type_semantic' = 'TimeSpan' THEN -- TimeSpan: convert to INTERVAL for correct comparison RETURN format('fv._String::interval IN (%s)', regexp_replace(in_values_list, '([^,]+)', '\1::interval', 'g')); ELSIF type_info->>'type_semantic' = '_RListItem' THEN -- ListItem: values stored in _listitem column as list element IDs RETURN format('fv._listitem IN (%s)', in_values_list); ELSIF db_type = 'String' THEN RETURN format('fv._String IN (%s)', in_values_list); ELSIF db_type = 'Long' THEN RETURN format('fv._Long IN (%s)', in_values_list); ELSIF db_type = 'Double' THEN RETURN format('fv._Double IN (%s)', in_values_list); ELSIF db_type = 'Numeric' THEN RETURN format('fv._Numeric IN (%s)', in_values_list); ELSIF db_type = 'Boolean' THEN RETURN format('fv._Boolean IN (%s)', in_values_list); ELSIF db_type = 'DateTimeOffset' THEN RETURN format('fv._DateTimeOffset IN (%s)', in_values_list); ELSE -- Fallback: try all types (only if type unknown) RETURN format('(fv._String IN (%s) OR fv._Long IN (%s) OR fv._Double IN (%s) OR fv._Numeric IN (%s) OR fv._Boolean IN (%s) OR fv._DateTimeOffset IN (%s))', in_values_list, in_values_list, in_values_list, in_values_list, in_values_list, in_values_list); END IF; -- NOT EQUAL operator - requires special handling -- 🚀 OPTIMIZATION: removed fs.db_type checks - use db_type from type_info directly ELSIF operator_name = '$ne' THEN -- For $ne null this is a special case - look for existing records (in EAV null = no record) IF operator_value IS NULL OR operator_value = 'null' OR operator_value = '' THEN RETURN 'TRUE'; -- Any existing record means "not null" ELSE -- $ne specific value - build positive condition for negation via NOT EXISTS IF type_info->>'type_semantic' = '_RListItem' THEN RETURN format('fv._listitem = %L::bigint', operator_value); ELSIF db_type = 'DateTimeOffset' OR operator_value ~ '^\d{4}-\d{2}-\d{2}' THEN RETURN format('fv._DateTimeOffset = %L::timestamptz', operator_value); ELSIF db_type = 'Guid' OR operator_value ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN RETURN format('fv._Guid = %L::uuid', operator_value); ELSIF db_type = 'Long' THEN RETURN format('fv._Long = %L::bigint', operator_value); ELSIF db_type = 'Double' THEN RETURN format('fv._Double = %L::double precision', operator_value); ELSIF db_type = 'Numeric' THEN RETURN format('fv._Numeric = %L::numeric', operator_value); ELSIF db_type = 'Boolean' OR operator_value IN ('true', 'false') THEN RETURN format('fv._Boolean = %L::boolean', operator_value); ELSIF db_type = 'String' THEN RETURN format('fv._String = %L', operator_value); ELSIF operator_value ~ '^-?\d+(\.\d+)?$' THEN -- Fallback: numeric value, type unknown IF operator_value ~ '^-?\d+$' THEN RETURN format('(fv._Long = %L::bigint OR fv._Double = %L::double precision OR fv._Numeric = %L::numeric)', operator_value, operator_value, operator_value); ELSE RETURN format('(fv._Double = %L::double precision OR fv._Numeric = %L::numeric)', operator_value, operator_value); END IF; ELSE RETURN format('fv._String = %L', operator_value); END IF; END IF; -- Explicit equality operator -- 🚀 OPTIMIZATION: removed fs.db_type checks - use db_type from type_info directly ELSIF operator_name = '$eq' THEN IF type_info->>'type_semantic' = 'TimeSpan' THEN RETURN format('fv._String::interval = %L::interval', operator_value); ELSIF type_info->>'type_semantic' = '_RListItem' THEN RETURN format('fv._listitem = %L::bigint', operator_value); ELSIF db_type = 'DateTimeOffset' OR operator_value ~ '^\d{4}-\d{2}-\d{2}' THEN RETURN format('fv._DateTimeOffset = %L::timestamptz', operator_value); ELSIF db_type = 'Guid' OR operator_value ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN RETURN format('fv._Guid = %L::uuid', operator_value); ELSIF db_type = 'Long' THEN RETURN format('fv._Long = %L::bigint', operator_value); ELSIF db_type = 'Double' THEN RETURN format('fv._Double = %L::double precision', operator_value); ELSIF db_type = 'Numeric' THEN RETURN format('fv._Numeric = %L::numeric', operator_value); ELSIF db_type = 'Boolean' OR operator_value IN ('true', 'false') THEN RETURN format('fv._Boolean = %L::boolean', operator_value); ELSIF db_type = 'String' THEN RETURN format('fv._String = %L', operator_value); ELSIF operator_value ~ '^-?\d+(\.\d+)?$' THEN -- Fallback: numeric value, type unknown IF operator_value ~ '^-?\d+$' THEN RETURN format('(fv._Long = %L::bigint OR fv._Double = %L::double precision OR fv._Numeric = %L::numeric)', operator_value, operator_value, operator_value); ELSE RETURN format('(fv._Double = %L::double precision OR fv._Numeric = %L::numeric)', operator_value, operator_value); END IF; ELSE RETURN format('fv._String = %L', operator_value); END IF; -- 🚀 EXTENDED RELATIONAL ARRAY OPERATORS -- ✅ OPTIMIZATION: Simple condition instead of nested EXISTS -- _build_exists_condition already creates fv context with fv._array_index IS NOT NULL ELSIF operator_name = '$arrayContains' THEN -- 🎯 Search value in relational array with SMART typing IF db_type = 'Long' OR (operator_value ~ '^-?\d+$' AND type_info->>'type_semantic' != '_RListItem') THEN -- Numeric value (Long) RETURN format('fv._Long = %L::bigint', operator_value); ELSIF db_type = 'Boolean' OR operator_value IN ('true', 'false') THEN -- Boolean value RETURN format('fv._Boolean = %L::boolean', operator_value); ELSIF db_type = 'DateTimeOffset' OR operator_value ~ '^\d{4}-\d{2}-\d{2}' THEN -- DateTime value RETURN format('fv._DateTimeOffset = %L::timestamp', operator_value); ELSIF type_info->>'type_semantic' = '_RListItem' THEN -- ListItem array: search by _listitem column (stores ListItem ID) RETURN format('fv._listitem = %L::bigint', operator_value); ELSE -- String array (default) RETURN format('fv._String = %L', operator_value); END IF; -- Non-empty array check operator ELSIF operator_name = '$arrayAny' THEN RETURN 'EXISTS( SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL )'; -- Empty array check operator ELSIF operator_name = '$arrayEmpty' THEN RETURN 'NOT EXISTS( SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL )'; -- 📊 ARRAY ELEMENT COUNT OPERATORS ELSIF operator_name = '$arrayCount' THEN RETURN format('( SELECT COUNT(*) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL ) = %L::int', operator_value::int); ELSIF operator_name = '$arrayCountGt' THEN RETURN format('( SELECT COUNT(*) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL ) > %L::int', operator_value::int); ELSIF operator_name = '$arrayCountGte' THEN RETURN format('( SELECT COUNT(*) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL ) >= %L::int', operator_value::int); ELSIF operator_name = '$arrayCountLt' THEN RETURN format('( SELECT COUNT(*) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL ) < %L::int', operator_value::int); ELSIF operator_name = '$arrayCountLte' THEN RETURN format('( SELECT COUNT(*) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL ) <= %L::int', operator_value::int); -- 🎯 OPERATORS FOR RELATIONAL ARRAYS ELSIF operator_name = '$arrayAt' THEN -- Get array element by index RETURN format('EXISTS( SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = %L )', operator_value::text); ELSIF operator_name = '$arrayFirst' THEN -- Check first array element -- 🚀 OPTIMIZATION: use db_type from type_info IF db_type = 'String' THEN RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = ''0'' AND av._String = %L)', operator_value); ELSIF db_type = 'Long' THEN RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = ''0'' AND av._Long = %L::bigint)', operator_value); ELSIF db_type = 'Double' THEN RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = ''0'' AND av._Double = %L::double precision)', operator_value); ELSIF db_type = 'Boolean' THEN RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = ''0'' AND av._Boolean = %L::boolean)', operator_value); ELSIF db_type = 'DateTimeOffset' THEN RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = ''0'' AND av._DateTimeOffset = %L::timestamp)', operator_value); ELSE -- Fallback: check all types RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = ''0'' AND (av._String = %L OR av._Long = %L::bigint OR av._Double = %L::double precision))', operator_value, operator_value, operator_value); END IF; ELSIF operator_name = '$arrayLast' THEN -- Check last array element -- 🚀 OPTIMIZATION: use db_type from type_info IF db_type = 'String' THEN RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = (SELECT MAX(av2._array_index::int)::text FROM _values av2 WHERE av2._id_object = fv._id_object AND av2._id_structure = fv._id_structure AND av2._array_index IS NOT NULL) AND av._String = %L)', operator_value); ELSIF db_type = 'Long' THEN RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = (SELECT MAX(av2._array_index::int)::text FROM _values av2 WHERE av2._id_object = fv._id_object AND av2._id_structure = fv._id_structure AND av2._array_index IS NOT NULL) AND av._Long = %L::bigint)', operator_value); ELSIF db_type = 'Double' THEN RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = (SELECT MAX(av2._array_index::int)::text FROM _values av2 WHERE av2._id_object = fv._id_object AND av2._id_structure = fv._id_structure AND av2._array_index IS NOT NULL) AND av._Double = %L::double precision)', operator_value); ELSE -- Fallback RETURN format('EXISTS(SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index = (SELECT MAX(av2._array_index::int)::text FROM _values av2 WHERE av2._id_object = fv._id_object AND av2._id_structure = fv._id_structure AND av2._array_index IS NOT NULL) AND (av._String = %L OR av._Long = %L::bigint))', operator_value, operator_value); END IF; -- 🔍 ARRAY SEARCH OPERATORS -- 🚀 OPTIMIZATION: removed JOIN and fs._collection_type ELSIF operator_name = '$arrayStartsWith' THEN RETURN format('EXISTS( SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL AND av._String LIKE %L )', operator_value || '%'); ELSIF operator_name = '$arrayEndsWith' THEN RETURN format('EXISTS( SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL AND av._String LIKE %L )', '%' || operator_value); ELSIF operator_name = '$arrayMatches' THEN RETURN format('EXISTS( SELECT 1 FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL AND av._String ~ %L )', operator_value); -- 📈 ARRAY AGGREGATION OPERATORS -- 🚀 OPTIMIZATION: use db_type from type_info ELSIF operator_name = '$arraySum' THEN IF db_type = 'Long' THEN RETURN format('(SELECT COALESCE(SUM(av._Long), 0) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::bigint', operator_value); ELSIF db_type = 'Double' THEN RETURN format('(SELECT COALESCE(SUM(av._Double), 0) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::double precision', operator_value); ELSIF db_type = 'Numeric' THEN RETURN format('(SELECT COALESCE(SUM(av._Numeric), 0) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); ELSE -- Fallback: Long + Double RETURN format('(SELECT COALESCE(SUM(COALESCE(av._Long, 0) + COALESCE(av._Double, 0)), 0) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); END IF; ELSIF operator_name = '$arrayAvg' THEN IF db_type = 'Long' THEN RETURN format('(SELECT AVG(av._Long) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); ELSIF db_type = 'Double' THEN RETURN format('(SELECT AVG(av._Double) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::double precision', operator_value); ELSIF db_type = 'Numeric' THEN RETURN format('(SELECT AVG(av._Numeric) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); ELSE RETURN format('(SELECT AVG(COALESCE(av._Long, av._Double)) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); END IF; ELSIF operator_name = '$arrayMin' THEN -- 🚀 OPTIMIZATION: use db_type from type_info IF db_type = 'Long' THEN RETURN format('(SELECT MIN(av._Long) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::bigint', operator_value); ELSIF db_type = 'Double' THEN RETURN format('(SELECT MIN(av._Double) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::double precision', operator_value); ELSIF db_type = 'Numeric' THEN RETURN format('(SELECT MIN(av._Numeric) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); ELSIF db_type = 'DateTimeOffset' THEN RETURN format('(SELECT MIN(av._DateTimeOffset) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::timestamp', operator_value); ELSE RETURN format('(SELECT MIN(COALESCE(av._Long, av._Double)) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); END IF; ELSIF operator_name = '$arrayMax' THEN IF db_type = 'Long' THEN RETURN format('(SELECT MAX(av._Long) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::bigint', operator_value); ELSIF db_type = 'Double' THEN RETURN format('(SELECT MAX(av._Double) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::double precision', operator_value); ELSIF db_type = 'Numeric' THEN RETURN format('(SELECT MAX(av._Numeric) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); ELSIF db_type = 'DateTimeOffset' THEN RETURN format('(SELECT MAX(av._DateTimeOffset) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::timestamp', operator_value); ELSE RETURN format('(SELECT MAX(COALESCE(av._Long, av._Double)) FROM _values av WHERE av._id_object = fv._id_object AND av._id_structure = fv._id_structure AND av._array_index IS NOT NULL) = %L::numeric', operator_value); END IF; ELSE -- 🚀 OPTIMIZATION: Simple equality - use db_type from type_info if known IF type_info->>'type_semantic' = 'TimeSpan' THEN RETURN format('fv._String::interval = %L::interval', operator_value); ELSIF db_type = 'DateTimeOffset' OR operator_value ~ '^\d{4}-\d{2}-\d{2}' THEN RETURN format('fv._DateTimeOffset = %L::timestamptz', operator_value); ELSIF db_type = 'Guid' OR operator_value ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN RETURN format('fv._Guid = %L::uuid', operator_value); ELSIF operator_value ~ '^\d+(\.\d+)?:\d{2}:\d{2}' THEN -- TimeSpan format (HH:MM:SS) RETURN format('fv._String::interval = %L::interval', operator_value); ELSIF db_type = 'Long' THEN RETURN format('fv._Long = %L::bigint', operator_value); ELSIF db_type = 'Double' THEN RETURN format('fv._Double = %L::double precision', operator_value); ELSIF db_type = 'Numeric' THEN RETURN format('fv._Numeric = %L::numeric', operator_value); ELSIF db_type = 'Boolean' OR operator_value IN ('true', 'false') THEN RETURN format('fv._Boolean = %L::boolean', operator_value); ELSIF db_type = 'String' THEN RETURN format('fv._String = %L', operator_value); ELSIF operator_value ~ '^-?\d+(\.\d+)?$' THEN -- Fallback: numeric value, type unknown IF operator_value ~ '^-?\d+$' THEN RETURN format('(fv._Long = %L::bigint OR fv._Double = %L::double precision OR fv._Numeric = %L::numeric)', operator_value, operator_value, operator_value); ELSE RETURN format('(fv._Double = %L::double precision OR fv._Numeric = %L::numeric)', operator_value, operator_value); END IF; ELSE -- String value by default RETURN format('fv._String = %L', operator_value); END IF; END IF; END; $BODY$; COMMENT ON FUNCTION pvt_build_inner_condition(text, text, jsonb) IS '🚀 EXTENDED core system of LINQ operators. Supports 25+ operators: 📊 Numeric: $gt, $gte, $lt, $lte, $ne, $in (Long, Double, Numeric) 📝 String: $contains, $startsWith, $endsWith ⏱️ TimeSpan: $gt, $lt, $eq (conversion to INTERVAL for correct comparison) 📅 DateTimeOffset: $gt, $lt, $eq (timestamptz with timezone) 🔢 Arrays (basic): $arrayContains, $arrayAny, $arrayEmpty, $arrayCount* 🎯 Arrays (position): $arrayAt, $arrayFirst, $arrayLast 🔍 Arrays (search): $arrayStartsWith, $arrayEndsWith, $arrayMatches 📈 Arrays (aggregation): $arraySum, $arrayAvg, $arrayMin, $arrayMax All operators adapted for relational arrays via _array_index. Supports distinguishing _RObject vs Object types. Auto type detection by value format. Special handling for TimeSpan via INTERVAL.'; Path: redb/redb.SQLite/sql/v2-pvt/05_pvt_single_facet.sql 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/v2-pvt/05_pvt_single_facet.sql ---- -- ===================================================================== -- pvt_build_single_facet_condition: build a single field facet WHERE fragment (legacy EXISTS engine; used as fallback for complex ops in PVT) -- --------------------------------------------------------------------- -- Forked from redb_facets_search.sql L1311 on 2026-05-18. -- Legacy version stays untouched. Mirror legacy bug fixes here. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_build_single_facet_condition( facet_condition jsonb, scheme_id bigint, table_alias text DEFAULT 'o', max_depth integer DEFAULT 50 ) RETURNS text LANGUAGE 'plpgsql' IMMUTABLE AS $BODY$ DECLARE condition_key text; condition_value jsonb; field_path text; parsed_path RECORD; structure_info structure_info_type; operator_name text; operator_value text; inner_condition_sql text; all_conditions text := ''; single_condition text; BEGIN -- Recursion depth check IF max_depth <= 0 THEN RAISE EXCEPTION 'Maximum recursion depth (50) reached for filter. Simplify JSON filter.'; END IF; -- Check input data type IF jsonb_typeof(facet_condition) != 'object' THEN RETURN ''; END IF; -- Process each key-value pair FOR condition_key, condition_value IN SELECT * FROM jsonb_each(facet_condition) LOOP -- Logical operators - ACCUMULATE instead of RETURN to process ALL keys at same level -- NOTE: Pass max_depth WITHOUT decrement, because _build_and/or/not decrement themselves when calling _build_single IF condition_key = '$and' THEN single_condition := _build_and_condition(condition_value, scheme_id, table_alias, max_depth); IF single_condition != '' THEN single_condition := ltrim(single_condition, ' AND '); IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || single_condition; ELSE all_conditions := single_condition; END IF; END IF; CONTINUE; ELSIF condition_key = '$or' THEN single_condition := _build_or_condition(condition_value, scheme_id, table_alias, max_depth); IF single_condition != '' THEN single_condition := ltrim(single_condition, ' AND '); IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || single_condition; ELSE all_conditions := single_condition; END IF; END IF; CONTINUE; ELSIF condition_key = '$not' THEN single_condition := _build_not_condition(condition_value, scheme_id, table_alias, max_depth); IF single_condition != '' THEN single_condition := ltrim(single_condition, ' AND '); IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || single_condition; ELSE all_conditions := single_condition; END IF; END IF; CONTINUE; -- Hierarchical operators (processed separately) ELSIF condition_key IN ('$hasAncestor', '$hasDescendant', '$level', '$isRoot', '$isLeaf', '$childrenOf') THEN CONTINUE; -- Skip, they are processed in pvt_build_hierarchical_conditions -- 🆕 Property functions: Field.$length, Field[].$count -- p.Name.Length > 3 → {"Name.$length": {"$gt": 3}} -- p.Tags.Count >= 5 → {"Tags[].$count": {"$gte": 5}} ELSIF condition_key ~ '\.\$length$' OR condition_key ~ '\.\$count$' THEN DECLARE func_is_length boolean := condition_key ~ '\.\$length$'; func_field_name text; func_structure_id bigint; func_condition text; func_op_name text; func_op_value text; func_compare_op text; BEGIN -- Extract field name: "Name.$length" -> "Name", "Tags[].$count" -> "Tags" IF func_is_length THEN func_field_name := regexp_replace(condition_key, '\.\$length$', ''); ELSE func_field_name := regexp_replace(condition_key, '\[\]\.\$count$', ''); func_field_name := regexp_replace(func_field_name, '\.\$count$', ''); END IF; -- Find structure SELECT _id INTO func_structure_id FROM _structures WHERE _id_scheme = scheme_id AND _name = func_field_name AND _id_parent IS NULL; IF func_structure_id IS NULL THEN CONTINUE; -- Field not found, skip END IF; -- Process operators IF jsonb_typeof(condition_value) = 'object' THEN FOR func_op_name, func_op_value IN SELECT key, value #>> '{}' FROM jsonb_each(condition_value) LOOP func_compare_op := CASE func_op_name WHEN '$eq' THEN '=' WHEN '$ne' THEN '<>' WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' ELSE '=' END; IF func_is_length THEN -- String length: LENGTH(v._String) func_condition := format( 'EXISTS (SELECT 1 FROM _values fv WHERE fv._id_object = %I._id AND fv._id_structure = %L AND fv._array_index IS NULL AND LENGTH(fv._String) %s %L::integer)', table_alias, func_structure_id, func_compare_op, func_op_value ); ELSE -- Array count func_condition := format( '(SELECT COUNT(*) FROM _values fv WHERE fv._id_object = %I._id AND fv._id_structure = %L AND fv._array_index IS NOT NULL) %s %L::integer', table_alias, func_structure_id, func_compare_op, func_op_value ); END IF; IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || func_condition; ELSE all_conditions := func_condition; END IF; END LOOP; END IF; END; -- 🚀 _objects TABLE BASE FIELDS (with "0$:" prefix) -- 🆕 CRITICAL BUG FIX: Now base fields are EXPLICITLY marked with "0$:" prefix -- This resolves name conflicts: Props.Name vs RedbObject.name -- Prefix "0$:" is impossible as identifier in any programming language -- C# passes: "0$:name", "0$:parent_id", "0$:Id" etc. ELSIF condition_key LIKE '0$:%' THEN DECLARE raw_field_name text := substring(condition_key from 4); -- remove '0$:' sql_field_name text := pvt_normalize_base_field_name(raw_field_name); base_condition text := ''; BEGIN -- 🛡️ PROTECTION: Check that field is recognized as base IF sql_field_name IS NULL THEN RAISE EXCEPTION 'Unknown RedbObject base field: "%" (passed as "0$:%"). Valid fields: id, parent_id, scheme_id, owner_id, who_change_id, 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, name, note, hash', raw_field_name, raw_field_name; END IF; -- Determine field type and build condition -- Numeric fields (bigint): _id, _id_parent, _id_scheme, _id_owner, _id_who_change, _value_long, _key -- 🛡️ SECURITY: Use %L::bigint instead of %s to protect against SQL injection IF sql_field_name IN ('_id', '_id_parent', '_id_scheme', '_id_owner', '_id_who_change', '_value_long', '_key') THEN IF jsonb_typeof(condition_value) = 'object' THEN FOR operator_name, operator_value IN SELECT key, COALESCE(value #>> '{}', 'null') FROM jsonb_each(condition_value) LOOP single_condition := CASE operator_name WHEN '$in' THEN format('%I.%I IN (%s)', table_alias, sql_field_name, _format_json_array_for_in(condition_value->'$in')) WHEN '$eq' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NULL', table_alias, sql_field_name) ELSE format('%I.%I = %L::bigint', table_alias, sql_field_name, operator_value) END WHEN '$ne' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I != %L::bigint', table_alias, sql_field_name, operator_value) END WHEN '$gt' THEN format('%I.%I > %L::bigint', table_alias, sql_field_name, operator_value) WHEN '$gte' THEN format('%I.%I >= %L::bigint', table_alias, sql_field_name, operator_value) WHEN '$lt' THEN format('%I.%I < %L::bigint', table_alias, sql_field_name, operator_value) WHEN '$lte' THEN format('%I.%I <= %L::bigint', table_alias, sql_field_name, operator_value) -- 🎯 $exists for base fields: IS NULL / IS NOT NULL WHEN '$exists' THEN CASE WHEN operator_value = 'true' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I IS NULL', table_alias, sql_field_name) END ELSE NULL END; IF single_condition IS NOT NULL THEN IF base_condition != '' THEN base_condition := base_condition || ' AND ' || single_condition; ELSE base_condition := single_condition; END IF; END IF; END LOOP; ELSIF jsonb_typeof(condition_value) = 'array' THEN base_condition := format('%I.%I IN (%s)', table_alias, sql_field_name, _format_json_array_for_in(condition_value)); ELSIF jsonb_typeof(condition_value) = 'number' THEN base_condition := format('%I.%I = %L::bigint', table_alias, sql_field_name, condition_value::text); ELSIF condition_value = 'null'::jsonb THEN base_condition := format('%I.%I IS NULL', table_alias, sql_field_name); END IF; -- String fields (text): _value_string, _name, _note ELSIF sql_field_name IN ('_value_string', '_name', '_note') THEN IF jsonb_typeof(condition_value) = 'object' THEN FOR operator_name, operator_value IN SELECT key, COALESCE(value #>> '{}', 'null') FROM jsonb_each(condition_value) LOOP single_condition := CASE operator_name WHEN '$eq' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NULL', table_alias, sql_field_name) ELSE format('%I.%I = %L', table_alias, sql_field_name, operator_value) END WHEN '$ne' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I != %L', table_alias, sql_field_name, operator_value) END WHEN '$in' THEN format('%I.%I IN (%s)', table_alias, sql_field_name, _format_json_array_for_in(condition_value->'$in')) WHEN '$contains' THEN format('%I.%I LIKE %L', table_alias, sql_field_name, '%' || operator_value || '%') WHEN '$containsIgnoreCase' THEN format('%I.%I ILIKE %L', table_alias, sql_field_name, '%' || operator_value || '%') WHEN '$startsWith' THEN format('%I.%I LIKE %L', table_alias, sql_field_name, operator_value || '%') WHEN '$startsWithIgnoreCase' THEN format('%I.%I ILIKE %L', table_alias, sql_field_name, operator_value || '%') WHEN '$endsWith' THEN format('%I.%I LIKE %L', table_alias, sql_field_name, '%' || operator_value) WHEN '$endsWithIgnoreCase' THEN format('%I.%I ILIKE %L', table_alias, sql_field_name, '%' || operator_value) WHEN '$exists' THEN CASE WHEN operator_value = 'true' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I IS NULL', table_alias, sql_field_name) END ELSE NULL END; IF single_condition IS NOT NULL THEN IF base_condition != '' THEN base_condition := base_condition || ' AND ' || single_condition; ELSE base_condition := single_condition; END IF; END IF; END LOOP; ELSIF jsonb_typeof(condition_value) = 'array' THEN base_condition := format('%I.%I IN (%s)', table_alias, sql_field_name, _format_json_array_for_in(condition_value)); ELSIF jsonb_typeof(condition_value) = 'string' THEN base_condition := format('%I.%I = %L', table_alias, sql_field_name, condition_value #>> '{}'); ELSIF condition_value = 'null'::jsonb THEN base_condition := format('%I.%I IS NULL', table_alias, sql_field_name); END IF; -- UUID fields: _value_guid, _hash ELSIF sql_field_name IN ('_value_guid', '_hash') THEN IF jsonb_typeof(condition_value) = 'object' THEN FOR operator_name, operator_value IN SELECT key, COALESCE(value #>> '{}', 'null') FROM jsonb_each(condition_value) LOOP single_condition := CASE operator_name WHEN '$eq' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NULL', table_alias, sql_field_name) ELSE format('%I.%I = %L::uuid', table_alias, sql_field_name, operator_value) END WHEN '$ne' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I != %L::uuid', table_alias, sql_field_name, operator_value) END WHEN '$in' THEN format('%I.%I IN (%s)', table_alias, sql_field_name, _format_json_array_for_in(condition_value->'$in')) WHEN '$exists' THEN CASE WHEN operator_value = 'true' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I IS NULL', table_alias, sql_field_name) END ELSE NULL END; IF single_condition IS NOT NULL THEN IF base_condition != '' THEN base_condition := base_condition || ' AND ' || single_condition; ELSE base_condition := single_condition; END IF; END IF; END LOOP; ELSIF jsonb_typeof(condition_value) = 'string' THEN base_condition := format('%I.%I = %L::uuid', table_alias, sql_field_name, condition_value #>> '{}'); ELSIF condition_value = 'null'::jsonb THEN base_condition := format('%I.%I IS NULL', table_alias, sql_field_name); END IF; -- DateTime fields: _date_create, _date_modify, _date_begin, _date_complete ELSIF sql_field_name IN ('_date_create', '_date_modify', '_date_begin', '_date_complete', '_value_datetime') THEN IF jsonb_typeof(condition_value) = 'object' THEN FOR operator_name, operator_value IN SELECT key, COALESCE(value #>> '{}', 'null') FROM jsonb_each(condition_value) LOOP single_condition := CASE operator_name WHEN '$eq' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NULL', table_alias, sql_field_name) ELSE format('%I.%I = %L::timestamptz', table_alias, sql_field_name, operator_value) END WHEN '$ne' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I != %L::timestamptz', table_alias, sql_field_name, operator_value) END WHEN '$gt' THEN format('%I.%I > %L::timestamptz', table_alias, sql_field_name, operator_value) WHEN '$gte' THEN format('%I.%I >= %L::timestamptz', table_alias, sql_field_name, operator_value) WHEN '$lt' THEN format('%I.%I < %L::timestamptz', table_alias, sql_field_name, operator_value) WHEN '$lte' THEN format('%I.%I <= %L::timestamptz', table_alias, sql_field_name, operator_value) WHEN '$exists' THEN CASE WHEN operator_value = 'true' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I IS NULL', table_alias, sql_field_name) END ELSE NULL END; IF single_condition IS NOT NULL THEN IF base_condition != '' THEN base_condition := base_condition || ' AND ' || single_condition; ELSE base_condition := single_condition; END IF; END IF; END LOOP; ELSIF jsonb_typeof(condition_value) = 'string' THEN base_condition := format('%I.%I = %L::timestamptz', table_alias, sql_field_name, condition_value #>> '{}'); ELSIF condition_value = 'null'::jsonb THEN base_condition := format('%I.%I IS NULL', table_alias, sql_field_name); END IF; -- 🛡️ SECURITY: Boolean field with %L::boolean -- Boolean field: _value_bool ELSIF sql_field_name = '_value_bool' THEN IF jsonb_typeof(condition_value) = 'object' THEN FOR operator_name, operator_value IN SELECT key, COALESCE(value #>> '{}', 'null') FROM jsonb_each(condition_value) LOOP single_condition := CASE operator_name WHEN '$eq' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NULL', table_alias, sql_field_name) ELSE format('%I.%I = %L::boolean', table_alias, sql_field_name, operator_value) END WHEN '$ne' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I != %L::boolean', table_alias, sql_field_name, operator_value) END WHEN '$exists' THEN CASE WHEN operator_value = 'true' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I IS NULL', table_alias, sql_field_name) END ELSE NULL END; IF single_condition IS NOT NULL THEN IF base_condition != '' THEN base_condition := base_condition || ' AND ' || single_condition; ELSE base_condition := single_condition; END IF; END IF; END LOOP; ELSIF jsonb_typeof(condition_value) = 'boolean' THEN base_condition := format('%I.%I = %L::boolean', table_alias, sql_field_name, condition_value::text); ELSIF condition_value = 'null'::jsonb THEN base_condition := format('%I.%I IS NULL', table_alias, sql_field_name); END IF; -- Double/Numeric fields: _value_double, _value_numeric ELSIF sql_field_name IN ('_value_double', '_value_numeric') THEN IF jsonb_typeof(condition_value) = 'object' THEN FOR operator_name, operator_value IN SELECT key, COALESCE(value #>> '{}', 'null') FROM jsonb_each(condition_value) LOOP single_condition := CASE operator_name WHEN '$eq' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NULL', table_alias, sql_field_name) ELSE format('%I.%I = %L::numeric', table_alias, sql_field_name, operator_value) END WHEN '$ne' THEN CASE WHEN operator_value = 'null' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I != %L::numeric', table_alias, sql_field_name, operator_value) END WHEN '$gt' THEN format('%I.%I > %L::numeric', table_alias, sql_field_name, operator_value) WHEN '$gte' THEN format('%I.%I >= %L::numeric', table_alias, sql_field_name, operator_value) WHEN '$lt' THEN format('%I.%I < %L::numeric', table_alias, sql_field_name, operator_value) WHEN '$lte' THEN format('%I.%I <= %L::numeric', table_alias, sql_field_name, operator_value) WHEN '$exists' THEN CASE WHEN operator_value = 'true' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I IS NULL', table_alias, sql_field_name) END ELSE NULL END; IF single_condition IS NOT NULL THEN IF base_condition != '' THEN base_condition := base_condition || ' AND ' || single_condition; ELSE base_condition := single_condition; END IF; END IF; END LOOP; ELSIF jsonb_typeof(condition_value) = 'number' THEN base_condition := format('%I.%I = %L::numeric', table_alias, sql_field_name, condition_value::text); ELSIF condition_value = 'null'::jsonb THEN base_condition := format('%I.%I IS NULL', table_alias, sql_field_name); END IF; -- Bytes field: _value_bytes (only $exists supported) ELSIF sql_field_name = '_value_bytes' THEN IF jsonb_typeof(condition_value) = 'object' THEN FOR operator_name, operator_value IN SELECT key, COALESCE(value #>> '{}', 'null') FROM jsonb_each(condition_value) LOOP single_condition := CASE operator_name WHEN '$exists' THEN CASE WHEN operator_value = 'true' THEN format('%I.%I IS NOT NULL', table_alias, sql_field_name) ELSE format('%I.%I IS NULL', table_alias, sql_field_name) END ELSE NULL END; IF single_condition IS NOT NULL THEN IF base_condition != '' THEN base_condition := base_condition || ' AND ' || single_condition; ELSE base_condition := single_condition; END IF; END IF; END LOOP; ELSIF condition_value = 'null'::jsonb THEN base_condition := format('%I.%I IS NULL', table_alias, sql_field_name); END IF; END IF; -- ✅ ACCUMULATE base condition in all_conditions (instead of RETURN) IF base_condition != '' THEN IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || base_condition; ELSE all_conditions := base_condition; END IF; END IF; END; -- Do NOT RETURN - continue processing other fields! -- 🆕 Collection != null / == null: Check that Array/Dictionary has/does not have elements -- Triggers when condition_value = {"$ne": null} or {"$exists": true/false} for collection field -- ⚠️ Only match $ne when the value IS null (not a specific value like "TEST") -- Otherwise $ne with specific value must fall through to standard ELSE handler ELSIF jsonb_typeof(condition_value) = 'object' AND ( (condition_value ? '$ne' AND (condition_value->>'$ne' IS NULL OR condition_value->>'$ne' = 'null')) OR condition_value ? '$exists' ) AND condition_key ~ '^[A-Za-z_][A-Za-z0-9_]*$' THEN DECLARE coll_field_name text := condition_key; coll_structure_id bigint; coll_collection_type text; coll_condition text; coll_is_ne_null boolean; eav_ne_null_value text; eav_exists_value text; BEGIN -- Check if this is a Collection field (Array or Dictionary) SELECT s._id, s._collection_type INTO coll_structure_id, coll_collection_type FROM _structures s WHERE s._id_scheme = scheme_id AND s._name = coll_field_name AND s._id_parent IS NULL; -- Only handle if it's a Collection (Array or Dictionary) IF coll_structure_id IS NOT NULL AND coll_collection_type IS NOT NULL THEN -- Determine if checking for "not null" or "null" coll_is_ne_null := (condition_value->>'$ne' IS NULL AND condition_value ? '$ne') OR (condition_value->>'$exists' = 'true'); IF coll_is_ne_null OR condition_value ? '$ne' THEN -- Collection != null: at least one element exists coll_condition := format( 'EXISTS (SELECT 1 FROM _values cv WHERE cv._id_object = %I._id AND cv._id_structure = %L AND cv._array_index IS NOT NULL)', table_alias, coll_structure_id ); ELSE -- Collection == null: no elements coll_condition := format( 'NOT EXISTS (SELECT 1 FROM _values cv WHERE cv._id_object = %I._id AND cv._id_structure = %L AND cv._array_index IS NOT NULL)', table_alias, coll_structure_id ); END IF; IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || coll_condition; ELSE all_conditions := coll_condition; END IF; CONTINUE; -- Skip to next field, don't fall through to standard handling -- 🆕 FIX: Regular EAV fields with $ne null or $exists (NOT collections!) ELSIF coll_structure_id IS NOT NULL THEN -- This is a regular EAV field (not a collection) eav_ne_null_value := condition_value->>'$ne'; eav_exists_value := condition_value->>'$exists'; -- $ne null OR $exists true = "field exists" (record exists in _values) IF (condition_value ? '$ne' AND (eav_ne_null_value IS NULL OR eav_ne_null_value = 'null')) OR (eav_exists_value = 'true') THEN -- In EAV model: record existence = field exists and not null coll_condition := format( 'EXISTS (SELECT 1 FROM _values ev WHERE ev._id_object = %I._id AND ev._id_structure = %L AND ev._array_index IS NULL)', table_alias, coll_structure_id ); IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || coll_condition; ELSE all_conditions := coll_condition; END IF; CONTINUE; -- $exists false = "field does NOT exist" (no record in _values) ELSIF eav_exists_value = 'false' THEN coll_condition := format( 'NOT EXISTS (SELECT 1 FROM _values ev WHERE ev._id_object = %I._id AND ev._id_structure = %L AND ev._array_index IS NULL)', table_alias, coll_structure_id ); IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || coll_condition; ELSE all_conditions := coll_condition; END IF; CONTINUE; END IF; -- Guard already filters: only $ne null or $exists reach here END IF; -- If structure not found, fall through to standard handling END; -- 🆕 Dictionary indexer: FieldName[key] (example: "PhoneBook[home]": {"$eq": "+7-999..."}) -- Direct implementation without pvt_build_inner_condition (it uses incompatible aliases fs/fv) ELSIF condition_key ~ '^[A-Za-z_][A-Za-z0-9_]*\[.+\]$' THEN DECLARE dict_field_name text; dict_key text; dict_structure_id bigint; dict_type_info jsonb; dict_db_type text; dict_condition text; dict_op_name text; dict_op_value text; dict_value text; dict_value_condition text; BEGIN -- Parse: "PhoneBook[home]" -> field="PhoneBook", key="home" dict_field_name := substring(condition_key from '^([A-Za-z_][A-Za-z0-9_]*)\['); dict_key := substring(condition_key from '\[(.+)\]$'); -- Find structure and type_info for dictionary field SELECT fi.root_structure_id, fi.root_type_info INTO dict_structure_id, dict_type_info FROM pvt_find_structure_info(scheme_id, dict_field_name, NULL) AS fi LIMIT 1; IF dict_structure_id IS NULL THEN RAISE EXCEPTION 'Dictionary field "%" not found in scheme %', dict_field_name, scheme_id; END IF; -- Get db_type from type_info for correct column selection dict_db_type := dict_type_info->>'db_type'; -- Process condition_value - build value comparison IF jsonb_typeof(condition_value) = 'object' THEN -- Complex condition: {"$eq": "value"}, {"$ne": "x"}, {"$contains": "substr"}, {"$in": [...]}, etc. FOR dict_op_name, dict_op_value IN SELECT key, value FROM jsonb_each_text(condition_value) LOOP -- Build value condition based on operator IF dict_op_name = '$in' THEN -- $in operator: value in list (use db_type for correct column) dict_value_condition := CASE dict_db_type WHEN 'Long' THEN format('dv._Long IN (SELECT (jsonb_array_elements_text(%L::jsonb))::bigint)', dict_op_value) WHEN 'Numeric' THEN format('dv._Numeric IN (SELECT (jsonb_array_elements_text(%L::jsonb))::numeric)', dict_op_value) WHEN 'Double' THEN format('dv._Double IN (SELECT (jsonb_array_elements_text(%L::jsonb))::double precision)', dict_op_value) ELSE format('dv._String IN (SELECT jsonb_array_elements_text(%L::jsonb))', dict_op_value) END; ELSIF dict_op_name = '$nin' THEN -- $nin operator: value not in list (use db_type for correct column) dict_value_condition := CASE dict_db_type WHEN 'Long' THEN format('dv._Long NOT IN (SELECT (jsonb_array_elements_text(%L::jsonb))::bigint)', dict_op_value) WHEN 'Numeric' THEN format('dv._Numeric NOT IN (SELECT (jsonb_array_elements_text(%L::jsonb))::numeric)', dict_op_value) WHEN 'Double' THEN format('dv._Double NOT IN (SELECT (jsonb_array_elements_text(%L::jsonb))::double precision)', dict_op_value) ELSE format('dv._String NOT IN (SELECT jsonb_array_elements_text(%L::jsonb))', dict_op_value) END; ELSE -- Numeric comparisons - use db_type to select correct column IF dict_op_name IN ('$gt', '$gte', '$lt', '$lte') THEN dict_value_condition := CASE dict_db_type WHEN 'Numeric' THEN format('dv._Numeric %s %L::numeric', CASE dict_op_name WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' END, dict_op_value) WHEN 'Double' THEN format('dv._Double %s %L::double precision', CASE dict_op_name WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' END, dict_op_value) ELSE format('dv._Long %s %L::bigint', CASE dict_op_name WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' END, dict_op_value) END; ELSE dict_value_condition := CASE dict_op_name -- Equality/Inequality - use db_type for correct column WHEN '$eq' THEN CASE dict_db_type WHEN 'Long' THEN format('dv._Long = %L::bigint', dict_op_value) WHEN 'Numeric' THEN format('dv._Numeric = %L::numeric', dict_op_value) WHEN 'Double' THEN format('dv._Double = %L::double precision', dict_op_value) ELSE format('dv._String = %L', dict_op_value) END WHEN '$ne' THEN CASE dict_db_type WHEN 'Long' THEN format('dv._Long <> %L::bigint', dict_op_value) WHEN 'Numeric' THEN format('dv._Numeric <> %L::numeric', dict_op_value) WHEN 'Double' THEN format('dv._Double <> %L::double precision', dict_op_value) ELSE format('dv._String <> %L', dict_op_value) END -- String operations WHEN '$contains' THEN format('dv._String LIKE %L', '%' || dict_op_value || '%') WHEN '$startsWith' THEN format('dv._String LIKE %L', dict_op_value || '%') WHEN '$endsWith' THEN format('dv._String LIKE %L', '%' || dict_op_value) WHEN '$containsIgnoreCase' THEN format('dv._String ILIKE %L', '%' || dict_op_value || '%') WHEN '$startsWithIgnoreCase' THEN format('dv._String ILIKE %L', dict_op_value || '%') WHEN '$endsWithIgnoreCase' THEN format('dv._String ILIKE %L', '%' || dict_op_value) -- Regex WHEN '$regex' THEN format('dv._String ~ %L', dict_op_value) WHEN '$iregex' THEN format('dv._String ~* %L', dict_op_value) -- Explicit Double comparisons (legacy support) WHEN '$gtDouble' THEN format('dv._Double > %L', dict_op_value::double precision) WHEN '$gteDouble' THEN format('dv._Double >= %L', dict_op_value::double precision) WHEN '$ltDouble' THEN format('dv._Double < %L', dict_op_value::double precision) WHEN '$lteDouble' THEN format('dv._Double <= %L', dict_op_value::double precision) ELSE format('dv._String = %L', dict_op_value) -- fallback to equality END; END IF; END IF; dict_condition := format( 'EXISTS (SELECT 1 FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index = %L AND %s)', table_alias, dict_structure_id, dict_key, dict_value_condition ); IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || dict_condition; ELSE all_conditions := dict_condition; END IF; END LOOP; ELSE -- Simple value: direct equality (use db_type for correct column) dict_value := condition_value #>> '{}'; dict_condition := format( 'EXISTS (SELECT 1 FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index = %L AND %s)', table_alias, dict_structure_id, dict_key, CASE dict_db_type WHEN 'Long' THEN format('dv._Long = %L::bigint', dict_value) WHEN 'Numeric' THEN format('dv._Numeric = %L::numeric', dict_value) WHEN 'Double' THEN format('dv._Double = %L::double precision', dict_value) ELSE format('dv._String = %L', dict_value) END ); IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || dict_condition; ELSE all_conditions := dict_condition; END IF; END IF; END; -- 🆕 Dictionary ContainsKey: FieldName.ContainsKey (example: "PhoneBook.ContainsKey": "home") -- ⚠️ For Dictionary records are stored in child structures, not in the structure itself! ELSIF condition_key ~ '^[A-Za-z_][A-Za-z0-9_]*\.ContainsKey$' THEN DECLARE dict_field_name text; dict_key text; dict_structure_id bigint; dict_condition text; BEGIN -- Parse: "PhoneBook.ContainsKey" -> field="PhoneBook" dict_field_name := substring(condition_key from '^([A-Za-z_][A-Za-z0-9_]*)\.ContainsKey$'); -- Get the key (handle both {"$eq": "key"} and "key") IF condition_value ? '$eq' THEN dict_key := condition_value->>'$eq'; ELSE dict_key := condition_value #>> '{}'; END IF; -- Find structure for dictionary field SELECT _id INTO dict_structure_id FROM _structures WHERE _id_scheme = scheme_id AND _name = dict_field_name AND _id_parent IS NULL; IF dict_structure_id IS NULL THEN RAISE EXCEPTION 'Dictionary field "%" not found in scheme %', dict_field_name, scheme_id; END IF; -- Build EXISTS condition -- 🆕 FIX: Check BOTH cases: -- 1) Dictionary: records in the structure itself (_id_structure = dict_id) -- 2) Dictionary: records in child structures (_id_parent = dict_id) dict_condition := format( 'EXISTS (SELECT 1 FROM _values dv JOIN _structures s ON dv._id_structure = s._id WHERE dv._id_object = %I._id AND (s._id = %L OR s._id_parent = %L) AND dv._array_index = %L)', table_alias, dict_structure_id, dict_structure_id, dict_key ); IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || dict_condition; ELSE all_conditions := dict_condition; END IF; END; -- 🆕 Dictionary aggregation operators: FieldName.$dictCount, FieldName.$dictSum, etc. ELSIF condition_key ~ '^[A-Za-z_][A-Za-z0-9_]*\.\$dict(Count|Sum|Avg|Min|Max|Keys|Values|HasValue)$' THEN DECLARE dict_field_name text; dict_op text; dict_structure_id bigint; dict_condition text; dict_value text; BEGIN -- Parse: "PhoneBook.$dictCount" -> field="PhoneBook", op="Count" dict_field_name := substring(condition_key from '^([A-Za-z_][A-Za-z0-9_]*)\.\$dict'); dict_op := substring(condition_key from '\$dict([A-Za-z]+)$'); dict_value := condition_value #>> '{}'; -- Find structure for dictionary field SELECT _id INTO dict_structure_id FROM _structures WHERE _id_scheme = scheme_id AND _name = dict_field_name AND _id_parent IS NULL; IF dict_structure_id IS NULL THEN RAISE EXCEPTION 'Dictionary field "%" not found in scheme %', dict_field_name, scheme_id; END IF; -- Build aggregation condition dict_condition := CASE dict_op WHEN 'Count' THEN format( '(SELECT COUNT(*) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) = %L::int', table_alias, dict_structure_id, dict_value::int) WHEN 'Sum' THEN format( '(SELECT COALESCE(SUM(dv._Long), 0) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) = %L::bigint', table_alias, dict_structure_id, dict_value::bigint) WHEN 'Avg' THEN format( '(SELECT AVG(dv._Long) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) = %L::numeric', table_alias, dict_structure_id, dict_value::numeric) WHEN 'Min' THEN format( '(SELECT MIN(dv._Long) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) = %L::bigint', table_alias, dict_structure_id, dict_value::bigint) WHEN 'Max' THEN format( '(SELECT MAX(dv._Long) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) = %L::bigint', table_alias, dict_structure_id, dict_value::bigint) WHEN 'Keys' THEN format( 'EXISTS (SELECT 1 FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index = %L)', table_alias, dict_structure_id, dict_value) WHEN 'Values' THEN format( 'EXISTS (SELECT 1 FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._String = %L)', table_alias, dict_structure_id, dict_value) WHEN 'HasValue' THEN format( 'EXISTS (SELECT 1 FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._String = %L)', table_alias, dict_structure_id, dict_value) ELSE 'TRUE' END; IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || dict_condition; ELSE all_conditions := dict_condition; END IF; END; -- 🆕 Dictionary comparison operators: FieldName.$dictCountGt, FieldName.$dictCountLt, etc. ELSIF condition_key ~ '^[A-Za-z_][A-Za-z0-9_]*\.\$dict(Count|Sum|Avg|Min|Max)(Gt|Gte|Lt|Lte)$' THEN DECLARE dict_field_name text; dict_agg text; dict_cmp text; dict_structure_id bigint; dict_condition text; dict_value text; dict_cmp_op text; BEGIN -- Parse: "PhoneBook.$dictCountGt" -> field="PhoneBook", agg="Count", cmp="Gt" dict_field_name := substring(condition_key from '^([A-Za-z_][A-Za-z0-9_]*)\.\$dict'); dict_agg := substring(condition_key from '\$dict(Count|Sum|Avg|Min|Max)'); dict_cmp := substring(condition_key from '(Gt|Gte|Lt|Lte)$'); dict_value := condition_value #>> '{}'; dict_cmp_op := CASE dict_cmp WHEN 'Gt' THEN '>' WHEN 'Gte' THEN '>=' WHEN 'Lt' THEN '<' WHEN 'Lte' THEN '<=' END; -- Find structure for dictionary field SELECT _id INTO dict_structure_id FROM _structures WHERE _id_scheme = scheme_id AND _name = dict_field_name AND _id_parent IS NULL; IF dict_structure_id IS NULL THEN RAISE EXCEPTION 'Dictionary field "%" not found in scheme %', dict_field_name, scheme_id; END IF; -- Build aggregation condition with comparison dict_condition := CASE dict_agg WHEN 'Count' THEN format( '(SELECT COUNT(*) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) %s %L::int', table_alias, dict_structure_id, dict_cmp_op, dict_value::int) WHEN 'Sum' THEN format( '(SELECT COALESCE(SUM(dv._Long), 0) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) %s %L::bigint', table_alias, dict_structure_id, dict_cmp_op, dict_value::bigint) WHEN 'Avg' THEN format( '(SELECT AVG(dv._Long) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) %s %L::numeric', table_alias, dict_structure_id, dict_cmp_op, dict_value::numeric) WHEN 'Min' THEN format( '(SELECT MIN(dv._Long) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) %s %L::bigint', table_alias, dict_structure_id, dict_cmp_op, dict_value::bigint) WHEN 'Max' THEN format( '(SELECT MAX(dv._Long) FROM _values dv WHERE dv._id_object = %I._id AND dv._id_structure = %L AND dv._array_index IS NOT NULL) %s %L::bigint', table_alias, dict_structure_id, dict_cmp_op, dict_value::bigint) ELSE 'TRUE' END; IF all_conditions != '' THEN all_conditions := all_conditions || ' AND ' || dict_condition; ELSE all_conditions := dict_condition; END IF; END; -- Field operators ELSE -- Parse field path field_path := condition_key; SELECT * INTO parsed_path FROM pvt_parse_field_path(field_path); -- Get structure information for all fields -- 🎯 FIX: Explicit assignment of fields from TABLE-returning function to RECORD SELECT fi.root_structure_id, fi.nested_structure_id, fi.root_type_info, fi.nested_type_info INTO structure_info FROM pvt_find_structure_info(scheme_id, parsed_path.root_field, parsed_path.nested_field) AS fi LIMIT 1; -- Process field value IF jsonb_typeof(condition_value) = 'object' THEN -- Complex condition with operators like {"$gt": 100, "$lt": 200} FOR operator_name, operator_value IN SELECT key, value FROM jsonb_each_text(condition_value) LOOP inner_condition_sql := pvt_build_inner_condition( operator_name, operator_value, CASE WHEN parsed_path.is_nested THEN structure_info.nested_type_info ELSE structure_info.root_type_info END ); -- $ne for specific value (not null) requires NOT EXISTS single_condition := _build_exists_condition( field_path, inner_condition_sql, operator_name = '$ne' AND operator_value IS NOT NULL AND operator_value != 'null' AND operator_value != '', scheme_id, table_alias ); -- Accumulate conditions via AND IF all_conditions != '' THEN all_conditions := all_conditions || ' AND '; END IF; all_conditions := all_conditions || ltrim(single_condition, ' AND '); END LOOP; ELSIF jsonb_typeof(condition_value) = 'array' THEN -- Array of values - process as $in inner_condition_sql := pvt_build_inner_condition( '$in', condition_value::text, CASE WHEN parsed_path.is_nested THEN structure_info.nested_type_info ELSE structure_info.root_type_info END ); single_condition := _build_exists_condition(field_path, inner_condition_sql, false, scheme_id, table_alias); -- Accumulate conditions via AND IF all_conditions != '' THEN all_conditions := all_conditions || ' AND '; END IF; all_conditions := all_conditions || ltrim(single_condition, ' AND '); ELSE -- Simple value - equality inner_condition_sql := pvt_build_inner_condition( '=', -- Remove extra quotes from string values CASE WHEN jsonb_typeof(condition_value) = 'string' THEN condition_value #>> '{}' ELSE condition_value::text END, CASE WHEN parsed_path.is_nested THEN structure_info.nested_type_info ELSE structure_info.root_type_info END ); single_condition := _build_exists_condition(field_path, inner_condition_sql, false, scheme_id, table_alias); -- Accumulate conditions via AND IF all_conditions != '' THEN all_conditions := all_conditions || ' AND '; END IF; all_conditions := all_conditions || ltrim(single_condition, ' AND '); END IF; END IF; END LOOP; -- Return all accumulated conditions IF all_conditions != '' THEN RETURN ' AND (' || all_conditions || ')'; END IF; RETURN ''; END; $BODY$; Path: redb/redb.SQLite/sql/v2-pvt/06_pvt_hierarchical.sql 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/v2-pvt/06_pvt_hierarchical.sql ---- -- ===================================================================== -- pvt_build_hierarchical_conditions: build tree predicates ($hasAncestor, $hasDescendant, $level, ...) -- --------------------------------------------------------------------- -- Forked from redb_facets_search.sql L2818 on 2026-05-18. -- Legacy version stays untouched. Mirror legacy bug fixes here. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_build_hierarchical_conditions( facet_filters jsonb, table_alias text DEFAULT 'o' ) RETURNS text LANGUAGE 'plpgsql' COST 50 VOLATILE NOT LEAKPROOF AS $BODY$ DECLARE where_conditions text := ''; ancestor_id bigint; descendant_id bigint; target_level integer; BEGIN IF facet_filters IS NOT NULL AND jsonb_typeof(facet_filters) = 'object' THEN -- $hasAncestor: Polymorphic ancestor search with condition, scheme_id and max_depth IF facet_filters ? '$hasAncestor' THEN where_conditions := where_conditions || build_has_ancestor_condition(facet_filters->'$hasAncestor', table_alias); END IF; -- $hasDescendant: Polymorphic descendant search with condition, scheme_id and max_depth IF facet_filters ? '$hasDescendant' THEN where_conditions := where_conditions || build_has_descendant_condition(facet_filters->'$hasDescendant', table_alias); END IF; -- $level: Support for comparison operators {"$gt": 2}, {"$eq": 3} etc. IF facet_filters ? '$level' THEN -- ✅ FIX: Processing JSON operators for $level IF jsonb_typeof(facet_filters->'$level') = 'object' THEN -- Complex condition with operators like {"$gt": 2}, {"$lt": 5} where_conditions := where_conditions || pvt_build_level_condition_with_operators(facet_filters->'$level', table_alias); ELSE -- Simple value - exact equality target_level := (facet_filters->>'$level')::integer; where_conditions := where_conditions || pvt_build_level_condition(target_level, table_alias); END IF; END IF; -- $isRoot IF facet_filters ? '$isRoot' AND (facet_filters->>'$isRoot')::boolean THEN where_conditions := where_conditions || format(' AND %s._id_parent IS NULL', table_alias); END IF; -- $isLeaf IF facet_filters ? '$isLeaf' AND (facet_filters->>'$isLeaf')::boolean THEN where_conditions := where_conditions || format( ' AND NOT EXISTS (SELECT 1 FROM _objects child WHERE child._id_parent = %s._id)', table_alias ); END IF; -- $childrenOf - direct children of specified parent IF facet_filters ? '$childrenOf' THEN where_conditions := where_conditions || format( ' AND %s._id_parent = %s', table_alias, (facet_filters->>'$childrenOf')::bigint ); END IF; END IF; RETURN where_conditions; END; $BODY$; Path: redb/redb.SQLite/sql/v2-pvt/06a_pvt_legacy_helpers.sql 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/v2-pvt/06a_pvt_legacy_helpers.sql ---- -- ===================================================================== -- pvt_build_level_condition / pvt_build_level_condition_with_operators -- --------------------------------------------------------------------- -- Forked from redb_init.sql (deprecated) on 2026-05-23. -- Required by pvt_build_hierarchical_conditions (06_pvt_hierarchical.sql). -- The legacy bundle that originally defined `build_level_condition`/ -- `build_level_condition_with_operators` was removed in PG free -- (v2-pvt is now the only engine), so we re-host these helpers under -- the pvt_* namespace. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_build_level_condition( target_level integer, table_alias text DEFAULT 'o' ) RETURNS text LANGUAGE 'plpgsql' COST 50 IMMUTABLE AS $BODY$ BEGIN -- Calculate level going UP from object to root. -- Level 0 = root (where _id_parent IS NULL). -- Level 1 = direct child of root, etc. RETURN format( ' AND ( SELECT COUNT(*)::integer FROM ( WITH RECURSIVE ancestors AS ( SELECT %s._id_parent as parent_id UNION ALL SELECT o._id_parent FROM _objects o JOIN ancestors ON o._id = ancestors.parent_id WHERE o._id_parent IS NOT NULL ) SELECT parent_id FROM ancestors WHERE parent_id IS NOT NULL ) AS a ) = %s', table_alias, target_level ); END; $BODY$; CREATE OR REPLACE FUNCTION pvt_build_level_condition_with_operators( level_operators jsonb, table_alias text DEFAULT 'o' ) RETURNS text LANGUAGE 'plpgsql' COST 50 IMMUTABLE AS $BODY$ DECLARE operator_name text; operator_value text; level_condition text := ''; op_symbol text; BEGIN FOR operator_name, operator_value IN SELECT key, value FROM jsonb_each_text(level_operators) LOOP CASE operator_name WHEN '$gt' THEN op_symbol := '>'; WHEN '$gte' THEN op_symbol := '>='; WHEN '$lt' THEN op_symbol := '<'; WHEN '$lte' THEN op_symbol := '<='; WHEN '$eq' THEN op_symbol := '='; WHEN '$ne' THEN op_symbol := '!='; ELSE CONTINUE; END CASE; IF level_condition != '' THEN level_condition := level_condition || ' AND '; END IF; level_condition := level_condition || format( '( SELECT COUNT(*)::integer FROM ( WITH RECURSIVE ancestors AS ( SELECT %s._id_parent as parent_id UNION ALL SELECT o._id_parent FROM _objects o JOIN ancestors ON o._id = ancestors.parent_id WHERE o._id_parent IS NOT NULL ) SELECT parent_id FROM ancestors WHERE parent_id IS NOT NULL ) AS a ) %s %s', table_alias, op_symbol, operator_value ); END LOOP; IF level_condition != '' THEN RETURN ' AND (' || level_condition || ')'; END IF; RETURN ''; END; $BODY$; Path: redb/redb.SQLite/sql/v2-pvt/07_pvt_base_fields.sql 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/v2-pvt/07_pvt_base_fields.sql ---- -- ===================================================================== -- pvt_get_object_base_fields: return JSONB with all base fields of a single object (no Props) -- --------------------------------------------------------------------- -- Forked from redb_lazy_loading_search.sql L17 on 2026-05-18. -- Legacy version stays untouched. Mirror legacy bug fixes here. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_get_object_base_fields(object_id bigint) RETURNS jsonb LANGUAGE SQL IMMUTABLE AS $$ SELECT jsonb_build_object( 'id', o._id, 'name', o._name, 'scheme_id', o._id_scheme, 'parent_id', o._id_parent, 'owner_id', o._id_owner, 'who_change_id', o._id_who_change, 'date_create', o._date_create, 'date_modify', o._date_modify, 'date_begin', o._date_begin, 'date_complete', o._date_complete, 'key', o._key, 'value_long', o._value_long, 'value_string', o._value_string, 'value_guid', o._value_guid, 'note', o._note, 'value_bool', o._value_bool, 'value_double', o._value_double, 'value_numeric', o._value_numeric, 'value_datetime', o._value_datetime, 'value_bytes', o._value_bytes, 'hash', o._hash -- CRITICAL for cache! ) FROM _objects o WHERE o._id = object_id; $$; COMMENT ON FUNCTION pvt_get_object_base_fields(bigint) IS 'Returns base object fields WITHOUT Props for lazy loading. Includes hash for cache validation. 10-50x faster than get_object_json(). ATTENTION: Function kept for compatibility and direct use. In aggregate queries (search_*_base), direct JOIN is used instead of function call for optimization.'; Path: redb/redb.SQLite/sql/v2-pvt/10_pvt_field_collection.sql 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/v2-pvt/10_pvt_field_collection.sql ---- -- ===================================================================== -- 10_pvt_field_collection.sql -- --------------------------------------------------------------------- -- Field-name collection from filter/order JSON and metadata resolution -- via _scheme_metadata_cache. Produces the `fields` jsonb consumed by -- pvt_build_column_expr / pvt_build_cte_sql / pvt_build_*_condition. -- -- Functions: -- pvt_extract_field_names(p_filter jsonb) RETURNS SETOF text -- pvt_collect_fields(p_scheme_id, p_filter, p_order, p_include_all) RETURNS jsonb -- pvt_has_null_check(p_filter jsonb) RETURNS boolean -- -- The result of pvt_collect_fields is a jsonb object: -- { -- "": { -- "semantic": "base"|"scalar"|"listitem"|"collection"|"nested", -- "column": "_id_parent" -- only when semantic = "base" -- "sid": 42, -- _structure_id -- "db_type": "Long", -- db_type from cache -- "type_semantic": "TimeSpan"|null, -- type_semantic from cache -- "collection_type": null|, -- "list_id": null|, -- "parent_sid": null| -- }, -- ... -- } -- ===================================================================== -- ---------- pvt_extract_field_names ------------------------------------ -- Walk a filter JSON recursively and return every field-name reference -- (a key whose name does NOT start with '$'). Logical operators ($and, -- $or, $not, ...) are recursed into but never emitted themselves. CREATE OR REPLACE FUNCTION pvt_extract_field_names(p_filter jsonb) RETURNS SETOF text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; elem jsonb; BEGIN IF p_filter IS NULL OR jsonb_typeof(p_filter) <> 'object' THEN RETURN; END IF; FOR k, v IN SELECT key, value FROM jsonb_each(p_filter) LOOP IF left(k, 1) = '$' THEN -- $case has shape: [ {when:, then:}, ..., {else:}? ]. -- Iterate VALUES of each branch object, not its keys, so that -- "when" / "then" / "else" never get harvested as field paths. IF lower(k) = '$case' AND jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP IF jsonb_typeof(elem) = 'object' THEN IF elem ? 'when' THEN RETURN QUERY SELECT pvt_extract_field_names(elem->'when'); END IF; IF elem ? 'then' THEN RETURN QUERY SELECT pvt_extract_field_names(elem->'then'); END IF; IF elem ? 'else' THEN RETURN QUERY SELECT pvt_extract_field_names(elem->'else'); END IF; END IF; END LOOP; CONTINUE; END IF; -- $fts object form: { "query": , "fields": [...], "language": "..." }. -- Only `query` and `fields` carry field references; `language` is a literal. IF lower(k) = '$fts' AND jsonb_typeof(v) = 'object' THEN IF v ? 'query' THEN RETURN QUERY SELECT pvt_extract_field_names(v->'query'); END IF; IF v ? 'fields' AND jsonb_typeof(v->'fields') = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v->'fields') LOOP RETURN QUERY SELECT pvt_extract_field_names(elem); END LOOP; END IF; CONTINUE; END IF; -- $cast(["", expr]) -- type literal must not be walked. IF lower(k) = '$cast' AND jsonb_typeof(v) = 'array' AND jsonb_array_length(v) >= 2 THEN RETURN QUERY SELECT pvt_extract_field_names(v->1); CONTINUE; END IF; -- $dateAdd/$dateSub/$dateDiff/$dateTrunc: first element is a unit string literal. IF lower(k) IN ('$dateadd','$datesub','$datediff','$datetrunc') AND jsonb_typeof(v) = 'array' AND jsonb_array_length(v) >= 1 THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) WITH ORDINALITY AS t(value, ord) WHERE ord >= 2 LOOP RETURN QUERY SELECT pvt_extract_field_names(elem); END LOOP; CONTINUE; END IF; -- Logical operator: recurse into children. IF jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP RETURN QUERY SELECT pvt_extract_field_names(elem); END LOOP; ELSIF jsonb_typeof(v) = 'object' THEN RETURN QUERY SELECT pvt_extract_field_names(v); END IF; ELSE -- Field reference. RETURN NEXT k; END IF; END LOOP; END; $BODY$; COMMENT ON FUNCTION pvt_extract_field_names(jsonb) IS 'Recursively extracts every field-name reference from a filter JSON. Logical operators ($and/$or/$not/...) are descended into but never returned.'; -- ---------- pvt_extract_field_pairs ----------------------------------- -- Walk a filter JSON recursively and emit (path, op_value) pairs. -- `op_value` is the underlying string operand when path ends with -- `.ContainsKey` (Pro-style dictionary normalization); NULL otherwise. CREATE OR REPLACE FUNCTION pvt_extract_field_pairs(p_filter jsonb) RETURNS TABLE (path text, op_value text) LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; elem jsonb; BEGIN IF p_filter IS NULL OR jsonb_typeof(p_filter) <> 'object' THEN RETURN; END IF; -- Expression node shortcuts: only `$field` yields a path; `$const` -- carries a literal and contributes no field references. IF p_filter ? '$field' THEN RETURN QUERY SELECT (p_filter->>'$field')::text, NULL::text; RETURN; END IF; IF p_filter ? '$const' THEN RETURN; END IF; FOR k, v IN SELECT key, value FROM jsonb_each(p_filter) LOOP IF left(k, 1) = '$' THEN -- $case has shape: [ {when:, then:}, ..., {else:}? ]. -- Descend into branch values only, never treat "when"/"then"/"else" as paths. IF lower(k) = '$case' AND jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP IF jsonb_typeof(elem) = 'object' THEN IF elem ? 'when' THEN RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(elem->'when') pp; END IF; IF elem ? 'then' THEN RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(elem->'then') pp; END IF; IF elem ? 'else' THEN RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(elem->'else') pp; END IF; END IF; END LOOP; CONTINUE; END IF; -- $fts object form: descend only into `query` and `fields` array. IF lower(k) = '$fts' AND jsonb_typeof(v) = 'object' THEN IF v ? 'query' THEN RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(v->'query') pp; END IF; IF v ? 'fields' AND jsonb_typeof(v->'fields') = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v->'fields') LOOP RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(elem) pp; END LOOP; END IF; CONTINUE; END IF; -- $cast(["", expr]): skip the type literal. IF lower(k) = '$cast' AND jsonb_typeof(v) = 'array' AND jsonb_array_length(v) >= 2 THEN RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(v->1) pp; CONTINUE; END IF; -- $dateAdd/$dateSub/$dateDiff/$dateTrunc: skip the unit literal. IF lower(k) IN ('$dateadd','$datesub','$datediff','$datetrunc') AND jsonb_typeof(v) = 'array' AND jsonb_array_length(v) >= 1 THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) WITH ORDINALITY AS t(value, ord) WHERE ord >= 2 LOOP RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(elem) pp; END LOOP; CONTINUE; END IF; IF jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(elem) pp; END LOOP; ELSIF jsonb_typeof(v) = 'object' THEN RETURN QUERY SELECT pp.path, pp.op_value FROM pvt_extract_field_pairs(v) pp; END IF; ELSE IF right(k, length('.ContainsKey')) = '.ContainsKey' THEN RETURN QUERY SELECT k, pvt_peek_contains_key_value(v); ELSE RETURN QUERY SELECT k, NULL::text; END IF; END IF; END LOOP; END; $BODY$; COMMENT ON FUNCTION pvt_extract_field_pairs(jsonb) IS 'Recursive walker: yields (path, op_value) pairs. op_value carries the operand text for `*.ContainsKey` predicates so the caller can normalize them to `[]`.'; -- ---------- pvt_collect_fields ---------------------------------------- -- Resolve metadata for every field mentioned in filter/order. When -- p_include_all is true, ALL scheme fields are collected (used by the -- full-result entry point that may need to project arbitrary fields). CREATE OR REPLACE FUNCTION pvt_collect_fields( p_scheme_id bigint, p_filter jsonb, p_order jsonb, p_include_all boolean DEFAULT false ) RETURNS jsonb LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_pair RECORD; v_normalized text; v_meta jsonb; v_order_path text; v_all_name text; v_result jsonb := '{}'::jsonb; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_collect_fields: p_scheme_id is required'; END IF; -- ---------- p_include_all: project every top-level field ---------- IF p_include_all THEN FOR v_all_name IN SELECT DISTINCT _name FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id AND _parent_structure_id IS NULL LOOP v_meta := pvt_resolve_field_path(p_scheme_id, v_all_name); v_result := v_result || jsonb_build_object(v_all_name, v_meta); END LOOP; RETURN v_result; END IF; -- ---------- Collect from filter (ContainsKey-aware) --------------- FOR v_pair IN SELECT DISTINCT path, op_value FROM pvt_extract_field_pairs(p_filter) WHERE path IS NOT NULL LOOP -- Detect .$length / .$count suffix: targets count of the base -- array. We register BOTH the base field (so the CTE pivots it) -- AND a modifier entry that the condition builder rewrites to -- COALESCE(array_length(, 1), 0). DECLARE v_mod_kind text := NULL; v_base text := NULL; v_base_meta jsonb; BEGIN IF right(v_pair.path, length('.$length')) = '.$length' THEN v_mod_kind := 'length'; v_base := left(v_pair.path, length(v_pair.path) - length('.$length')); ELSIF right(v_pair.path, length('.$count')) = '.$count' THEN v_mod_kind := 'count'; v_base := left(v_pair.path, length(v_pair.path) - length('.$count')); END IF; IF v_mod_kind IS NOT NULL THEN IF NOT (v_result ? v_base) THEN v_base_meta := pvt_resolve_field_path(p_scheme_id, v_base); v_result := v_result || jsonb_build_object(v_base, v_base_meta); ELSE v_base_meta := v_result -> v_base; END IF; IF NOT (v_result ? v_pair.path) THEN v_result := v_result || jsonb_build_object( v_pair.path, v_base_meta || jsonb_build_object( 'length_modifier', true, 'modifier_kind', v_mod_kind, 'base_name', v_base)); END IF; CONTINUE; END IF; END; v_normalized := pvt_normalize_field_name(v_pair.path, v_pair.op_value); IF v_result ? v_normalized THEN CONTINUE; END IF; v_meta := pvt_resolve_field_path(p_scheme_id, v_normalized); IF v_normalized <> v_pair.path THEN -- Tag ContainsKey rewrites: WHERE builder emits IS NOT NULL. v_meta := v_meta || jsonb_build_object('was_contains_key', true); END IF; v_result := v_result || jsonb_build_object(v_normalized, v_meta); END LOOP; -- ---------- Collect from order paths ----------------------------- -- Each order entry may carry either: -- * plain path: { "field": "X" } or legacy { "field_path": "X" } -- * expression node: { "$expr": , "dir": "..." } -- For expressions we walk every `$field` inside via -- pvt_expr_field_names (defined in 17_pvt_expr.sql) so its metadata -- gets resolved and the field is pivoted into the CTE just like -- WHERE-referenced fields. IF p_order IS NOT NULL THEN FOR v_order_path IN SELECT path FROM ( SELECT COALESCE(e->>'field', e->>'field_path') AS path FROM jsonb_array_elements(p_order) AS e WHERE e ? 'field' OR e ? 'field_path' UNION ALL SELECT pvt_expr_field_names(e->'$expr') AS path FROM jsonb_array_elements(p_order) AS e WHERE e ? '$expr' ) s WHERE s.path IS NOT NULL LOOP IF v_order_path IS NULL OR v_result ? v_order_path THEN CONTINUE; END IF; v_meta := pvt_resolve_field_path(p_scheme_id, v_order_path); v_result := v_result || jsonb_build_object(v_order_path, v_meta); END LOOP; END IF; RETURN v_result; END; $BODY$; COMMENT ON FUNCTION pvt_collect_fields(bigint, jsonb, jsonb, boolean) IS 'Walks filter/order JSON, normalizes Dict.ContainsKey paths, resolves each via pvt_resolve_field_path, and returns a jsonb keyed by the (possibly rewritten) field name. ContainsKey-rewritten entries carry was_contains_key=true so the WHERE builder collapses the predicate to IS NOT NULL.'; -- ---------- pvt_has_null_check ---------------------------------------- -- True iff the filter contains an explicit null-aware predicate. Used -- by the CTE builder to decide LEFT JOIN (need NULL surface) vs INNER -- JOIN (faster, suffices when all predicates require a present value). CREATE OR REPLACE FUNCTION pvt_has_null_check(p_filter jsonb) RETURNS boolean LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; sk text; sv jsonb; elem jsonb; BEGIN IF p_filter IS NULL OR jsonb_typeof(p_filter) <> 'object' THEN RETURN false; END IF; FOR k, v IN SELECT key, value FROM jsonb_each(p_filter) LOOP IF left(k, 1) = '$' THEN IF k IN ('$null', '$exists', '$isNull', '$notNull') THEN RETURN true; END IF; IF jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP IF pvt_has_null_check(elem) THEN RETURN true; END IF; END LOOP; ELSIF jsonb_typeof(v) = 'object' THEN IF pvt_has_null_check(v) THEN RETURN true; END IF; END IF; ELSE -- Field leaf: inspect its operator object. IF jsonb_typeof(v) = 'object' THEN FOR sk, sv IN SELECT key, value FROM jsonb_each(v) LOOP IF sk IN ('$null', '$exists', '$isNull', '$notNull') THEN RETURN true; END IF; IF sk IN ('$eq', '$ne') AND jsonb_typeof(sv) = 'null' THEN RETURN true; END IF; END LOOP; ELSIF jsonb_typeof(v) = 'null' THEN RETURN true; END IF; END IF; END LOOP; RETURN false; END; $BODY$; COMMENT ON FUNCTION pvt_has_null_check(jsonb) IS 'Returns true if the filter contains any explicit null-aware predicate ($null/$exists/$isNull/$notNull or $eq/$ne with null). The CTE builder uses this to pick LEFT vs INNER JOIN on _values.'; -- ---------- pvt_has_absence_check ------------------------------------- -- Strict subset of pvt_has_null_check: returns true only for predicates -- that REQUIRE detecting absent _values rows (i.e. an object without -- any value for the field must still appear in the outer result set). -- These predicates demand the legacy wide+LEFT JOIN shape: -- -- * `$null` / `$isNull` : field must be NULL. -- * `{$eq: null}` : same as $null. -- * `$exists` (any value, incl. false) : tests presence; safest -- kept in the "absence" -- bucket. -- -- Predicates that can be satisfied by an INNER JOIN over _values are -- intentionally NOT flagged here: -- -- * `$notNull` : "must be present" -- INNER drops absent rows -- automatically (the desired outcome). -- * `{$ne: null}` : equivalent to "must be present". -- -- The narrow Pro-shape pivot CTE inherently CANNOT represent absent -- objects (its `FROM _values v` GROUP BY v._id_object only yields -- object ids that have at least one matching row); hence the narrow -- branch is gated on `NOT pvt_has_absence_check(...)` rather than the -- broader pvt_has_null_check. CREATE OR REPLACE FUNCTION pvt_has_absence_check(p_filter jsonb) RETURNS boolean LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; sk text; sv jsonb; elem jsonb; BEGIN IF p_filter IS NULL OR jsonb_typeof(p_filter) <> 'object' THEN RETURN false; END IF; FOR k, v IN SELECT key, value FROM jsonb_each(p_filter) LOOP IF left(k, 1) = '$' THEN IF k IN ('$null', '$isNull', '$exists') THEN RETURN true; END IF; IF jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP IF pvt_has_absence_check(elem) THEN RETURN true; END IF; END LOOP; ELSIF jsonb_typeof(v) = 'object' THEN IF pvt_has_absence_check(v) THEN RETURN true; END IF; END IF; ELSE IF jsonb_typeof(v) = 'object' THEN FOR sk, sv IN SELECT key, value FROM jsonb_each(v) LOOP IF sk IN ('$null', '$isNull', '$exists') THEN RETURN true; END IF; IF sk = '$eq' AND jsonb_typeof(sv) = 'null' THEN RETURN true; END IF; END LOOP; ELSIF jsonb_typeof(v) = 'null' THEN RETURN true; END IF; END IF; END LOOP; RETURN false; END; $BODY$; COMMENT ON FUNCTION pvt_has_absence_check(jsonb) IS 'Strict subset of pvt_has_null_check: true only for predicates that require detecting absent _values rows ($null/$isNull/$exists/{$eq:null}). $notNull and {$ne:null} are NOT flagged because INNER JOIN already drops absent rows. Used to gate the narrow Pro-shape pivot, which cannot represent missing objects.'; -- ===================================================================== -- pvt_resolve_field_path: port of redb.Core.Pro.Schema.SchemeFieldResolver -- --------------------------------------------------------------------- -- Resolves a logical field path (e.g. "Name", "Dict[key]", "Status.Value", -- "Auction.Costs", "Roles[].Value") to a rich FieldInfo jsonb consumed -- by pvt_build_column_expr / pvt_build_cte_sql / pvt_build_field_condition. -- -- Returned shape: -- { "kind":"base", "column":"_id_parent", "name":"", -- "is_array":false, "list_item_prop":null, "dict_key":null, -- "parent_sid":null, "sid":null, "db_type":null, "db_column":null } -- OR -- { "kind":"field", "sid":, "db_type":"String|...", -- "db_column":"_String|_Long|...", "name":"", -- "is_array":bool, "list_item_prop":null|"Id"|"Value"|"Alias", -- "dict_key":null|"", "parent_sid":null| } -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_resolve_field_path( p_scheme_id bigint, p_path text ) RETURNS jsonb LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_dict_match text[]; v_root_name text; v_dict_key text; v_rest text; v_child_name text; v_parts text[]; v_last text; v_root_li text; v_base_col text; v_db_col text; v_sid bigint; v_db_type text; v_is_array boolean; v_parent_sid bigint := NULL; v_list_item_prop text := NULL; v_cur_sid bigint; v_base_name text; v_force_array boolean := false; i int; BEGIN IF p_scheme_id IS NULL OR p_path IS NULL OR p_path = '' THEN RAISE EXCEPTION 'pvt_resolve_field_path: scheme_id/path are required (got %, %)', p_scheme_id, p_path; END IF; -- 0. Base field? v_base_col := pvt_normalize_base_field_name(p_path); IF v_base_col IS NOT NULL THEN RETURN jsonb_build_object( 'kind','base','column',v_base_col,'name',p_path, 'is_array',false,'list_item_prop',NULL,'dict_key',NULL, 'parent_sid',NULL,'sid',NULL,'db_type',NULL,'db_column',NULL); END IF; -- 1. Dictionary path: Name[key] or Name[key].Child v_dict_match := regexp_match(p_path, '^([A-Za-z_][A-Za-z0-9_]*)\[([^\]]+)\](.*)$'); IF v_dict_match IS NOT NULL THEN v_root_name := v_dict_match[1]; v_dict_key := v_dict_match[2]; v_rest := v_dict_match[3]; SELECT _structure_id, db_type INTO v_sid, v_db_type FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id AND _name = v_root_name AND _parent_structure_id IS NULL LIMIT 1; IF NOT FOUND THEN RAISE EXCEPTION 'pvt_resolve_field_path: dict root field "%" not found in scheme %', v_root_name, p_scheme_id; END IF; IF v_rest IS NOT NULL AND v_rest LIKE '.%' THEN v_parent_sid := v_sid; v_child_name := substring(v_rest from 2); SELECT _structure_id, db_type, (_collection_type IS NOT NULL) INTO v_sid, v_db_type, v_is_array FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id AND _name = v_child_name AND _parent_structure_id = v_parent_sid LIMIT 1; IF NOT FOUND THEN RAISE EXCEPTION 'pvt_resolve_field_path: nested-dict child "%" not found under "%"', v_child_name, v_root_name; END IF; ELSE v_is_array := false; END IF; v_db_col := pvt_db_type_to_value_column(v_db_type); RETURN jsonb_build_object( 'kind','field','sid',v_sid,'db_type',v_db_type,'db_column',v_db_col, 'name',p_path,'is_array',v_is_array, 'list_item_prop',NULL,'dict_key',v_dict_key,'parent_sid',v_parent_sid); END IF; -- 2. Dotted paths. IF position('.' in p_path) > 0 THEN v_parts := string_to_array(p_path, '.'); v_last := v_parts[array_length(v_parts,1)]; -- 2a. Roles[].Value / .Alias / .Id (ListItem array accessors) IF array_length(v_parts,1) = 2 AND v_last IN ('Id','Value','Alias') AND v_parts[1] LIKE '%[]' THEN v_root_li := left(v_parts[1], length(v_parts[1]) - 2); SELECT _structure_id, db_type, (_collection_type IS NOT NULL) INTO v_sid, v_db_type, v_is_array FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id AND _name = v_root_li AND _parent_structure_id IS NULL LIMIT 1; IF FOUND AND v_db_type = 'ListItem' AND v_is_array THEN RETURN jsonb_build_object( 'kind','field','sid',v_sid,'db_type','ListItem','db_column','_ListItem', 'name',p_path,'is_array',true, 'list_item_prop',v_last,'dict_key',NULL,'parent_sid',NULL); END IF; END IF; -- 2b. Status.Value / .Alias / .Id (ListItem scalar accessors) IF array_length(v_parts,1) = 2 AND v_last IN ('Id','Value','Alias') THEN SELECT _structure_id, db_type, (_collection_type IS NOT NULL) INTO v_sid, v_db_type, v_is_array FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id AND _name = v_parts[1] AND _parent_structure_id IS NULL LIMIT 1; IF FOUND AND v_db_type = 'ListItem' THEN RETURN jsonb_build_object( 'kind','field','sid',v_sid,'db_type','ListItem','db_column','_ListItem', 'name',p_path,'is_array',v_is_array, 'list_item_prop',v_last,'dict_key',NULL,'parent_sid',NULL); END IF; END IF; -- 2c. Generic nested: walk parent chain. SELECT _structure_id INTO v_cur_sid FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id AND _name = v_parts[1] AND _parent_structure_id IS NULL LIMIT 1; IF NOT FOUND THEN RAISE EXCEPTION 'pvt_resolve_field_path: root "%" of nested path "%" not found in scheme %', v_parts[1], p_path, p_scheme_id; END IF; FOR i IN 2..array_length(v_parts,1) LOOP SELECT _structure_id INTO v_cur_sid FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id AND _name = v_parts[i] AND _parent_structure_id = v_cur_sid LIMIT 1; IF NOT FOUND THEN RAISE EXCEPTION 'pvt_resolve_field_path: nested segment "%" of path "%" not found', v_parts[i], p_path; END IF; END LOOP; SELECT db_type, (_collection_type IS NOT NULL) INTO v_db_type, v_is_array FROM _scheme_metadata_cache WHERE _structure_id = v_cur_sid LIMIT 1; v_db_col := pvt_db_type_to_value_column(v_db_type); RETURN jsonb_build_object( 'kind','field','sid',v_cur_sid,'db_type',v_db_type,'db_column',v_db_col, 'name',p_path,'is_array',v_is_array, 'list_item_prop',NULL,'dict_key',NULL,'parent_sid',NULL); END IF; -- 3. Bare root field (possibly `Foo[]` for arrays). v_base_name := p_path; IF p_path LIKE '%[]' THEN v_base_name := left(p_path, length(p_path) - 2); v_force_array := true; END IF; SELECT _structure_id, db_type, (_collection_type IS NOT NULL) INTO v_sid, v_db_type, v_is_array FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id AND _name = v_base_name AND _parent_structure_id IS NULL LIMIT 1; IF NOT FOUND THEN RAISE EXCEPTION 'pvt_resolve_field_path: field "%" not found in scheme %', p_path, p_scheme_id; END IF; IF v_force_array THEN v_is_array := true; END IF; IF v_db_type = 'ListItem' THEN v_db_col := '_ListItem'; v_list_item_prop := 'Id'; -- bare `Status` defaults to `.Id` (bigint FK) ELSE v_db_col := pvt_db_type_to_value_column(v_db_type); END IF; RETURN jsonb_build_object( 'kind','field','sid',v_sid,'db_type',v_db_type,'db_column',v_db_col, 'name',p_path,'is_array',v_is_array, 'list_item_prop',v_list_item_prop,'dict_key',NULL,'parent_sid',NULL); END; $BODY$; COMMENT ON FUNCTION pvt_resolve_field_path(bigint, text) IS 'Resolves a logical field path to a rich FieldInfo jsonb (kind/sid/db_type/db_column/is_array/list_item_prop/dict_key/parent_sid). Mirrors redb.Core.Pro.Schema.SchemeFieldResolver. Throws when the path cannot be matched against the scheme metadata cache.'; Path: redb/redb.SQLite/sql/v2-pvt/11_pvt_column_expr.sql 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/v2-pvt/11_pvt_column_expr.sql ---- -- ===================================================================== -- 11_pvt_column_expr.sql -- --------------------------------------------------------------------- -- Build a single column expression for the PVT CTE: each scheme field -- becomes a `MAX(v._) FILTER (WHERE v._id_structure = ) -- AS ""` aggregate; base fields are projected from `o.*` -- directly without aggregation. -- -- Functions: -- pvt_db_type_to_value_column(p_db_type text) RETURNS text -- pvt_build_column_expr(p_field_name text, p_field_meta jsonb) RETURNS text -- ===================================================================== -- ---------- pvt_db_type_to_value_column ------------------------------- -- Maps a logical db_type (as stored in _scheme_metadata_cache.db_type) -- to the actual physical column name on the _values table. Returns -- NULL for unsupported types so the caller can raise a clear error. CREATE OR REPLACE FUNCTION pvt_db_type_to_value_column(p_db_type text) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $BODY$ BEGIN RETURN CASE p_db_type WHEN 'String' THEN '_String' WHEN 'Long' THEN '_Long' WHEN 'Double' THEN '_Double' WHEN 'Numeric' THEN '_Numeric' WHEN 'Boolean' THEN '_Boolean' WHEN 'Guid' THEN '_Guid' WHEN 'DateTimeOffset' THEN '_DateTimeOffset' WHEN 'ByteArray' THEN '_ByteArray' WHEN 'ListItem' THEN '_ListItem' WHEN 'Object' THEN '_Object' -- Legacy / type_semantic aliases. WHEN 'TimeSpan' THEN '_String' -- TimeSpan stored as text WHEN 'DateTime' THEN '_DateTimeOffset' ELSE NULL END; END; $BODY$; COMMENT ON FUNCTION pvt_db_type_to_value_column(text) IS 'Maps a logical db_type to the physical typed column name on _values. Returns NULL if the type is unknown.'; -- ---------- pvt_build_column_expr ------------------------------------- -- Builds a single SELECT-list expression for the PVT pivot CTE. -- Dispatches on the rich FieldInfo emitted by pvt_resolve_field_path -- (kind/sid/db_type/db_column/is_array/list_item_prop/dict_key/parent_sid). -- -- Adopts the Pro pivot idiom `(array_agg(...) FILTER (...))[1]` for -- scalars (works for booleans/uuids/non-orderable types) and the -- "_array_index IS NULL" / "IS NOT NULL" / "= ''" filter -- conventions to distinguish scalar / array / dict element values. -- -- Nested-dict fields (parent_sid AND dict_key both set) are NOT -- emitted as pivot columns; they live in a side CTE generated by -- pvt_build_cte_sql and reach the outer query via a LEFT JOIN alias. CREATE OR REPLACE FUNCTION pvt_build_column_expr( p_field_name text, p_field_meta jsonb, p_array_index_in_outer boolean DEFAULT false -- when true, omit `AND v._array_index IS NULL` from scalar FILTER; caller hoists it to an outer WHERE for inline-pivot shape (Pro-parity GROUP BY). ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_kind text; v_sid bigint; v_db_type text; v_col text; v_alias text; v_li_prop text; v_dict_key text; v_parent_sid bigint; v_is_array boolean; BEGIN IF p_field_meta IS NULL THEN RAISE EXCEPTION 'pvt_build_column_expr: p_field_meta is NULL for field "%"', p_field_name; END IF; v_alias := quote_ident(p_field_name); v_kind := p_field_meta->>'kind'; v_li_prop := p_field_meta->>'list_item_prop'; v_dict_key := p_field_meta->>'dict_key'; v_parent_sid := NULLIF(p_field_meta->>'parent_sid', '')::bigint; v_is_array := COALESCE((p_field_meta->>'is_array')::boolean, false); -- ---- Base field: straight projection from _objects. ------------- IF v_kind = 'base' THEN RETURN format('o.%I AS %s', p_field_meta->>'column', v_alias); END IF; v_sid := (p_field_meta->>'sid')::bigint; v_db_type := p_field_meta->>'db_type'; -- ---- Nested-dict: handled by a side CTE; must not reach here. --- IF v_parent_sid IS NOT NULL AND v_dict_key IS NOT NULL THEN RAISE EXCEPTION 'pvt_build_column_expr: nested-dict field "%" must be emitted via side CTE (caller bug)', p_field_name; END IF; -- ---- ListItem.Value / .Alias -------------------------------- -- Scalar projection emits the raw _ListItem id (parity with Pro); -- consumers wrap it in a _list_items lookup as needed (WHERE- -- builder, ORDER BY-builder). GROUP BY / SELECT pass the id -- through untouched. Array variants still dereference so that -- $arrayContains 'admin' / && {...} keep string semantics. IF v_li_prop = 'Value' THEN -- Pivot source provides `LEFT JOIN _list_items li ON -- li._id = v._ListItem` (emitted by pvt_build_cte_sql when any -- field is Value/Alias). Scalar takes [1], array keeps array_agg. IF v_is_array THEN RETURN format( 'array_agg(li._value) FILTER (WHERE v._id_structure = %s AND v._array_index IS NOT NULL) AS %s', v_sid::text, v_alias); END IF; IF p_array_index_in_outer THEN RETURN format( '(array_agg(li._value) FILTER (WHERE v._id_structure = %s))[1] AS %s', v_sid::text, v_alias); END IF; RETURN format( '(array_agg(li._value) FILTER (WHERE v._id_structure = %s AND v._array_index IS NULL))[1] AS %s', v_sid::text, v_alias); END IF; IF v_li_prop = 'Alias' THEN IF v_is_array THEN RETURN format( 'array_agg(li._alias) FILTER (WHERE v._id_structure = %s AND v._array_index IS NOT NULL) AS %s', v_sid::text, v_alias); END IF; IF p_array_index_in_outer THEN RETURN format( '(array_agg(li._alias) FILTER (WHERE v._id_structure = %s))[1] AS %s', v_sid::text, v_alias); END IF; RETURN format( '(array_agg(li._alias) FILTER (WHERE v._id_structure = %s AND v._array_index IS NULL))[1] AS %s', v_sid::text, v_alias); END IF; -- ---- Resolve typed column --------------------------------------- v_col := pvt_db_type_to_value_column(v_db_type); IF v_col IS NULL THEN RAISE EXCEPTION 'pvt_build_column_expr: unsupported db_type "%" for field "%"', v_db_type, p_field_name; END IF; -- ListItem.Id: project the foreign key column itself (bigint). IF v_li_prop = 'Id' THEN v_col := '_ListItem'; END IF; -- ---- Simple dictionary: PhoneBook[home] --> _array_index='' -- NOTE: value column references use %s (bare) instead of %I (quoted). -- Free PG DDL declares _String/_Long/... unquoted, so the actual -- column names are case-folded to lowercase; quoting them via %I -- (which preserves mixed case) would break the lookup. IF v_dict_key IS NOT NULL AND v_parent_sid IS NULL THEN RETURN format( '(array_agg(v.%s) FILTER (WHERE v._id_structure = %s AND v._array_index = %L))[1] AS %s', v_col, v_sid::text, v_dict_key, v_alias); END IF; -- ---- Array pivot ------------------------------------------------ IF v_is_array THEN RETURN format( 'array_agg(v.%s) FILTER (WHERE v._id_structure = %s AND v._array_index IS NOT NULL) AS %s', v_col, v_sid::text, v_alias); END IF; -- ---- Scalar pivot (Pro idiom) ----------------------------------- IF p_array_index_in_outer THEN RETURN format( '(array_agg(v.%s) FILTER (WHERE v._id_structure = %s))[1] AS %s', v_col, v_sid::text, v_alias); END IF; RETURN format( '(array_agg(v.%s) FILTER (WHERE v._id_structure = %s AND v._array_index IS NULL))[1] AS %s', v_col, v_sid::text, v_alias); END; $BODY$; COMMENT ON FUNCTION pvt_build_column_expr(text, jsonb, boolean) IS 'Builds a single SELECT-list expression for the PVT pivot CTE. Dispatches on the rich FieldInfo jsonb (kind/sid/db_type/is_array/list_item_prop/dict_key/parent_sid). Supports base / scalar / array / simple-dict / ListItem.Id|Value|Alias (scalar+array). Nested-dict fields are deferred to a side CTE emitted by pvt_build_cte_sql. p_array_index_in_outer=true drops `AND v._array_index IS NULL` from scalar/ListItem.Id|Value|Alias FILTER clauses; caller must hoist it to an outer WHERE (Pro-parity inline GROUP BY shape).';; Path: redb/redb.SQLite/sql/v2-pvt/12_pvt_cte_builder.sql 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/v2-pvt/12_pvt_cte_builder.sql ---- -- ===================================================================== -- 12_pvt_cte_builder.sql -- --------------------------------------------------------------------- -- Build the `WITH _pvt_cte AS (...)` clause that pivots _values into -- one column per requested scheme field. All downstream predicates -- (WHERE / ORDER BY) reference columns of this CTE. -- -- Output shape (legacy WIDE, used for null-checks and tree mode): -- WITH _pvt_cte AS ( -- SELECT -- o._id, o._id_parent, ... , -- -- FROM _objects o -- JOIN _values v ON v._id_object = o._id -- WHERE o._id_scheme = -- [AND tree-restriction] -- [AND ] -- GROUP BY o._id, o._id_parent, ... (all _objects columns above) -- ) -- -- Output shape (NARROW Pro-parity, used for flat + non-null queries): -- WITH _pvt_cte AS ( -- SELECT -- v._id_object, -- -- FROM _values v -- WHERE v._id_structure = ANY(ARRAY[, , ...]::bigint[]) -- AND v._id_object IN ( -- SELECT _id FROM _objects -- WHERE _id_scheme = -- [AND ] -- [AND o._id IN (SELECT _id FROM _pvt_tree)] -- ) -- GROUP BY v._id_object -- ) -- The narrow shape skips the wide GROUP BY (21 cols -> 1 col), -- narrows the _values scan via the `_id_structure = ANY` index hint, -- and lets the outer SELECT JOIN _objects so the planner can still -- short-circuit by system-column indexes. Tree pushdown (Pro -- CHANGELOG 2.0.1 parity): in tree mode the recursive `_pvt_tree` -- CTE is emitted alongside `_pvt_cte` and its restriction is folded -- INTO the narrow IN-subquery, so the recursive walk + base -- pushdown both filter the object set BEFORE _values is touched. -- -- Legacy WIDE always projects every _objects column the C# layer -- needs to hydrate base fields. Narrow shape projects only -- v._id_object; the outer query MUST `JOIN _objects o ON o._id = -- _pvt_cte._id_object` to access base columns. -- ===================================================================== -- Signature evolved in v0.6.0 (added p_include_seed + p_polymorphic and five -- explicit tree modes). CREATE OR REPLACE cannot change argument lists, so -- drop every legacy form here. DROP FUNCTION IF EXISTS pvt_build_cte_sql(bigint, jsonb, text, bigint[], integer, boolean); DROP FUNCTION IF EXISTS pvt_build_cte_sql(bigint, jsonb, text, bigint[], integer, boolean, text); DROP FUNCTION IF EXISTS pvt_build_cte_sql(bigint, jsonb, text, bigint[], integer, boolean, text, boolean); DROP FUNCTION IF EXISTS pvt_build_cte_sql(bigint, jsonb, text, bigint[], integer, boolean, text, boolean, boolean, boolean); CREATE OR REPLACE FUNCTION pvt_build_cte_sql( p_scheme_id bigint, p_fields jsonb, p_source_mode text DEFAULT 'flat', p_tree_ids bigint[] DEFAULT NULL, p_max_depth integer DEFAULT NULL, p_force_outer boolean DEFAULT true, p_extra_where text DEFAULT NULL, -- Pro-style base-field pushdown: extra predicate AND-ed into the inner WHERE. p_narrow boolean DEFAULT false, -- emit Pro-shape narrow pivot (FROM _values + IN (...) + GROUP BY 1). p_include_seed boolean DEFAULT true, -- include the seed object(s) themselves in tree_descendants / tree (false matches old free `WHERE depth>0`). p_polymorphic boolean DEFAULT true, -- when false, AND `_id_scheme = p_scheme_id` into the recursive walk (Pro keeps walk polymorphic). p_residual_where text DEFAULT NULL -- Pro-parity WHERE pushdown: residual predicate (refs pivot cols only) wrapped INSIDE _pvt_cte so it filters BEFORE the outer JOIN _objects. ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_pivot_cols text := ''; v_join_kind text; v_field_name text; v_field_meta jsonb; v_first boolean := true; v_base_cols constant text := 'o._id, o._id_parent, o._id_scheme, o._id_owner, o._id_who_change, ' || 'o._name, o._date_create, o._date_modify, o._date_begin, o._date_complete, ' || 'o._key, o._note, o._hash, ' || 'o._value_long, o._value_string, o._value_guid, o._value_bool, ' || 'o._value_double, o._value_numeric, o._value_datetime, o._value_bytes'; v_where text := format('o._id_scheme = %s', p_scheme_id::text); v_cte_parts text[] := ARRAY[]::text[]; v_has_recursive boolean := false; v_nested_groups jsonb := '{}'::jsonb; v_group_key text; v_group_entry jsonb; v_group_fields jsonb; v_inner_field jsonb; v_inner_meta jsonb; v_inner_col text; v_inner_sid text; v_inner_alias text; v_inner_is_array boolean; v_inner_sub text; v_inner_subs text; v_group_idx integer := 0; v_group_cte_name text; v_nested_cols_sql text := ''; v_nested_joins text := ''; v_inner_pivot text; v_pvt_body text; v_sids bigint[] := ARRAY[]::bigint[]; v_sid_text text; v_objects_subq text; v_tree_filter text := ''; -- Nested-only optimization (Pro-parity, see E062 in CHANGELOG): -- when v_pivot_cols is empty AND there's exactly one nested-dict -- group AND no force_outer AND narrow flag set, skip the heavy -- `pi` wrapper (SELECT 21 base cols FROM _objects ... GROUP BY 21) -- and emit `_pvt_cte AS (SELECT ndN._id_object, ndN. FROM -- nested_dict_N ndN)` directly. Object-set restriction (scheme + -- base pushdown + tree filter) is folded into the nested CTE's -- inner WHERE via v_nested_obj_filter. v_is_nested_only boolean := false; v_nested_obj_filter text := ''; v_flat_cols_sql text := ''; v_pivot_cols_empty boolean; -- Quoted aliases of every column projected by the pivot body -- (scalar + nested-dict). Used to emit Pro-shape `SELECT pvt._id_object, -- pvt."col1", pvt."col2" FROM () pvt WHERE ` when -- pvt_build_query_sql pushes a residual predicate inside _pvt_cte. v_pivot_aliases text[] := ARRAY[]::text[]; -- True when any pivot field is ListItem.Value/.Alias (scalar or -- array). Triggers `LEFT JOIN _list_items li ON li._id = v._ListItem` -- on the pivot source so column exprs can reference `li._value` -- / `li._alias` instead of correlated subselects (Pro parity). v_has_listitem_join boolean := false; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_build_cte_sql: p_scheme_id is required'; END IF; IF p_source_mode NOT IN ('flat', 'tree', 'tree_descendants', 'tree_children', 'tree_roots', 'tree_leaves', 'tree_ancestors') THEN RAISE EXCEPTION 'pvt_build_cte_sql: invalid p_source_mode "%", expected flat|tree|tree_descendants|tree_children|tree_roots|tree_leaves|tree_ancestors', p_source_mode; END IF; -- ------- Partition requested fields: base / nested-dict / pivot -- IF p_fields IS NOT NULL AND p_fields <> '{}'::jsonb THEN FOR v_field_name, v_field_meta IN SELECT key, value FROM jsonb_each(p_fields) LOOP -- Base fields are already in v_base_cols; skip to avoid dupes. IF v_field_meta->>'kind' = 'base' THEN CONTINUE; END IF; -- Modifier-only entries (.$length / .$count) project no -- column of their own; their base entry was inserted by -- pvt_collect_fields and will be emitted normally below. IF COALESCE((v_field_meta->>'length_modifier')::boolean, false) THEN CONTINUE; END IF; -- Collect structure id for the narrow Pro-shape -- `_id_structure = ANY(...)` filter. Skip nested-dict child -- fields (parent_sid set: they project from a side CTE -- scoped to the parent dict row, not the main _values scan). -- Simple-dict fields (dict_key set, parent_sid NULL) keep -- their sid here because pvt_build_column_expr's FILTER -- (_id_structure = X AND _array_index = 'key') reads -- straight from the main scan. IF (v_field_meta->>'sid') IS NOT NULL AND (v_field_meta->>'parent_sid') IS NULL THEN v_sids := v_sids || ((v_field_meta->>'sid')::bigint); END IF; -- Nested-dict: accumulate per (parent_sid, dict_key) group. IF (v_field_meta->>'dict_key') IS NOT NULL AND (v_field_meta->>'parent_sid') IS NOT NULL THEN v_group_key := (v_field_meta->>'parent_sid') || '|' || (v_field_meta->>'dict_key'); v_group_entry := COALESCE( v_nested_groups -> v_group_key, jsonb_build_object( 'parent_sid', v_field_meta->>'parent_sid', 'dict_key', v_field_meta->>'dict_key', 'fields', '[]'::jsonb)); v_group_entry := jsonb_set( v_group_entry, '{fields}', (v_group_entry->'fields') || jsonb_build_array( jsonb_build_object( 'name', v_field_name, 'meta', v_field_meta))); v_nested_groups := jsonb_set( v_nested_groups, ARRAY[v_group_key], v_group_entry, true); CONTINUE; END IF; -- Regular pivot column. IF NOT v_first THEN v_pivot_cols := v_pivot_cols || ',' || E'\n '; ELSE v_pivot_cols := E',\n '; v_first := false; END IF; v_pivot_cols := v_pivot_cols || pvt_build_column_expr(v_field_name, v_field_meta); v_pivot_aliases := v_pivot_aliases || quote_ident(v_field_name); IF (v_field_meta->>'list_item_prop') IN ('Value', 'Alias') THEN v_has_listitem_join := true; END IF; END LOOP; END IF; -- ------- JOIN kind: LEFT keeps objects with no _values rows ------- v_join_kind := CASE WHEN p_force_outer THEN 'LEFT JOIN' ELSE 'INNER JOIN' END; -- ------- Tree-mode object-set restriction ------------------------- -- Emit the `_pvt_tree(_id, depth)` CTE matching the requested -- tree mode (descendants / children / roots / leaves / ancestors), -- then capture the restriction `o._id IN (SELECT _id FROM -- _pvt_tree [WHERE depth>0])` in v_tree_filter so it can be -- AND-ed into either the wide WHERE or the narrow IN-subquery. -- -- tree / tree_descendants recursive walk DOWN from p_tree_ids. -- depth=0 at seed; descendants depth>0. -- p_max_depth caps walk; p_include_seed -- controls whether seed itself stays. -- tree_children single-level non-recursive: direct -- children of p_tree_ids. -- tree_roots non-recursive: scheme roots -- (`_id_parent IS NULL`). p_tree_ids -- optional and restricts the root set. -- tree_leaves non-recursive: scheme objects with -- no children. p_tree_ids optional. -- tree_ancestors recursive walk UP from p_tree_ids. -- seed depth=1 = direct parent; the -- objects themselves are NOT in the -- walk (seed=parent), so p_include_seed -- does not apply here. -- -- Polymorphic flag: when p_polymorphic = false AND scheme filter -- is folded into the recursive parts (Pro keeps walks polymorphic -- so cross-scheme parents can stitch hierarchies together). DECLARE v_seed_arr text; v_scheme_pred text := ''; BEGIN IF p_source_mode <> 'flat' THEN v_seed_arr := CASE WHEN p_tree_ids IS NULL OR array_length(p_tree_ids, 1) IS NULL THEN NULL ELSE quote_literal(p_tree_ids::text) || '::bigint[]' END; IF NOT p_polymorphic THEN v_scheme_pred := ' AND o._id_scheme = ' || p_scheme_id::text; END IF; END IF; IF p_source_mode IN ('tree', 'tree_descendants') THEN IF v_seed_arr IS NULL THEN RAISE EXCEPTION 'pvt_build_cte_sql: p_tree_ids is required when p_source_mode = ''%''', p_source_mode; END IF; v_cte_parts := v_cte_parts || ( '_pvt_tree(_id, depth) AS (' || E'\n SELECT _id, 0 FROM _objects WHERE _id = ANY(' || v_seed_arr || ')' || E'\n UNION ALL' || E'\n SELECT o._id, t.depth + 1 FROM _objects o ' || 'JOIN _pvt_tree t ON o._id_parent = t._id' || CASE WHEN p_max_depth IS NOT NULL OR NOT p_polymorphic THEN ' WHERE ' || CASE WHEN p_max_depth IS NOT NULL THEN 't.depth < ' || p_max_depth::text ELSE 'TRUE' END || CASE WHEN NOT p_polymorphic THEN v_scheme_pred ELSE '' END ELSE '' END || E'\n)'); v_has_recursive := true; v_tree_filter := CASE WHEN p_include_seed THEN 'o._id IN (SELECT _id FROM _pvt_tree)' ELSE 'o._id IN (SELECT _id FROM _pvt_tree WHERE depth > 0)' END; ELSIF p_source_mode = 'tree_children' THEN IF v_seed_arr IS NULL THEN RAISE EXCEPTION 'pvt_build_cte_sql: p_tree_ids is required when p_source_mode = ''tree_children'''; END IF; v_cte_parts := v_cte_parts || ( '_pvt_tree(_id, depth) AS (' || E'\n SELECT o._id, 1 FROM _objects o ' || 'WHERE o._id_parent = ANY(' || v_seed_arr || ')' || CASE WHEN NOT p_polymorphic THEN v_scheme_pred ELSE '' END || E'\n)'); v_tree_filter := 'o._id IN (SELECT _id FROM _pvt_tree)'; ELSIF p_source_mode = 'tree_roots' THEN v_cte_parts := v_cte_parts || ( '_pvt_tree(_id, depth) AS (' || E'\n SELECT o._id, 0 FROM _objects o ' || 'WHERE o._id_parent IS NULL AND o._id_scheme = ' || p_scheme_id::text || CASE WHEN v_seed_arr IS NOT NULL THEN ' AND o._id = ANY(' || v_seed_arr || ')' ELSE '' END || E'\n)'); v_tree_filter := 'o._id IN (SELECT _id FROM _pvt_tree)'; ELSIF p_source_mode = 'tree_leaves' THEN v_cte_parts := v_cte_parts || ( '_pvt_tree(_id, depth) AS (' || E'\n SELECT o._id, 0 FROM _objects o ' || 'WHERE o._id_scheme = ' || p_scheme_id::text || ' AND NOT EXISTS (SELECT 1 FROM _objects c WHERE c._id_parent = o._id)' || CASE WHEN v_seed_arr IS NOT NULL THEN ' AND o._id = ANY(' || v_seed_arr || ')' ELSE '' END || E'\n)'); v_tree_filter := 'o._id IN (SELECT _id FROM _pvt_tree)'; ELSIF p_source_mode = 'tree_ancestors' THEN IF v_seed_arr IS NULL THEN RAISE EXCEPTION 'pvt_build_cte_sql: p_tree_ids is required when p_source_mode = ''tree_ancestors'''; END IF; -- Walk UP via _id_parent. Seed: immediate parents of -- p_tree_ids (depth=1). Recursive step: grandparents and -- so on until _id_parent IS NULL or depth cap reached. v_cte_parts := v_cte_parts || ( '_pvt_tree(_id, depth) AS (' || E'\n SELECT seed._id_parent, 1 FROM _objects seed ' || 'WHERE seed._id = ANY(' || v_seed_arr || ') AND seed._id_parent IS NOT NULL' || E'\n UNION ALL' || E'\n SELECT o._id_parent, t.depth + 1 FROM _objects o ' || 'JOIN _pvt_tree t ON o._id = t._id' || ' WHERE o._id_parent IS NOT NULL' || CASE WHEN p_max_depth IS NOT NULL THEN ' AND t.depth < ' || p_max_depth::text ELSE '' END || CASE WHEN NOT p_polymorphic THEN v_scheme_pred ELSE '' END || E'\n)'); v_has_recursive := true; v_tree_filter := 'o._id IN (SELECT _id FROM _pvt_tree)'; END IF; IF v_tree_filter <> '' THEN v_where := v_where || ' AND ' || v_tree_filter; END IF; END; -- ------- Base-field pushdown (Pro parity) ------------------------- -- pvt_split_filter feeds us a ready-baked predicate fragment that -- references `o.*` directly. We AND it into the inner WHERE so the -- planner can apply system-column indexes BEFORE the JOIN with -- _values and BEFORE the GROUP BY. Cuts work from O(scheme_size) -- down to O(filtered_objects). IF p_extra_where IS NOT NULL AND p_extra_where <> '' THEN v_where := v_where || ' AND ' || p_extra_where; END IF; -- ------- Nested-dict side CTEs (Pro pattern) ---------------------- -- For each group (parent_sid, dict_key) we emit ONE CTE that scans -- the parent dict-row from _values and projects each child field as -- a correlated subselect over child _values rows. Outer _pvt_cte -- then LEFT JOINs all groups by _id_object. -- -- Nested-only detection: when v_pivot_cols is empty AND exactly -- one nested-dict group is present AND p_narrow / NOT p_force_outer, -- the outer pi wrapper is wasteful. Fold the object-set restriction -- (scheme + base pushdown + tree filter) into the nested CTE's WHERE -- and emit a flat _pvt_cte body below. v_pivot_cols_empty := (COALESCE(v_pivot_cols, '') = ''); v_is_nested_only := p_narrow AND NOT p_force_outer AND v_pivot_cols_empty AND (v_nested_groups <> '{}'::jsonb); -- Pro-parity: always fold object-set restriction (scheme + base -- pushdown + tree filter) into every nested_dict_N CTE so the -- planner can prune dp rows by _id_scheme BEFORE the LEFT JOIN nv -- expansion. Previously we set this only on the nested-only path; -- mixed scalar+nested queries were left scanning the full _values -- partition for the parent sid. Mirrors PG PRO 12. v_nested_obj_filter := format( ' AND dp._id_object IN (SELECT o._id FROM _objects o WHERE o._id_scheme = %s%s%s)', p_scheme_id::text, CASE WHEN p_extra_where IS NOT NULL AND p_extra_where <> '' THEN ' AND ' || p_extra_where ELSE '' END, CASE WHEN v_tree_filter <> '' THEN ' AND ' || v_tree_filter ELSE '' END); FOR v_group_key, v_group_entry IN SELECT key, value FROM jsonb_each(v_nested_groups) LOOP v_group_idx := v_group_idx + 1; v_group_cte_name := 'nested_dict_' || v_group_idx::text; v_group_fields := v_group_entry->'fields'; v_inner_subs := ''; DECLARE v_inner_sids text := ''; -- comma-sep sid list for the LEFT JOIN predicate v_seen jsonb := '{}'::jsonb; BEGIN FOR v_inner_field IN SELECT * FROM jsonb_array_elements(v_group_fields) LOOP v_inner_meta := v_inner_field->'meta'; v_inner_alias := v_inner_field->>'name'; v_inner_sid := v_inner_meta->>'sid'; v_inner_col := v_inner_meta->>'db_column'; v_inner_is_array := COALESCE((v_inner_meta->>'is_array')::boolean, false); IF (v_inner_meta->>'list_item_prop') IS NOT NULL THEN RAISE EXCEPTION 'pvt_build_cte_sql: nested-dict ListItem accessor not supported in v0.3.0 (field "%")', v_inner_alias; END IF; -- Pro-parity aggregate: one LEFT JOIN over all sids in the -- group + per-field array_agg(...) FILTER (WHERE _id_structure -- = SID AND _array_index ). Scalar takes [1]; array -- takes the array_agg as-is. IF v_inner_is_array THEN v_inner_sub := format( 'array_agg(nv.%s) FILTER (WHERE nv._id_structure = %s AND nv._array_index IS NOT NULL) AS %I', v_inner_col, v_inner_sid, v_inner_alias); ELSE v_inner_sub := format( '(array_agg(nv.%s) FILTER (WHERE nv._id_structure = %s AND nv._array_index IS NULL))[1] AS %I', v_inner_col, v_inner_sid, v_inner_alias); END IF; IF v_inner_subs <> '' THEN v_inner_subs := v_inner_subs || ',' || E'\n '; END IF; v_inner_subs := v_inner_subs || v_inner_sub; -- Collect distinct sids for the JOIN predicate. IF (v_seen ? v_inner_sid) = false THEN v_seen := v_seen || jsonb_build_object(v_inner_sid, true); IF v_inner_sids <> '' THEN v_inner_sids := v_inner_sids || ', '; END IF; v_inner_sids := v_inner_sids || v_inner_sid; END IF; -- Track alias for the explicit-cols residual wrapper. v_pivot_aliases := v_pivot_aliases || quote_ident(v_inner_alias); -- Outer projection + JOIN parts v_nested_cols_sql := v_nested_cols_sql || ', ' || quote_ident(v_group_cte_name) || '.' || quote_ident(v_inner_alias) || ' AS ' || quote_ident(v_inner_alias); -- Flat projection (nested-only path): no `pi.` prefix; the -- outer SELECT JOINs _objects on _pvt_cte._id_object. IF v_is_nested_only THEN IF v_flat_cols_sql <> '' THEN v_flat_cols_sql := v_flat_cols_sql || ', '; END IF; v_flat_cols_sql := v_flat_cols_sql || quote_ident(v_group_cte_name) || '.' || quote_ident(v_inner_alias) || ' AS ' || quote_ident(v_inner_alias); END IF; -- (joins built once per group below) END LOOP; v_cte_parts := v_cte_parts || format( '%I AS (' || E'\n SELECT dp._id_object,\n %s\n FROM _values dp\n LEFT JOIN _values nv ON nv._array_parent_id = dp._id AND nv._id_structure %s\n WHERE dp._id_structure = %s AND dp._array_index = %L%s\n GROUP BY dp._id_object\n )', v_group_cte_name, v_inner_subs, CASE WHEN position(',' in v_inner_sids) > 0 THEN 'IN (' || v_inner_sids || ')' ELSE '= ' || v_inner_sids END, v_group_entry->>'parent_sid', v_group_entry->>'dict_key', v_nested_obj_filter); v_nested_joins := v_nested_joins || E'\n LEFT JOIN ' || quote_ident(v_group_cte_name) || ' ON ' || quote_ident(v_group_cte_name) || '._id_object = pi._id'; END; END LOOP; -- ------- Inner pivot SELECT --------------------------------------- -- Narrow Pro-shape: scan _values directly, restrict by -- _id_structure ANY(), restrict object set via an -- IN-subquery over _objects (carrying scheme + base pushdown + -- tree restriction), and group by a single column (_id_object). -- The outer SELECT must JOIN _objects to expose base columns. -- Eligible iff: narrow flag set, no LEFT JOIN required (would -- lose missing _values rows), no nested-dict groups (they require -- pi.* projection over the wide source), and at least one pivot -- sid was collected. Tree mode IS supported: v_tree_filter is -- folded into the IN-subquery so the recursive `_pvt_tree` walk -- and base pushdown both run before the _values scan. IF p_narrow AND NOT p_force_outer AND v_group_idx = 0 AND array_length(v_sids, 1) IS NOT NULL THEN SELECT string_agg(DISTINCT s::text, ', ') INTO v_sid_text FROM unnest(v_sids) AS s; v_objects_subq := format( '(SELECT o._id FROM _objects o WHERE o._id_scheme = %s%s%s)', p_scheme_id::text, CASE WHEN p_extra_where IS NOT NULL AND p_extra_where <> '' THEN ' AND ' || p_extra_where ELSE '' END, CASE WHEN v_tree_filter <> '' THEN ' AND ' || v_tree_filter ELSE '' END); v_inner_pivot := E'SELECT\n v._id_object' || v_pivot_cols || E'\n FROM _values v' || CASE WHEN v_has_listitem_join THEN E'\n LEFT JOIN _list_items li ON li._id = v._ListItem' ELSE '' END || E'\n WHERE v._id_structure = ANY(ARRAY[' || v_sid_text || ']::bigint[])' || E'\n AND v._id_object IN ' || v_objects_subq || E'\n GROUP BY v._id_object'; ELSE v_inner_pivot := E'SELECT\n ' || v_base_cols || v_pivot_cols || E'\n FROM _objects o\n ' || v_join_kind || E' _values v ON v._id_object = o._id' || CASE WHEN v_has_listitem_join THEN E'\n LEFT JOIN _list_items li ON li._id = v._ListItem' ELSE '' END || E'\n WHERE ' || v_where || E'\n GROUP BY ' || v_base_cols; END IF; -- ------- Final _pvt_cte body -------------------------------------- IF v_is_nested_only THEN -- Nested-only: flatten across all nested_dict_N groups joined -- on _id_object. First group is the seed, additional groups -- LEFT JOIN onto it (objects missing entries in later groups -- keep NULL for those cols, matching wide-path LEFT JOIN). DECLARE v_nested_from text := ''; v_idx integer; BEGIN FOR v_idx IN 1..v_group_idx LOOP IF v_idx = 1 THEN v_nested_from := 'nested_dict_1'; ELSE v_nested_from := v_nested_from || E'\n LEFT JOIN ' || 'nested_dict_' || v_idx::text || ' ON ' || 'nested_dict_' || v_idx::text || '._id_object = nested_dict_1._id_object'; END IF; END LOOP; v_pvt_body := 'SELECT nested_dict_1._id_object, ' || v_flat_cols_sql || E'\n FROM ' || v_nested_from; END; ELSIF v_group_idx = 0 THEN v_pvt_body := v_inner_pivot; ELSE v_pvt_body := E'SELECT pi.*' || v_nested_cols_sql || E'\n FROM (' || v_inner_pivot || E') pi' || v_nested_joins; END IF; -- ------- Residual WHERE pushdown (Pro parity) --------------------- -- When pvt_build_query_sql determines the outer filter touches only -- pivoted columns, it passes the pre-rendered SQL here. Wrapping it -- inside _pvt_cte lets the planner prune rows BEFORE the outer -- JOIN _objects, mirroring Pro's `WHERE pvt. = $N` shape. -- Explicit column list (not SELECT *): matches Pro 1:1 and keeps -- the projection contract stable for downstream consumers. IF p_residual_where IS NOT NULL AND p_residual_where <> '' AND p_residual_where <> 'TRUE' THEN DECLARE v_wrap_cols text; BEGIN v_wrap_cols := 'pvt._id_object'; IF array_length(v_pivot_aliases, 1) IS NOT NULL THEN v_wrap_cols := v_wrap_cols || ', pvt.' || array_to_string(v_pivot_aliases, ', pvt.'); END IF; v_pvt_body := 'SELECT ' || v_wrap_cols || E'\n FROM (' || E'\n ' || v_pvt_body || E'\n ) pvt WHERE ' || p_residual_where; END; END IF; v_cte_parts := v_cte_parts || ('_pvt_cte AS (' || E'\n ' || v_pvt_body || E'\n )'); -- ------- Assemble final CTE SQL ----------------------------------- RETURN (CASE WHEN v_has_recursive THEN 'WITH RECURSIVE ' ELSE 'WITH ' END) || array_to_string(v_cte_parts, E',\n'); END; $BODY$; COMMENT ON FUNCTION pvt_build_cte_sql(bigint, jsonb, text, bigint[], integer, boolean, text, boolean, boolean, boolean, text) IS 'Builds the WITH _pvt_cte AS (...) clause. Two pivot shapes: wide legacy (`FROM _objects o JOIN _values v` GROUP BY 21 base cols) used for null-checks, tree mode, and nested-dict groups; narrow Pro-shape (`FROM _values v WHERE _id_structure=ANY(...) AND _id_object IN (SELECT _id FROM _objects WHERE ...)` GROUP BY 1) selected via p_narrow=true. In narrow mode the outer SELECT must JOIN _objects to expose base columns. Source modes: flat | tree (alias for tree_descendants) | tree_descendants | tree_children (single level, non-recursive) | tree_roots (`_id_parent IS NULL`) | tree_leaves (no children, non-recursive) | tree_ancestors (recursive walk UP via _id_parent). p_include_seed=false strips the seed from tree_descendants results; p_polymorphic=false ANDs scheme_id into recursive walk.'; Path: redb/redb.SQLite/sql/v2-pvt/13_pvt_condition.sql 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/v2-pvt/13_pvt_condition.sql ---- -- ===================================================================== -- 13_pvt_condition.sql -- --------------------------------------------------------------------- -- Build a SQL predicate fragment for a single leaf node in the filter -- JSON, referencing a CTE column (NOT the raw _values row). All -- supported operators in v0.1.0 are emitted here; unsupported ones -- raise with a clear message. -- -- Function: -- pvt_build_field_condition(p_field_name, p_field_meta, p_op_json) RETURNS text -- -- Input shapes: -- p_op_json = scalar -> shorthand for {"$eq": } -- p_op_json = {"$op": , ...} -- -- Supported operators in v0.1.0: -- $eq, $ne, $gt, $gte, $lt, $lte, -- $in, $nin, -- $like, $ilike, -- $startsWith, $endsWith, $contains (case-sensitive, LIKE), -- $startsWithIgnoreCase, $endsWithIgnoreCase, -- $containsIgnoreCase (case-insensitive, ILIKE), -- $null, $exists, $isNull, $notNull -- ===================================================================== -- Signature evolved in v0.4.0 (added p_base_prefix). CREATE OR REPLACE -- cannot change a function's argument list, so drop the legacy form -- first if present. DROP FUNCTION IF EXISTS pvt_build_field_condition(text, jsonb, jsonb); CREATE OR REPLACE FUNCTION pvt_build_field_condition( p_field_name text, p_field_meta jsonb, p_op_json jsonb, p_base_prefix text DEFAULT '' -- '' → reference CTE column; 'o.' → reference _objects directly (pushdown) ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_col text; v_kind text; v_db_type text; v_cast text; v_elem_cast text; v_li_prop text; v_is_array boolean; v_length_mod boolean; v_arr_col text; v_op_key text; v_op_val jsonb; v_parts text[] := ARRAY[]::text[]; v_op_count integer := 0; v_op_norm text; v_lit text; v_arr_lit text; BEGIN IF p_field_meta IS NULL THEN RAISE EXCEPTION 'pvt_build_field_condition: p_field_meta is NULL for field "%"', p_field_name; END IF; v_kind := p_field_meta->>'kind'; v_li_prop := p_field_meta->>'list_item_prop'; v_is_array := COALESCE((p_field_meta->>'is_array')::boolean, false); v_db_type := p_field_meta->>'db_type'; v_length_mod := COALESCE((p_field_meta->>'length_modifier')::boolean, false); v_arr_col := quote_ident(COALESCE(p_field_meta->>'base_name', p_field_name)); -- ---- Element-type cast (used by $arrayXxx scalar operands) ------ v_elem_cast := CASE pvt_db_type_to_value_column(v_db_type) WHEN '_String' THEN '::text' WHEN '_Long' THEN '::bigint' WHEN '_Double' THEN '::double precision' WHEN '_Numeric' THEN '::numeric' WHEN '_Boolean' THEN '::boolean' WHEN '_Guid' THEN '::uuid' WHEN '_DateTimeOffset' THEN '::timestamptz' WHEN '_ByteArray' THEN '::bytea' WHEN '_ListItem' THEN '::bigint' WHEN '_Object' THEN '::bigint' ELSE '' END; -- ---- LHS column reference --------------------------------------- -- length/count modifier rewrites the LHS to a scalar-int expression: -- * is_array=true -> array_length(, 1) -- * is_array=false -> LENGTH() (string length, e.g. p.Name.Length) -- Base fields project from _objects under their system column name -- (e.g. `_id`, `_name`) and never under the user-facing path (e.g. -- `0$:Id`); ordinary cases reference the CTE alias which matches the -- original field path. DECLARE v_length_target text; BEGIN v_length_target := CASE WHEN v_kind = 'base' THEN p_base_prefix || quote_ident(p_field_meta->>'column') ELSE v_arr_col END; v_col := CASE WHEN v_length_mod AND v_is_array THEN 'COALESCE(array_length(' || v_length_target || ', 1), 0)' WHEN v_length_mod THEN 'COALESCE(LENGTH(' || v_length_target || '), 0)' WHEN v_kind = 'base' THEN p_base_prefix || quote_ident(p_field_meta->>'column') ELSE quote_ident(p_field_name) END; -- Scalar ListItem.Value / .Alias: pivot column holds the raw -- _ListItem id (parity with Pro). WHERE compares by id; the caller -- (LINQ translator) is responsible for resolving a string like -- 'Active' to its _list_items._id before passing it down. Only -- ORDER BY dereferences to _value / _alias for textual sort. -- Array path is unchanged: pivot emits text[] of values. END; -- ---- Pick a SQL cast suitable for the resolved CTE column type -- -- For base fields the cast must reflect the underlying _objects -- column type, otherwise comparisons such as `o._id IN (text...)` -- raise `bigint = text`. v_cast := CASE WHEN v_length_mod THEN '' WHEN v_kind = 'base' THEN CASE p_field_meta->>'column' WHEN '_id' THEN '::bigint' WHEN '_id_parent' THEN '::bigint' WHEN '_id_scheme' THEN '::bigint' WHEN '_id_owner' THEN '::bigint' WHEN '_id_who_change' THEN '::bigint' WHEN '_value_long' THEN '::bigint' WHEN '_key' THEN '::bigint' WHEN '_value_double' THEN '::double precision' WHEN '_value_numeric' THEN '::numeric' WHEN '_value_bool' THEN '::boolean' WHEN '_value_guid' THEN '::uuid' WHEN '_value_datetime' THEN '::timestamptz' WHEN '_date_create' THEN '::timestamptz' WHEN '_date_modify' THEN '::timestamptz' WHEN '_date_begin' THEN '::timestamptz' WHEN '_date_complete' THEN '::timestamptz' ELSE '' -- _name / _note / _value_string / _hash / _value_bytes -> text/bytea, no cast needed END -- Scalar ListItem.Value/.Alias pivot column holds the resolved -- _list_items._value / _alias string (pvt_build_cte_sql adds a -- LEFT JOIN _list_items li when needed; pvt_build_column_expr -- aggregates li._value / li._alias). Free LINQ passes string -- literals; comparison is text. Array path also dereferences -- to text[]. ListItem.Id keeps bigint. WHEN v_li_prop IN ('Value', 'Alias') THEN '::text' WHEN v_li_prop = 'Id' THEN '::bigint' ELSE v_elem_cast END; -- ---- Shorthand: scalar literal == {"$eq": } ---- IF jsonb_typeof(p_op_json) <> 'object' THEN IF jsonb_typeof(p_op_json) = 'null' THEN RETURN format('%s IS NULL', v_col); END IF; RETURN format('%s = %L%s', v_col, pvt_jsonb_to_sql_literal(p_op_json), v_cast); END IF; -- ---- Iterate operator object (AND of every op present) ---- FOR v_op_key, v_op_val IN SELECT key, value FROM jsonb_each(p_op_json) LOOP v_op_count := v_op_count + 1; v_op_norm := lower(v_op_key); IF v_op_norm IN ('$eq', '$ne', '$gt', '$gte', '$lt', '$lte') THEN IF jsonb_typeof(v_op_val) = 'null' THEN v_parts := v_parts || (CASE v_op_norm WHEN '$eq' THEN format('%s IS NULL', v_col) WHEN '$ne' THEN format('%s IS NOT NULL', v_col) ELSE format('%s %s NULL', v_col, CASE v_op_norm WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' END) END); ELSIF v_is_array AND NOT v_length_mod AND v_op_norm IN ('$eq', '$ne') THEN -- Array LHS: scalar = ANY / NOT (= ANY) semantics, e.g. -- Roles[].Any(r => r.Value == "X") -> 'X' = ANY() v_parts := v_parts || (CASE v_op_norm WHEN '$eq' THEN format('(%L%s = ANY(%s))', pvt_jsonb_to_sql_literal(v_op_val), v_cast, v_col) WHEN '$ne' THEN format('(%s IS NULL OR NOT (%L%s = ANY(%s)))', v_col, pvt_jsonb_to_sql_literal(v_op_val), v_cast, v_col) END); ELSE v_parts := v_parts || format('%s %s %L%s', v_col, CASE v_op_norm WHEN '$eq' THEN '=' WHEN '$ne' THEN '<>' WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' END, pvt_jsonb_to_sql_literal(v_op_val), v_cast); END IF; ELSIF v_op_norm IN ('$in', '$nin') THEN IF jsonb_typeof(v_op_val) <> 'array' THEN RAISE EXCEPTION 'pvt_build_field_condition: % expects array (field "%")', v_op_key, p_field_name; END IF; IF v_is_array AND NOT v_length_mod THEN -- Array LHS: use overlap (&&) instead of IN, since -- `text[] IN (text,...)` is not a valid SQL expression. IF v_op_norm = '$in' THEN v_parts := v_parts || format( '%s && (SELECT array_agg(x%s) FROM jsonb_array_elements_text(%L::jsonb) AS x)', v_col, v_cast, v_op_val::text); ELSE v_parts := v_parts || format( '(%s IS NULL OR NOT (%s && (SELECT array_agg(x%s) FROM jsonb_array_elements_text(%L::jsonb) AS x)))', v_col, v_col, v_cast, v_op_val::text); END IF; ELSE v_parts := v_parts || format('%s %s (SELECT (jsonb_array_elements_text(%L::jsonb))%s)', v_col, CASE v_op_norm WHEN '$in' THEN 'IN' ELSE 'NOT IN' END, v_op_val::text, v_cast); END IF; ELSIF v_op_norm IN ('$like', '$ilike') THEN v_parts := v_parts || format('%s %s %L', v_col, CASE v_op_norm WHEN '$like' THEN 'LIKE' ELSE 'ILIKE' END, v_op_val #>> '{}'); ELSIF v_op_norm = '$startswith' THEN v_parts := v_parts || format('%s LIKE %L', v_col, (v_op_val #>> '{}') || '%'); ELSIF v_op_norm = '$endswith' THEN v_parts := v_parts || format('%s LIKE %L', v_col, '%' || (v_op_val #>> '{}')); ELSIF v_op_norm = '$contains' THEN v_parts := v_parts || format('%s LIKE %L', v_col, '%' || (v_op_val #>> '{}') || '%'); ELSIF v_op_norm = '$startswithignorecase' THEN v_parts := v_parts || format('%s ILIKE %L', v_col, (v_op_val #>> '{}') || '%'); ELSIF v_op_norm = '$endswithignorecase' THEN v_parts := v_parts || format('%s ILIKE %L', v_col, '%' || (v_op_val #>> '{}')); ELSIF v_op_norm = '$containsignorecase' THEN v_parts := v_parts || format('%s ILIKE %L', v_col, '%' || (v_op_val #>> '{}') || '%'); ELSIF v_op_norm IN ('$null', '$isnull') THEN v_parts := v_parts || (CASE WHEN (v_op_val::text)::boolean THEN format('%s IS NULL', v_col) ELSE format('%s IS NOT NULL', v_col) END); ELSIF v_op_norm IN ('$notnull', '$exists') THEN v_parts := v_parts || (CASE WHEN (v_op_val::text)::boolean THEN format('%s IS NOT NULL', v_col) ELSE format('%s IS NULL', v_col) END); -- ============ POSIX regex shorthand ========================= -- {"Field": {"$regex": "pattern"}} -> Field ~ 'pattern' -- {"Field": {"$iregex": "pattern"}} -> Field ~* 'pattern' -- {"Field": {"$notregex": "pattern"}} -> Field !~ 'pattern' -- {"Field": {"$inotregex": "pattern"}} -> Field !~* 'pattern' ELSIF v_op_norm IN ('$regex', '$iregex', '$notregex', '$inotregex') THEN v_parts := v_parts || format('%s %s %L', v_col, CASE v_op_norm WHEN '$regex' THEN '~' WHEN '$iregex' THEN '~*' WHEN '$notregex' THEN '!~' WHEN '$inotregex' THEN '!~*' END, v_op_val #>> '{}'); -- ============ Full-text-search shorthand ==================== -- {"Field": {"$fts": "query"}} -- lang='simple' -- {"Field": {"$fts": {"query":"...", -- "language":"english"}}} -- explicit lang ELSIF v_op_norm = '$fts' THEN DECLARE v_fts_lang text := 'simple'; v_fts_query text; BEGIN IF jsonb_typeof(v_op_val) = 'string' THEN v_fts_query := v_op_val #>> '{}'; ELSIF jsonb_typeof(v_op_val) = 'object' AND v_op_val ? 'query' THEN v_fts_query := v_op_val ->> 'query'; IF v_op_val ? 'language' THEN v_fts_lang := lower(v_op_val ->> 'language'); END IF; ELSE RAISE EXCEPTION 'pvt_build_field_condition: $fts expects string or {"query":..., "language"?}'; END IF; v_parts := v_parts || format( '(to_tsvector(%L, COALESCE(%s::text, '''')) @@ websearch_to_tsquery(%L, %L))', v_fts_lang, v_col, v_fts_lang, v_fts_query); END; -- ============ Array operators (Pro parity, v0.3.0) =========== -- All $arrayXxx require an array-shaped CTE column (typed array -- or ListItem-array projection: bigint[] for .Id / text[] for -- .Value / .Alias). The length/count modifier is incompatible -- because it collapses the array to a scalar. ELSIF v_op_norm LIKE '$array%' THEN IF v_length_mod THEN RAISE EXCEPTION 'pvt_build_field_condition: % cannot be combined with .$length / .$count (field "%")', v_op_key, p_field_name; END IF; IF NOT v_is_array THEN RAISE EXCEPTION 'pvt_build_field_condition: % requires an array field (field "%")', v_op_key, p_field_name; END IF; IF v_op_norm = '$arraycontains' THEN v_parts := v_parts || format('%L%s = ANY(%s)', pvt_jsonb_to_sql_literal(v_op_val), v_elem_cast, v_col); ELSIF v_op_norm = '$arrayany' THEN -- Boolean-shorthand: true => not empty, false => empty. v_parts := v_parts || (CASE WHEN (v_op_val::text)::boolean THEN format('COALESCE(array_length(%s, 1), 0) > 0', v_col) ELSE format('COALESCE(array_length(%s, 1), 0) = 0', v_col) END); ELSIF v_op_norm = '$arrayempty' THEN v_parts := v_parts || (CASE WHEN (v_op_val::text)::boolean THEN format('COALESCE(array_length(%s, 1), 0) = 0', v_col) ELSE format('COALESCE(array_length(%s, 1), 0) > 0', v_col) END); ELSIF v_op_norm IN ('$arraycount', '$arraycountgt', '$arraycountgte', '$arraycountlt', '$arraycountlte') THEN v_parts := v_parts || format('COALESCE(array_length(%s, 1), 0) %s %L::bigint', v_col, CASE v_op_norm WHEN '$arraycount' THEN '=' WHEN '$arraycountgt' THEN '>' WHEN '$arraycountgte' THEN '>=' WHEN '$arraycountlt' THEN '<' WHEN '$arraycountlte' THEN '<=' END, pvt_jsonb_to_sql_literal(v_op_val)); ELSIF v_op_norm = '$arrayat' THEN -- Operand: {"index": N, "value": V} (PG arrays are 1-based, -- but our convention is 0-based at the API; add 1). IF jsonb_typeof(v_op_val) <> 'object' OR NOT (v_op_val ? 'index') OR NOT (v_op_val ? 'value') THEN RAISE EXCEPTION 'pvt_build_field_condition: $arrayAt expects {"index":N,"value":V} (field "%")', p_field_name; END IF; v_parts := v_parts || format('%s[(%L::int) + 1] = %L%s', v_col, (v_op_val->>'index'), pvt_jsonb_to_sql_literal(v_op_val->'value'), v_elem_cast); ELSIF v_op_norm = '$arrayfirst' THEN v_parts := v_parts || format('%s[1] = %L%s', v_col, pvt_jsonb_to_sql_literal(v_op_val), v_elem_cast); ELSIF v_op_norm = '$arraylast' THEN v_parts := v_parts || format('%s[array_length(%s, 1)] = %L%s', v_col, v_col, pvt_jsonb_to_sql_literal(v_op_val), v_elem_cast); ELSIF v_op_norm = '$arraystartswith' THEN v_parts := v_parts || format('%s[1] LIKE %L', v_col, (v_op_val #>> '{}') || '%'); ELSIF v_op_norm = '$arrayendswith' THEN v_parts := v_parts || format('%s[array_length(%s, 1)] LIKE %L', v_col, v_col, '%' || (v_op_val #>> '{}')); ELSIF v_op_norm = '$arraymatches' THEN v_parts := v_parts || format( 'EXISTS (SELECT 1 FROM unnest(%s) AS _x WHERE _x LIKE %L)', v_col, v_op_val #>> '{}'); ELSIF v_op_norm IN ('$arraysum', '$arrayavg', '$arraymin', '$arraymax') THEN v_parts := v_parts || format( '(SELECT %s(_x) FROM unnest(%s) AS _x) = %L%s', CASE v_op_norm WHEN '$arraysum' THEN 'SUM' WHEN '$arrayavg' THEN 'AVG' WHEN '$arraymin' THEN 'MIN' WHEN '$arraymax' THEN 'MAX' END, v_col, pvt_jsonb_to_sql_literal(v_op_val), v_elem_cast); ELSE RAISE EXCEPTION 'pvt_build_field_condition: array operator "%" is not supported in v0.3.0 (field "%")', v_op_key, p_field_name; END IF; ELSE RAISE EXCEPTION 'pvt_build_field_condition: operator "%" is not supported in v0.3.0 (field "%")', v_op_key, p_field_name; END IF; END LOOP; IF v_op_count = 0 THEN RAISE EXCEPTION 'pvt_build_field_condition: empty operator object for field "%"', p_field_name; END IF; IF v_op_count = 1 THEN RETURN v_parts[1]; END IF; RETURN '(' || array_to_string(v_parts, ' AND ') || ')'; END; $BODY$; COMMENT ON FUNCTION pvt_build_field_condition(text, jsonb, jsonb, text) IS 'Builds an AND-joined predicate fragment for one leaf field. v0.3.0 supports $eq/$ne/$gt/$gte/$lt/$lte/$in/$nin/$like/$ilike/$startsWith/$endsWith/$contains/$startsWithIgnoreCase/$endsWithIgnoreCase/$containsIgnoreCase/$null/$exists/$isNull/$notNull plus array ops $arrayContains/$arrayAny/$arrayEmpty/$arrayCount/$arrayCountGt|Gte|Lt|Lte/$arrayAt/$arrayFirst/$arrayLast/$arrayStartsWith|EndsWith|Matches/$arraySum|Avg|Min|Max and .$length/.$count modifiers. References CTE alias columns, not raw _values.'; -- ---------- pvt_jsonb_to_sql_literal ----------------------------------- -- Convert a JSON scalar into a string suitable for the %L format spec -- (which adds the surrounding single quotes). Objects/arrays are not -- valid here and cause an error. CREATE OR REPLACE FUNCTION pvt_jsonb_to_sql_literal(p_val jsonb) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $BODY$ BEGIN IF p_val IS NULL OR jsonb_typeof(p_val) = 'null' THEN RETURN NULL; END IF; IF jsonb_typeof(p_val) IN ('object', 'array') THEN RAISE EXCEPTION 'pvt_jsonb_to_sql_literal: cannot coerce % to scalar literal', jsonb_typeof(p_val); END IF; -- jsonb_typeof in ('string','number','boolean'): #>> '{}' strips -- the JSON quoting for strings and gives a plain text rendering -- for numbers/booleans that PostgreSQL accepts in casts. RETURN p_val #>> '{}'; END; $BODY$; COMMENT ON FUNCTION pvt_jsonb_to_sql_literal(jsonb) IS 'Unwraps a JSON scalar to the text form expected by format() %L. Throws on objects/arrays.'; Path: redb/redb.SQLite/sql/v2-pvt/14_pvt_where.sql 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/v2-pvt/14_pvt_where.sql ---- -- ===================================================================== -- 14_pvt_where.sql -- --------------------------------------------------------------------- -- Recursive walker: turns the full filter JSON into a single WHERE -- expression. Column references default to bare names (matching the -- legacy wide _pvt_cte shape), but when p_base_prefix='o.' is passed -- the walker rewrites base-field references to `o.` so the -- predicate composes against `FROM _objects o` directly (used by the -- narrow Pro-shape outer SELECT that JOINs _objects on the pivot CTE). -- -- Function: -- pvt_build_where_from_json(p_filter jsonb, p_fields jsonb, -- p_base_prefix text DEFAULT '') RETURNS text -- -- Grammar: -- { "$and": [ ... ] } -> ( ... AND ... ) -- { "$or": [ ... ] } -> ( ... OR ... ) -- { "$not": { ... } } -> NOT ( ... ) -- { "": , ... } -> AND of per-field conditions -- -- An empty filter (NULL or {}) returns the SQL literal 'TRUE'. -- ===================================================================== -- Signature evolved in v0.5.0 (added p_base_prefix for narrow Pro-shape -- outer SELECT). CREATE OR REPLACE cannot change argument lists. DROP FUNCTION IF EXISTS pvt_build_where_from_json(jsonb, jsonb); CREATE OR REPLACE FUNCTION pvt_build_where_from_json( p_filter jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; elem jsonb; parts text[] := ARRAY[]::text[]; children text[] := ARRAY[]::text[]; meta jsonb; v_normalized text; v_peek text; BEGIN IF p_filter IS NULL OR p_filter = '{}'::jsonb THEN RETURN 'TRUE'; END IF; IF jsonb_typeof(p_filter) <> 'object' THEN RAISE EXCEPTION 'pvt_build_where_from_json: filter must be a JSON object (got %)', jsonb_typeof(p_filter); END IF; FOR k, v IN SELECT key, value FROM jsonb_each(p_filter) LOOP -- ---------- logical $and ---------- IF lower(k) = '$and' THEN IF jsonb_typeof(v) <> 'array' THEN RAISE EXCEPTION '$and expects an array'; END IF; children := ARRAY[]::text[]; FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP children := children || pvt_build_where_from_json(elem, p_fields, p_base_prefix); END LOOP; IF array_length(children, 1) IS NULL THEN parts := parts || 'TRUE'; ELSE parts := parts || ('(' || array_to_string(children, ' AND ') || ')'); END IF; -- ---------- logical $or ---------- ELSIF lower(k) = '$or' THEN IF jsonb_typeof(v) <> 'array' THEN RAISE EXCEPTION '$or expects an array'; END IF; children := ARRAY[]::text[]; FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP children := children || pvt_build_where_from_json(elem, p_fields, p_base_prefix); END LOOP; IF array_length(children, 1) IS NULL THEN parts := parts || 'FALSE'; ELSE parts := parts || ('(' || array_to_string(children, ' OR ') || ')'); END IF; -- ---------- logical $not ---------- ELSIF lower(k) = '$not' THEN parts := parts || ('NOT (' || pvt_build_where_from_json(v, p_fields, p_base_prefix) || ')'); -- ---------- hierarchical (tree) operators ---------- ELSIF lower(k) IN ('$hasancestor', '$hasdescendant', '$level', '$isroot', '$isleaf') THEN -- Delegate to forked legacy helper. It operates on _objects -- columns which are all present inside the PVT CTE under -- their original names, so the predicates compose cleanly. parts := parts || pvt_build_hierarchical_conditions( jsonb_build_object(k, v), 'o' -- legacy expects an alias prefix; CTE column names match _objects column names ); -- ---------- expression-form predicate ---------- -- { "$gt": [exprL, exprR] }, { "$between": [L, lo, hi] }, etc. -- Disambiguated from `{ "$gt": value }` shorthand by the fact -- that the shorthand never appears at filter-level: it always -- lives inside `{ "": { ... } }`. ELSIF lower(k) IN ( '$eq', '$ne', '$lt', '$lte', '$gt', '$gte', '$like', '$ilike', '$in', '$nin', '$between', '$null', '$notnull', '$isnull', '$exists', '$contains', '$startswith', '$endswith', '$containsignorecase', '$startswithignorecase', '$endswithignorecase', '$regex', '$iregex', '$notregex', '$inotregex', '$fts' ) THEN parts := parts || pvt_build_expr_predicate(k, v, p_fields, p_base_prefix); -- ---------- $expr: arbitrary boolean expression -------------- -- { "$expr": } — full pvt_build_bool_expr, -- including $and/$or/$not, and any predicate compiled by -- pvt_build_expr_predicate. Useful for cross-field arithmetic -- filters and for $regex / $fts on multiple fields. ELSIF lower(k) = '$expr' THEN parts := parts || pvt_build_bool_expr(v, p_fields, p_base_prefix); -- ---------- field leaf ---------- ELSE -- Pro-style ContainsKey normalization: rewrite `Dict.ContainsKey` -- to `Dict[]` and look up the resolved metadata under the -- rewritten name. When the rewrite fired, the predicate -- collapses to ` IS NOT NULL` on the dict pivot column. v_peek := pvt_peek_contains_key_value(v); v_normalized := pvt_normalize_field_name(k, v_peek); meta := p_fields -> v_normalized; IF meta IS NULL THEN RAISE EXCEPTION 'pvt_build_where_from_json: field "%" (normalized "%") has no metadata. Did pvt_collect_fields miss it?', k, v_normalized; END IF; IF v_normalized <> k AND COALESCE((meta->>'was_contains_key')::boolean, false) THEN parts := parts || format('%I IS NOT NULL', v_normalized); ELSE parts := parts || pvt_build_field_condition(v_normalized, meta, v, p_base_prefix); END IF; END IF; END LOOP; IF array_length(parts, 1) IS NULL THEN RETURN 'TRUE'; END IF; IF array_length(parts, 1) = 1 THEN RETURN parts[1]; END IF; RETURN '(' || array_to_string(parts, ' AND ') || ')'; END; $BODY$; COMMENT ON FUNCTION pvt_build_where_from_json(jsonb, jsonb, text) IS 'Recursive filter walker. Emits a SQL WHERE expression. With default p_base_prefix='''' base columns are referenced bare (matches the legacy wide CTE shape); with p_base_prefix=''o.'' base references are emitted as `o.` so the predicate composes against `FROM _objects o` in the narrow Pro-shape outer SELECT.'; Path: redb/redb.SQLite/sql/v2-pvt/15_pvt_order.sql 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/v2-pvt/15_pvt_order.sql ---- -- ===================================================================== -- 15_pvt_order.sql -- --------------------------------------------------------------------- -- Build an ORDER BY clause for the outer SELECT, referencing CTE -- columns. Returns the empty string when no ordering is requested. -- -- Function: -- pvt_build_order_conditions(p_order jsonb, p_fields jsonb, -- p_base_prefix text DEFAULT '') RETURNS text -- -- Input shape (accepted variants): -- [ -- { "field": "FullName", "dir": "asc" }, -- { "field": "Age", "dir": "desc", "nulls": "last" } -- ] -- [ -- { "field": "FullName", "direction": "ASC" }, -- legacy C# emits this -- { "field_path": "Age", "direction": "DESC" } -- legacy SQL emits this -- ] -- [ -- { "$expr": {"$mul":[{"$field":"Age"},{"$const":2}]}, -- arithmetic -- "dir": "desc" }, -- { "$expr": {"$upper":{"$field":"FirstName"}}, -- function -- "dir": "asc", "nulls": "last" } -- ] -- -- ORDER BY always runs on the OUTER SELECT (over the materialized CTE -- row + JOIN _objects o in narrow Pro shape). Expression compilation -- is delegated to pvt_build_scalar_expr from 17_pvt_expr.sql so the -- same $field/$const/$add/.../$upper/.../$cast grammar that WHERE -- accepts works in ORDER BY too. Base fields are emitted as -- p_base_prefix || quote_ident(), pivot fields as -- quote_ident() (= the CTE column). -- ===================================================================== -- Signature evolved in v0.6.0 (expression-form $expr support) and -- v0.6.1 (p_distinct_on prepend for SELECT DISTINCT ON parity). -- CREATE OR REPLACE cannot change argument lists, so drop legacy forms. DROP FUNCTION IF EXISTS pvt_build_order_conditions(jsonb, jsonb); DROP FUNCTION IF EXISTS pvt_build_order_conditions(jsonb, jsonb, text); DROP FUNCTION IF EXISTS pvt_build_order_conditions(jsonb, jsonb, text, jsonb); DROP FUNCTION IF EXISTS _pvt_compile_order_col(jsonb, jsonb, text); -- ---------- internal helper: compile one entry column expression ------ -- Shared by ORDER BY, DISTINCT ON, GROUP BY and window PARTITION BY -- builders. Returns the column-side SQL fragment (no direction, no -- NULLS, no DISTINCT ON wrapping). -- -- p_listitem_as_id (v0.4.x): controls how ListItem.Value / .Alias are -- emitted. Pivot columns store raw `_ListItem` ids (parity with Pro); -- ORDER BY / DISTINCT ON need the dereferenced string so that sorting -- has a meaningful order, while GROUP BY / SELECT projection keep the -- id directly. Pass `true` from GROUP BY-style builders. CREATE OR REPLACE FUNCTION _pvt_compile_order_col( p_elem jsonb, p_fields jsonb, p_base_prefix text, p_listitem_as_id boolean DEFAULT false ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_field text; v_meta jsonb; v_li_prop text; v_is_arr boolean; v_col text; BEGIN IF p_elem IS NULL OR jsonb_typeof(p_elem) <> 'object' THEN RAISE EXCEPTION '_pvt_compile_order_col: each entry must be a JSON object (got %)', jsonb_typeof(p_elem); END IF; IF p_elem ? '$expr' THEN RETURN pvt_build_scalar_expr(p_elem->'$expr', p_fields, p_base_prefix); END IF; v_field := COALESCE(p_elem->>'field', p_elem->>'field_path'); IF v_field IS NULL OR v_field = '' THEN RAISE EXCEPTION '_pvt_compile_order_col: entry must include "field", "field_path" or "$expr"'; END IF; v_meta := p_fields -> v_field; IF v_meta IS NULL THEN RAISE EXCEPTION '_pvt_compile_order_col: field "%" has no metadata. Did pvt_collect_fields miss it?', v_field; END IF; IF v_meta->>'kind' = 'base' THEN RETURN p_base_prefix || quote_ident(v_meta->>'column'); END IF; v_col := quote_ident(v_field); v_li_prop := v_meta->>'list_item_prop'; v_is_arr := COALESCE((v_meta->>'is_array')::boolean, false); -- ListItem.Value / .Alias scalar: pivot column already holds the -- dereferenced _list_items._value / _alias string (see -- pvt_build_column_expr), so ORDER BY / GROUP BY just reference -- the column directly. No extra _list_items lookup needed. RETURN v_col; END; $BODY$; -- ---------- pvt_build_distinct_on_select ------------------------------ -- Render a "DISTINCT ON (expr1, expr2) " SELECT-list prefix from a JSON -- array of {field|$expr} entries. Returns the empty string when -- p_distinct_on is NULL/empty. Used by the orchestrator inside the -- three outer-SELECT shapes (Shape A, narrow, wide). CREATE OR REPLACE FUNCTION pvt_build_distinct_on_select( p_distinct_on jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE elem jsonb; parts text[] := ARRAY[]::text[]; BEGIN IF p_distinct_on IS NULL OR jsonb_typeof(p_distinct_on) <> 'array' OR jsonb_array_length(p_distinct_on) = 0 THEN RETURN ''; END IF; FOR elem IN SELECT value FROM jsonb_array_elements(p_distinct_on) LOOP parts := parts || _pvt_compile_order_col(elem, p_fields, p_base_prefix); END LOOP; RETURN 'DISTINCT ON (' || array_to_string(parts, ', ') || ') '; END; $BODY$; COMMENT ON FUNCTION pvt_build_distinct_on_select(jsonb, jsonb, text) IS 'Renders a "DISTINCT ON (expr1, expr2) " SELECT-list prefix from a JSON array of {field|$expr} entries. PostgreSQL requires these expressions to also appear at the head of ORDER BY -- the caller pairs this with pvt_build_order_conditions(..., p_distinct_on) which auto-prepends them.'; CREATE OR REPLACE FUNCTION pvt_build_order_conditions( p_order jsonb, p_fields jsonb, p_base_prefix text DEFAULT '', p_distinct_on jsonb DEFAULT NULL ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE elem jsonb; dir text; nulls text; parts text[] := ARRAY[]::text[]; v_col text; BEGIN -- ---------- DISTINCT ON prefix -------------------------------- -- PostgreSQL requires every DISTINCT ON expression to appear at -- the head of ORDER BY (with matching direction). We always emit -- them ASC -- callers needing the opposite must include the same -- expression explicitly in p_order with their desired direction -- before any other ordering keys, in which case PG will use that -- direction and we MUST NOT double-add (deduplicate by textual -- equality of the compiled fragment). IF p_distinct_on IS NOT NULL AND jsonb_typeof(p_distinct_on) = 'array' AND jsonb_array_length(p_distinct_on) > 0 THEN FOR elem IN SELECT value FROM jsonb_array_elements(p_distinct_on) LOOP v_col := _pvt_compile_order_col(elem, p_fields, p_base_prefix); parts := parts || (v_col || ' ASC'); END LOOP; END IF; IF p_order IS NULL OR jsonb_typeof(p_order) <> 'array' OR jsonb_array_length(p_order) = 0 THEN IF array_length(parts, 1) IS NULL THEN RETURN ''; END IF; RETURN E'\nORDER BY ' || array_to_string(parts, ', '); END IF; FOR elem IN SELECT value FROM jsonb_array_elements(p_order) LOOP dir := lower(COALESCE(elem->>'dir', elem->>'direction', 'asc')); nulls := lower(COALESCE(elem->>'nulls', '')); IF dir NOT IN ('asc', 'desc') THEN RAISE EXCEPTION 'pvt_build_order_conditions: invalid direction "%" (asc|desc only)', dir; END IF; v_col := _pvt_compile_order_col(elem, p_fields, p_base_prefix); parts := parts || ( v_col || ' ' || upper(dir) || CASE WHEN nulls = 'first' THEN ' NULLS FIRST' WHEN nulls = 'last' THEN ' NULLS LAST' ELSE '' END ); END LOOP; RETURN E'\nORDER BY ' || array_to_string(parts, ', '); END; $BODY$; COMMENT ON FUNCTION pvt_build_order_conditions(jsonb, jsonb, text, jsonb) IS 'Builds an ORDER BY clause for the outer SELECT. Accepts plain {"field"|"field_path","dir","nulls"} entries and Pro-parity {"$expr":,"dir","nulls"} entries; expressions are compiled via pvt_build_scalar_expr. Base fields use p_base_prefix (default '''', or ''o.'' for the narrow Pro-shape outer that JOINs _objects). When p_distinct_on is provided its expressions are auto-prepended ASC (PostgreSQL DISTINCT ON requirement). Returns empty string when both p_order and p_distinct_on are empty.'; Path: redb/redb.SQLite/sql/v2-pvt/16_pvt_split.sql 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/v2-pvt/16_pvt_split.sql ---- -- ===================================================================== -- 16_pvt_split.sql -- --------------------------------------------------------------------- -- Pro-parity "base pushdown" optimizer. Walks the filter JSON and -- splits it into two parts: -- -- * pushdown_sql -- a SQL predicate over `_objects o.*` that is -- safe to AND with `o._id_scheme = X` inside -- the pivot CTE; lets PG use indexes on -- system columns BEFORE the JOIN with _values -- and the GROUP BY agg. -- * residual_filter -- the JSON subtree that still needs to be -- evaluated against pivot/props columns AFTER -- the CTE materializes; fed to the regular -- pvt_build_where_from_json walker. -- -- Function: -- pvt_split_filter( -- p_filter jsonb, -- p_fields jsonb, -- OUT v_pushdown_sql text, -- OUT v_residual_filter jsonb -- ) -- -- Splitting rules (conservative — never changes semantics): -- leaf {f: ops} base/hierarchical -> push, -- else -> residual. -- {$and: [c1, c2, ...]} split each child; AND the push parts; -- residual = $and of non-null residuals -- (degraded to single child or NULL). -- {$or: [c1, c2, ...]} pushable ONLY when every child is fully -- base (residual_i is NULL for all i). -- Mixed-leaf $or stays entirely in residual. -- {$not: c} pushable ONLY when c is fully base. -- Otherwise stays entirely in residual. -- top-level multi-key object treated as implicit $and of singletons. -- -- Hierarchical operators ($hasAncestor / $hasDescendant / $level / -- $isRoot / $isLeaf) are always pushable because the legacy helper -- already emits SQL over the `o` alias of _objects. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_split_filter( p_filter jsonb, p_fields jsonb, OUT v_pushdown_sql text, OUT v_residual_filter jsonb ) LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; elem jsonb; child_push text; child_residual jsonb; push_parts text[] := ARRAY[]::text[]; residual_children jsonb := '[]'::jsonb; is_logical boolean := false; is_field_object boolean := false; key_count integer; v_peek text; v_normalized text; v_meta jsonb; v_kind text; v_op_key text; v_singleton jsonb; BEGIN v_pushdown_sql := NULL; v_residual_filter := NULL; -- Empty filter: nothing to push, nothing to filter. IF p_filter IS NULL OR p_filter = '{}'::jsonb THEN RETURN; END IF; IF jsonb_typeof(p_filter) <> 'object' THEN RAISE EXCEPTION 'pvt_split_filter: filter must be a JSON object (got %)', jsonb_typeof(p_filter); END IF; SELECT count(*) INTO key_count FROM jsonb_object_keys(p_filter); -- Detect logical operator at this node. SELECT key INTO v_op_key FROM jsonb_object_keys(p_filter) AS k(key) WHERE lower(k.key) IN ('$and', '$or', '$not'); -- A node is "logical" only when it is a singleton {$and|$or|$not: ...}. -- Mixing {$and: [...], "Age": 18} is legal in the outer parser -- (treated as implicit AND), so re-route those through the multi-key -- path below. IF v_op_key IS NOT NULL AND key_count = 1 THEN is_logical := true; END IF; -- ============================================================ -- 1) Logical singleton: $and / $or / $not -- ============================================================ IF is_logical THEN v := p_filter -> v_op_key; IF lower(v_op_key) = '$and' THEN IF jsonb_typeof(v) <> 'array' THEN RAISE EXCEPTION 'pvt_split_filter: $and expects an array'; END IF; FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP SELECT s.v_pushdown_sql, s.v_residual_filter INTO child_push, child_residual FROM pvt_split_filter(elem, p_fields) s; IF child_push IS NOT NULL THEN push_parts := push_parts || child_push; END IF; IF child_residual IS NOT NULL THEN residual_children := residual_children || jsonb_build_array(child_residual); END IF; END LOOP; IF array_length(push_parts, 1) IS NOT NULL THEN IF array_length(push_parts, 1) = 1 THEN v_pushdown_sql := push_parts[1]; ELSE v_pushdown_sql := '(' || array_to_string(push_parts, ' AND ') || ')'; END IF; END IF; IF jsonb_array_length(residual_children) > 0 THEN IF jsonb_array_length(residual_children) = 1 THEN v_residual_filter := residual_children -> 0; ELSE v_residual_filter := jsonb_build_object('$and', residual_children); END IF; END IF; RETURN; END IF; IF lower(v_op_key) = '$or' THEN IF jsonb_typeof(v) <> 'array' THEN RAISE EXCEPTION 'pvt_split_filter: $or expects an array'; END IF; -- Pushable only if EVERY child is fully base (residual=NULL). -- Otherwise the whole $or must stay in residual unchanged, -- else we would tighten the predicate inside the CTE. DECLARE all_pushable boolean := true; or_pushes text[] := ARRAY[]::text[]; BEGIN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP SELECT s.v_pushdown_sql, s.v_residual_filter INTO child_push, child_residual FROM pvt_split_filter(elem, p_fields) s; IF child_residual IS NOT NULL OR child_push IS NULL THEN all_pushable := false; EXIT; END IF; or_pushes := or_pushes || child_push; END LOOP; IF all_pushable AND array_length(or_pushes, 1) IS NOT NULL THEN v_pushdown_sql := '(' || array_to_string(or_pushes, ' OR ') || ')'; v_residual_filter := NULL; ELSE v_pushdown_sql := NULL; v_residual_filter := p_filter; END IF; END; RETURN; END IF; IF lower(v_op_key) = '$not' THEN SELECT s.v_pushdown_sql, s.v_residual_filter INTO child_push, child_residual FROM pvt_split_filter(v, p_fields) s; IF child_residual IS NULL AND child_push IS NOT NULL THEN v_pushdown_sql := 'NOT (' || child_push || ')'; v_residual_filter := NULL; ELSE v_pushdown_sql := NULL; v_residual_filter := p_filter; END IF; RETURN; END IF; END IF; -- ============================================================ -- 2) Multi-key object: implicit $and. Split each {k: v} singleton -- and reassemble. -- ============================================================ IF key_count > 1 THEN FOR k, v IN SELECT key, value FROM jsonb_each(p_filter) LOOP v_singleton := jsonb_build_object(k, v); SELECT s.v_pushdown_sql, s.v_residual_filter INTO child_push, child_residual FROM pvt_split_filter(v_singleton, p_fields) s; IF child_push IS NOT NULL THEN push_parts := push_parts || child_push; END IF; IF child_residual IS NOT NULL THEN residual_children := residual_children || jsonb_build_array(child_residual); END IF; END LOOP; IF array_length(push_parts, 1) IS NOT NULL THEN IF array_length(push_parts, 1) = 1 THEN v_pushdown_sql := push_parts[1]; ELSE v_pushdown_sql := '(' || array_to_string(push_parts, ' AND ') || ')'; END IF; END IF; IF jsonb_array_length(residual_children) > 0 THEN IF jsonb_array_length(residual_children) = 1 THEN v_residual_filter := residual_children -> 0; ELSE v_residual_filter := jsonb_build_object('$and', residual_children); END IF; END IF; RETURN; END IF; -- ============================================================ -- 3) Single-key leaf: either a hierarchical op or a field leaf. -- ============================================================ SELECT key, value INTO k, v FROM jsonb_each(p_filter); -- Hierarchical operators -> always pushable. Reuse legacy helper. -- The legacy helper returns conditions with a leading ` AND ` so -- they can be concatenated to a pre-existing WHERE; we strip it -- here so the caller controls AND-joining. IF lower(k) IN ('$hasancestor', '$hasdescendant', '$level', '$isroot', '$isleaf', '$childrenof') THEN v_pushdown_sql := pvt_build_hierarchical_conditions( jsonb_build_object(k, v), 'o'); IF v_pushdown_sql IS NOT NULL THEN v_pushdown_sql := regexp_replace(v_pushdown_sql, '^\s*AND\s+', ''); v_pushdown_sql := trim(v_pushdown_sql); IF v_pushdown_sql = '' THEN v_pushdown_sql := NULL; END IF; END IF; v_residual_filter := NULL; RETURN; END IF; -- Expression-form predicate ($eq/$ne/$lt/.../$between/$in/...). -- Pushable iff every $field referenced inside resolves to a base -- column; otherwise the whole node stays in residual unchanged. IF lower(k) IN ( '$eq', '$ne', '$lt', '$lte', '$gt', '$gte', '$like', '$ilike', '$in', '$nin', '$between', '$null', '$notnull', '$isnull', '$exists', '$contains', '$startswith', '$endswith', '$containsignorecase', '$startswithignorecase', '$endswithignorecase' ) THEN IF pvt_expr_is_base_only(v, p_fields) THEN v_pushdown_sql := pvt_build_expr_predicate(k, v, p_fields, 'o.'); v_residual_filter := NULL; ELSE v_pushdown_sql := NULL; v_residual_filter := p_filter; END IF; RETURN; END IF; -- Top-level $expr: arbitrary boolean expression. Pushable iff every -- $field reference inside resolves to a base column; otherwise the -- whole node stays in residual unchanged. IF lower(k) = '$expr' THEN IF pvt_expr_is_base_only(v, p_fields) THEN v_pushdown_sql := pvt_build_bool_expr(v, p_fields, 'o.'); v_residual_filter := NULL; ELSE v_pushdown_sql := NULL; v_residual_filter := p_filter; END IF; RETURN; END IF; -- Field leaf -> look up metadata; push only if kind = 'base'. v_peek := pvt_peek_contains_key_value(v); v_normalized := pvt_normalize_field_name(k, v_peek); v_meta := p_fields -> v_normalized; IF v_meta IS NULL THEN -- Unknown field: leave to the outer walker so its RAISE fires -- with the existing, descriptive error message. v_pushdown_sql := NULL; v_residual_filter := p_filter; RETURN; END IF; v_kind := v_meta->>'kind'; IF v_kind = 'base' THEN -- ContainsKey rewrites are dict-pivot only, never base. v_pushdown_sql := pvt_build_field_condition( v_normalized, v_meta, v, 'o.'); v_residual_filter := NULL; ELSE v_pushdown_sql := NULL; v_residual_filter := p_filter; END IF; END; $BODY$; COMMENT ON FUNCTION pvt_split_filter(jsonb, jsonb) IS 'Splits a filter tree into (pushdown_sql over _objects o, residual_filter for outer CTE WHERE). Conservative: $or/$not are pushed only when every leaf inside is a base/hierarchical predicate; mixed branches stay in residual unchanged so semantics never change.'; -- ===================================================================== -- pvt_filter_has_base_refs: scan a residual filter and report whether it -- references any base/hierarchical column. Used to gate WHERE pushdown -- into _pvt_cte (Pro-parity perf): when false, the residual is safe to -- evaluate inside the CTE wrapper that exposes only pivoted columns. -- ===================================================================== CREATE OR REPLACE FUNCTION pvt_filter_has_base_refs(p_filter jsonb, p_fields jsonb) RETURNS boolean LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; elem jsonb; v_norm text; v_meta jsonb; v_peek text; BEGIN IF p_filter IS NULL OR p_filter = '{}'::jsonb THEN RETURN false; END IF; IF jsonb_typeof(p_filter) <> 'object' THEN RETURN true; -- conservative END IF; FOR k, v IN SELECT key, value FROM jsonb_each(p_filter) LOOP IF lower(k) IN ('$hasancestor','$hasdescendant','$level','$isroot','$isleaf') THEN RETURN true; END IF; IF lower(k) IN ('$and','$or') THEN IF jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP IF pvt_filter_has_base_refs(elem, p_fields) THEN RETURN true; END IF; END LOOP; END IF; CONTINUE; END IF; IF lower(k) = '$not' THEN IF pvt_filter_has_base_refs(v, p_fields) THEN RETURN true; END IF; CONTINUE; END IF; IF left(k, 1) = '$' THEN -- $expr / expression-form ops: conservative -> true RETURN true; END IF; -- field leaf v_peek := pvt_peek_contains_key_value(v); v_norm := pvt_normalize_field_name(k, v_peek); v_meta := p_fields -> v_norm; IF v_meta IS NULL THEN RETURN true; -- conservative END IF; IF (v_meta->>'kind') = 'base' THEN RETURN true; END IF; END LOOP; RETURN false; END; $BODY$; COMMENT ON FUNCTION pvt_filter_has_base_refs(jsonb, jsonb) IS 'Returns true when the residual filter references any base column or hierarchical operator. Used to gate WHERE pushdown into the _pvt_cte wrapper (which projects only pivoted columns).'; Path: redb/redb.SQLite/sql/v2-pvt/17_pvt_expr.sql 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/v2-pvt/17_pvt_expr.sql ---- -- ===================================================================== -- 17_pvt_expr.sql -- --------------------------------------------------------------------- -- Expression engine for the free PVT pipeline. Implements arithmetic, -- string and Math.* style functions, parenthesized nesting and full -- expression-form predicates --- matching Pro's `WhereRedb` / -- `IRedbTreeQueryable` capability (Pro emits the same SQL by walking -- the LINQ AST via ExpressionToSqlCompiler; here we accept a JSON AST -- shaped 1:1 with that compiler's output). -- -- --------------------------------------------------------------------- -- Scalar expression grammar (returns a SQL fragment): -- -- { "$field": "" } -> "PathColumn" -- or 'o."_id"' under pushdown -- { "$const": } -> quoted literal -- { "$add": [a, b, ...] } -> (a + b + ...) -- { "$sub": [a, b] } -> (a - b) -- { "$mul": [a, b, ...] } -> (a * b * ...) -- { "$div": [a, b] } -> (a / b) -- { "$mod": [a, b] } -> (a % b) -- { "$neg": a } -> (-a) -- { "$abs": a } -> ABS(a) -- { "$round": [a, digits] } -> ROUND(a, digits) -- { "$floor": a } -> FLOOR(a) -- { "$ceil": a } -> CEIL(a) -- { "$min": [a, b, ...] } -> LEAST(a, b, ...) -- { "$max": [a, b, ...] } -> GREATEST(a, b, ...) -- { "$upper": a } -> UPPER(a) -- { "$lower": a } -> LOWER(a) -- { "$trim": a } -> TRIM(a) -- { "$length": a } -> LENGTH(a) (str) or -- COALESCE(array_length(a,1),0) -- { "$concat": [a, b, ...] } -> (a || b || ...) -- { "$coalesce":[a, b, ...] } -> COALESCE(a, b, ...) -- { "$cast": ["", a] } -> (a):: -- -- Expression-form predicate grammar (returns a SQL boolean fragment): -- -- { "$eq" | "$ne" | "$lt" | "$lte" | "$gt" | "$gte": -- [exprL, exprR] } -> (L op R) -- { "$like" | "$ilike": -- [exprL, exprR] } -> (L LIKE / ILIKE R) -- { "$contains" | "$startsWith" | "$endsWith": -- [exprL, "literal"] } -> sugar over LIKE -- { "$containsIgnoreCase" | "$startsWithIgnoreCase" | "$endsWithIgnoreCase": -- [exprL, "literal"] } -> sugar over ILIKE -- { "$in" | "$nin": -- [exprL, [v1, v2, ...]] } -> L [NOT] IN (...) -- { "$between": -- [exprL, low, high] } -> L BETWEEN low AND high -- { "$null" | "$notNull" | "$isNull": -- expr | true } -> expr IS [NOT] NULL -- -- Push-down classification: pvt_expr_is_base_only(node, fields) returns -- true iff every `$field` reference inside resolves to kind='base'. SQL -- functions and arithmetic are pushable by construction (they map 1:1 -- to PG operators). -- ===================================================================== -- ---------- pvt_expr_field_names -------------------------------------- -- Yield every `$field` reference inside a scalar expression node. -- Used by pvt_collect_fields so metadata is resolved for them. CREATE OR REPLACE FUNCTION pvt_expr_field_names(p_node jsonb) RETURNS SETOF text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; elem jsonb; BEGIN IF p_node IS NULL THEN RETURN; END IF; -- Array node (predicate args or n-ary operand list): walk each element. IF jsonb_typeof(p_node) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(p_node) LOOP RETURN QUERY SELECT pvt_expr_field_names(elem); END LOOP; RETURN; END IF; -- Scalar literal: nothing to harvest. IF jsonb_typeof(p_node) <> 'object' THEN RETURN; END IF; IF p_node ? '$field' THEN RETURN NEXT p_node->>'$field'; RETURN; END IF; IF p_node ? '$const' THEN RETURN; END IF; -- Generic recursion over every operand. FOR k, v IN SELECT key, value FROM jsonb_each(p_node) LOOP IF left(k, 1) <> '$' THEN CONTINUE; END IF; -- $case has named branches {when,then,else}: descend into values only. IF lower(k) = '$case' AND jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP IF jsonb_typeof(elem) = 'object' THEN IF elem ? 'when' THEN RETURN QUERY SELECT pvt_expr_field_names(elem->'when'); END IF; IF elem ? 'then' THEN RETURN QUERY SELECT pvt_expr_field_names(elem->'then'); END IF; IF elem ? 'else' THEN RETURN QUERY SELECT pvt_expr_field_names(elem->'else'); END IF; END IF; END LOOP; CONTINUE; END IF; -- $fts object form has `query` (expression) + `fields` array; -- `language` is a literal config name and must not be walked. IF lower(k) = '$fts' AND jsonb_typeof(v) = 'object' THEN IF v ? 'query' THEN RETURN QUERY SELECT pvt_expr_field_names(v->'query'); END IF; IF v ? 'fields' AND jsonb_typeof(v->'fields') = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v->'fields') LOOP RETURN QUERY SELECT pvt_expr_field_names(elem); END LOOP; END IF; CONTINUE; END IF; -- $cast: ["", expr] -- type literal must not be walked. IF lower(k) = '$cast' AND jsonb_typeof(v) = 'array' AND jsonb_array_length(v) >= 2 THEN RETURN QUERY SELECT pvt_expr_field_names(v->1); CONTINUE; END IF; -- Date helpers whose first array slot is a unit string literal. IF lower(k) IN ('$dateadd', '$datesub', '$datediff', '$datetrunc') AND jsonb_typeof(v) = 'array' AND jsonb_array_length(v) >= 1 THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) WITH ORDINALITY AS t(value, ord) WHERE ord >= 2 LOOP RETURN QUERY SELECT pvt_expr_field_names(elem); END LOOP; CONTINUE; END IF; IF jsonb_typeof(v) = 'array' THEN FOR elem IN SELECT value FROM jsonb_array_elements(v) LOOP RETURN QUERY SELECT pvt_expr_field_names(elem); END LOOP; ELSIF jsonb_typeof(v) = 'object' THEN RETURN QUERY SELECT pvt_expr_field_names(v); END IF; END LOOP; END; $BODY$; COMMENT ON FUNCTION pvt_expr_field_names(jsonb) IS 'Yields every "$field" path referenced inside a scalar expression node (recursive). Empty for $const / non-object nodes.'; -- ---------- pvt_expr_is_base_only ------------------------------------- -- Recursive check: every `$field` inside the node maps to a metadata -- entry with kind='base'. Used by the pushdown splitter to decide -- whether an expression predicate can move inside the pivot CTE. CREATE OR REPLACE FUNCTION pvt_expr_is_base_only( p_node jsonb, p_fields jsonb ) RETURNS boolean LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_name text; v_meta jsonb; BEGIN IF p_node IS NULL THEN RETURN true; END IF; FOR v_name IN SELECT pvt_expr_field_names(p_node) LOOP v_meta := p_fields -> v_name; IF v_meta IS NULL OR v_meta->>'kind' <> 'base' THEN RETURN false; END IF; END LOOP; RETURN true; END; $BODY$; COMMENT ON FUNCTION pvt_expr_is_base_only(jsonb, jsonb) IS 'True iff every $field inside the expression resolves (per pvt_collect_fields) to kind=base. Pushable predicates run inside the pivot CTE on _objects o.*.'; -- ---------- pvt_format_const ------------------------------------------ -- Convert a JSON scalar to a SQL literal. Strings are single-quoted -- with `''` escaping; booleans/null/numbers map natively. No casts: -- callers wrap with `$cast` when an explicit type is needed. CREATE OR REPLACE FUNCTION pvt_format_const(p_value jsonb) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $BODY$ DECLARE v_t text; BEGIN IF p_value IS NULL OR jsonb_typeof(p_value) = 'null' THEN RETURN 'NULL'; END IF; v_t := jsonb_typeof(p_value); IF v_t = 'string' THEN RETURN quote_literal(p_value #>> '{}'); END IF; IF v_t = 'number' THEN RETURN p_value::text; END IF; IF v_t = 'boolean' THEN RETURN p_value::text; END IF; -- Arrays and objects are not scalar literals. RAISE EXCEPTION 'pvt_format_const: unsupported JSON type % for scalar literal (use $const for scalars only)', v_t; END; $BODY$; -- ---------- pvt_build_scalar_expr ------------------------------------- -- Recursive scalar-expression compiler. Always wraps binary/unary -- results in parentheses so operator precedence is preserved through -- nesting. CREATE OR REPLACE FUNCTION pvt_build_scalar_expr( p_node jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_name text; v_meta jsonb; v_kind text; v_args jsonb; v_parts text[]; v_elem jsonb; v_op_key text; v_n integer; v_a text; v_b text; v_type text; BEGIN IF p_node IS NULL OR jsonb_typeof(p_node) = 'null' THEN RETURN 'NULL'; END IF; -- Bare JSON scalar / array literal: tolerate it as shorthand for -- $const (saves callers from wrapping every literal). IF jsonb_typeof(p_node) <> 'object' THEN IF jsonb_typeof(p_node) = 'array' THEN RAISE EXCEPTION 'pvt_build_scalar_expr: bare JSON array is not a scalar expression (wrap each element or use a list-aware operator like $in)'; END IF; RETURN pvt_format_const(p_node); END IF; -- ---------------- $field --------------------------------------- IF p_node ? '$field' THEN v_name := p_node->>'$field'; v_meta := p_fields -> v_name; IF v_meta IS NULL THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $field "%" has no metadata (did pvt_collect_fields miss it?)', v_name; END IF; v_kind := v_meta->>'kind'; IF v_kind = 'base' THEN RETURN p_base_prefix || quote_ident(v_meta->>'column'); END IF; RETURN quote_ident(v_name); END IF; -- ---------------- $const --------------------------------------- IF p_node ? '$const' THEN RETURN pvt_format_const(p_node->'$const'); END IF; -- Dispatch on the single $-key. SELECT key INTO v_op_key FROM jsonb_object_keys(p_node) AS t(key) WHERE left(key,1) = '$' LIMIT 1; IF v_op_key IS NULL THEN RAISE EXCEPTION 'pvt_build_scalar_expr: no operator key in node: %', p_node::text; END IF; v_args := p_node -> v_op_key; -- ---------------- Aggregate passthrough ------------------------ -- Aggregate expressions ($count/$sum/$avg/$min*/$max*/$string_agg/ -- $bool_and/$bool_or) appearing inside a scalar context delegate to -- pvt_build_agg_expr. This makes HAVING / ORDER BY / window args -- agg-aware without a separate compiler stack. PostgreSQL itself -- rejects aggregates in WHERE / GROUP BY so this is not a footgun. -- $min and $max overlap with n-ary LEAST/GREATEST helpers; the -- aggregate form is recognised only when the operand is a single -- non-array scalar-expression node (or "*"). LEAST/GREATEST callers -- always pass an array of >=1 operands. IF lower(v_op_key) IN ('$count', '$sum', '$avg', '$string_agg', '$bool_and', '$bool_or') OR (lower(v_op_key) IN ('$min', '$max') AND jsonb_typeof(v_args) <> 'array') THEN RETURN pvt_build_agg_expr(p_node, p_fields, p_base_prefix); END IF; -- ---------------- Window passthrough --------------------------- -- {"$over": } delegates to pvt_build_window_expr. -- PostgreSQL itself rejects window calls outside SELECT / ORDER BY. IF lower(v_op_key) = '$over' THEN RETURN pvt_build_window_expr(v_args, p_fields, p_base_prefix); END IF; -- N-ary helpers -------------------------------------------------- IF lower(v_op_key) IN ('$add', '$sub', '$mul', '$div', '$mod', '$concat', '$min', '$max', '$coalesce') THEN IF jsonb_typeof(v_args) <> 'array' THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % expects a JSON array of operands', v_op_key; END IF; v_n := jsonb_array_length(v_args); IF v_n < 1 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % expects at least 1 operand', v_op_key; END IF; IF lower(v_op_key) IN ('$sub', '$div', '$mod') AND v_n <> 2 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % expects exactly 2 operands (got %)', v_op_key, v_n; END IF; v_parts := ARRAY[]::text[]; FOR v_elem IN SELECT value FROM jsonb_array_elements(v_args) LOOP v_parts := v_parts || pvt_build_scalar_expr(v_elem, p_fields, p_base_prefix); END LOOP; IF lower(v_op_key) = '$add' THEN RETURN '(' || array_to_string(v_parts, ' + ') || ')'; END IF; IF lower(v_op_key) = '$sub' THEN RETURN '(' || v_parts[1] || ' - ' || v_parts[2] || ')'; END IF; IF lower(v_op_key) = '$mul' THEN RETURN '(' || array_to_string(v_parts, ' * ') || ')'; END IF; IF lower(v_op_key) = '$div' THEN RETURN '(' || v_parts[1] || ' / ' || v_parts[2] || ')'; END IF; IF lower(v_op_key) = '$mod' THEN RETURN '(' || v_parts[1] || ' % ' || v_parts[2] || ')'; END IF; IF lower(v_op_key) = '$concat' THEN RETURN '(' || array_to_string(v_parts, ' || ') || ')'; END IF; IF lower(v_op_key) = '$min' THEN RETURN 'LEAST(' || array_to_string(v_parts, ', ') || ')'; END IF; IF lower(v_op_key) = '$max' THEN RETURN 'GREATEST(' || array_to_string(v_parts, ', ') || ')'; END IF; IF lower(v_op_key) = '$coalesce' THEN RETURN 'COALESCE(' || array_to_string(v_parts, ', ') || ')'; END IF; END IF; -- Unary ----------------------------------------------------------- IF lower(v_op_key) IN ('$neg', '$abs', '$floor', '$ceil', '$upper', '$lower', '$trim', '$length') THEN -- Accept both { $op: expr } and { $op: [expr] } (array-wrapped -- form, which is how the C# compilers emit single-arg calls). IF jsonb_typeof(v_args) = 'array' THEN IF jsonb_array_length(v_args) <> 1 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % expects exactly 1 operand (got %)', v_op_key, jsonb_array_length(v_args); END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); ELSE v_a := pvt_build_scalar_expr(v_args, p_fields, p_base_prefix); END IF; IF lower(v_op_key) = '$neg' THEN RETURN '(-' || v_a || ')'; END IF; IF lower(v_op_key) = '$abs' THEN RETURN 'ABS(' || v_a || ')'; END IF; IF lower(v_op_key) = '$floor' THEN RETURN 'FLOOR(' || v_a || ')'; END IF; IF lower(v_op_key) = '$ceil' THEN RETURN 'CEIL(' || v_a || ')'; END IF; IF lower(v_op_key) = '$upper' THEN RETURN 'UPPER(' || v_a || ')'; END IF; IF lower(v_op_key) = '$lower' THEN RETURN 'LOWER(' || v_a || ')'; END IF; IF lower(v_op_key) = '$trim' THEN RETURN 'TRIM(' || v_a || ')'; END IF; IF lower(v_op_key) = '$length' THEN -- Polymorphic: array → array_length, otherwise → text length. -- We can't always know the type statically, so prefer the -- string form; callers wanting array-length should use the -- `.$length` legacy modifier on a registered array field. RETURN 'LENGTH(' || v_a || ')'; END IF; END IF; -- Round (2-arg) --------------------------------------------------- IF lower(v_op_key) = '$round' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) NOT IN (1, 2) THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $round expects [value] or [value, digits]'; END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); IF jsonb_array_length(v_args) = 1 THEN RETURN 'ROUND(' || v_a || ')'; END IF; v_b := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); RETURN 'ROUND(' || v_a || ', ' || v_b || ')'; END IF; -- $cast ----------------------------------------------------------- IF lower(v_op_key) = '$cast' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 2 OR jsonb_typeof(v_args->0) <> 'string' THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $cast expects ["", expr]'; END IF; v_type := v_args->>0; -- Whitelist SQL types to keep the surface area sane. IF v_type NOT IN ( 'text', 'varchar', 'bigint', 'integer', 'int', 'smallint', 'numeric', 'double precision', 'real', 'boolean', 'uuid', 'timestamptz', 'timestamp', 'date', 'bytea' ) THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $cast unsupported type "%"', v_type; END IF; v_a := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); RETURN '(' || v_a || ')::' || v_type; END IF; -- ---------------- Extended unary (Pro-parity + free extras) ----- -- Strings: $trimStart -> LTRIM, $trimEnd -> RTRIM -- Math: $sqrt, $sign, $exp, $ln (natural log) -- Dates: $year/$month/$day/$hour/$minute/$second -- $dayOfWeek/$dayOfYear (free extras over Pro) IF lower(v_op_key) IN ( '$trimstart', '$trimend', '$sqrt', '$sign', '$exp', '$ln', '$year', '$month', '$day', '$hour', '$minute', '$second', '$dayofweek', '$dayofyear' ) THEN IF jsonb_typeof(v_args) = 'array' THEN IF jsonb_array_length(v_args) <> 1 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % expects exactly 1 operand (got %)', v_op_key, jsonb_array_length(v_args); END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); ELSE v_a := pvt_build_scalar_expr(v_args, p_fields, p_base_prefix); END IF; IF lower(v_op_key) = '$trimstart' THEN RETURN 'LTRIM(' || v_a || ')'; END IF; IF lower(v_op_key) = '$trimend' THEN RETURN 'RTRIM(' || v_a || ')'; END IF; IF lower(v_op_key) = '$sqrt' THEN RETURN 'SQRT(' || v_a || ')'; END IF; IF lower(v_op_key) = '$sign' THEN RETURN 'SIGN(' || v_a || ')'; END IF; IF lower(v_op_key) = '$exp' THEN RETURN 'EXP(' || v_a || ')'; END IF; IF lower(v_op_key) = '$ln' THEN RETURN 'LN(' || v_a || ')'; END IF; IF lower(v_op_key) = '$year' THEN RETURN 'EXTRACT(YEAR FROM ' || v_a || ')'; END IF; IF lower(v_op_key) = '$month' THEN RETURN 'EXTRACT(MONTH FROM ' || v_a || ')'; END IF; IF lower(v_op_key) = '$day' THEN RETURN 'EXTRACT(DAY FROM ' || v_a || ')'; END IF; IF lower(v_op_key) = '$hour' THEN RETURN 'EXTRACT(HOUR FROM ' || v_a || ')'; END IF; IF lower(v_op_key) = '$minute' THEN RETURN 'EXTRACT(MINUTE FROM ' || v_a || ')'; END IF; IF lower(v_op_key) = '$second' THEN RETURN 'EXTRACT(SECOND FROM ' || v_a || ')'; END IF; IF lower(v_op_key) = '$dayofweek' THEN RETURN 'EXTRACT(DOW FROM ' || v_a || ')'; END IF; IF lower(v_op_key) = '$dayofyear' THEN RETURN 'EXTRACT(DOY FROM ' || v_a || ')'; END IF; END IF; -- ---------------- $power (2-arg) ------------------------------- IF lower(v_op_key) = '$power' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 2 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $power expects [base, exponent]'; END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); v_b := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); RETURN 'POWER(' || v_a || ', ' || v_b || ')'; END IF; -- ---------------- $log (2-arg: base, value) -------------------- IF lower(v_op_key) = '$log' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 2 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $log expects [base, value]'; END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); v_b := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); RETURN 'LOG(' || v_a || ', ' || v_b || ')'; END IF; -- ---------------- $substring (2 or 3 args) --------------------- -- $substring: [str, start] -> SUBSTRING(str FROM start) -- $substring: [str, start, length] -> SUBSTRING(str FROM start FOR length) -- Note: PostgreSQL SUBSTRING is 1-based; callers translating from -- C#'s 0-based String.Substring must add 1 in the AST. IF lower(v_op_key) = '$substring' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) NOT IN (2, 3) THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $substring expects [str, start] or [str, start, length]'; END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); v_b := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); IF jsonb_array_length(v_args) = 2 THEN RETURN 'SUBSTRING(' || v_a || ' FROM ' || v_b || ')'; END IF; DECLARE v_c text := pvt_build_scalar_expr(v_args->2, p_fields, p_base_prefix); BEGIN RETURN 'SUBSTRING(' || v_a || ' FROM ' || v_b || ' FOR ' || v_c || ')'; END; END IF; -- ---------------- $replace (3-arg) ----------------------------- IF lower(v_op_key) = '$replace' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 3 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $replace expects [str, find, replaceWith]'; END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); DECLARE v_find text := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); v_replace text := pvt_build_scalar_expr(v_args->2, p_fields, p_base_prefix); BEGIN RETURN 'REPLACE(' || v_a || ', ' || v_find || ', ' || v_replace || ')'; END; END IF; -- ---------------- $indexOf (2-arg) ----------------------------- -- Returns 1-based position; 0 when not found (Postgres POSITION). -- For C#'s 0-based IndexOf, subtract 1 in the caller AST. IF lower(v_op_key) = '$indexof' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 2 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $indexOf expects [str, needle]'; END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); v_b := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); RETURN 'POSITION(' || v_b || ' IN ' || v_a || ')'; END IF; -- ---------------- $padLeft / $padRight (2 or 3-arg) ------------ IF lower(v_op_key) IN ('$padleft', '$padright') THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) NOT IN (2, 3) THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % expects [str, length] or [str, length, padChar]', v_op_key; END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); v_b := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); DECLARE v_kw text := CASE WHEN lower(v_op_key) = '$padleft' THEN 'LPAD' ELSE 'RPAD' END; -- PG LPAD/RPAD truncate when target length < input length, while -- C# PadLeft/PadRight are no-op in that case. Use GREATEST() so we -- never request a width smaller than the input string. v_len text := 'GREATEST(length(' || v_a || '), ' || v_b || ')'; BEGIN IF jsonb_array_length(v_args) = 2 THEN RETURN v_kw || '(' || v_a || ', ' || v_len || ')'; END IF; RETURN v_kw || '(' || v_a || ', ' || v_len || ', ' || pvt_build_scalar_expr(v_args->2, p_fields, p_base_prefix) || ')'; END; END IF; -- ---------------- $dateAdd / $dateSub (3-arg) ------------------ -- $dateAdd: ["day"|"month"|..., , ] -- Emits: + ( * INTERVAL '1 day') IF lower(v_op_key) IN ('$dateadd', '$datesub') THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 3 OR jsonb_typeof(v_args->0) <> 'string' THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % expects ["", date_expr, int_expr]', v_op_key; END IF; DECLARE v_unit text := lower(v_args->>0); v_op text := CASE WHEN lower(v_op_key) = '$dateadd' THEN ' + ' ELSE ' - ' END; BEGIN IF v_unit NOT IN ('year','month','week','day','hour','minute','second','millisecond') THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % unsupported unit "%"', v_op_key, v_unit; END IF; v_a := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); v_b := pvt_build_scalar_expr(v_args->2, p_fields, p_base_prefix); RETURN '(' || v_a || v_op || '(' || v_b || ' * INTERVAL ''1 ' || v_unit || '''))'; END; END IF; -- ---------------- $dateDiff (3-arg) ---------------------------- -- $dateDiff: ["", a, b] -> integer count of from b to a. -- Implemented via EXTRACT(EPOCH ...) for sub-day units and AGE for -- year/month so calendar arithmetic is preserved. IF lower(v_op_key) = '$datediff' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 3 OR jsonb_typeof(v_args->0) <> 'string' THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $dateDiff expects ["", a, b]'; END IF; DECLARE v_unit text := lower(v_args->>0); BEGIN v_a := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); v_b := pvt_build_scalar_expr(v_args->2, p_fields, p_base_prefix); IF v_unit IN ('second','millisecond','minute','hour','day','week') THEN DECLARE v_divisor text := CASE v_unit WHEN 'millisecond' THEN '0.001' WHEN 'second' THEN '1' WHEN 'minute' THEN '60' WHEN 'hour' THEN '3600' WHEN 'day' THEN '86400' WHEN 'week' THEN '604800' END; BEGIN RETURN '(EXTRACT(EPOCH FROM (' || v_a || ' - ' || v_b || ')) / ' || v_divisor || ')::bigint'; END; ELSIF v_unit = 'month' THEN RETURN '((EXTRACT(YEAR FROM AGE(' || v_a || ', ' || v_b || ')) * 12' || ' + EXTRACT(MONTH FROM AGE(' || v_a || ', ' || v_b || '))))'; ELSIF v_unit = 'year' THEN RETURN 'EXTRACT(YEAR FROM AGE(' || v_a || ', ' || v_b || '))'; END IF; RAISE EXCEPTION 'pvt_build_scalar_expr: $dateDiff unsupported unit "%"', v_unit; END; END IF; -- ---------------- $if (3-arg: cond, then, else) ---------------- -- cond is a boolean expression node compiled via pvt_build_bool_expr. IF lower(v_op_key) = '$if' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 3 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $if expects [cond, then, else]'; END IF; DECLARE v_cond text := pvt_build_bool_expr(v_args->0, p_fields, p_base_prefix); v_then text := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); v_else text := pvt_build_scalar_expr(v_args->2, p_fields, p_base_prefix); BEGIN RETURN '(CASE WHEN ' || v_cond || ' THEN ' || v_then || ' ELSE ' || v_else || ' END)'; END; END IF; -- ---------------- $case ---------------------------------------- -- $case: [ {"when": , "then": }, ..., {"else": }? ] -- The trailing else entry is optional; when absent NULL is used. IF lower(v_op_key) = '$case' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) = 0 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $case expects a non-empty array of {when,then} / {else} entries'; END IF; DECLARE v_sb text := '(CASE'; v_entry jsonb; v_else text := 'NULL'; v_seen_else boolean := false; BEGIN FOR v_entry IN SELECT value FROM jsonb_array_elements(v_args) LOOP IF v_entry ? 'else' THEN IF v_seen_else THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $case has multiple else entries'; END IF; v_else := pvt_build_scalar_expr(v_entry->'else', p_fields, p_base_prefix); v_seen_else := true; ELSIF v_entry ? 'when' AND v_entry ? 'then' THEN v_sb := v_sb || ' WHEN ' || pvt_build_bool_expr(v_entry->'when', p_fields, p_base_prefix) || ' THEN ' || pvt_build_scalar_expr(v_entry->'then', p_fields, p_base_prefix); ELSE RAISE EXCEPTION 'pvt_build_scalar_expr: $case entry must be {when,then} or {else} (got %)', v_entry::text; END IF; END LOOP; RETURN v_sb || ' ELSE ' || v_else || ' END)'; END; END IF; -- ---------------- Trigonometry / log10 (unary) ----------------- IF lower(v_op_key) IN ('$sin', '$cos', '$tan', '$asin', '$acos', '$atan', '$log10') THEN IF jsonb_typeof(v_args) = 'array' THEN IF jsonb_array_length(v_args) <> 1 THEN RAISE EXCEPTION 'pvt_build_scalar_expr: % expects exactly 1 operand (got %)', v_op_key, jsonb_array_length(v_args); END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); ELSE v_a := pvt_build_scalar_expr(v_args, p_fields, p_base_prefix); END IF; IF lower(v_op_key) = '$sin' THEN RETURN 'SIN(' || v_a || ')'; END IF; IF lower(v_op_key) = '$cos' THEN RETURN 'COS(' || v_a || ')'; END IF; IF lower(v_op_key) = '$tan' THEN RETURN 'TAN(' || v_a || ')'; END IF; IF lower(v_op_key) = '$asin' THEN RETURN 'ASIN(' || v_a || ')'; END IF; IF lower(v_op_key) = '$acos' THEN RETURN 'ACOS(' || v_a || ')'; END IF; IF lower(v_op_key) = '$atan' THEN RETURN 'ATAN(' || v_a || ')'; END IF; IF lower(v_op_key) = '$log10' THEN RETURN 'LOG(' || v_a || ')'; END IF; END IF; -- ---------------- $now / $today (zero-arg) --------------------- -- Shape: {"$now": null}, {"$now": []}, {"$today": []}. IF lower(v_op_key) IN ('$now', '$today', '$utcnow') THEN IF lower(v_op_key) = '$now' THEN RETURN 'NOW()'; END IF; IF lower(v_op_key) = '$utcnow' THEN RETURN '(NOW() AT TIME ZONE ''UTC'')'; END IF; IF lower(v_op_key) = '$today' THEN RETURN 'CURRENT_DATE'; END IF; END IF; -- ---------------- $dateTrunc(["", expr]) ----------------- -- Emits DATE_TRUNC('', expr). IF lower(v_op_key) = '$datetrunc' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) <> 2 OR jsonb_typeof(v_args->0) <> 'string' THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $dateTrunc expects ["", date_expr]'; END IF; DECLARE v_unit text := lower(v_args->>0); BEGIN IF v_unit NOT IN ( 'microseconds','milliseconds','second','minute','hour', 'day','week','month','quarter','year','decade','century','millennium' ) THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $dateTrunc unsupported unit "%"', v_unit; END IF; v_a := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); RETURN 'DATE_TRUNC(' || quote_literal(v_unit) || ', ' || v_a || ')'; END; END IF; -- ---------------- $regexReplace([str, pat, repl, flags?]) ------ IF lower(v_op_key) = '$regexreplace' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) NOT IN (3, 4) THEN RAISE EXCEPTION 'pvt_build_scalar_expr: $regexReplace expects [str, pattern, replacement] or [str, pattern, replacement, flags]'; END IF; v_a := pvt_build_scalar_expr(v_args->0, p_fields, p_base_prefix); DECLARE v_pat text := pvt_build_scalar_expr(v_args->1, p_fields, p_base_prefix); v_repl text := pvt_build_scalar_expr(v_args->2, p_fields, p_base_prefix); BEGIN IF jsonb_array_length(v_args) = 3 THEN RETURN 'REGEXP_REPLACE(' || v_a || ', ' || v_pat || ', ' || v_repl || ')'; END IF; RETURN 'REGEXP_REPLACE(' || v_a || ', ' || v_pat || ', ' || v_repl || ', ' || pvt_build_scalar_expr(v_args->3, p_fields, p_base_prefix) || ')'; END; END IF; RAISE EXCEPTION 'pvt_build_scalar_expr: unsupported operator "%"', v_op_key; END; $BODY$; COMMENT ON FUNCTION pvt_build_scalar_expr(jsonb, jsonb, text) IS 'Compiles a JSON scalar-expression AST into a SQL fragment. Supports field/const, full arithmetic (+ - * / %), math (abs/round/floor/ceil/min/max), string (upper/lower/trim/length/concat), coalesce and cast. Recursive: every binary node wraps in parens so precedence is preserved.'; -- ---------- pvt_build_expr_predicate ---------------------------------- -- Compiles an expression-form predicate (key = $op, value = arguments) -- into a SQL boolean fragment. CREATE OR REPLACE FUNCTION pvt_build_expr_predicate( p_op text, p_args jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_op text := lower(p_op); v_n integer; v_l text; v_r text; v_lo text; v_hi text; v_parts text[]; v_elem jsonb; v_pat text; BEGIN -- Unary: $null / $notNull / $isNull / $exists IF v_op IN ('$null', '$notnull', '$isnull', '$exists') THEN -- Value may be the expression itself, or a boolean toggle -- ({"$null": true} is only legal in shorthand form, not here). v_l := pvt_build_scalar_expr(p_args, p_fields, p_base_prefix); IF v_op IN ('$null', '$isnull') THEN RETURN v_l || ' IS NULL'; END IF; IF v_op = '$notnull' THEN RETURN v_l || ' IS NOT NULL'; END IF; IF v_op = '$exists' THEN RETURN v_l || ' IS NOT NULL'; END IF; END IF; -- $between [L, lo, hi] IF v_op = '$between' THEN IF jsonb_typeof(p_args) <> 'array' OR jsonb_array_length(p_args) <> 3 THEN RAISE EXCEPTION 'pvt_build_expr_predicate: $between expects [expr, low, high]'; END IF; v_l := pvt_build_scalar_expr(p_args->0, p_fields, p_base_prefix); v_lo := pvt_build_scalar_expr(p_args->1, p_fields, p_base_prefix); v_hi := pvt_build_scalar_expr(p_args->2, p_fields, p_base_prefix); RETURN '(' || v_l || ' BETWEEN ' || v_lo || ' AND ' || v_hi || ')'; END IF; -- $in / $nin [L, [v1, v2, ...]] IF v_op IN ('$in', '$nin') THEN IF jsonb_typeof(p_args) <> 'array' OR jsonb_array_length(p_args) <> 2 THEN RAISE EXCEPTION 'pvt_build_expr_predicate: % expects [expr, [v1, v2, ...]]', p_op; END IF; v_l := pvt_build_scalar_expr(p_args->0, p_fields, p_base_prefix); IF jsonb_typeof(p_args->1) <> 'array' THEN RAISE EXCEPTION 'pvt_build_expr_predicate: % RHS must be a JSON array of literals', p_op; END IF; IF jsonb_array_length(p_args->1) = 0 THEN RETURN CASE WHEN v_op = '$in' THEN 'FALSE' ELSE 'TRUE' END; END IF; v_parts := ARRAY[]::text[]; FOR v_elem IN SELECT value FROM jsonb_array_elements(p_args->1) LOOP v_parts := v_parts || pvt_format_const(v_elem); END LOOP; IF v_op = '$in' THEN RETURN '(' || v_l || ' IN (' || array_to_string(v_parts, ', ') || '))'; END IF; IF v_op = '$nin' THEN RETURN '(' || v_l || ' NOT IN (' || array_to_string(v_parts, ', ') || '))'; END IF; END IF; -- ---------------- $fts (full-text search) ---------------------- -- Shape A: {"$fts": [, , , ...]} -- (lang defaults to 'simple') -- Shape B: {"$fts": {"query": , "fields": [, ...], -- "language": "english"|"simple"|"russian"|...}} -- Emits: ((to_tsvector(L, F1) || to_tsvector(L, F2) || ...) -- @@ websearch_to_tsquery(L, Q)) IF v_op = '$fts' THEN DECLARE v_lang text := 'simple'; v_query text; v_fields jsonb; v_vec text; BEGIN IF jsonb_typeof(p_args) = 'array' THEN IF jsonb_array_length(p_args) < 2 THEN RAISE EXCEPTION 'pvt_build_expr_predicate: $fts array form expects [query, field, ...] (>=2 elements)'; END IF; v_query := pvt_build_scalar_expr(p_args->0, p_fields, p_base_prefix); v_fields := jsonb_path_query_array(p_args, '$[1 to last]'); ELSIF jsonb_typeof(p_args) = 'object' THEN IF NOT (p_args ? 'query') OR NOT (p_args ? 'fields') THEN RAISE EXCEPTION 'pvt_build_expr_predicate: $fts object form expects {"query":..., "fields":[...], "language"?}'; END IF; v_query := pvt_build_scalar_expr(p_args->'query', p_fields, p_base_prefix); IF jsonb_typeof(p_args->'fields') <> 'array' OR jsonb_array_length(p_args->'fields') = 0 THEN RAISE EXCEPTION 'pvt_build_expr_predicate: $fts "fields" must be a non-empty array'; END IF; v_fields := p_args->'fields'; IF p_args ? 'language' THEN IF jsonb_typeof(p_args->'language') <> 'string' THEN RAISE EXCEPTION 'pvt_build_expr_predicate: $fts "language" must be a string'; END IF; v_lang := lower(p_args->>'language'); END IF; ELSE RAISE EXCEPTION 'pvt_build_expr_predicate: $fts expects array or object form'; END IF; v_parts := ARRAY[]::text[]; FOR v_elem IN SELECT value FROM jsonb_array_elements(v_fields) LOOP v_parts := v_parts || ('to_tsvector(' || quote_literal(v_lang) || ', COALESCE(' || pvt_build_scalar_expr(v_elem, p_fields, p_base_prefix) || '::text, ''''))'); END LOOP; IF array_length(v_parts, 1) = 1 THEN v_vec := v_parts[1]; ELSE v_vec := '(' || array_to_string(v_parts, ' || ') || ')'; END IF; RETURN '(' || v_vec || ' @@ websearch_to_tsquery(' || quote_literal(v_lang) || ', ' || v_query || '))'; END; END IF; -- Binary infix / LIKE family ------------------------------------- IF jsonb_typeof(p_args) <> 'array' OR jsonb_array_length(p_args) <> 2 THEN RAISE EXCEPTION 'pvt_build_expr_predicate: % expects [exprL, exprR]', p_op; END IF; v_l := pvt_build_scalar_expr(p_args->0, p_fields, p_base_prefix); v_r := pvt_build_scalar_expr(p_args->1, p_fields, p_base_prefix); IF v_op = '$eq' THEN RETURN '(' || v_l || ' = ' || v_r || ')'; END IF; IF v_op = '$ne' THEN RETURN '(' || v_l || ' <> ' || v_r || ')'; END IF; IF v_op = '$lt' THEN RETURN '(' || v_l || ' < ' || v_r || ')'; END IF; IF v_op = '$lte' THEN RETURN '(' || v_l || ' <= ' || v_r || ')'; END IF; IF v_op = '$gt' THEN RETURN '(' || v_l || ' > ' || v_r || ')'; END IF; IF v_op = '$gte' THEN RETURN '(' || v_l || ' >= ' || v_r || ')'; END IF; IF v_op IN ('$like', '$ilike') THEN RETURN '(' || v_l || CASE WHEN v_op = '$like' THEN ' LIKE ' ELSE ' ILIKE ' END || v_r || ')'; END IF; -- Sugar over LIKE/ILIKE: RHS must be a string literal so we can -- splice the wildcards. Accept $const-wrapped or bare-string form. IF v_op IN ('$contains', '$startswith', '$endswith', '$containsignorecase', '$startswithignorecase', '$endswithignorecase') THEN IF jsonb_typeof(p_args->1) = 'object' AND (p_args->1) ? '$const' THEN v_pat := (p_args->1)->>'$const'; ELSIF jsonb_typeof(p_args->1) = 'string' THEN v_pat := p_args->1 #>> '{}'; ELSE RAISE EXCEPTION 'pvt_build_expr_predicate: % RHS must be a string literal (got %)', p_op, jsonb_typeof(p_args->1); END IF; DECLARE v_lit text; v_kw text; BEGIN v_kw := CASE WHEN right(v_op, length('ignorecase')) = 'ignorecase' THEN ' ILIKE ' ELSE ' LIKE ' END; v_lit := CASE WHEN v_op IN ('$contains', '$containsignorecase') THEN quote_literal('%' || v_pat || '%') WHEN v_op IN ('$startswith', '$startswithignorecase') THEN quote_literal(v_pat || '%') WHEN v_op IN ('$endswith', '$endswithignorecase') THEN quote_literal('%' || v_pat) END; RETURN '(' || v_l || v_kw || v_lit || ')'; END; END IF; -- ---------------- $regex / $iregex / $notregex / $inotregex ---- -- Shape: {"$regex": [strExpr, patternStringOrConst]} (PG POSIX regex). IF v_op IN ('$regex', '$iregex', '$notregex', '$inotregex') THEN IF jsonb_typeof(p_args) <> 'array' OR jsonb_array_length(p_args) <> 2 THEN RAISE EXCEPTION 'pvt_build_expr_predicate: % expects [expr, pattern]', p_op; END IF; v_l := pvt_build_scalar_expr(p_args->0, p_fields, p_base_prefix); v_r := pvt_build_scalar_expr(p_args->1, p_fields, p_base_prefix); DECLARE v_op_sql text := CASE v_op WHEN '$regex' THEN ' ~ ' WHEN '$iregex' THEN ' ~* ' WHEN '$notregex' THEN ' !~ ' WHEN '$inotregex' THEN ' !~* ' END; BEGIN RETURN '(' || v_l || v_op_sql || v_r || ')'; END; END IF; RAISE EXCEPTION 'pvt_build_expr_predicate: unsupported predicate "%"', p_op; END; $BODY$; COMMENT ON FUNCTION pvt_build_expr_predicate(text, jsonb, jsonb, text) IS 'Compiles an expression-form predicate (key = $eq/$ne/$lt/$gt/$like/$in/$between/...) into a SQL boolean fragment. LHS and RHS are full pvt_build_scalar_expr expressions; LIKE-family operators expect a string literal on RHS so wildcards can be spliced.'; -- ---------- pvt_build_bool_expr --------------------------------------- -- Boolean-expression compiler used by $if / $case scalar nodes (and by -- HAVING/window-FILTER builders). The node is either: -- * { "$and": [, ...] } / { "$or": [, ...] } -- * { "$not": } -- * { "": } (delegates to pvt_build_expr_predicate) -- Bare booleans `true`/`false` map to SQL TRUE/FALSE literals. CREATE OR REPLACE FUNCTION pvt_build_bool_expr( p_node jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_op text; v_args jsonb; v_elem jsonb; v_parts text[]; BEGIN IF p_node IS NULL OR jsonb_typeof(p_node) = 'null' THEN RETURN 'TRUE'; END IF; IF jsonb_typeof(p_node) = 'boolean' THEN RETURN CASE WHEN (p_node)::text = 'true' THEN 'TRUE' ELSE 'FALSE' END; END IF; IF jsonb_typeof(p_node) <> 'object' THEN RAISE EXCEPTION 'pvt_build_bool_expr: bool node must be object/boolean (got %)', jsonb_typeof(p_node); END IF; SELECT key INTO v_op FROM jsonb_object_keys(p_node) AS t(key) WHERE left(key, 1) = '$' LIMIT 1; IF v_op IS NULL THEN RAISE EXCEPTION 'pvt_build_bool_expr: bool node has no operator key: %', p_node::text; END IF; v_args := p_node -> v_op; IF lower(v_op) = '$and' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) = 0 THEN RAISE EXCEPTION '$and expects a non-empty array'; END IF; v_parts := ARRAY[]::text[]; FOR v_elem IN SELECT value FROM jsonb_array_elements(v_args) LOOP v_parts := v_parts || pvt_build_bool_expr(v_elem, p_fields, p_base_prefix); END LOOP; RETURN '(' || array_to_string(v_parts, ' AND ') || ')'; END IF; IF lower(v_op) = '$or' THEN IF jsonb_typeof(v_args) <> 'array' OR jsonb_array_length(v_args) = 0 THEN RAISE EXCEPTION '$or expects a non-empty array'; END IF; v_parts := ARRAY[]::text[]; FOR v_elem IN SELECT value FROM jsonb_array_elements(v_args) LOOP v_parts := v_parts || pvt_build_bool_expr(v_elem, p_fields, p_base_prefix); END LOOP; RETURN '(' || array_to_string(v_parts, ' OR ') || ')'; END IF; IF lower(v_op) = '$not' THEN RETURN 'NOT (' || pvt_build_bool_expr(v_args, p_fields, p_base_prefix) || ')'; END IF; RETURN pvt_build_expr_predicate(v_op, v_args, p_fields, p_base_prefix); END; $BODY$; COMMENT ON FUNCTION pvt_build_bool_expr(jsonb, jsonb, text) IS 'Compiles a boolean expression node (with $and/$or/$not support) into a SQL boolean fragment. Leaf operators delegate to pvt_build_expr_predicate. Used by $if/$case scalar forms and by HAVING/window-FILTER builders.'; Path: redb/redb.SQLite/sql/v2-pvt/19_pvt_agg_expr.sql 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/v2-pvt/19_pvt_agg_expr.sql ---- -- ===================================================================== -- 19_pvt_agg_expr.sql -- --------------------------------------------------------------------- -- Aggregate-expression compiler used by terminal aggregations (21), -- GROUP BY projections / HAVING (22) and window aggregate flavours (23). -- A single aggregate entry has the shape: -- -- { -- "alias": "", -- "$": "*" | , -- "distinct": true | false, -- optional, default false -- "filter": -- optional, emits FILTER (WHERE ...) -- } -- -- Where `` is one of: count / sum / avg / min / max / string_agg / -- bool_and / bool_or. -- -- `string_agg` requires a 2-element scalar-expr array `[value, separator]` -- because Postgres demands a separator argument. -- -- Free extras over Pro (which only knows COUNT/SUM/AVG/MIN/MAX without -- DISTINCT, without FILTER, and without string_agg): -- * `distinct: true` -> COUNT(DISTINCT expr) etc. -- * `filter: ` -> COUNT(...) FILTER (WHERE ...) (per-aggregate -- conditional aggregation; HAVING-of-one-aggregate) -- * string_agg / bool_and / bool_or -- -- All entries return text fragments without the `AS ""` suffix; -- callers append aliasing themselves so the same compiler is reusable -- inside HAVING / OVER / nested expressions. -- ===================================================================== -- ---------- pvt_agg_entry_field_names --------------------------------- -- Yield every field path referenced inside an aggregate entry. Used by -- pvt_collect_fields callers (orchestrators of 21/22/23 wrap each entry -- as `{"$expr": }` and rely on this helper to -- enumerate field refs in $ operand + filter). CREATE OR REPLACE FUNCTION pvt_agg_entry_field_names(p_entry jsonb) RETURNS SETOF text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE k text; v jsonb; BEGIN IF p_entry IS NULL OR jsonb_typeof(p_entry) <> 'object' THEN RETURN; END IF; FOR k, v IN SELECT key, value FROM jsonb_each(p_entry) LOOP IF k IN ('alias', 'distinct') THEN CONTINUE; END IF; IF k = 'filter' THEN RETURN QUERY SELECT pvt_expr_field_names(v); CONTINUE; END IF; IF left(k, 1) <> '$' THEN CONTINUE; END IF; -- $ operand: bare "*" yields nothing; otherwise full expr walk. IF jsonb_typeof(v) = 'string' AND (v #>> '{}') = '*' THEN CONTINUE; END IF; RETURN QUERY SELECT pvt_expr_field_names(v); END LOOP; END; $BODY$; -- ---------- pvt_build_agg_expr ---------------------------------------- -- Compile a single aggregate entry into a SQL fragment (without alias). -- Validates exactly one $ key per entry and dispatches by name. CREATE OR REPLACE FUNCTION pvt_build_agg_expr( p_entry jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_op text; v_arg jsonb; v_distinct boolean := false; v_filter jsonb; v_inner text; v_func text; v_filt_sql text := ''; v_keys int; v_args jsonb; v_elem jsonb; v_sep text; v_fld_name text; v_fld_meta jsonb; v_is_array boolean := false; v_col_expr text; BEGIN IF p_entry IS NULL OR jsonb_typeof(p_entry) <> 'object' THEN RAISE EXCEPTION 'pvt_build_agg_expr: entry must be a JSON object'; END IF; -- Pick the single $-key inside the entry (alias/distinct/filter -- are sidecars, not operators). SELECT key INTO v_op FROM jsonb_object_keys(p_entry) AS t(key) WHERE left(key, 1) = '$' LIMIT 1; IF v_op IS NULL THEN RAISE EXCEPTION 'pvt_build_agg_expr: entry has no $ key: %', p_entry::text; END IF; -- Sanity: no more than one $-key per entry. SELECT count(*) INTO v_keys FROM jsonb_object_keys(p_entry) AS t(key) WHERE left(key, 1) = '$'; IF v_keys > 1 THEN RAISE EXCEPTION 'pvt_build_agg_expr: entry has multiple $ keys (%): %', v_keys, p_entry::text; END IF; v_arg := p_entry -> v_op; IF p_entry ? 'distinct' AND jsonb_typeof(p_entry->'distinct') = 'boolean' THEN v_distinct := (p_entry->>'distinct')::boolean; END IF; IF p_entry ? 'filter' THEN v_filter := p_entry->'filter'; v_filt_sql := ' FILTER (WHERE ' || pvt_build_bool_expr(v_filter, p_fields, p_base_prefix) || ')'; END IF; -- ---------------- COUNT ---------------------------------------- IF lower(v_op) = '$count' THEN -- "*" shorthand for COUNT(*) - DISTINCT meaningless here. IF jsonb_typeof(v_arg) = 'string' AND (v_arg #>> '{}') = '*' THEN IF v_distinct THEN RAISE EXCEPTION 'pvt_build_agg_expr: $count "*" with distinct=true is not allowed'; END IF; RETURN 'COUNT(*)' || v_filt_sql; END IF; -- Detect array-typed $field operand (e.g. {"$count":{"$field":"SkillLevels[]"}}) -- and route through per-row unnest so $count returns total element count -- across all rows (rows × array_length), matching Pro semantics. v_is_array := false; IF jsonb_typeof(v_arg) = 'object' AND v_arg ? '$field' THEN v_fld_name := v_arg->>'$field'; v_fld_meta := p_fields -> v_fld_name; IF v_fld_meta IS NOT NULL AND COALESCE((v_fld_meta->>'is_array')::boolean, false) AND COALESCE(v_fld_meta->>'kind','') <> 'base' THEN v_is_array := true; END IF; END IF; IF v_is_array THEN IF v_distinct THEN RAISE EXCEPTION 'pvt_build_agg_expr: distinct=true is not supported for $count over array field "%"', v_fld_name; END IF; v_col_expr := pvt_build_scalar_expr(v_arg, p_fields, p_base_prefix); -- COUNT over unnested elements = SUM(per-row element count). -- COALESCE handles empty/NULL array (array_length returns NULL). RETURN 'SUM(COALESCE(array_length(' || v_col_expr || ', 1), 0))::bigint' || v_filt_sql; END IF; v_inner := pvt_build_scalar_expr(v_arg, p_fields, p_base_prefix); RETURN 'COUNT(' || CASE WHEN v_distinct THEN 'DISTINCT ' ELSE '' END || v_inner || ')' || v_filt_sql; END IF; -- ---------------- SUM / AVG / MIN / MAX ------------------------ IF lower(v_op) IN ('$sum', '$avg', '$min', '$max') THEN v_func := CASE lower(v_op) WHEN '$sum' THEN 'SUM' WHEN '$avg' THEN 'AVG' WHEN '$min' THEN 'MIN' WHEN '$max' THEN 'MAX' END; -- Detect array-typed $field operand (e.g. {"$sum":{"$field":"SkillLevels[]"}}) -- and route through per-row unnest so PG can aggregate element values -- instead of failing with "function sum([]) does not exist". v_is_array := false; IF jsonb_typeof(v_arg) = 'object' AND v_arg ? '$field' THEN v_fld_name := v_arg->>'$field'; v_fld_meta := p_fields -> v_fld_name; IF v_fld_meta IS NOT NULL AND COALESCE((v_fld_meta->>'is_array')::boolean, false) AND COALESCE(v_fld_meta->>'kind','') <> 'base' THEN v_is_array := true; END IF; END IF; IF v_is_array THEN IF v_distinct THEN RAISE EXCEPTION 'pvt_build_agg_expr: distinct=true is not supported for aggregate over array field "%"', v_fld_name; END IF; v_col_expr := pvt_build_scalar_expr(v_arg, p_fields, p_base_prefix); IF lower(v_op) = '$avg' THEN -- AVG over all elements across all rows = SUM(elements) / COUNT(elements). -- Per-row sum and per-row count are computed in subqueries; outer SUMs -- combine them. NULLIF guards an all-empty-array result. RETURN '(SUM((SELECT SUM(_x) FROM unnest(' || v_col_expr || ') AS _x))::numeric' || ' / NULLIF(SUM(COALESCE(array_length(' || v_col_expr || ', 1), 0)), 0))' || v_filt_sql; ELSE -- SUM/MIN/MAX of aggregates is associative -> outer FUNC over per-row FUNC. RETURN v_func || '((SELECT ' || v_func || '(_x) FROM unnest(' || v_col_expr || ') AS _x))' || v_filt_sql; END IF; END IF; v_inner := pvt_build_scalar_expr(v_arg, p_fields, p_base_prefix); RETURN v_func || '(' || CASE WHEN v_distinct THEN 'DISTINCT ' ELSE '' END || v_inner || ')' || v_filt_sql; END IF; -- ---------------- STRING_AGG ----------------------------------- -- { "$string_agg": [value, separator] } IF lower(v_op) = '$string_agg' THEN IF jsonb_typeof(v_arg) <> 'array' OR jsonb_array_length(v_arg) <> 2 THEN RAISE EXCEPTION 'pvt_build_agg_expr: $string_agg expects [value, separator]'; END IF; v_inner := pvt_build_scalar_expr(v_arg->0, p_fields, p_base_prefix); v_sep := pvt_build_scalar_expr(v_arg->1, p_fields, p_base_prefix); RETURN 'STRING_AGG(' || CASE WHEN v_distinct THEN 'DISTINCT ' ELSE '' END || v_inner || ', ' || v_sep || ')' || v_filt_sql; END IF; -- ---------------- BOOL_AND / BOOL_OR --------------------------- IF lower(v_op) IN ('$bool_and', '$bool_or') THEN v_func := CASE lower(v_op) WHEN '$bool_and' THEN 'BOOL_AND' WHEN '$bool_or' THEN 'BOOL_OR' END; v_inner := pvt_build_scalar_expr(v_arg, p_fields, p_base_prefix); RETURN v_func || '(' || v_inner || ')' || v_filt_sql; END IF; RAISE EXCEPTION 'pvt_build_agg_expr: unsupported aggregate "%"', v_op; END; $BODY$; COMMENT ON FUNCTION pvt_build_agg_expr(jsonb, jsonb, text) IS 'Compiles a single aggregate entry into a SQL fragment. Supports $count|$sum|$avg|$min|$max|$string_agg|$bool_and|$bool_or with optional distinct=true and per-aggregate filter={...}. Free extras over Pro: DISTINCT modifier and FILTER clause.'; -- ---------- pvt_build_agg_projection ---------------------------------- -- Compile an array of aggregate entries into a SQL SELECT-list fragment -- like `agg1 AS "alias1", agg2 AS "alias2", ...`. Aliases default to -- positional `_agg_` when omitted; duplicates raise. CREATE OR REPLACE FUNCTION pvt_build_agg_projection( p_aggs jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_entry jsonb; v_alias text; v_sql text; v_seen text[] := ARRAY[]::text[]; v_parts text[] := ARRAY[]::text[]; v_idx integer := 0; BEGIN IF p_aggs IS NULL OR jsonb_typeof(p_aggs) <> 'array' OR jsonb_array_length(p_aggs) = 0 THEN RAISE EXCEPTION 'pvt_build_agg_projection: p_aggs must be a non-empty JSON array'; END IF; FOR v_entry IN SELECT value FROM jsonb_array_elements(p_aggs) LOOP v_idx := v_idx + 1; v_alias := CASE WHEN v_entry ? 'alias' AND jsonb_typeof(v_entry->'alias') = 'string' THEN v_entry->>'alias' ELSE '_agg_' || v_idx::text END; IF v_alias = ANY(v_seen) THEN RAISE EXCEPTION 'pvt_build_agg_projection: duplicate alias "%"', v_alias; END IF; v_seen := v_seen || v_alias; v_sql := pvt_build_agg_expr(v_entry, p_fields, p_base_prefix); v_parts := v_parts || (v_sql || ' AS ' || quote_ident(v_alias)); END LOOP; RETURN array_to_string(v_parts, ', '); END; $BODY$; COMMENT ON FUNCTION pvt_build_agg_projection(jsonb, jsonb, text) IS 'Compiles an array of aggregate entries into a ` AS "", ...` projection fragment. Aliases default to positional `_agg_`. Used by terminal aggregations and GROUP BY projections.'; Path: redb/redb.SQLite/sql/v2-pvt/20_pvt_build_query_sql.sql 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/v2-pvt/20_pvt_build_query_sql.sql ---- -- ===================================================================== -- 20_pvt_build_query_sql.sql -- --------------------------------------------------------------------- -- Factor-1 orchestrator: produce the full SQL string for a base-fields -- search query. Pure SQL generation, no execution. The result is used -- both by pvt_search_objects_base (via EXECUTE) and by the SQL preview -- entry point. -- -- Function: -- pvt_build_query_sql( -- p_scheme_id bigint, -- p_filter jsonb, -- p_limit integer, -- p_offset integer, -- p_order jsonb, -- p_max_depth integer, -- p_distinct boolean, -- p_source_mode text, -- flat | tree | tree_descendants | tree_children | tree_roots | tree_leaves | tree_ancestors -- p_tree_ids bigint[], -- p_include_seed boolean, -- false strips seed from tree_descendants -- p_polymorphic boolean -- false ANDs scheme_id into recursive walks -- ) RETURNS text -- -- Generated shape (depending on filter content): -- -- Shape A (pure base, no props referenced) -- emitted directly: -- SELECT [DISTINCT] _id FROM _objects o -- WHERE o._id_scheme = X [AND ] -- [ORDER BY ...] [LIMIT ... OFFSET ...] -- -- Shape B narrow (props referenced, no null-check, no tree, -- no nested-dict groups) -- Pro-parity outer: -- WITH _pvt_cte AS ( -- SELECT v._id_object, -- FROM _values v -- WHERE v._id_structure = ANY(ARRAY[]::bigint[]) -- AND v._id_object IN (SELECT _id FROM _objects -- WHERE _id_scheme=X [AND ]) -- GROUP BY v._id_object -- ) -- SELECT [DISTINCT] o._id -- FROM _pvt_cte -- JOIN _objects o ON o._id = _pvt_cte._id_object -- WHERE -- [ORDER BY ...] [LIMIT ... OFFSET ...] -- -- Shape C wide (null-check, tree mode, or nested-dict groups) -- -- legacy wide CTE outer: -- -- SELECT [DISTINCT] _id FROM _pvt_cte -- WHERE -- [ORDER BY ...] [LIMIT ... OFFSET ...] -- ===================================================================== -- Signature evolved in v0.6.0 (added p_include_seed + p_polymorphic) and -- v0.6.1 (added p_distinct_on for SELECT DISTINCT ON parity). -- CREATE OR REPLACE cannot change argument lists, so drop legacy forms. DROP FUNCTION IF EXISTS pvt_build_query_sql(bigint, jsonb, integer, integer, jsonb, integer, boolean); DROP FUNCTION IF EXISTS pvt_build_query_sql(bigint, jsonb, integer, integer, jsonb, integer, boolean, text, bigint[]); DROP FUNCTION IF EXISTS pvt_build_query_sql(bigint, jsonb, integer, integer, jsonb, integer, boolean, text, bigint[], boolean, boolean); CREATE OR REPLACE FUNCTION pvt_build_query_sql( p_scheme_id bigint, p_filter jsonb DEFAULT NULL, p_limit integer DEFAULT NULL, p_offset integer DEFAULT 0, p_order jsonb DEFAULT NULL, p_max_depth integer DEFAULT NULL, p_distinct boolean DEFAULT false, p_source_mode text DEFAULT 'flat', p_tree_ids bigint[] DEFAULT NULL, p_include_seed boolean DEFAULT true, p_polymorphic boolean DEFAULT true, p_distinct_on jsonb DEFAULT NULL ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_fields jsonb; v_cte_sql text; v_where_sql text; v_order_sql text; v_paging text := ''; v_force_outer boolean; v_narrow boolean; v_push_sql text; v_residual jsonb; v_outer_filter jsonb; v_residual_sql text; v_can_push boolean; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_build_query_sql: p_scheme_id is required'; END IF; -- DISTINCT and DISTINCT ON are mutually exclusive; PostgreSQL does -- not allow combining them in a single SELECT. IF p_distinct AND p_distinct_on IS NOT NULL AND jsonb_typeof(p_distinct_on) = 'array' AND jsonb_array_length(p_distinct_on) > 0 THEN RAISE EXCEPTION 'pvt_build_query_sql: p_distinct and p_distinct_on are mutually exclusive'; END IF; -- 1. Resolve metadata for every referenced field. DISTINCT ON -- entries share shape with ORDER BY entries (field|field_path|$expr), -- so we concat them into the order channel for collection only; -- actual rendering happens via separate builders. v_fields := pvt_collect_fields( p_scheme_id, p_filter, CASE WHEN p_distinct_on IS NULL THEN p_order WHEN p_order IS NULL THEN p_distinct_on ELSE p_order || p_distinct_on END, false); -- 2. Pro-style base pushdown: peel off base/hierarchical predicates -- so they can be AND-ed inside the pivot CTE (before JOIN/GROUP -- BY) instead of after it. Indexes on _objects(_id_scheme, -- _date_*, _id_parent, _id_owner, ...) become usable. SELECT s.v_pushdown_sql, s.v_residual_filter INTO v_push_sql, v_residual FROM pvt_split_filter(p_filter, v_fields) s; -- The outer WHERE walker only sees the residual; if pushdown -- swallowed the entire filter the outer becomes 'TRUE'. v_outer_filter := v_residual; -- 2b. Shape A shortcut: pure-base flat query. When the filter -- references zero PROPS fields (only base / hierarchical), -- split swallowed everything (residual = NULL), and we are -- not in tree mode, the whole query collapses to a plain -- SELECT over _objects -- no CTE, no JOIN with _values, no -- GROUP BY. This is the same shape Pro emits for queries -- like `WhereRedb(o => o._id > 0)`. IF v_outer_filter IS NULL AND p_source_mode = 'flat' AND (p_tree_ids IS NULL OR array_length(p_tree_ids, 1) IS NULL) AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') <> 'base' ) THEN v_order_sql := pvt_build_order_conditions(p_order, v_fields, '', p_distinct_on); IF p_limit IS NOT NULL AND p_limit >= 0 THEN v_paging := v_paging || E'\nLIMIT ' || p_limit::text; END IF; IF COALESCE(p_offset, 0) > 0 THEN v_paging := v_paging || E'\nOFFSET ' || p_offset::text; END IF; RETURN 'SELECT ' || CASE WHEN p_distinct THEN 'DISTINCT ' ELSE '' END || pvt_build_distinct_on_select(p_distinct_on, v_fields, 'o.') || '_id FROM _objects o' || E'\nWHERE o._id_scheme = ' || p_scheme_id::text || CASE WHEN v_push_sql IS NOT NULL AND v_push_sql <> '' THEN ' AND ' || v_push_sql ELSE '' END || v_order_sql || v_paging; END IF; -- 3. Decide LEFT vs INNER JOIN on _values: use LEFT only when the -- RESIDUAL filter explicitly tests for ABSENCE (i.e. needs to -- surface rows that have no matching _values record). Base-only -- null tests are already pushed; $notNull/{$ne:null} are handled -- correctly by INNER JOIN (it drops absent rows, which is the -- desired outcome). See pvt_has_absence_check for the exact set. -- Also force outer when v_fields contains zero PROPS entries -- (only base/hierarchical refs from order/distinct_on): the -- narrow shape requires a non-empty pivot SID array, otherwise -- pvt_build_cte_sql silently downgrades the inner CTE to wide -- and the outer 'JOIN _objects o ON o._id = _pvt_cte._id_object' -- references a column the wide CTE does not project. v_force_outer := pvt_has_absence_check(v_outer_filter) OR (v_fields = '{}'::jsonb) OR NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') <> 'base' ); -- 3b. Decide narrow vs wide CTE shape. Narrow Pro-parity shape -- applies when (a) we don't need LEFT JOIN (no absence check) -- and (b) the field set is NOT mixed (scalar pivot + nested-dict -- in the same query). Pure scalar pivot -> narrow _values scan. -- Pure nested-dict -> nested-only optimization (pvt_build_cte_sql -- skips the heavy pi wrapper and folds the object-set restriction -- into the nested CTE). Tree mode IS compatible in both. In -- narrow mode the outer SELECT JOINs _objects to expose base -- columns for residual / order refs. DECLARE v_has_nested boolean; v_has_scalar boolean; BEGIN v_has_nested := EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE (val->>'dict_key') IS NOT NULL AND (val->>'parent_sid') IS NOT NULL); v_has_scalar := EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') <> 'base' AND NOT (COALESCE((val->>'length_modifier')::boolean, false)) AND NOT ((val->>'dict_key') IS NOT NULL AND (val->>'parent_sid') IS NOT NULL)); v_narrow := NOT v_force_outer AND NOT (v_has_nested AND v_has_scalar); END; -- 4. Pro-parity residual WHERE pushdown: when the outer filter -- references only pivoted columns (no base/hierarchical refs), -- render it now and feed to pvt_build_cte_sql so it wraps -- _pvt_cte body as `SELECT * FROM () pvt WHERE `. -- The planner then prunes rows BEFORE the outer JOIN _objects. -- Mixed filters keep the legacy outer WHERE (base refs can only -- be resolved via the `o` alias the JOIN exposes). v_can_push := v_narrow AND v_outer_filter IS NOT NULL AND v_outer_filter <> '{}'::jsonb AND NOT pvt_filter_has_base_refs(v_outer_filter, v_fields); IF v_can_push THEN v_residual_sql := pvt_build_where_from_json(v_outer_filter, v_fields, ''); ELSE v_residual_sql := NULL; END IF; -- 5. Build the CTE (with optional base + residual pushdown). v_cte_sql := pvt_build_cte_sql( p_scheme_id => p_scheme_id, p_fields => v_fields, p_source_mode => p_source_mode, p_tree_ids => p_tree_ids, p_max_depth => p_max_depth, p_force_outer => v_force_outer, p_extra_where => v_push_sql, p_narrow => v_narrow, p_include_seed => p_include_seed, p_polymorphic => p_polymorphic, p_residual_where => v_residual_sql ); -- 6. Build outer predicates and ordering. In narrow shape base -- columns live on _objects (alias `o`), so base references in -- the residual / order BY must be emitted as `o.`. In wide -- shape base columns are projected into _pvt_cte unaliased and -- references stay bare (legacy behavior). When residual was -- pushed inside _pvt_cte we skip the outer WHERE. IF v_can_push THEN v_where_sql := 'TRUE'; ELSE v_where_sql := pvt_build_where_from_json( v_outer_filter, v_fields, CASE WHEN v_narrow THEN 'o.' ELSE '' END); END IF; v_order_sql := pvt_build_order_conditions( p_order, v_fields, CASE WHEN v_narrow THEN 'o.' ELSE '' END, p_distinct_on); -- 6. Paging. IF p_limit IS NOT NULL AND p_limit >= 0 THEN v_paging := v_paging || E'\nLIMIT ' || p_limit::text; END IF; IF COALESCE(p_offset, 0) > 0 THEN v_paging := v_paging || E'\nOFFSET ' || p_offset::text; END IF; -- 7. Assemble outer SELECT. Narrow shape JOINs _objects so the -- residual WHERE / ORDER BY can address base columns via the -- `o` alias; wide shape selects directly from _pvt_cte. IF v_narrow THEN RETURN v_cte_sql || E'\nSELECT ' || CASE WHEN p_distinct THEN 'DISTINCT ' ELSE '' END || pvt_build_distinct_on_select(p_distinct_on, v_fields, 'o.') || 'o._id FROM _pvt_cte' || E'\nJOIN _objects o ON o._id = _pvt_cte._id_object' || CASE WHEN v_where_sql = 'TRUE' THEN '' ELSE E'\nWHERE ' || v_where_sql END || v_order_sql || v_paging; END IF; RETURN v_cte_sql || E'\nSELECT ' || CASE WHEN p_distinct THEN 'DISTINCT ' ELSE '' END || pvt_build_distinct_on_select(p_distinct_on, v_fields, '') || '_id FROM _pvt_cte' || CASE WHEN v_where_sql = 'TRUE' THEN '' ELSE E'\nWHERE ' || v_where_sql END || v_order_sql || v_paging; END; $BODY$; COMMENT ON FUNCTION pvt_build_query_sql(bigint, jsonb, integer, integer, jsonb, integer, boolean, text, bigint[], boolean, boolean, jsonb) IS 'Factor-1 of the PVT engine: pure SQL generation. Composes pvt_collect_fields + pvt_build_cte_sql + pvt_build_where_from_json + pvt_build_order_conditions into a complete SELECT statement that yields a single _id column. p_source_mode: flat | tree | tree_descendants | tree_children | tree_roots | tree_leaves | tree_ancestors. p_include_seed=false strips seed objects from tree_descendants. p_polymorphic=false restricts recursive walks to p_scheme_id (default polymorphic matches Pro). p_distinct_on accepts the same {field|field_path|$expr} entries as p_order; its expressions are rendered as SELECT DISTINCT ON (...) and auto-prepended ASC to ORDER BY (PostgreSQL requirement). Mutually exclusive with p_distinct.'; Path: redb/redb.SQLite/sql/v2-pvt/21_pvt_aggregate.sql 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/v2-pvt/21_pvt_aggregate.sql ---- -- ===================================================================== -- 21_pvt_aggregate.sql -- --------------------------------------------------------------------- -- Terminal aggregations: produce a single-row result of N aggregates -- over a (filtered) PVT source. Sister of pvt_build_query_sql (file 20) -- - same source-mode / tree / push-down plumbing, different projection -- and no LIMIT/OFFSET/ORDER BY/DISTINCT (a single row has no order). -- -- pvt_build_aggregate_sql( -- p_scheme_id bigint, -- p_filter jsonb, -- p_aggregations jsonb, -- non-empty array of agg entries -- p_source_mode text, -- p_tree_ids bigint[], -- p_max_depth integer, -- p_include_seed boolean, -- p_polymorphic boolean -- ) RETURNS text -- -- Generated shape (Shape A vs Shape B/C selection mirrors file 20): -- -- Shape A (pure-base filter, no PROPS refs, flat mode): -- SELECT AS "", ... FROM _objects o -- WHERE o._id_scheme = X [AND ] -- -- Shape B narrow: -- -- SELECT AS "", ... -- FROM _pvt_cte JOIN _objects o ON o._id = _pvt_cte._id_object -- WHERE -- -- Shape C wide: -- -- SELECT AS "", ... FROM _pvt_cte -- WHERE -- ===================================================================== -- ---------- pvt_collect_extra_fields ---------------------------------- -- Resolve metadata for a flat array of field paths. Used by aggregation -- / window orchestrators to register fields referenced inside aggregate -- operands / window arguments (which don't fit the field|field_path| -- $expr shape consumed by pvt_collect_fields). CREATE OR REPLACE FUNCTION pvt_collect_extra_fields( p_scheme_id bigint, p_paths text[] ) RETURNS jsonb LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_path text; v_meta jsonb; v_result jsonb := '{}'::jsonb; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_collect_extra_fields: p_scheme_id is required'; END IF; IF p_paths IS NULL OR array_length(p_paths, 1) IS NULL THEN RETURN v_result; END IF; FOREACH v_path IN ARRAY p_paths LOOP IF v_path IS NULL OR v_path = '' THEN CONTINUE; END IF; v_meta := pvt_resolve_field_path(p_scheme_id, v_path); v_result := v_result || jsonb_build_object(v_path, v_meta); END LOOP; RETURN v_result; END; $BODY$; COMMENT ON FUNCTION pvt_collect_extra_fields(bigint, text[]) IS 'Resolve metadata for a flat array of field paths and merge into a JSONB fields map. Used to register fields referenced inside aggregate operands / window arguments that do not fit the order/filter shapes consumed by pvt_collect_fields.'; -- ---------- pvt_aggregations_field_names ------------------------------ -- Yield every field path referenced inside an aggregation array (operands -- + per-aggregate filters). Used by orchestrators to extend the fields -- map fed into pvt_build_cte_sql. CREATE OR REPLACE FUNCTION pvt_aggregations_field_names(p_aggs jsonb) RETURNS SETOF text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_entry jsonb; BEGIN IF p_aggs IS NULL OR jsonb_typeof(p_aggs) <> 'array' THEN RETURN; END IF; FOR v_entry IN SELECT value FROM jsonb_array_elements(p_aggs) LOOP RETURN QUERY SELECT pvt_agg_entry_field_names(v_entry); END LOOP; END; $BODY$; COMMENT ON FUNCTION pvt_aggregations_field_names(jsonb) IS 'Yields every field path referenced inside an array of aggregate entries (operands + filters). Empty when p_aggs is null or non-array.'; -- --------------------------------------------------------------------- -- pvt_build_aggregate_sql -- --------------------------------------------------------------------- DROP FUNCTION IF EXISTS pvt_build_aggregate_sql(bigint, jsonb, jsonb, text, bigint[], integer, boolean, boolean); CREATE OR REPLACE FUNCTION pvt_build_aggregate_sql( p_scheme_id bigint, p_filter jsonb, p_aggregations jsonb, p_source_mode text DEFAULT 'flat', p_tree_ids bigint[] DEFAULT NULL, p_max_depth integer DEFAULT NULL, p_include_seed boolean DEFAULT true, p_polymorphic boolean DEFAULT true ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_fields jsonb; v_extra jsonb; v_extra_names text[]; v_cte_sql text; v_where_sql text; v_force_outer boolean; v_narrow boolean; v_push_sql text; v_residual jsonb; v_outer_filter jsonb; v_proj text; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_build_aggregate_sql: p_scheme_id is required'; END IF; IF p_aggregations IS NULL OR jsonb_typeof(p_aggregations) <> 'array' OR jsonb_array_length(p_aggregations) = 0 THEN RAISE EXCEPTION 'pvt_build_aggregate_sql: p_aggregations must be a non-empty JSON array'; END IF; -- 1. Collect fields from filter (no order entries for aggregations). v_fields := pvt_collect_fields(p_scheme_id, p_filter, NULL, false); -- 2. Extend with fields referenced inside aggregate operands / -- per-aggregate filters. v_extra_names := ARRAY(SELECT DISTINCT n FROM pvt_aggregations_field_names(p_aggregations) AS n WHERE n IS NOT NULL); v_extra := pvt_collect_extra_fields(p_scheme_id, v_extra_names); v_fields := v_fields || v_extra; -- 3. Base pushdown. SELECT s.v_pushdown_sql, s.v_residual_filter INTO v_push_sql, v_residual FROM pvt_split_filter(p_filter, v_fields) s; v_outer_filter := v_residual; -- 4. Shape A shortcut: pure-base flat aggregation. IF v_outer_filter IS NULL AND p_source_mode = 'flat' AND (p_tree_ids IS NULL OR array_length(p_tree_ids, 1) IS NULL) AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') <> 'base' ) THEN v_proj := pvt_build_agg_projection(p_aggregations, v_fields, 'o.'); RETURN 'SELECT ' || v_proj || ' FROM _objects o' || E'\nWHERE o._id_scheme = ' || p_scheme_id::text || CASE WHEN v_push_sql IS NOT NULL AND v_push_sql <> '' THEN ' AND ' || v_push_sql ELSE '' END; END IF; -- 5. Narrow vs wide decision (mirrors file 20). Tree modes always go -- wide because pvt_build_cte_sql ignores narrow=true in tree mode -- and emits the base-cols CTE keyed on _id (not _id_object). v_force_outer := pvt_has_absence_check(v_outer_filter) OR (v_fields = '{}'::jsonb); v_narrow := p_source_mode = 'flat' AND NOT v_force_outer AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE (val->>'dict_key') IS NOT NULL AND (val->>'parent_sid') IS NOT NULL); -- 6. Build CTE. v_cte_sql := pvt_build_cte_sql( p_scheme_id => p_scheme_id, p_fields => v_fields, p_source_mode => p_source_mode, p_tree_ids => p_tree_ids, p_max_depth => p_max_depth, p_force_outer => v_force_outer, p_extra_where => v_push_sql, p_narrow => v_narrow, p_include_seed => p_include_seed, p_polymorphic => p_polymorphic ); -- 7. Residual WHERE + projection (prefix depends on shape). v_where_sql := pvt_build_where_from_json( v_outer_filter, v_fields, CASE WHEN v_narrow THEN 'o.' ELSE '' END); v_proj := pvt_build_agg_projection( p_aggregations, v_fields, CASE WHEN v_narrow THEN 'o.' ELSE '' END); IF v_narrow THEN RETURN v_cte_sql || E'\nSELECT ' || v_proj || ' FROM _pvt_cte' || E'\nJOIN _objects o ON o._id = _pvt_cte._id_object' || E'\nWHERE ' || v_where_sql; END IF; RETURN v_cte_sql || E'\nSELECT ' || v_proj || ' FROM _pvt_cte' || E'\nWHERE ' || v_where_sql; END; $BODY$; COMMENT ON FUNCTION pvt_build_aggregate_sql(bigint, jsonb, jsonb, text, bigint[], integer, boolean, boolean) IS 'Terminal aggregation orchestrator: emits a single-row SELECT projecting N aggregate columns over the PVT source. p_aggregations is a non-empty JSON array of {alias, $: |"*", distinct?, filter?} entries. Tree variants reuse the same p_source_mode / p_tree_ids / p_max_depth / p_include_seed / p_polymorphic plumbing as pvt_build_query_sql.'; Path: redb/redb.SQLite/sql/v2-pvt/22_pvt_groupby.sql 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/v2-pvt/22_pvt_groupby.sql ---- -- ===================================================================== -- 22_pvt_groupby.sql -- --------------------------------------------------------------------- -- GROUP BY orchestrator: project group keys + aggregates, with optional -- HAVING / ORDER BY / LIMIT / OFFSET clauses. Sister of files 20 and 21 -- - reuses the same field-collection, push-down and CTE-shape decisions. -- -- pvt_build_groupby_sql( -- p_scheme_id bigint, -- p_filter jsonb, -- p_group_by jsonb, -- non-empty array of {field|$expr,alias?} -- p_aggregations jsonb, -- optional array of agg entries (see 19) -- p_having jsonb, -- optional boolean-expression node -- p_order jsonb, -- optional ORDER BY entries -- p_limit integer, -- p_offset integer, -- p_source_mode text, -- p_tree_ids bigint[], -- p_max_depth integer, -- p_include_seed boolean, -- p_polymorphic boolean -- ) RETURNS text -- -- Generated shape (narrow / wide selection mirrors files 20-21): -- -- SELECT AS "", ..., AS "", ... -- FROM (CTE or _objects) -- WHERE -- GROUP BY , , ... -- [HAVING ] -- [ORDER BY ...] [LIMIT ...] [OFFSET ...] -- -- HAVING is a free feature over Pro: Pro currently emits zero HAVING -- support, so any predicate over an aggregate had to be done client-side. -- In HAVING, ORDER BY (and select-side projections), aggregates may be -- written inline as {"$count":"*"} / {"$sum":{"$field":"X"}} thanks to -- pvt_build_scalar_expr's aggregate-passthrough extension; alias refs -- are not supported -- repeat the expression (PostgreSQL is fine with -- HAVING on raw aggregate expressions). -- ===================================================================== DROP FUNCTION IF EXISTS pvt_build_groupby_sql(bigint, jsonb, jsonb, jsonb, jsonb, jsonb, integer, integer, text, bigint[], integer, boolean, boolean); CREATE OR REPLACE FUNCTION pvt_build_groupby_sql( p_scheme_id bigint, p_filter jsonb, p_group_by jsonb, p_aggregations jsonb DEFAULT NULL, p_having jsonb DEFAULT NULL, p_order jsonb DEFAULT NULL, p_limit integer DEFAULT NULL, p_offset integer DEFAULT 0, p_source_mode text DEFAULT 'flat', p_tree_ids bigint[] DEFAULT NULL, p_max_depth integer DEFAULT NULL, p_include_seed boolean DEFAULT true, p_polymorphic boolean DEFAULT true ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_fields jsonb; v_extra jsonb; v_extra_names text[]; v_cte_sql text; v_where_sql text; v_having_sql text := ''; v_order_sql text; v_paging text := ''; v_force_outer boolean; v_narrow boolean; v_push_sql text; v_residual jsonb; v_outer_filter jsonb; v_prefix text; v_grp_entry jsonb; v_grp_idx integer := 0; v_grp_col text; v_grp_alias text; v_grp_seen text[] := ARRAY[]::text[]; v_select_parts text[] := ARRAY[]::text[]; v_groupby_parts text[] := ARRAY[]::text[]; v_select_sql text; v_groupby_sql text; -- Pro-parity inline GROUP BY: when the field set is pure scalar -- pivot (no base/nested-dict/simple-dict/array refs) AND filter is -- narrow-eligible, skip the CTE wrapper and emit -- `SELECT pvt., agg(...) FROM () pvt GROUP BY pvt.`. -- The inline pivot lifts `v._array_index IS NULL` out of every -- column FILTER into a single outer WHERE -- index-friendly at scale. v_inline boolean := false; v_inline_sql text; v_inline_cols text := ''; v_inline_sids text := ''; v_inline_li_join boolean := false; v_inline_first boolean := true; v_fname text; v_fmeta jsonb; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_build_groupby_sql: p_scheme_id is required'; END IF; IF p_group_by IS NULL OR jsonb_typeof(p_group_by) <> 'array' OR jsonb_array_length(p_group_by) = 0 THEN RAISE EXCEPTION 'pvt_build_groupby_sql: p_group_by must be a non-empty JSON array'; END IF; -- 1. Collect fields from filter + group_by (piped via order channel) -- + ORDER BY entries. v_fields := pvt_collect_fields( p_scheme_id, p_filter, CASE WHEN p_order IS NULL THEN p_group_by ELSE p_group_by || p_order END, false); -- 2. Extend with fields from aggregations + HAVING. v_extra_names := ARRAY( SELECT DISTINCT n FROM ( SELECT pvt_aggregations_field_names(p_aggregations) AS n UNION ALL SELECT pvt_expr_field_names(p_having) AS n ) z WHERE n IS NOT NULL); v_extra := pvt_collect_extra_fields(p_scheme_id, v_extra_names); v_fields := v_fields || v_extra; -- 3. Base pushdown. SELECT s.v_pushdown_sql, s.v_residual_filter INTO v_push_sql, v_residual FROM pvt_split_filter(p_filter, v_fields) s; v_outer_filter := v_residual; -- 4. Narrow vs wide. Tree modes always go wide (pvt_build_cte_sql -- emits base-cols CTE keyed on _id in tree mode, not _id_object). v_force_outer := pvt_has_absence_check(v_outer_filter) OR (v_fields = '{}'::jsonb); v_narrow := p_source_mode = 'flat' AND NOT v_force_outer AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE (val->>'dict_key') IS NOT NULL AND (val->>'parent_sid') IS NOT NULL); v_prefix := CASE WHEN v_narrow THEN 'o.' ELSE '' END; -- 5. Shape A shortcut: pure-base flat group-by, no aggregates touch -- PROPS. Skip CTE entirely. IF v_outer_filter IS NULL AND p_source_mode = 'flat' AND (p_tree_ids IS NULL OR array_length(p_tree_ids, 1) IS NULL) AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') <> 'base' ) THEN v_prefix := 'o.'; v_narrow := false; -- mark so assembly below picks the "no CTE" branch ELSE -- 5b. Pro-parity inline GROUP BY eligibility. Pure scalar pivot, -- narrow shape, no tree, no base refs anywhere (filter, -- group_by, having, order, aggregations -- all live in v_fields). v_inline := v_narrow AND p_source_mode = 'flat' AND (p_tree_ids IS NULL OR array_length(p_tree_ids, 1) IS NULL) AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') = 'base' ) AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') <> 'base' AND ( COALESCE((val->>'is_array')::boolean, false) OR (val->>'dict_key') IS NOT NULL OR (val->>'parent_sid') IS NOT NULL OR COALESCE((val->>'length_modifier')::boolean, false) ) ); IF v_inline THEN -- Build inline pivot subquery: project _id + every scalar -- pivot column WITHOUT `_array_index IS NULL` per-FILTER -- (hoisted to outer WHERE). Cuts FILTER overhead and lets -- the planner use a single ANY()-index scan. FOR v_fname, v_fmeta IN SELECT key, value FROM jsonb_each(v_fields) LOOP IF COALESCE(v_fmeta->>'kind', '') = 'base' THEN CONTINUE; END IF; IF NOT v_inline_first THEN v_inline_cols := v_inline_cols || ',' || E'\n '; ELSE v_inline_cols := E',\n '; v_inline_first := false; END IF; v_inline_cols := v_inline_cols || pvt_build_column_expr(v_fname, v_fmeta, true); IF v_inline_sids <> '' THEN v_inline_sids := v_inline_sids || ', '; END IF; v_inline_sids := v_inline_sids || (v_fmeta->>'sid'); IF (v_fmeta->>'list_item_prop') IN ('Value', 'Alias') THEN v_inline_li_join := true; END IF; END LOOP; v_inline_sql := E'SELECT\n o._id' || v_inline_cols || E'\n FROM _objects o' || E'\n INNER JOIN _values v ON v._id_object = o._id' || CASE WHEN v_inline_li_join THEN E'\n LEFT JOIN _list_items li ON li._id = v._ListItem' ELSE '' END || E'\n WHERE o._id_scheme = ' || p_scheme_id::text || CASE WHEN v_push_sql IS NOT NULL AND v_push_sql <> '' THEN ' AND ' || v_push_sql ELSE '' END || E'\n AND v._id_structure = ANY(ARRAY[' || v_inline_sids || ']::bigint[])' || E'\n AND v._array_index IS NULL' || E'\n GROUP BY o._id'; v_prefix := 'pvt.'; ELSE -- 6. Build CTE (legacy path: mixed types / tree / base refs). v_cte_sql := pvt_build_cte_sql( p_scheme_id => p_scheme_id, p_fields => v_fields, p_source_mode => p_source_mode, p_tree_ids => p_tree_ids, p_max_depth => p_max_depth, p_force_outer => v_force_outer, p_extra_where => v_push_sql, p_narrow => v_narrow, p_include_seed => p_include_seed, p_polymorphic => p_polymorphic ); END IF; END IF; -- 7. Build group-key projection + GROUP BY clause. FOR v_grp_entry IN SELECT value FROM jsonb_array_elements(p_group_by) LOOP v_grp_idx := v_grp_idx + 1; v_grp_col := _pvt_compile_order_col(v_grp_entry, v_fields, v_prefix, true); v_grp_alias := CASE WHEN v_grp_entry ? 'alias' AND jsonb_typeof(v_grp_entry->'alias') = 'string' THEN v_grp_entry->>'alias' WHEN v_grp_entry ? 'field' THEN v_grp_entry->>'field' WHEN v_grp_entry ? 'field_path' THEN v_grp_entry->>'field_path' ELSE '_grp_' || v_grp_idx::text END; IF v_grp_alias = ANY(v_grp_seen) THEN RAISE EXCEPTION 'pvt_build_groupby_sql: duplicate group-by alias "%"', v_grp_alias; END IF; v_grp_seen := v_grp_seen || v_grp_alias; v_select_parts := v_select_parts || (v_grp_col || ' AS ' || quote_ident(v_grp_alias)); v_groupby_parts := v_groupby_parts || v_grp_col; END LOOP; -- 8. Append aggregate projection. IF p_aggregations IS NOT NULL AND jsonb_typeof(p_aggregations) = 'array' AND jsonb_array_length(p_aggregations) > 0 THEN v_select_parts := v_select_parts || pvt_build_agg_projection(p_aggregations, v_fields, v_prefix); END IF; v_select_sql := array_to_string(v_select_parts, ', '); v_groupby_sql := array_to_string(v_groupby_parts, ', '); -- 9. WHERE / HAVING / ORDER BY / paging. v_where_sql := pvt_build_where_from_json(v_outer_filter, v_fields, v_prefix); IF p_having IS NOT NULL AND p_having <> '{}'::jsonb THEN v_having_sql := E'\nHAVING ' || pvt_build_bool_expr(p_having, v_fields, v_prefix); END IF; v_order_sql := pvt_build_order_conditions(p_order, v_fields, v_prefix, NULL); IF p_limit IS NOT NULL AND p_limit >= 0 THEN v_paging := v_paging || E'\nLIMIT ' || p_limit::text; END IF; IF COALESCE(p_offset, 0) > 0 THEN v_paging := v_paging || E'\nOFFSET ' || p_offset::text; END IF; -- 10. Assemble. Shape A: SELECT ... FROM _objects o. Inline: SELECT -- ... FROM () pvt (Pro-parity). Narrow: from -- _pvt_cte JOIN _objects o. Wide: from _pvt_cte. IF v_cte_sql IS NULL AND NOT v_inline THEN -- Shape A: pure-base flat. RETURN 'SELECT ' || v_select_sql || ' FROM _objects o' || E'\nWHERE o._id_scheme = ' || p_scheme_id::text || CASE WHEN v_push_sql IS NOT NULL AND v_push_sql <> '' THEN ' AND ' || v_push_sql ELSE '' END || E'\nGROUP BY ' || v_groupby_sql || v_having_sql || v_order_sql || v_paging; END IF; IF v_inline THEN -- Pro-parity inline GROUP BY: no CTE, pivot is a derived table. RETURN 'SELECT ' || v_select_sql || E'\n FROM (' || v_inline_sql || E'\n ) pvt' || CASE WHEN v_where_sql = 'TRUE' THEN '' ELSE E'\n WHERE ' || v_where_sql END || E'\n GROUP BY ' || v_groupby_sql || v_having_sql || v_order_sql || v_paging; END IF; IF v_narrow THEN RETURN v_cte_sql || E'\nSELECT ' || v_select_sql || ' FROM _pvt_cte' || E'\nJOIN _objects o ON o._id = _pvt_cte._id_object' || E'\nWHERE ' || v_where_sql || E'\nGROUP BY ' || v_groupby_sql || v_having_sql || v_order_sql || v_paging; END IF; RETURN v_cte_sql || E'\nSELECT ' || v_select_sql || ' FROM _pvt_cte' || E'\nWHERE ' || v_where_sql || E'\nGROUP BY ' || v_groupby_sql || v_having_sql || v_order_sql || v_paging; END; $BODY$; COMMENT ON FUNCTION pvt_build_groupby_sql(bigint, jsonb, jsonb, jsonb, jsonb, jsonb, integer, integer, text, bigint[], integer, boolean, boolean) IS 'GROUP BY orchestrator. p_group_by is a non-empty array of {field|field_path|$expr, alias?} entries (ORDER-BY-shape minus direction). p_aggregations is an optional array of {alias, $: |"*", distinct?, filter?} entries. p_having is an optional boolean-expression node where aggregates can be referenced inline via {"$count":"*"} / {"$sum":{"$field":"X"}} (alias refs not supported). HAVING support is a free feature over Pro.'; Path: redb/redb.SQLite/sql/v2-pvt/23_pvt_window.sql 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/v2-pvt/23_pvt_window.sql ---- -- ===================================================================== -- 23_pvt_window.sql -- --------------------------------------------------------------------- -- Window functions over PVT source. Window calls are scalar expressions -- carrying an OVER (...) clause; the compiler is exposed both as an -- explicit pvt_build_window_expr() entry point and as a `$over` scalar- -- expression key so callers can drop windows anywhere a scalar fits -- (PostgreSQL itself enforces SELECT/ORDER-BY only at execution time). -- -- Window node shape: -- { -- "func": "row_number" | "rank" | "dense_rank" -- | "percent_rank" | "cume_dist" | "ntile" -- | "lag" | "lead" | "first_value" | "last_value" -- | "nth_value" -- | "sum" | "avg" | "min" | "max" | "count", -- "args": [, ...]?, -- function arguments -- "partition_by": [, ...]?, -- "order_by": [, ...]?, -- "frame": { -- "type": "rows" | "range" | "groups", -- "start": , -- "end": ?, -- "exclude": "current_row" | "group" | "ties" | "no_others"? -- }? -- } -- -- Frame bound forms: -- "unbounded_preceding" -- "current_row" -- "unbounded_following" -- { "preceding": } -- { "following": } -- -- pvt_build_window_sql( -- p_scheme_id bigint, -- p_filter jsonb, -- p_select jsonb, -- non-empty array of select entries -- p_order jsonb, -- p_limit integer, -- p_offset integer, -- p_source_mode text, -- p_tree_ids bigint[], -- p_max_depth integer, -- p_include_seed boolean, -- p_polymorphic boolean -- ) RETURNS text -- -- Select entries follow the ORDER-BY shape: {field|field_path|$expr, -- alias?}. Aggregates and window expressions are emitted via $expr. -- ===================================================================== -- ---------- pvt_window_field_names ------------------------------------ -- Recursively yield every field path referenced inside a window node -- (args + partition_by + order_by). Used by orchestrators to extend the -- fields map fed into pvt_build_cte_sql. CREATE OR REPLACE FUNCTION pvt_window_field_names(p_node jsonb) RETURNS SETOF text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_elem jsonb; BEGIN IF p_node IS NULL OR jsonb_typeof(p_node) <> 'object' THEN RETURN; END IF; IF p_node ? 'args' AND jsonb_typeof(p_node->'args') = 'array' THEN FOR v_elem IN SELECT value FROM jsonb_array_elements(p_node->'args') LOOP RETURN QUERY SELECT pvt_expr_field_names(v_elem); END LOOP; END IF; IF p_node ? 'partition_by' AND jsonb_typeof(p_node->'partition_by') = 'array' THEN FOR v_elem IN SELECT value FROM jsonb_array_elements(p_node->'partition_by') LOOP IF v_elem ? '$expr' THEN RETURN QUERY SELECT pvt_expr_field_names(v_elem->'$expr'); ELSIF v_elem ? 'field' OR v_elem ? 'field_path' THEN RETURN NEXT COALESCE(v_elem->>'field', v_elem->>'field_path'); END IF; END LOOP; END IF; IF p_node ? 'order_by' AND jsonb_typeof(p_node->'order_by') = 'array' THEN FOR v_elem IN SELECT value FROM jsonb_array_elements(p_node->'order_by') LOOP IF v_elem ? '$expr' THEN RETURN QUERY SELECT pvt_expr_field_names(v_elem->'$expr'); ELSIF v_elem ? 'field' OR v_elem ? 'field_path' THEN RETURN NEXT COALESCE(v_elem->>'field', v_elem->>'field_path'); END IF; END LOOP; END IF; END; $BODY$; COMMENT ON FUNCTION pvt_window_field_names(jsonb) IS 'Recursively yields every field path referenced inside a window node (args + partition_by + order_by). Used by pvt_build_window_sql to extend the fields map.'; -- ---------- _pvt_compile_frame_bound (internal) ----------------------- CREATE OR REPLACE FUNCTION _pvt_compile_frame_bound(p_bound jsonb, p_label text) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $BODY$ DECLARE v_t text; v_n bigint; BEGIN IF p_bound IS NULL OR jsonb_typeof(p_bound) = 'null' THEN RAISE EXCEPTION '_pvt_compile_frame_bound: frame.% is required', p_label; END IF; v_t := jsonb_typeof(p_bound); IF v_t = 'string' THEN DECLARE v_s text := lower(p_bound #>> '{}'); BEGIN IF v_s = 'unbounded_preceding' THEN RETURN 'UNBOUNDED PRECEDING'; END IF; IF v_s = 'current_row' THEN RETURN 'CURRENT ROW'; END IF; IF v_s = 'unbounded_following' THEN RETURN 'UNBOUNDED FOLLOWING'; END IF; RAISE EXCEPTION '_pvt_compile_frame_bound: invalid string bound "%"', v_s; END; END IF; IF v_t = 'object' THEN IF p_bound ? 'preceding' THEN v_n := (p_bound->>'preceding')::bigint; RETURN v_n::text || ' PRECEDING'; END IF; IF p_bound ? 'following' THEN v_n := (p_bound->>'following')::bigint; RETURN v_n::text || ' FOLLOWING'; END IF; END IF; RAISE EXCEPTION '_pvt_compile_frame_bound: bound must be "unbounded_preceding"/"current_row"/"unbounded_following" or {preceding|following: N}, got %', p_bound::text; END; $BODY$; -- ---------- _pvt_compile_window_over (internal) ----------------------- -- Emit `OVER (PARTITION BY ... ORDER BY ... ROWS BETWEEN ... AND ...)`. -- Returns the empty string when no window keys are present (caller emits -- `OVER ()` for those, e.g. unframed ROW_NUMBER). CREATE OR REPLACE FUNCTION _pvt_compile_window_over( p_node jsonb, p_fields jsonb, p_base_prefix text ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_parts text[] := ARRAY[]::text[]; v_pb_parts text[] := ARRAY[]::text[]; v_elem jsonb; v_order_sql text; v_frame jsonb; v_frame_kw text; v_frame_start text; v_frame_end text; v_frame_excl text; v_frame_sql text; v_synth_order jsonb; BEGIN -- PARTITION BY ------------------------------------------------- IF p_node ? 'partition_by' AND jsonb_typeof(p_node->'partition_by') = 'array' AND jsonb_array_length(p_node->'partition_by') > 0 THEN FOR v_elem IN SELECT value FROM jsonb_array_elements(p_node->'partition_by') LOOP v_pb_parts := v_pb_parts || _pvt_compile_order_col(v_elem, p_fields, p_base_prefix, true); END LOOP; v_parts := v_parts || ('PARTITION BY ' || array_to_string(v_pb_parts, ', ')); END IF; -- ORDER BY (reuse pvt_build_order_conditions to keep direction/ -- NULLS handling consistent; strip the leading "ORDER BY " prefix -- because we are inside OVER (...)). IF p_node ? 'order_by' AND jsonb_typeof(p_node->'order_by') = 'array' AND jsonb_array_length(p_node->'order_by') > 0 THEN v_synth_order := p_node->'order_by'; v_order_sql := pvt_build_order_conditions(v_synth_order, p_fields, p_base_prefix, NULL); -- pvt_build_order_conditions returns either '' or E'\nORDER BY ...'. IF v_order_sql IS NOT NULL AND v_order_sql <> '' THEN v_parts := v_parts || ltrim(v_order_sql, E'\n'); END IF; END IF; -- FRAME --------------------------------------------------------- IF p_node ? 'frame' THEN v_frame := p_node->'frame'; IF jsonb_typeof(v_frame) <> 'object' THEN RAISE EXCEPTION '_pvt_compile_window_over: frame must be an object'; END IF; v_frame_kw := upper(COALESCE(v_frame->>'type', 'rows')); IF v_frame_kw NOT IN ('ROWS', 'RANGE', 'GROUPS') THEN RAISE EXCEPTION '_pvt_compile_window_over: frame.type must be rows|range|groups (got %)', v_frame_kw; END IF; v_frame_start := _pvt_compile_frame_bound(v_frame->'start', 'start'); IF v_frame ? 'end' AND jsonb_typeof(v_frame->'end') <> 'null' THEN v_frame_end := _pvt_compile_frame_bound(v_frame->'end', 'end'); v_frame_sql := v_frame_kw || ' BETWEEN ' || v_frame_start || ' AND ' || v_frame_end; ELSE v_frame_sql := v_frame_kw || ' ' || v_frame_start; END IF; IF v_frame ? 'exclude' AND jsonb_typeof(v_frame->'exclude') = 'string' THEN v_frame_excl := lower(v_frame->>'exclude'); v_frame_sql := v_frame_sql || ' EXCLUDE ' || CASE v_frame_excl WHEN 'current_row' THEN 'CURRENT ROW' WHEN 'group' THEN 'GROUP' WHEN 'ties' THEN 'TIES' WHEN 'no_others' THEN 'NO OTHERS' ELSE NULL END; IF v_frame_excl NOT IN ('current_row', 'group', 'ties', 'no_others') THEN RAISE EXCEPTION '_pvt_compile_window_over: frame.exclude must be current_row|group|ties|no_others (got %)', v_frame_excl; END IF; END IF; v_parts := v_parts || v_frame_sql; END IF; IF array_length(v_parts, 1) IS NULL THEN RETURN 'OVER ()'; END IF; RETURN 'OVER (' || array_to_string(v_parts, ' ') || ')'; END; $BODY$; -- ---------- pvt_build_window_expr ------------------------------------- CREATE OR REPLACE FUNCTION pvt_build_window_expr( p_node jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_func text; v_args jsonb; v_args_sql text[] := ARRAY[]::text[]; v_elem jsonb; v_arg_sql text; v_call text; v_over text; v_distinct boolean := false; v_filter jsonb; v_filt_sql text := ''; BEGIN IF p_node IS NULL OR jsonb_typeof(p_node) <> 'object' THEN RAISE EXCEPTION 'pvt_build_window_expr: window node must be an object'; END IF; IF NOT (p_node ? 'func') OR jsonb_typeof(p_node->'func') <> 'string' THEN RAISE EXCEPTION 'pvt_build_window_expr: window node must include "func" (string)'; END IF; v_func := lower(p_node->>'func'); IF v_func NOT IN ( 'row_number', 'rank', 'dense_rank', 'percent_rank', 'cume_dist', 'ntile', 'lag', 'lead', 'first_value', 'last_value', 'nth_value', 'sum', 'avg', 'min', 'max', 'count' ) THEN RAISE EXCEPTION 'pvt_build_window_expr: unsupported window func "%"', v_func; END IF; -- Build the argument list. count(*) is a special shorthand. IF p_node ? 'args' THEN v_args := p_node->'args'; IF v_func = 'count' AND jsonb_typeof(v_args) = 'array' AND jsonb_array_length(v_args) = 1 AND jsonb_typeof(v_args->0) = 'string' AND (v_args->0 #>> '{}') = '*' THEN v_call := 'COUNT(*)'; ELSE IF jsonb_typeof(v_args) <> 'array' THEN RAISE EXCEPTION 'pvt_build_window_expr: args must be an array (got %)', jsonb_typeof(v_args); END IF; FOR v_elem IN SELECT value FROM jsonb_array_elements(v_args) LOOP v_arg_sql := pvt_build_scalar_expr(v_elem, p_fields, p_base_prefix); v_args_sql := v_args_sql || v_arg_sql; END LOOP; v_call := upper(v_func) || '(' || array_to_string(v_args_sql, ', ') || ')'; END IF; ELSE IF v_func IN ('ntile', 'lag', 'lead', 'first_value', 'last_value', 'nth_value') THEN RAISE EXCEPTION 'pvt_build_window_expr: % requires "args"', v_func; END IF; IF v_func IN ('sum', 'avg', 'min', 'max', 'count') THEN RAISE EXCEPTION 'pvt_build_window_expr: aggregate window % requires "args"', v_func; END IF; v_call := upper(v_func) || '()'; END IF; -- Optional FILTER (WHERE ...) for aggregate windows. IF p_node ? 'filter' AND v_func IN ('sum', 'avg', 'min', 'max', 'count') THEN v_filter := p_node->'filter'; v_filt_sql := ' FILTER (WHERE ' || pvt_build_bool_expr(v_filter, p_fields, p_base_prefix) || ')'; END IF; v_over := _pvt_compile_window_over(p_node, p_fields, p_base_prefix); RETURN v_call || v_filt_sql || ' ' || v_over; END; $BODY$; COMMENT ON FUNCTION pvt_build_window_expr(jsonb, jsonb, text) IS 'Compiles a window-function node into a SQL fragment `FUNC(args) [FILTER (WHERE ...)] OVER (...)`. Supports ranking, navigation (lag/lead/first_value/...), and aggregate windows with optional FILTER. Frame spec: rows|range|groups + start/end bounds + optional exclude.'; -- ---------- Hook $over into pvt_build_scalar_expr --------------------- -- We can't extend scalar_expr from this file, but $over is recognised by -- the existing dispatcher's "no matching operator" branch via a tiny -- shim wrapper: callers may use either {"$over": } or a -- bare window node passed directly to pvt_build_window_expr. -- The shim is registered as a scalar-expr operator by replacing the -- final RAISE in pvt_build_scalar_expr -- see 17_pvt_expr.sql tail. -- --------------------------------------------------------------------- -- pvt_build_window_sql -- --------------------------------------------------------------------- DROP FUNCTION IF EXISTS pvt_build_window_sql(bigint, jsonb, jsonb, jsonb, integer, integer, text, bigint[], integer, boolean, boolean); CREATE OR REPLACE FUNCTION pvt_build_window_sql( p_scheme_id bigint, p_filter jsonb, p_select jsonb, p_order jsonb DEFAULT NULL, p_limit integer DEFAULT NULL, p_offset integer DEFAULT 0, p_source_mode text DEFAULT 'flat', p_tree_ids bigint[] DEFAULT NULL, p_max_depth integer DEFAULT NULL, p_include_seed boolean DEFAULT true, p_polymorphic boolean DEFAULT true ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_fields jsonb; v_extra jsonb; v_extra_names text[]; v_cte_sql text; v_where_sql text; v_order_sql text; v_paging text := ''; v_force_outer boolean; v_narrow boolean; v_push_sql text; v_residual jsonb; v_outer_filter jsonb; v_prefix text; v_sel_entry jsonb; v_sel_idx integer := 0; v_sel_col text; v_sel_alias text; v_sel_seen text[] := ARRAY[]::text[]; v_select_parts text[] := ARRAY[]::text[]; v_select_sql text; v_win_node jsonb; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_build_window_sql: p_scheme_id is required'; END IF; IF p_select IS NULL OR jsonb_typeof(p_select) <> 'array' OR jsonb_array_length(p_select) = 0 THEN RAISE EXCEPTION 'pvt_build_window_sql: p_select must be a non-empty JSON array'; END IF; -- 1. Collect fields from filter + select + order. v_fields := pvt_collect_fields( p_scheme_id, p_filter, CASE WHEN p_order IS NULL THEN p_select ELSE p_select || p_order END, false); -- 2. Extend with fields referenced inside window args / partition / -- order. Walk every $expr in the select array and harvest from -- nested $over nodes via pvt_window_field_names. (Regular $field -- refs inside $expr are already covered by pvt_collect_fields.) v_extra_names := ARRAY( SELECT DISTINCT n FROM ( SELECT pvt_window_field_names(e->'$expr'->'$over') AS n FROM jsonb_array_elements(p_select) e WHERE e ? '$expr' AND (e->'$expr') ? '$over' ) z WHERE n IS NOT NULL); v_extra := pvt_collect_extra_fields(p_scheme_id, v_extra_names); v_fields := v_fields || v_extra; -- 3. Base pushdown. SELECT s.v_pushdown_sql, s.v_residual_filter INTO v_push_sql, v_residual FROM pvt_split_filter(p_filter, v_fields) s; v_outer_filter := v_residual; -- 4. Narrow vs wide. Tree modes always go wide (CTE keyed on _id). v_force_outer := pvt_has_absence_check(v_outer_filter) OR (v_fields = '{}'::jsonb); v_narrow := p_source_mode = 'flat' AND NOT v_force_outer AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE (val->>'dict_key') IS NOT NULL AND (val->>'parent_sid') IS NOT NULL); v_prefix := CASE WHEN v_narrow THEN 'o.' ELSE '' END; -- 5. Shape A shortcut. IF v_outer_filter IS NULL AND p_source_mode = 'flat' AND (p_tree_ids IS NULL OR array_length(p_tree_ids, 1) IS NULL) AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') <> 'base' ) THEN v_prefix := 'o.'; v_narrow := false; ELSE v_cte_sql := pvt_build_cte_sql( p_scheme_id => p_scheme_id, p_fields => v_fields, p_source_mode => p_source_mode, p_tree_ids => p_tree_ids, p_max_depth => p_max_depth, p_force_outer => v_force_outer, p_extra_where => v_push_sql, p_narrow => v_narrow, p_include_seed => p_include_seed, p_polymorphic => p_polymorphic ); END IF; -- 6. Build select projection. FOR v_sel_entry IN SELECT value FROM jsonb_array_elements(p_select) LOOP v_sel_idx := v_sel_idx + 1; -- $over shortcut: {"$over": } as the entry's expression. IF v_sel_entry ? '$expr' AND jsonb_typeof(v_sel_entry->'$expr') = 'object' AND (v_sel_entry->'$expr') ? '$over' THEN v_win_node := (v_sel_entry->'$expr')->'$over'; v_sel_col := pvt_build_window_expr(v_win_node, v_fields, v_prefix); ELSE v_sel_col := _pvt_compile_order_col(v_sel_entry, v_fields, v_prefix, true); END IF; v_sel_alias := CASE WHEN v_sel_entry ? 'alias' AND jsonb_typeof(v_sel_entry->'alias') = 'string' THEN v_sel_entry->>'alias' WHEN v_sel_entry ? 'field' THEN v_sel_entry->>'field' WHEN v_sel_entry ? 'field_path' THEN v_sel_entry->>'field_path' ELSE '_sel_' || v_sel_idx::text END; IF v_sel_alias = ANY(v_sel_seen) THEN RAISE EXCEPTION 'pvt_build_window_sql: duplicate select alias "%"', v_sel_alias; END IF; v_sel_seen := v_sel_seen || v_sel_alias; v_select_parts := v_select_parts || (v_sel_col || ' AS ' || quote_ident(v_sel_alias)); END LOOP; v_select_sql := array_to_string(v_select_parts, ', '); -- 7. WHERE / ORDER BY / paging. v_where_sql := pvt_build_where_from_json(v_outer_filter, v_fields, v_prefix); v_order_sql := pvt_build_order_conditions(p_order, v_fields, v_prefix, NULL); IF p_limit IS NOT NULL AND p_limit >= 0 THEN v_paging := v_paging || E'\nLIMIT ' || p_limit::text; END IF; IF COALESCE(p_offset, 0) > 0 THEN v_paging := v_paging || E'\nOFFSET ' || p_offset::text; END IF; -- 8. Assemble. IF v_cte_sql IS NULL THEN RETURN 'SELECT ' || v_select_sql || ' FROM _objects o' || E'\nWHERE o._id_scheme = ' || p_scheme_id::text || CASE WHEN v_push_sql IS NOT NULL AND v_push_sql <> '' THEN ' AND ' || v_push_sql ELSE '' END || v_order_sql || v_paging; END IF; IF v_narrow THEN RETURN v_cte_sql || E'\nSELECT ' || v_select_sql || ' FROM _pvt_cte' || E'\nJOIN _objects o ON o._id = _pvt_cte._id_object' || E'\nWHERE ' || v_where_sql || v_order_sql || v_paging; END IF; RETURN v_cte_sql || E'\nSELECT ' || v_select_sql || ' FROM _pvt_cte' || E'\nWHERE ' || v_where_sql || v_order_sql || v_paging; END; $BODY$; COMMENT ON FUNCTION pvt_build_window_sql(bigint, jsonb, jsonb, jsonb, integer, integer, text, bigint[], integer, boolean, boolean) IS 'Window-function orchestrator. p_select is a non-empty array of {field|field_path|$expr, alias?} entries; window expressions are written as {alias, $expr: {$over: {func, args, partition_by, order_by, frame}}}. Tree variants reuse the same p_source_mode / p_tree_ids / p_max_depth / p_include_seed / p_polymorphic plumbing as pvt_build_query_sql.'; Path: redb/redb.SQLite/sql/v2-pvt/24_pvt_projection.sql 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/v2-pvt/24_pvt_projection.sql ---- -- ===================================================================== -- 24_pvt_projection.sql -- --------------------------------------------------------------------- -- Generic column projection ("Select" shaping). Sister of -- pvt_build_query_sql (file 20): same source-mode / tree / push-down -- plumbing, but instead of returning a single `_id` column the outer -- SELECT yields an arbitrary list of typed columns built from the -- entries in p_projection. -- -- A projection entry has one of the following shapes: -- -- { "field": "Name" } -- bare field -- { "field_path": "Address.City", "alias": "city" } -- nested path -- { "alias": "yr", -- "$expr": { "$year": { "$field": "HireDate" } } } -- expression -- { "alias": "kind", -- "$expr": { "$case": [ -- { "when": {"$gt":[{"$field":"Age"},{"$const":18}]}, -- "then": {"$const":"adult"} }, -- { "else": {"$const":"kid"} } ] } } -- -- Functions: -- pvt_projection_field_names(p_projection) -- -> SETOF text (every field path referenced by projection -- entries, for pvt_collect_extra_fields) -- pvt_build_projection(p_projection, p_fields, p_base_prefix) -- -> text (a ` AS "", ...` fragment, no -- leading SELECT) -- pvt_build_projection_sql(...) -> text (full SELECT orchestrator, -- Shape A / B narrow / C wide) -- -- Free-over-Pro angle: projections can carry arbitrary scalar-expr -- nodes ($case / $coalesce / $cast / $year / $power / $concat / ...); -- Pro's projection path is limited to bare field references plus a -- handful of arithmetic / string ops on primitives. -- ===================================================================== -- ---------- pvt_projection_field_names -------------------------------- -- Yield every field path referenced inside a projection array. Used by -- the orchestrator to extend the fields map fed into pvt_build_cte_sql -- via pvt_collect_extra_fields. CREATE OR REPLACE FUNCTION pvt_projection_field_names(p_projection jsonb) RETURNS SETOF text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_entry jsonb; v_path text; BEGIN IF p_projection IS NULL OR jsonb_typeof(p_projection) <> 'array' THEN RETURN; END IF; FOR v_entry IN SELECT value FROM jsonb_array_elements(p_projection) LOOP IF v_entry IS NULL OR jsonb_typeof(v_entry) <> 'object' THEN CONTINUE; END IF; IF v_entry ? 'field' AND jsonb_typeof(v_entry->'field') = 'string' THEN v_path := v_entry->>'field'; IF v_path IS NOT NULL AND v_path <> '' THEN RETURN NEXT v_path; END IF; END IF; IF v_entry ? 'field_path' AND jsonb_typeof(v_entry->'field_path') = 'string' THEN v_path := v_entry->>'field_path'; IF v_path IS NOT NULL AND v_path <> '' THEN RETURN NEXT v_path; END IF; END IF; IF v_entry ? '$expr' THEN RETURN QUERY SELECT pvt_expr_field_names(v_entry->'$expr'); END IF; END LOOP; END; $BODY$; COMMENT ON FUNCTION pvt_projection_field_names(jsonb) IS 'Yields every field path referenced inside a projection array (bare field / field_path entries plus $expr operands). Empty when p_projection is null or non-array.'; -- ---------- pvt_build_projection -------------------------------------- -- Compile a projection array into a SELECT-list fragment. -- Aliases default to: the field/field_path value (when present) or -- `_proj_` (positional). Duplicate aliases raise. CREATE OR REPLACE FUNCTION pvt_build_projection( p_projection jsonb, p_fields jsonb, p_base_prefix text DEFAULT '' ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_entry jsonb; v_alias text; v_expr jsonb; v_sql text; v_seen text[] := ARRAY[]::text[]; v_parts text[] := ARRAY[]::text[]; v_idx integer := 0; v_keys integer; BEGIN IF p_projection IS NULL OR jsonb_typeof(p_projection) <> 'array' OR jsonb_array_length(p_projection) = 0 THEN RAISE EXCEPTION 'pvt_build_projection: p_projection must be a non-empty JSON array'; END IF; FOR v_entry IN SELECT value FROM jsonb_array_elements(p_projection) LOOP v_idx := v_idx + 1; IF v_entry IS NULL OR jsonb_typeof(v_entry) <> 'object' THEN RAISE EXCEPTION 'pvt_build_projection: entry #% is not a JSON object', v_idx; END IF; -- Exactly one source key per entry: field | field_path | $expr. v_keys := (CASE WHEN v_entry ? 'field' THEN 1 ELSE 0 END) + (CASE WHEN v_entry ? 'field_path' THEN 1 ELSE 0 END) + (CASE WHEN v_entry ? '$expr' THEN 1 ELSE 0 END); IF v_keys = 0 THEN RAISE EXCEPTION 'pvt_build_projection: entry #% has no source key (field|field_path|$expr): %', v_idx, v_entry::text; END IF; IF v_keys > 1 THEN RAISE EXCEPTION 'pvt_build_projection: entry #% has more than one source key (field|field_path|$expr): %', v_idx, v_entry::text; END IF; -- Determine alias. IF v_entry ? 'alias' AND jsonb_typeof(v_entry->'alias') = 'string' THEN v_alias := v_entry->>'alias'; ELSIF v_entry ? 'field' THEN v_alias := v_entry->>'field'; ELSIF v_entry ? 'field_path' THEN v_alias := v_entry->>'field_path'; ELSE v_alias := '_proj_' || v_idx::text; END IF; IF v_alias IS NULL OR v_alias = '' THEN RAISE EXCEPTION 'pvt_build_projection: entry #% has empty alias', v_idx; END IF; IF v_alias = ANY(v_seen) THEN RAISE EXCEPTION 'pvt_build_projection: duplicate alias "%"', v_alias; END IF; v_seen := v_seen || v_alias; -- Normalize source to a scalar-expr node. IF v_entry ? '$expr' THEN v_expr := v_entry->'$expr'; ELSIF v_entry ? 'field' THEN v_expr := jsonb_build_object('$field', v_entry->>'field'); ELSE v_expr := jsonb_build_object('$field', v_entry->>'field_path'); END IF; v_sql := pvt_build_scalar_expr(v_expr, p_fields, p_base_prefix); v_parts := v_parts || (v_sql || ' AS ' || quote_ident(v_alias)); END LOOP; RETURN array_to_string(v_parts, ', '); END; $BODY$; COMMENT ON FUNCTION pvt_build_projection(jsonb, jsonb, text) IS 'Compiles a projection array into a SELECT-list fragment ` AS "", ...`. Supports {field} | {field_path} | {$expr:} entries. Aliases default to the field name or `_proj_` (positional).'; -- ===================================================================== -- pvt_build_projection_sql -- --------------------------------------------------------------------- -- Full orchestrator: produce a complete SELECT statement that yields -- the requested projection. Mirrors pvt_build_query_sql for filter / -- order / distinct / tree / push-down handling; the only difference is -- the SELECT list comes from p_projection instead of being a fixed -- `_id`. -- ===================================================================== DROP FUNCTION IF EXISTS pvt_build_projection_sql(bigint, jsonb, jsonb, integer, integer, jsonb, integer, boolean, text, bigint[], boolean, boolean, jsonb); CREATE OR REPLACE FUNCTION pvt_build_projection_sql( p_scheme_id bigint, p_projection jsonb, p_filter jsonb DEFAULT NULL, p_limit integer DEFAULT NULL, p_offset integer DEFAULT 0, p_order jsonb DEFAULT NULL, p_max_depth integer DEFAULT NULL, p_distinct boolean DEFAULT false, p_source_mode text DEFAULT 'flat', p_tree_ids bigint[] DEFAULT NULL, p_include_seed boolean DEFAULT true, p_polymorphic boolean DEFAULT true, p_distinct_on jsonb DEFAULT NULL ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_fields jsonb; v_extra jsonb; v_extra_names text[]; v_cte_sql text; v_where_sql text; v_order_sql text; v_paging text := ''; v_force_outer boolean; v_narrow boolean; v_push_sql text; v_residual jsonb; v_outer_filter jsonb; v_proj text; v_prefix text; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_build_projection_sql: p_scheme_id is required'; END IF; IF p_projection IS NULL OR jsonb_typeof(p_projection) <> 'array' OR jsonb_array_length(p_projection) = 0 THEN RAISE EXCEPTION 'pvt_build_projection_sql: p_projection must be a non-empty JSON array'; END IF; -- DISTINCT and DISTINCT ON are mutually exclusive. IF p_distinct AND p_distinct_on IS NOT NULL AND jsonb_typeof(p_distinct_on) = 'array' AND jsonb_array_length(p_distinct_on) > 0 THEN RAISE EXCEPTION 'pvt_build_projection_sql: p_distinct and p_distinct_on are mutually exclusive'; END IF; -- 1. Collect fields from filter + order + distinct_on (same channel -- as pvt_build_query_sql), then extend with projection refs. v_fields := pvt_collect_fields( p_scheme_id, p_filter, CASE WHEN p_distinct_on IS NULL THEN p_order WHEN p_order IS NULL THEN p_distinct_on ELSE p_order || p_distinct_on END, false); v_extra_names := ARRAY(SELECT DISTINCT n FROM pvt_projection_field_names(p_projection) AS n WHERE n IS NOT NULL); v_extra := pvt_collect_extra_fields(p_scheme_id, v_extra_names); v_fields := v_fields || v_extra; -- 2. Base pushdown. SELECT s.v_pushdown_sql, s.v_residual_filter INTO v_push_sql, v_residual FROM pvt_split_filter(p_filter, v_fields) s; v_outer_filter := v_residual; -- 3. Shape A shortcut: pure-base flat projection. IF v_outer_filter IS NULL AND p_source_mode = 'flat' AND (p_tree_ids IS NULL OR array_length(p_tree_ids, 1) IS NULL) AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE COALESCE(val->>'kind', '') <> 'base' ) THEN v_order_sql := pvt_build_order_conditions(p_order, v_fields, 'o.', p_distinct_on); v_proj := pvt_build_projection(p_projection, v_fields, 'o.'); IF p_limit IS NOT NULL AND p_limit >= 0 THEN v_paging := v_paging || E'\nLIMIT ' || p_limit::text; END IF; IF COALESCE(p_offset, 0) > 0 THEN v_paging := v_paging || E'\nOFFSET ' || p_offset::text; END IF; RETURN 'SELECT ' || CASE WHEN p_distinct THEN 'DISTINCT ' ELSE '' END || pvt_build_distinct_on_select(p_distinct_on, v_fields, 'o.') || v_proj || ' FROM _objects o' || E'\nWHERE o._id_scheme = ' || p_scheme_id::text || CASE WHEN v_push_sql IS NOT NULL AND v_push_sql <> '' THEN ' AND ' || v_push_sql ELSE '' END || v_order_sql || v_paging; END IF; -- 4. Narrow vs wide. Tree modes always go wide (pvt_build_cte_sql -- emits base-cols CTE keyed on _id in tree mode, not _id_object). v_force_outer := pvt_has_absence_check(v_outer_filter) OR (v_fields = '{}'::jsonb); v_narrow := p_source_mode = 'flat' AND NOT v_force_outer AND NOT EXISTS ( SELECT 1 FROM jsonb_each(v_fields) AS e(k, val) WHERE (val->>'dict_key') IS NOT NULL AND (val->>'parent_sid') IS NOT NULL); v_prefix := CASE WHEN v_narrow THEN 'o.' ELSE '' END; -- 5. Build CTE. v_cte_sql := pvt_build_cte_sql( p_scheme_id => p_scheme_id, p_fields => v_fields, p_source_mode => p_source_mode, p_tree_ids => p_tree_ids, p_max_depth => p_max_depth, p_force_outer => v_force_outer, p_extra_where => v_push_sql, p_narrow => v_narrow, p_include_seed => p_include_seed, p_polymorphic => p_polymorphic ); -- 6. WHERE / ORDER / projection (prefix depends on shape). v_where_sql := pvt_build_where_from_json(v_outer_filter, v_fields, v_prefix); v_order_sql := pvt_build_order_conditions(p_order, v_fields, v_prefix, p_distinct_on); v_proj := pvt_build_projection(p_projection, v_fields, v_prefix); -- 7. Paging. IF p_limit IS NOT NULL AND p_limit >= 0 THEN v_paging := v_paging || E'\nLIMIT ' || p_limit::text; END IF; IF COALESCE(p_offset, 0) > 0 THEN v_paging := v_paging || E'\nOFFSET ' || p_offset::text; END IF; -- 8. Assemble outer SELECT. IF v_narrow THEN RETURN v_cte_sql || E'\nSELECT ' || CASE WHEN p_distinct THEN 'DISTINCT ' ELSE '' END || pvt_build_distinct_on_select(p_distinct_on, v_fields, v_prefix) || v_proj || ' FROM _pvt_cte' || E'\nJOIN _objects o ON o._id = _pvt_cte._id_object' || E'\nWHERE ' || v_where_sql || v_order_sql || v_paging; END IF; RETURN v_cte_sql || E'\nSELECT ' || CASE WHEN p_distinct THEN 'DISTINCT ' ELSE '' END || pvt_build_distinct_on_select(p_distinct_on, v_fields, v_prefix) || v_proj || ' FROM _pvt_cte' || E'\nWHERE ' || v_where_sql || v_order_sql || v_paging; END; $BODY$; COMMENT ON FUNCTION pvt_build_projection_sql(bigint, jsonb, jsonb, integer, integer, jsonb, integer, boolean, text, bigint[], boolean, boolean, jsonb) IS 'Factor-1 projection orchestrator. Composes pvt_collect_fields + pvt_collect_extra_fields + pvt_build_cte_sql + pvt_build_where_from_json + pvt_build_order_conditions + pvt_build_projection into a complete SELECT statement with arbitrary projected columns. p_projection accepts entries {field} | {field_path} | {alias?, $expr:}. Filter / order / distinct / source-mode / pushdown semantics are identical to pvt_build_query_sql.'; Path: redb/redb.SQLite/sql/v2-pvt/25_object_props_v2.sql 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/v2-pvt/25_object_props_v2.sql ---- -- ===================================================================== -- 25_object_props_v2.sql -- --------------------------------------------------------------------- -- Experimental SQL-driven re-implementation of the per-level reader -- build_hierarchical_properties_optimized() → build_hierarchical_properties_sql() -- and a wrapper -- get_object_json() → get_object_json_v2() -- for A/B benchmarking against the production reader. -- -- Goal: -- replace the plpgsql FOR-LOOP over _scheme_metadata_cache fields with -- a single SQL statement that materializes all field values at the -- current nesting level via jsonb_object_agg(field_name, field_value). -- -- Semantics: -- MUST be byte-for-byte identical to build_hierarchical_properties_optimized() -- for a fixed depth. Verified by comparing md5(get_object_json(id)::text) -- against md5(get_object_json_v2(id)::text) over all objects. -- -- Notes: -- - These functions live alongside the production ones; nothing existing -- is overridden. To switch the reader globally, change get_object_json -- in redb_json_objects.sql to call build_hierarchical_properties_sql. -- - File is bundled into pvt_bundle.sql by _bundle.ps1. It only adds new -- functions, so re-running the bundle on prod is safe. -- ===================================================================== DROP FUNCTION IF EXISTS build_hierarchical_properties_sql(bigint, bigint, bigint, _values[], integer, text, bigint); DROP FUNCTION IF EXISTS get_object_json_v2(bigint, integer); -- --------------------------------------------------------------------- -- build_hierarchical_properties_sql -- --------------------------------------------------------------------- CREATE OR REPLACE FUNCTION build_hierarchical_properties_sql( object_id bigint, parent_structure_id bigint, object_scheme_id bigint, all_values _values[], max_depth integer DEFAULT 10, array_index text DEFAULT NULL, parent_value_id bigint DEFAULT NULL ) RETURNS jsonb LANGUAGE plpgsql COST 100 VOLATILE NOT LEAKPROOF AS $BODY$ DECLARE result_json jsonb; BEGIN -- Defensive recursion guard (matches original behavior) IF max_depth < -100 THEN RETURN jsonb_build_object('error', 'Max recursion depth reached for hierarchical fields'); END IF; -- Auto-populate metadata cache (matches original behavior) IF NOT EXISTS(SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = object_scheme_id LIMIT 1) THEN PERFORM sync_metadata_cache_for_scheme(object_scheme_id); END IF; -- ONE SQL statement: build all fields at this nesting level. -- jsonb_object_agg replaces the plpgsql FOR-LOOP + `||` concat. SELECT jsonb_object_agg(field_name, field_value ORDER BY field_order, field_struct_id) INTO result_json FROM ( SELECT c._name AS field_name, c._order AS field_order, c._structure_id AS field_struct_id, CASE -- =========== ARRAY =========== WHEN c._collection_type = -9223372036854775668 THEN CASE -- No head record => array property is NULL WHEN NOT EXISTS ( SELECT 1 FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND v._array_index IS NULL AND ((parent_value_id IS NULL AND v._array_parent_id IS NULL) OR (parent_value_id IS NOT NULL AND v._array_parent_id = parent_value_id)) ) THEN NULL -- Array of Class WHEN c.type_semantic = 'Object' THEN COALESCE( (SELECT jsonb_agg( build_hierarchical_properties_sql( object_id, c._structure_id, object_scheme_id, all_values, max_depth, v._array_index, v._id) ORDER BY CASE WHEN v._array_index ~ '^[0-9]+$' THEN v._array_index::int ELSE 0 END, v._array_index) FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND v._array_index IS NOT NULL AND v._array_parent_id = ( SELECT v2._id FROM unnest(all_values) v2 WHERE v2._id_structure = c._structure_id AND v2._array_index IS NULL AND ((parent_value_id IS NULL AND v2._array_parent_id IS NULL) OR (parent_value_id IS NOT NULL AND v2._array_parent_id = parent_value_id)) LIMIT 1)), '[]'::jsonb) -- Array of primitives / RObject ELSE COALESCE( (SELECT jsonb_agg( CASE WHEN c.type_semantic = '_RObject' AND v._Object IS NOT NULL THEN get_object_json(v._Object, max_depth - 1) WHEN c.db_type = 'String' THEN to_jsonb(v._String) WHEN c.db_type = 'Long' THEN CASE WHEN v._ListItem IS NOT NULL THEN build_listitem_jsonb(v._ListItem, max_depth) ELSE to_jsonb(v._Long) END WHEN c.db_type = 'Guid' THEN to_jsonb(v._Guid) WHEN c.db_type = 'Double' THEN to_jsonb(v._Double) WHEN c.db_type = 'Numeric' THEN to_jsonb(v._Numeric) WHEN c.db_type = 'DateTimeOffset' THEN to_jsonb(v._DateTimeOffset) WHEN c.db_type = 'Boolean' THEN to_jsonb(v._Boolean) WHEN c.db_type = 'ListItem' THEN build_listitem_jsonb(v._ListItem, max_depth) WHEN c.db_type = 'ByteArray' THEN to_jsonb(encode(decode(v._ByteArray::text, 'base64'), 'base64')) ELSE NULL END ORDER BY CASE WHEN v._array_index ~ '^[0-9]+$' THEN v._array_index::int ELSE 0 END, v._array_index) FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND v._array_index IS NOT NULL AND v._array_parent_id = ( SELECT v2._id FROM unnest(all_values) v2 WHERE v2._id_structure = c._structure_id AND v2._array_index IS NULL AND ((parent_value_id IS NULL AND v2._array_parent_id IS NULL) OR (parent_value_id IS NOT NULL AND v2._array_parent_id = parent_value_id)) LIMIT 1)), '[]'::jsonb) END -- =========== DICTIONARY =========== WHEN c._collection_type = -9223372036854775667 THEN CASE WHEN NOT EXISTS ( SELECT 1 FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND v._array_index IS NULL AND ((parent_value_id IS NULL AND v._array_parent_id IS NULL) OR (parent_value_id IS NOT NULL AND v._array_parent_id = parent_value_id)) ) THEN NULL -- Dict WHEN c.type_semantic = '_RObject' THEN COALESCE( (SELECT jsonb_object_agg(v._array_index, CASE WHEN v._Object IS NOT NULL THEN get_object_json(v._Object, max_depth - 1) ELSE NULL END) FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND v._array_index IS NOT NULL AND v._array_parent_id = ( SELECT v2._id FROM unnest(all_values) v2 WHERE v2._id_structure = c._structure_id AND v2._array_index IS NULL AND ((parent_value_id IS NULL AND v2._array_parent_id IS NULL) OR (parent_value_id IS NOT NULL AND v2._array_parent_id = parent_value_id)) LIMIT 1)), '{}'::jsonb) -- Dict WHEN c.type_semantic = 'Object' THEN COALESCE( (SELECT jsonb_object_agg(v._array_index, build_hierarchical_properties_sql( object_id, c._structure_id, object_scheme_id, all_values, max_depth, NULL, v._id)) FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND v._array_index IS NOT NULL AND v._array_parent_id = ( SELECT v2._id FROM unnest(all_values) v2 WHERE v2._id_structure = c._structure_id AND v2._array_index IS NULL AND ((parent_value_id IS NULL AND v2._array_parent_id IS NULL) OR (parent_value_id IS NOT NULL AND v2._array_parent_id = parent_value_id)) LIMIT 1)), '{}'::jsonb) -- Dict ELSE COALESCE( (SELECT jsonb_object_agg(v._array_index, CASE WHEN c.db_type = 'String' THEN to_jsonb(v._String) WHEN c.db_type = 'Long' THEN to_jsonb(v._Long) WHEN c.db_type = 'Guid' THEN to_jsonb(v._Guid) WHEN c.db_type = 'Double' THEN to_jsonb(v._Double) WHEN c.db_type = 'Numeric' THEN to_jsonb(v._Numeric) WHEN c.db_type = 'DateTimeOffset' THEN to_jsonb(v._DateTimeOffset) WHEN c.db_type = 'Boolean' THEN to_jsonb(v._Boolean) ELSE NULL END) FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND v._array_index IS NOT NULL AND v._array_parent_id = ( SELECT v2._id FROM unnest(all_values) v2 WHERE v2._id_structure = c._structure_id AND v2._array_index IS NULL AND ((parent_value_id IS NULL AND v2._array_parent_id IS NULL) OR (parent_value_id IS NOT NULL AND v2._array_parent_id = parent_value_id)) LIMIT 1)), '{}'::jsonb) END -- =========== SCALAR RObject =========== WHEN c.type_name = 'Object' AND c.type_semantic = '_RObject' THEN (SELECT CASE WHEN v._Object IS NOT NULL THEN get_object_json(v._Object, max_depth - 1) ELSE NULL END FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND CASE WHEN parent_value_id IS NOT NULL THEN v._array_parent_id = parent_value_id WHEN array_index IS NOT NULL THEN v._array_index = array_index ELSE v._array_index IS NULL END LIMIT 1) -- =========== SCALAR Class =========== WHEN c.type_semantic = 'Object' THEN (SELECT CASE WHEN v._Guid IS NULL THEN NULL ELSE build_hierarchical_properties_sql( object_id, c._structure_id, object_scheme_id, all_values, max_depth, NULL, v._id) END FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND CASE WHEN parent_value_id IS NOT NULL THEN v._array_parent_id = parent_value_id WHEN array_index IS NOT NULL THEN v._array_index = array_index ELSE v._array_index IS NULL END LIMIT 1) -- =========== SCALAR primitives =========== ELSE (SELECT CASE WHEN c.db_type = 'String' THEN to_jsonb(v._String) WHEN c.db_type = 'Long' THEN CASE WHEN v._ListItem IS NOT NULL THEN build_listitem_jsonb(v._ListItem, max_depth) ELSE to_jsonb(v._Long) END WHEN c.db_type = 'Guid' THEN to_jsonb(v._Guid) WHEN c.db_type = 'Double' THEN to_jsonb(v._Double) WHEN c.db_type = 'Numeric' THEN to_jsonb(v._Numeric) WHEN c.db_type = 'DateTimeOffset' THEN to_jsonb(v._DateTimeOffset) WHEN c.db_type = 'Boolean' THEN to_jsonb(v._Boolean) WHEN c.db_type = 'ListItem' OR v._ListItem IS NOT NULL THEN CASE WHEN v._ListItem IS NOT NULL THEN build_listitem_jsonb(v._ListItem, max_depth) ELSE NULL END WHEN c.db_type = 'ByteArray' THEN CASE WHEN v._ByteArray IS NOT NULL THEN to_jsonb(encode(decode(v._ByteArray::text, 'base64'), 'base64')) ELSE NULL END ELSE NULL END FROM unnest(all_values) v WHERE v._id_structure = c._structure_id AND CASE WHEN parent_value_id IS NOT NULL THEN v._array_parent_id = parent_value_id WHEN array_index IS NOT NULL THEN v._array_index = array_index ELSE v._array_index IS NULL END LIMIT 1) END AS field_value FROM _scheme_metadata_cache c WHERE c._scheme_id = object_scheme_id AND ((parent_structure_id IS NULL AND c._parent_structure_id IS NULL) OR (parent_structure_id IS NOT NULL AND c._parent_structure_id = parent_structure_id)) ) f WHERE f.field_value IS NOT NULL; RETURN COALESCE(result_json, '{}'::jsonb); END; $BODY$; -- --------------------------------------------------------------------- -- get_object_json_v2 — wrapper that calls build_hierarchical_properties_sql. -- Top-level body identical to get_object_json (only the inner call differs). -- --------------------------------------------------------------------- CREATE OR REPLACE FUNCTION get_object_json_v2( object_id bigint, max_depth integer DEFAULT 10 ) RETURNS jsonb LANGUAGE plpgsql COST 100 VOLATILE NOT LEAKPROOF AS $BODY$ DECLARE result_json jsonb; object_exists boolean; base_info jsonb; properties_info jsonb; object_scheme_id bigint; all_values _values[]; BEGIN SELECT EXISTS(SELECT 1 FROM _objects WHERE _id = object_id) INTO object_exists; IF NOT object_exists THEN RETURN NULL; END IF; IF max_depth <= 0 THEN SELECT jsonb_build_object( 'id', o._id, 'name', o._name, 'scheme_id', o._id_scheme, 'scheme_name', sc._name, 'parent_id', o._id_parent, 'owner_id', o._id_owner, 'who_change_id', o._id_who_change, 'date_create', o._date_create, 'date_modify', o._date_modify, 'date_begin', o._date_begin, 'date_complete', o._date_complete, 'key', o._key, 'value_long', o._value_long, 'value_string', o._value_string, 'value_guid', o._value_guid, 'note', o._note, 'value_bool', o._value_bool, 'value_double', o._value_double, 'value_numeric', o._value_numeric, 'value_datetime', o._value_datetime, 'value_bytes', o._value_bytes, 'hash', o._hash ) INTO result_json FROM _objects o JOIN _schemes sc ON sc._id = o._id_scheme WHERE o._id = object_id; RETURN result_json; END IF; SELECT jsonb_build_object( 'id', o._id, 'name', o._name, 'scheme_id', o._id_scheme, 'scheme_name', sc._name, 'parent_id', o._id_parent, 'owner_id', o._id_owner, 'who_change_id', o._id_who_change, 'date_create', o._date_create, 'date_modify', o._date_modify, 'date_begin', o._date_begin, 'date_complete', o._date_complete, 'key', o._key, 'value_long', o._value_long, 'value_string', o._value_string, 'value_guid', o._value_guid, 'note', o._note, 'value_bool', o._value_bool, 'value_double', o._value_double, 'value_numeric', o._value_numeric, 'value_datetime', o._value_datetime, 'value_bytes', o._value_bytes, 'hash', o._hash ), o._id_scheme INTO base_info, object_scheme_id FROM _objects o JOIN _schemes sc ON sc._id = o._id_scheme WHERE o._id = object_id; SELECT array_agg(v) INTO all_values FROM _values v WHERE v._id_object = object_id; IF all_values IS NULL THEN RETURN base_info || jsonb_build_object('properties', NULL); END IF; SELECT build_hierarchical_properties_sql( object_id, NULL, object_scheme_id, COALESCE(all_values, ARRAY[]::_values[]), max_depth, NULL, NULL ) INTO properties_info; RETURN base_info || jsonb_build_object('properties', COALESCE(properties_info, '{}'::jsonb)); END; $BODY$; Path: redb/redb.SQLite/sql/v2-pvt/26_pvt_array_groupby.sql 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/v2-pvt/26_pvt_array_groupby.sql ---- -- ===================================================================== -- 26_pvt_array_groupby.sql -- --------------------------------------------------------------------- -- Array-element GROUP BY orchestrator. Sister of 22_pvt_groupby.sql but -- operates on a flat element-level subquery (LEFT JOINs on _values -- keyed via _array_parent_id), so it intentionally bypasses the -- object-pivot CTE machinery. -- -- pvt_build_array_groupby_sql( -- p_scheme_id bigint, -- p_array_path text, -- e.g. 'Items' -- p_filter jsonb, -- optional outer object filter (PVT shape); when -- -- non-empty, compiled via pvt_build_query_sql and -- -- applied as arr._id_object IN (). -- p_group_by jsonb, -- non-empty array of {field, alias?} -- p_aggregations jsonb, -- optional array of legacy agg entries -- -- ({field, func, alias}) - same shape as -- -- aggregate_array_grouped consumes -- p_having jsonb, -- optional bool expression (PVT shape: -- -- $and/$or/$not + $gt/$gte/$lt/$lte/$eq/$ne -- -- with $sum/$count/$avg/$min/$max/$field/$const) -- p_order jsonb, -- optional [{field, asc?}] over outer aliases -- p_limit integer, -- p_offset integer -- ) RETURNS text -- -- Inner subquery shape: -- SELECT g1. AS "Field1", a1. AS "Field2", ... -- FROM _values arr -- JOIN _objects o ON o._id = arr._id_object -- LEFT JOIN _values g1 ON g1._id_object = arr._id_object -- AND g1._id_structure = -- AND g1._array_parent_id = arr._id -- ... -- WHERE o._id_scheme = AND arr._id_structure = -- AND arr._array_index IS NOT NULL -- -- Outer query: SELECT/GROUP BY/HAVING/ORDER/LIMIT/OFFSET over inner. -- -- HAVING reuses pvt_build_bool_expr against a fields-map populated for -- non-base ('props' kind) entries, so $field references resolve to the -- bare quoted alias emitted by the inner subquery. -- ===================================================================== DROP FUNCTION IF EXISTS pvt_build_array_groupby_sql(bigint, text, jsonb, jsonb, jsonb, jsonb, jsonb, integer, integer); CREATE OR REPLACE FUNCTION pvt_build_array_groupby_sql( p_scheme_id bigint, p_array_path text, p_filter jsonb DEFAULT NULL, p_group_by jsonb DEFAULT NULL, p_aggregations jsonb DEFAULT NULL, p_having jsonb DEFAULT NULL, p_order jsonb DEFAULT NULL, p_limit integer DEFAULT NULL, p_offset integer DEFAULT 0 ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_arr_sid bigint; v_grp_entry jsonb; v_agg_entry jsonb; v_ord_entry jsonb; v_field_path text; v_alias text; v_func text; v_resolved record; v_join_alias text; v_col_name text; v_join_idx integer := 0; v_join_parts text[] := ARRAY[]::text[]; v_inner_select text[] := ARRAY[]::text[]; v_fields_map jsonb := '{}'::jsonb; v_select_parts text[] := ARRAY[]::text[]; v_group_parts text[] := ARRAY[]::text[]; v_alias_seen text[] := ARRAY[]::text[]; v_ord_parts text[] := ARRAY[]::text[]; v_having_sql text := ''; v_paging text := ''; v_inner_sql text; v_filter_sql text; v_filter_clause text := ''; BEGIN IF p_scheme_id IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: p_scheme_id is required'; END IF; IF p_array_path IS NULL OR p_array_path = '' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: p_array_path is required'; END IF; IF p_group_by IS NULL OR jsonb_typeof(p_group_by) <> 'array' OR jsonb_array_length(p_group_by) = 0 THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: p_group_by must be a non-empty JSON array'; END IF; -- Outer object filter: compile via pvt_build_query_sql into an -- "_id IN (...)" clause applied at the inner level (before unnest). IF p_filter IS NOT NULL AND jsonb_typeof(p_filter) = 'object' AND p_filter <> '{}'::jsonb THEN v_filter_sql := pvt_build_query_sql( p_scheme_id => p_scheme_id, p_filter => p_filter, p_limit => NULL, p_offset => 0, p_order => NULL, p_max_depth => NULL, p_distinct => false); v_filter_clause := format( E'\n AND arr._id_object IN (SELECT _id FROM (%s) _filt)', v_filter_sql); END IF; -- Resolve array structure id SELECT r.structure_id INTO v_arr_sid FROM pvt_resolve_field_path_table(p_scheme_id, p_array_path) r; IF v_arr_sid IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: array "%" not found in scheme %', p_array_path, p_scheme_id; END IF; -- ---- group_by entries: register joins, inner aliases, outer GROUP BY parts FOR v_grp_entry IN SELECT value FROM jsonb_array_elements(p_group_by) LOOP v_field_path := v_grp_entry->>'field'; IF v_field_path IS NULL OR v_field_path = '' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: group_by entry missing "field"'; END IF; v_alias := COALESCE(v_grp_entry->>'alias', v_field_path); IF v_alias = ANY(v_alias_seen) THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: duplicate alias "%"', v_alias; END IF; SELECT r.structure_id, r.db_type INTO v_resolved FROM pvt_resolve_field_path_table(p_scheme_id, p_array_path || '[].' || v_field_path) r; IF v_resolved.structure_id IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: group field "%" not found inside array "%"', v_field_path, p_array_path; END IF; v_join_idx := v_join_idx + 1; v_join_alias := 'g' || v_join_idx::text; v_col_name := pvt_db_type_to_value_column(v_resolved.db_type); IF v_col_name IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: unsupported db_type "%" for field "%"', v_resolved.db_type, v_field_path; END IF; v_join_parts := v_join_parts || format( 'LEFT JOIN _values %I ON %I._id_object = arr._id_object AND %I._id_structure = %s AND %I._array_parent_id = arr._id', v_join_alias, v_join_alias, v_join_alias, v_resolved.structure_id, v_join_alias); -- NOTE: typed value columns (_String/_Long/...) are declared unquoted in DDL -- and therefore case-folded to lowercase by PG. Reference them via %s (bare), -- never %I (quoted), to avoid 42703 column-not-found errors. v_inner_select := v_inner_select || format('%I.%s AS %I', v_join_alias, v_col_name, v_field_path); v_fields_map := v_fields_map || jsonb_build_object( v_field_path, jsonb_build_object('kind', 'props', 'db_type', v_resolved.db_type)); v_select_parts := v_select_parts || (quote_ident(v_field_path) || ' AS ' || quote_ident(v_alias)); v_group_parts := v_group_parts || quote_ident(v_field_path); v_alias_seen := v_alias_seen || v_alias; END LOOP; -- ---- aggregations IF p_aggregations IS NOT NULL AND jsonb_typeof(p_aggregations) = 'array' THEN FOR v_agg_entry IN SELECT value FROM jsonb_array_elements(p_aggregations) LOOP v_field_path := v_agg_entry->>'field'; v_func := upper(COALESCE(v_agg_entry->>'func', '')); v_alias := COALESCE(v_agg_entry->>'alias', v_func); IF v_alias = '' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: aggregation missing func'; END IF; IF v_alias = ANY(v_alias_seen) THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: duplicate alias "%"', v_alias; END IF; IF v_func = 'COUNT' AND (v_field_path IS NULL OR v_field_path = '*') THEN v_select_parts := v_select_parts || ('COUNT(*) AS ' || quote_ident(v_alias)); v_alias_seen := v_alias_seen || v_alias; CONTINUE; END IF; -- Add element-field join if not already projected by group_by IF NOT (v_fields_map ? v_field_path) THEN SELECT r.structure_id, r.db_type INTO v_resolved FROM pvt_resolve_field_path_table(p_scheme_id, p_array_path || '[].' || v_field_path) r; IF v_resolved.structure_id IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: agg field "%" not found inside array "%"', v_field_path, p_array_path; END IF; v_join_idx := v_join_idx + 1; v_join_alias := 'a' || v_join_idx::text; v_col_name := pvt_db_type_to_value_column(v_resolved.db_type); IF v_col_name IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: unsupported db_type "%" for agg field "%"', v_resolved.db_type, v_field_path; END IF; v_join_parts := v_join_parts || format( 'LEFT JOIN _values %I ON %I._id_object = arr._id_object AND %I._id_structure = %s AND %I._array_parent_id = arr._id', v_join_alias, v_join_alias, v_join_alias, v_resolved.structure_id, v_join_alias); -- See note above: %s (bare) for typed value columns. v_inner_select := v_inner_select || format('%I.%s AS %I', v_join_alias, v_col_name, v_field_path); v_fields_map := v_fields_map || jsonb_build_object( v_field_path, jsonb_build_object('kind', 'props', 'db_type', v_resolved.db_type)); END IF; v_select_parts := v_select_parts || ( v_func || '(' || quote_ident(v_field_path) || ') AS ' || quote_ident(v_alias)); v_alias_seen := v_alias_seen || v_alias; END LOOP; END IF; -- ---- HAVING: pre-collect $field refs, register joins, then translate IF p_having IS NOT NULL AND jsonb_typeof(p_having) = 'object' AND p_having <> '{}'::jsonb THEN FOR v_field_path IN SELECT DISTINCT n FROM pvt_expr_field_names(p_having) n WHERE n IS NOT NULL LOOP IF v_fields_map ? v_field_path THEN CONTINUE; END IF; SELECT r.structure_id, r.db_type INTO v_resolved FROM pvt_resolve_field_path_table(p_scheme_id, p_array_path || '[].' || v_field_path) r; IF v_resolved.structure_id IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: HAVING field "%" not found inside array "%"', v_field_path, p_array_path; END IF; v_join_idx := v_join_idx + 1; v_join_alias := 'h' || v_join_idx::text; v_col_name := pvt_db_type_to_value_column(v_resolved.db_type); IF v_col_name IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: unsupported db_type "%" for HAVING field "%"', v_resolved.db_type, v_field_path; END IF; v_join_parts := v_join_parts || format( 'LEFT JOIN _values %I ON %I._id_object = arr._id_object AND %I._id_structure = %s AND %I._array_parent_id = arr._id', v_join_alias, v_join_alias, v_join_alias, v_resolved.structure_id, v_join_alias); -- See note above: %s (bare) for typed value columns. v_inner_select := v_inner_select || format('%I.%s AS %I', v_join_alias, v_col_name, v_field_path); v_fields_map := v_fields_map || jsonb_build_object( v_field_path, jsonb_build_object('kind', 'props', 'db_type', v_resolved.db_type)); END LOOP; v_having_sql := E'\nHAVING ' || pvt_build_bool_expr(p_having, v_fields_map, ''); END IF; -- ---- ORDER BY (over outer aliases; minimal asc/desc support) IF p_order IS NOT NULL AND jsonb_typeof(p_order) = 'array' AND jsonb_array_length(p_order) > 0 THEN FOR v_ord_entry IN SELECT value FROM jsonb_array_elements(p_order) LOOP v_alias := v_ord_entry->>'field'; IF v_alias IS NULL OR v_alias = '' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: order entry missing "field"'; END IF; v_ord_parts := v_ord_parts || ( quote_ident(v_alias) || CASE WHEN COALESCE((v_ord_entry->>'asc')::boolean, true) THEN '' ELSE ' DESC' END); END LOOP; v_paging := E'\nORDER BY ' || array_to_string(v_ord_parts, ', '); END IF; IF p_limit IS NOT NULL AND p_limit >= 0 THEN v_paging := v_paging || E'\nLIMIT ' || p_limit::text; END IF; IF COALESCE(p_offset, 0) > 0 THEN v_paging := v_paging || E'\nOFFSET ' || p_offset::text; END IF; -- ---- Assemble v_inner_sql := format( E'SELECT %s\nFROM _values arr\nJOIN _objects o ON o._id = arr._id_object\n%s\nWHERE o._id_scheme = %s AND arr._id_structure = %s AND arr._array_index IS NOT NULL%s', array_to_string(v_inner_select, ', '), array_to_string(v_join_parts, E'\n'), p_scheme_id::text, v_arr_sid::text, v_filter_clause); RETURN format( E'SELECT %s\nFROM (\n%s\n) elements\nGROUP BY %s%s%s', array_to_string(v_select_parts, ', '), v_inner_sql, array_to_string(v_group_parts, ', '), v_having_sql, v_paging); END; $BODY$; COMMENT ON FUNCTION pvt_build_array_groupby_sql(bigint, text, jsonb, jsonb, jsonb, jsonb, jsonb, integer, integer) IS 'Builds a GROUP BY query over array elements. Element fields are projected into an inner subquery via LEFT JOINs on _values keyed by _array_parent_id; the outer query groups by inner aliases and applies HAVING through pvt_build_bool_expr.';