Bundle: redb / redb.Postgres (redb.Postgres.txt), 82 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.Postgres/Data/NpgsqlBulkOperations.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.Postgres/Data/NpgsqlBulkOperations.cs ---- using Npgsql; using NpgsqlTypes; 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.Postgres.Data { /// /// PostgreSQL implementation of IBulkOperations using COPY protocol. /// Much faster than individual INSERTs for large datasets. /// public class NpgsqlBulkOperations : IBulkOperations { private readonly IRedbConnection _db; /// /// Create bulk operations handler. /// Uses the same connection as the context for transaction consistency. /// public NpgsqlBulkOperations(IRedbConnection db) { _db = db ?? throw new ArgumentNullException(nameof(db)); } /// The timeout of one binary COPY, read at each load; the context hands its BulkInsertTimeout in. internal Func TimeoutSource { get; init; } = static () => null; /// /// Sets the importer's timeout from the configured one ( is Npgsql's "no limit"); /// null leaves the importer as the connection opened it. /// internal static void ApplyTimeout(NpgsqlBinaryImporter writer, TimeSpan? timeout) { if (timeout is { } value) writer.Timeout = value; } // === DATE/TIME CONVERSION HELPERS === /// /// Convert DateTimeOffset to UTC (required by Npgsql for timestamptz). /// private static DateTimeOffset ToUtc(DateTimeOffset value) => value.ToUniversalTime(); /// /// Convert nullable DateTimeOffset to UTC. /// private static DateTimeOffset? ToUtc(DateTimeOffset? value) => value?.ToUniversalTime(); /// /// Bulk insert objects using COPY protocol. /// public async Task BulkInsertObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var objectsList = objects.ToList(); if (!objectsList.Any()) return; await _db.ExecuteAtomicAsync(async () => { var conn = (NpgsqlConnection)await _db.GetUnderlyingConnectionAsync(); await using var writer = await conn.BeginBinaryImportAsync( "COPY _objects (_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) FROM STDIN (FORMAT BINARY)"); ApplyTimeout(writer, TimeoutSource()); foreach (var obj in objectsList) { await writer.StartRowAsync(); await writer.WriteAsync(obj.Id, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, obj.IdParent, NpgsqlDbType.Bigint); await writer.WriteAsync(obj.IdScheme, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, obj.Name, NpgsqlDbType.Text); await writer.WriteAsync(obj.IdOwner, NpgsqlDbType.Bigint); await writer.WriteAsync(obj.IdWhoChange, NpgsqlDbType.Bigint); await writer.WriteAsync(ToUtc(obj.DateCreate), NpgsqlDbType.TimestampTz); await writer.WriteAsync(ToUtc(obj.DateModify), NpgsqlDbType.TimestampTz); await WriteNullableDateTimeAsync(writer, obj.DateBegin); await WriteNullableDateTimeAsync(writer, obj.DateComplete); await WriteNullableAsync(writer, obj.Key, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, obj.ValueLong, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, obj.ValueString, NpgsqlDbType.Text); await WriteNullableAsync(writer, obj.ValueGuid, NpgsqlDbType.Uuid); await WriteNullableAsync(writer, obj.ValueBool, NpgsqlDbType.Boolean); await WriteNullableAsync(writer, obj.ValueDouble, NpgsqlDbType.Double); await WriteNullableAsync(writer, obj.ValueNumeric, NpgsqlDbType.Numeric); await WriteNullableDateTimeAsync(writer, obj.ValueDatetime); await WriteNullableAsync(writer, obj.ValueBytes, NpgsqlDbType.Bytea); await WriteNullableAsync(writer, obj.Note, NpgsqlDbType.Text); await WriteNullableAsync(writer, obj.Hash, NpgsqlDbType.Uuid); await WriteNullableAsync(writer, obj.ValueUnique, NpgsqlDbType.Text); } await writer.CompleteAsync(cancellationToken); }); } /// /// Bulk insert values using COPY protocol. /// public async Task BulkInsertValuesAsync(IEnumerable values, CancellationToken cancellationToken = default) { var valuesList = values.ToList(); if (!valuesList.Any()) return; await _db.ExecuteAtomicAsync(async () => { var conn = (NpgsqlConnection)await _db.GetUnderlyingConnectionAsync(); await using var writer = await conn.BeginBinaryImportAsync( "COPY _values (_id, _id_structure, _id_object, _String, _Long, _Guid, " + "_Double, _DateTimeOffset, _Boolean, _ByteArray, _Numeric, _ListItem, _Object, " + "_unique, _array_parent_id, _array_index) FROM STDIN (FORMAT BINARY)"); ApplyTimeout(writer, TimeoutSource()); foreach (var val in valuesList) { await writer.StartRowAsync(); await writer.WriteAsync(val.Id, NpgsqlDbType.Bigint); await writer.WriteAsync(val.IdStructure, NpgsqlDbType.Bigint); await writer.WriteAsync(val.IdObject, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, val.String, NpgsqlDbType.Text); await WriteNullableAsync(writer, val.Long, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, val.Guid, NpgsqlDbType.Uuid); await WriteNullableAsync(writer, val.Double, NpgsqlDbType.Double); await WriteNullableDateTimeAsync(writer, val.DateTimeOffset); await WriteNullableAsync(writer, val.Boolean, NpgsqlDbType.Boolean); await WriteNullableAsync(writer, val.ByteArray, NpgsqlDbType.Bytea); await WriteNullableAsync(writer, val.Numeric, NpgsqlDbType.Numeric); await WriteNullableAsync(writer, val.ListItem, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, val.Object, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, val.Unique, NpgsqlDbType.Uuid); await WriteNullableAsync(writer, val.ArrayParentId, NpgsqlDbType.Bigint); await WriteNullableAsync(writer, val.ArrayIndex, NpgsqlDbType.Text); } await writer.CompleteAsync(cancellationToken); }); } /// /// Bulk update objects using UPDATE FROM VALUES. /// Single round-trip for entire batch instead of N individual UPDATEs. /// public async Task BulkUpdateObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var objectsList = objects.ToList(); if (!objectsList.Any()) return; // PostgreSQL has no hard parameter limit, but use reasonable batch size const int batchSize = 500; foreach (var batch in objectsList.Chunk(batchSize)) { cancellationToken.ThrowIfCancellationRequested(); await ExecuteObjectsUpdateAsync(batch, cancellationToken); } } /// /// Execute UPDATE FROM VALUES for a batch of objects. /// private async Task ExecuteObjectsUpdateAsync(RedbObjectRow[] batch, CancellationToken cancellationToken) { var sb = new StringBuilder(); var parameters = new List(); sb.AppendLine("UPDATE _objects AS t SET"); sb.AppendLine(" _id_parent = s._id_parent,"); sb.AppendLine(" _id_scheme = s._id_scheme,"); sb.AppendLine(" _name = s._name,"); sb.AppendLine(" _id_owner = s._id_owner,"); sb.AppendLine(" _id_who_change = s._id_who_change,"); sb.AppendLine(" _date_modify = s._date_modify,"); sb.AppendLine(" _date_begin = s._date_begin,"); sb.AppendLine(" _date_complete = s._date_complete,"); sb.AppendLine(" _key = s._key,"); sb.AppendLine(" _value_long = s._value_long,"); sb.AppendLine(" _value_string = s._value_string,"); sb.AppendLine(" _value_guid = s._value_guid,"); sb.AppendLine(" _value_bool = s._value_bool,"); sb.AppendLine(" _value_double = s._value_double,"); sb.AppendLine(" _value_numeric = s._value_numeric,"); sb.AppendLine(" _value_datetime = s._value_datetime,"); sb.AppendLine(" _value_bytes = s._value_bytes,"); sb.AppendLine(" _note = s._note,"); sb.AppendLine(" _hash = s._hash,"); sb.AppendLine(" _value_unique = s._value_unique"); sb.AppendLine("FROM (VALUES"); for (int i = 0; i < batch.Length; i++) { var obj = batch[i]; var offset = i * 21 + 1; // PostgreSQL uses $1, $2, etc. 21 columns per row - keep in sync below. if (i > 0) sb.AppendLine(","); sb.Append($" (${offset}::bigint, ${offset + 1}::bigint, ${offset + 2}::bigint, ${offset + 3}::text, ${offset + 4}::bigint, "); sb.Append($"${offset + 5}::bigint, ${offset + 6}::timestamptz, ${offset + 7}::timestamptz, ${offset + 8}::timestamptz, "); sb.Append($"${offset + 9}::bigint, ${offset + 10}::bigint, ${offset + 11}::text, ${offset + 12}::uuid, "); sb.Append($"${offset + 13}::boolean, ${offset + 14}::double precision, ${offset + 15}::numeric, "); sb.Append($"${offset + 16}::timestamptz, ${offset + 17}::bytea, ${offset + 18}::text, ${offset + 19}::uuid, ${offset + 20}::text)"); parameters.Add(obj.Id); parameters.Add(obj.IdParent); parameters.Add(obj.IdScheme); parameters.Add(obj.Name); parameters.Add(obj.IdOwner); parameters.Add(obj.IdWhoChange); parameters.Add(obj.DateModify); parameters.Add(obj.DateBegin); parameters.Add(obj.DateComplete); parameters.Add(obj.Key); parameters.Add(obj.ValueLong); parameters.Add(obj.ValueString); parameters.Add(obj.ValueGuid); parameters.Add(obj.ValueBool); parameters.Add(obj.ValueDouble); parameters.Add(obj.ValueNumeric); parameters.Add(obj.ValueDatetime); parameters.Add(obj.ValueBytes); parameters.Add(obj.Note); parameters.Add(obj.Hash); parameters.Add(obj.ValueUnique); } sb.AppendLine(); sb.AppendLine(") AS s(_id, _id_parent, _id_scheme, _name, _id_owner, _id_who_change,"); sb.AppendLine(" _date_modify, _date_begin, _date_complete, _key, _value_long, _value_string,"); sb.AppendLine(" _value_guid, _value_bool, _value_double, _value_numeric, _value_datetime,"); sb.AppendLine(" _value_bytes, _note, _hash, _value_unique)"); sb.AppendLine("WHERE t._id = s._id"); await _db.ExecuteAsync(sb.ToString(), parameters.ToArray()!, cancellationToken); } /// /// Bulk update values using UPDATE FROM VALUES. /// Single round-trip for entire batch instead of N individual UPDATEs. /// public async Task BulkUpdateValuesAsync(IEnumerable values, CancellationToken cancellationToken = default) { var valuesList = values.ToList(); if (!valuesList.Any()) return; // PostgreSQL has no hard parameter limit, but use reasonable batch size const int batchSize = 500; foreach (var batch in valuesList.Chunk(batchSize)) { cancellationToken.ThrowIfCancellationRequested(); await ExecuteValuesUpdateAsync(batch, cancellationToken); } } /// /// Execute UPDATE FROM VALUES for a batch of values. /// private async Task ExecuteValuesUpdateAsync(RedbValue[] batch, CancellationToken cancellationToken) { var sb = new StringBuilder(); var parameters = new List(); sb.AppendLine("UPDATE _values AS t SET"); sb.AppendLine(" _string = s._string,"); sb.AppendLine(" _long = s._long,"); sb.AppendLine(" _guid = s._guid,"); sb.AppendLine(" _double = s._double,"); sb.AppendLine(" _datetimeoffset = s._datetimeoffset,"); sb.AppendLine(" _boolean = s._boolean,"); sb.AppendLine(" _bytearray = s._bytearray,"); sb.AppendLine(" _numeric = s._numeric,"); sb.AppendLine(" _listitem = s._listitem,"); sb.AppendLine(" _object = s._object,"); sb.AppendLine(" _unique = s._unique,"); sb.AppendLine(" _array_parent_id = s._array_parent_id,"); sb.AppendLine(" _array_index = s._array_index"); sb.AppendLine("FROM (VALUES"); for (int i = 0; i < batch.Length; i++) { var val = batch[i]; var offset = i * 14 + 1; // PostgreSQL uses $1, $2, etc. 14 columns per row - keep in sync with the source list below. if (i > 0) sb.AppendLine(","); sb.Append($" (${offset}::bigint, ${offset + 1}::text, ${offset + 2}::bigint, ${offset + 3}::uuid, "); sb.Append($"${offset + 4}::double precision, ${offset + 5}::timestamptz, ${offset + 6}::boolean, "); sb.Append($"${offset + 7}::bytea, ${offset + 8}::numeric, ${offset + 9}::bigint, "); sb.Append($"${offset + 10}::bigint, ${offset + 11}::uuid, ${offset + 12}::bigint, ${offset + 13}::text)"); parameters.Add(val.Id); parameters.Add(val.String); parameters.Add(val.Long); parameters.Add(val.Guid); parameters.Add(val.Double); parameters.Add(val.DateTimeOffset); parameters.Add(val.Boolean); parameters.Add(val.ByteArray); parameters.Add(val.Numeric); parameters.Add(val.ListItem); parameters.Add(val.Object); parameters.Add(val.Unique); parameters.Add(val.ArrayParentId); parameters.Add(val.ArrayIndex); } sb.AppendLine(); sb.AppendLine(") AS s(_id, _string, _long, _guid, _double, _datetimeoffset, _boolean,"); sb.AppendLine(" _bytearray, _numeric, _listitem, _object, _unique, _array_parent_id, _array_index)"); sb.AppendLine("WHERE t._id = s._id"); await _db.ExecuteAsync(sb.ToString(), parameters.ToArray()!, cancellationToken); } /// /// Bulk delete objects by IDs. /// public async Task BulkDeleteObjectsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) { var ids = objectIds.ToArray(); if (!ids.Any()) return; await _db.ExecuteAsync("DELETE FROM _objects WHERE _id = ANY($1)", new object[] { ids }, cancellationToken); } /// /// Bulk delete values by IDs. /// public async Task BulkDeleteValuesAsync(IEnumerable valueIds, CancellationToken cancellationToken = default) { var ids = valueIds.ToArray(); if (!ids.Any()) return; await _db.ExecuteAsync("DELETE FROM _values WHERE _id = ANY($1)", new object[] { ids }, cancellationToken); } /// /// Bulk delete values by object IDs. /// public async Task BulkDeleteValuesByObjectIdsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) { var ids = objectIds.ToArray(); if (!ids.Any()) return; await _db.ExecuteAsync("DELETE FROM _values WHERE _id_object = ANY($1)", new object[] { ids }, cancellationToken); } /// /// Bulk delete values by ListItem IDs. /// public async Task BulkDeleteValuesByListItemIdsAsync(IEnumerable listItemIds, CancellationToken cancellationToken = default) { var ids = listItemIds.ToArray(); if (!ids.Any()) return; await _db.ExecuteAsync("DELETE FROM _values WHERE _ListItem = ANY($1)", new object[] { ids }, cancellationToken); } // === HELPER METHODS === private static async Task WriteNullableAsync(NpgsqlBinaryImporter writer, T? value, NpgsqlDbType dbType) where T : struct { if (value.HasValue) await writer.WriteAsync(value.Value, dbType); else await writer.WriteNullAsync(); } private static async Task WriteNullableAsync(NpgsqlBinaryImporter writer, string? value, NpgsqlDbType dbType) { if (value != null) await writer.WriteAsync(value, dbType); else await writer.WriteNullAsync(); } private static async Task WriteNullableAsync(NpgsqlBinaryImporter writer, byte[]? value, NpgsqlDbType dbType) { if (value != null) await writer.WriteAsync(value, dbType); else await writer.WriteNullAsync(); } /// /// Write nullable DateTimeOffset with UTC conversion (required by Npgsql). /// private static async Task WriteNullableDateTimeAsync(NpgsqlBinaryImporter writer, DateTimeOffset? value) { if (value.HasValue) await writer.WriteAsync(value.Value.ToUniversalTime(), NpgsqlDbType.TimestampTz); else await writer.WriteNullAsync(); } } } Path: redb/redb.Postgres/Data/NpgsqlDataSourceFactory.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.Postgres/Data/NpgsqlDataSourceFactory.cs ---- using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Npgsql; using redb.Core.Query; namespace redb.Postgres.Data { /// /// Builds the every registration path uses, so the /// redb.string_collation and redb.lazy_refs session settings are installed in one /// place instead of six. /// /// /// Why a GUC at all. The Free query path builds its SQL inside the database: /// pvt_build_query_sql and the functions below it generate the text, and they take twelve /// positional parameters with nowhere to put an option. Threading a thirteenth through five /// layers would change every one of those signatures. A run-time setting reaches them without /// touching a single signature, and pvt_fold_case() reads it with /// current_setting('redb.string_collation', true), which yields NULL when unset. Unset /// therefore means byte-for-byte the SQL that was generated before this feature existed. The /// lazy-reference flag (V4, Л2) rides the same mechanism into the JSON builders. /// /// /// /// Why on every hand-out, not in the physical-connection initializer. A session GUC set /// with set_config(..., false) lives for the session - but Npgsql sends DISCARD ALL /// when a connection returns to the pool, and RESET ALL inside it puts every session /// setting back to its default. The physical-connection initializer runs once per backend, so /// only the first scope on each pooled connection saw the settings; every later scope got a /// connection with both GUCs empty (review, V4). The settings are therefore registered per data /// source here and re-applied by each time it opens its /// connection: one round trip per context, the same shape MSSQL and SQLite use. /// /// public static class NpgsqlDataSourceFactory { private sealed record SessionSettings(string? Collation, bool LazyReferences); // Weak by design: the data source owns its lifetime, the registry never keeps it alive. private static readonly ConditionalWeakTable Registry = new(); /// /// The session settings registered for as text: part of the signature under which a /// connection an ambient transaction holds is shared. /// internal static string SessionSettingsText(NpgsqlDataSource dataSource) => Registry.TryGetValue(dataSource, out var settings) ? $"collation={settings.Collation};lazy_refs={(settings.LazyReferences ? 1 : 0)}" : "collation=;lazy_refs=0"; /// /// Creates a data source. With null and /// false this is /// and nothing else. /// public static NpgsqlDataSource Create(string connectionString, string? stringCollation, bool lazyReferences = false) { connectionString = WithJitOff(connectionString); if (string.IsNullOrWhiteSpace(stringCollation) && !lazyReferences) return NpgsqlDataSource.Create(connectionString); // Validated before it can reach any SQL. It is also never interpolated: set_config // takes the value as a bound parameter, so there is no text to escape here at all. // (The in-database side does have to build an identifier, and quotes it there.) if (stringCollation != null) CollationNameValidator.Validate(stringCollation); var dataSource = NpgsqlDataSource.Create(connectionString); Registry.Add(dataSource, new SessionSettings(stringCollation, lazyReferences)); return dataSource; } /// /// The connection string with -c jit=off added to its Options, unless the Options already /// name jit, in which case the caller's choice stands. /// /// PostgreSQL compiles a plan with JIT once its estimated cost passes jit_above_cost /// (100 000 by default), and the estimate of a REDB query over a large scheme passes it easily, /// also for a branch that never runs. The compilation costs tens of milliseconds on a query that /// itself takes two: a page of 100 employees sorted by salary, 82 ms with JIT and 2.5 ms /// without. The server takes the option when the connection opens, so it costs no round trip. /// internal static string WithJitOff(string connectionString) { var builder = new NpgsqlConnectionStringBuilder(connectionString); var options = builder.Options ?? string.Empty; if (options.Contains("jit", StringComparison.OrdinalIgnoreCase)) return connectionString; builder.Options = (options + " -c jit=off").Trim(); return builder.ConnectionString; } /// /// Re-applies the session settings registered for on a /// connection it has just handed out. No-op for a data source created without settings. /// public static Task ApplySessionSettingsAsync(NpgsqlDataSource dataSource, NpgsqlConnection connection) { if (!Registry.TryGetValue(dataSource, out var settings)) return Task.CompletedTask; return ApplySettingsAsync(connection, settings.Collation, settings.LazyReferences); } private static async Task ApplySettingsAsync(NpgsqlConnection connection, string? collation, bool lazyReferences) { if (collation != null) await ApplyCollationAsync(connection, collation).ConfigureAwait(false); if (lazyReferences) await ApplyLazyRefsAsync(connection).ConfigureAwait(false); } /// /// Synchronous for the thread-pool-free lazy path: /// same settings, executed on the calling thread. /// public static void ApplySessionSettings(NpgsqlDataSource dataSource, NpgsqlConnection connection) { if (!Registry.TryGetValue(dataSource, out var settings)) return; if (settings.Collation != null) { using var cmd = CreateCommand(connection, settings.Collation); cmd.ExecuteNonQuery(); } if (settings.LazyReferences) { using var cmd = connection.CreateCommand(); cmd.CommandText = "SELECT set_config('redb.lazy_refs', '1', false)"; cmd.ExecuteNonQuery(); } } private static async Task ApplyLazyRefsAsync(NpgsqlConnection connection) { await using var cmd = connection.CreateCommand(); cmd.CommandText = "SELECT set_config('redb.lazy_refs', '1', false)"; await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); } private static async Task ApplyCollationAsync(NpgsqlConnection connection, string collation) { await using var cmd = CreateCommand(connection, collation); await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); } /// /// set_config rather than SET: it is an ordinary function, so the value binds /// as a parameter. SET takes a literal and would have to be built by concatenation. /// The third argument false makes the setting session-wide rather than transaction-local. /// private static NpgsqlCommand CreateCommand(NpgsqlConnection connection, string collation) { var cmd = connection.CreateCommand(); cmd.CommandText = "SELECT set_config('redb.string_collation', $1, false)"; cmd.Parameters.Add(new NpgsqlParameter { Value = collation }); return cmd; } } } Path: redb/redb.Postgres/Data/NpgsqlKeyGenerator.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.Postgres/Data/NpgsqlKeyGenerator.cs ---- using Npgsql; using redb.Core.Data; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Postgres.Data { /// /// PostgreSQL implementation of key generator. /// Uses global_identity sequence. Caching is static in base class. /// public class NpgsqlKeyGenerator : RedbKeyGeneratorBase { private readonly NpgsqlDataSource _dataSource; // The scope's connection wrapper: inside a TransactionScope it works on the transaction's connection. private readonly Func? _scopeConnection; private const string SEQUENCE_NAME = "global_identity"; /// /// Create PostgreSQL key generator. /// /// Npgsql data source. /// Cache domain for key isolation (optional). /// The owning scope's connection, used for keys inside an ambient transaction. public NpgsqlKeyGenerator(NpgsqlDataSource dataSource, string? domain = null, Func? scopeConnection = null) : base(domain) { _dataSource = dataSource; _scopeConnection = scopeConnection; } /// /// Create PostgreSQL key generator from connection string. /// public NpgsqlKeyGenerator(string connectionString, string? domain = null) : base(domain) { _dataSource = NpgsqlDataSource.Create(connectionString); } // === DB-SPECIFIC IMPLEMENTATIONS === /// /// Generate batch of keys from PostgreSQL sequence. /// protected override async Task> GenerateKeysAsync(int count) { var keys = new List(count); await using var conn = await _dataSource.OpenConnectionAsync(); await using var cmd = new NpgsqlCommand( $"SELECT nextval('{SEQUENCE_NAME}') FROM generate_series(1, {count})", conn); await using var reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { keys.Add(reader.GetInt64(0)); } return keys; } /// /// Inside a TransactionScope a refill on a connection of its own would be a second connection in the /// transaction, which PostgreSQL can only commit as a prepared (two-phase) transaction. The values are /// taken through the scope's wrapper instead - on the transaction's connection. nextval is not /// transactional: a rollback leaves a gap, never a duplicate. /// protected override async Task?> TryGenerateKeysInAmbientTransactionAsync(int count) { if (System.Transactions.Transaction.Current == null || _scopeConnection?.Invoke() is not { } db) return null; return await db.QueryScalarListAsync( $"SELECT nextval('{SEQUENCE_NAME}') FROM generate_series(1, $1)", new object[] { count }, CancellationToken.None); } } } Path: redb/redb.Postgres/Data/NpgsqlRedbConnection.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.Postgres/Data/NpgsqlRedbConnection.cs ---- using Npgsql; using redb.Core.Data; using System; using System.Collections.Generic; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using System.Transactions; namespace redb.Postgres.Data { /// /// PostgreSQL implementation of IRedbConnection using Npgsql. /// Provides pure ADO.NET database access with automatic transaction management. /// public class NpgsqlRedbConnection : IRedbConnection { private readonly NpgsqlDataSource _dataSource; private NpgsqlConnection? _connection; private NpgsqlRedbTransaction? _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; // Commands and teardown share ONE exclusion (CommandGate, a production report // 2026-09-11): a single NpgsqlRedbConnection wraps ONE physical connection and is NOT // thread-safe. Two concurrent commands fail fast with a clear message; a command after // teardown began is refused with ObjectDisposedException (the lazy loader falls back // to a detached scope on it); and DisposeAsync WAITS for the in-flight command instead // of racing it with Close/Reset. private readonly CommandGate _gate = new(nameof(NpgsqlRedbConnection)); private CommandScope EnterCommand() => new(this, _gate.Enter()); /// /// 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 NpgsqlRedbConnection _owner; private readonly CommandGate.Releaser _releaser; public CommandScope(NpgsqlRedbConnection owner, CommandGate.Releaser releaser) { _owner = owner; _releaser = releaser; } public void Dispose() { var lease = _owner._ambientLease; _owner._ambientLease = null; try { lease?.Dispose(); } finally { _releaser.Dispose(); } } } /// Host, port, database and login: two connection strings reaching the same data 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 session // settings. A connection the transaction already holds for this database is shared only when they match. private string SessionSignature => _sessionSignature ??= redb.Core.Models.Configuration.RedbServiceConfiguration.ComputeCacheDomain(_dataSource.ConnectionString) + "|" + NpgsqlDataSourceFactory.SessionSettingsText(_dataSource); private static string DatabaseKeyOf(string connectionString) { var builder = new NpgsqlConnectionStringBuilder(connectionString); return $"pg|{builder.Host}|{builder.Port}|{builder.Database}|{builder.Username}"; } /// /// Connection string. /// public string ConnectionString => _dataSource.ConnectionString; /// /// Current active transaction. /// public IRedbTransaction? CurrentTransaction => _currentTransaction; /// /// 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. /// /// Npgsql data source (pooled). public NpgsqlRedbConnection(NpgsqlDataSource dataSource) { _dataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource)); } /// /// Create connection from connection string. /// /// PostgreSQL connection string. public NpgsqlRedbConnection(string connectionString) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString)); _dataSource = NpgsqlDataSource.Create(NpgsqlDataSourceFactory.WithJitOff(connectionString)); } // === CONNECTION MANAGEMENT === // Dispose nulls _connection. Without this check a call after Dispose would see the null, // open a NEW physical connection on a wrapper whose second Dispose is a no-op, and that // connection would sit in the server's session list until the process died (prod, 2026-09). private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(nameof(NpgsqlRedbConnection), "The scope that owned this connection has ended. Resolve a fresh scoped IRedbService " + "instead of reusing one from a finished scope or exchange."); } /// /// Get underlying connection (for bulk operations). /// This ensures all operations use the same connection and transaction. /// public async Task GetUnderlyingConnectionAsync(CancellationToken cancellationToken = default) { // COPY runs between commands: inside an ambient transaction it takes the transaction's // connection without holding the gate a command holds. if (_currentTransaction is not { IsActive: true } && Transaction.Current is { } ambient) { ThrowIfDisposed(); var entry = await AmbientConnectionRegistry.GetOrOpenAsync(ambient, DatabaseKey, SessionSignature, OpenAmbientAsync, null, cancellationToken); return entry.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); // An enlisted connection (ambient) needs no transaction object; Npgsql runs every command in the // connection's transaction, the object is given for the holder's own driver APIs. var transaction = _currentTransaction is { IsActive: true } explicitTransaction ? explicitTransaction.NpgsqlTransaction : null; return new RedbConnectionLease(connection, transaction, command.Dispose); } catch { command.Dispose(); throw; } } private async Task GetOpenConnectionAsync(CancellationToken cancellationToken = default) { ThrowIfDisposed(); // Inside an ambient transaction the TRANSACTION holds the connection (AmbientConnectionRegistry): // every scope of this database works through it, and a second open connection would need a // prepared (two-phase) transaction. An explicit transaction of this wrapper keeps its own connection. if (_currentTransaction is not { IsActive: true } && Transaction.Current is { } ambient) { _ambientLease ??= await AmbientConnectionRegistry.AcquireAsync(ambient, DatabaseKey, SessionSignature, OpenAmbientAsync, null, cancellationToken); return (NpgsqlConnection)_ambientLease.Entry.Connection; } if (_connection == null) { _connection = await _dataSource.OpenConnectionAsync(cancellationToken); // Session settings (collation, lazy refs) do not survive the pool: DISCARD ALL on // return resets them. Re-armed on every hand-out, like MSSQL and SQLite do. await NpgsqlDataSourceFactory.ApplySessionSettingsAsync(_dataSource, _connection); } else if (_connection.State != System.Data.ConnectionState.Open) { // Closed OR Broken (a cancellation tearing down a COPY breaks the connector). // A broken NpgsqlConnection cannot be re-opened in place - replace it with a // fresh one so the scope heals instead of failing every call from here on. try { await _connection.DisposeAsync(); } finally { _connection = null; } _connection = await _dataSource.OpenConnectionAsync(cancellationToken); await NpgsqlDataSourceFactory.ApplySessionSettingsAsync(_dataSource, _connection); } return _connection; } /// Opens the connection an ambient transaction holds; opened inside the scope, Npgsql enlists it. private async Task OpenAmbientAsync(CancellationToken cancellationToken) { var connection = await _dataSource.OpenConnectionAsync(cancellationToken); try { await NpgsqlDataSourceFactory.ApplySessionSettingsAsync(_dataSource, connection); return connection; } catch { await connection.DisposeAsync(); throw; } } /// Synchronous . private System.Data.Common.DbConnection OpenAmbient() { var connection = _dataSource.OpenConnection(); try { NpgsqlDataSourceFactory.ApplySessionSettings(_dataSource, connection); return connection; } catch { connection.Dispose(); throw; } } private NpgsqlCommand CreateCommand(NpgsqlConnection connection, string sql, object[] parameters) { // Convert @p0, @p1 format to PostgreSQL $1, $2 format for cross-platform compatibility var convertedSql = ConvertParameters(sql, parameters.Length); var cmd = new NpgsqlCommand(convertedSql, connection); // Set transaction if active if (_currentTransaction != null) { cmd.Transaction = _currentTransaction.NpgsqlTransaction; } // Add positional parameters ($1, $2, etc.) foreach (var param in parameters) { NpgsqlParameter npgsqlParam; if (param == null) { npgsqlParam = new NpgsqlParameter { Value = DBNull.Value }; } else if (param is DateTimeOffset dto) { // Both DateTimeOffset and DateTimeOffset? (when HasValue) match here npgsqlParam = new NpgsqlParameter { Value = dto.ToUniversalTime() }; } else if (param is long[] longArray) { // Explicitly set array type for PostgreSQL bigint[] npgsqlParam = new NpgsqlParameter { Value = longArray, NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Array | NpgsqlTypes.NpgsqlDbType.Bigint }; } else if (param is int[] intArray) { // Explicitly set array type for PostgreSQL integer[] npgsqlParam = new NpgsqlParameter { Value = intArray, NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Array | NpgsqlTypes.NpgsqlDbType.Integer }; } else if (param is string[] stringArray) { // Explicitly set array type for PostgreSQL text[] npgsqlParam = new NpgsqlParameter { Value = stringArray, NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Array | NpgsqlTypes.NpgsqlDbType.Text }; } else { npgsqlParam = new NpgsqlParameter { Value = param }; } cmd.Parameters.Add(npgsqlParam); } return cmd; } // === 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) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } /// /// with a second statement in the same batch, one /// round trip: with its maps to , /// , which takes no parameters, to . The first statement is sent as /// it is, so its plan and its rows are those of a query of its own (a list page and the scheme hash it is read by). /// internal Task<(List First, List Second)> QueryThenAsync( string sql, object[] parameters, string then, CancellationToken cancellationToken) where T1 : new() where T2 : new() // One command, one span, as the context gives every query (RedbContextBase). => redb.Core.Diagnostics.RedbTelemetry.Enabled ? redb.Core.Diagnostics.RedbTelemetry.RunAsync(redb.Core.Diagnostics.RedbTelemetry.Query, () => QueryThenCoreAsync(sql, parameters, then, cancellationToken)) : QueryThenCoreAsync(sql, parameters, then, cancellationToken); private async Task<(List First, List Second)> QueryThenCoreAsync( string sql, object[] parameters, string then, CancellationToken cancellationToken) where T1 : new() where T2 : new() { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { await using var main = CreateCommand(conn, sql, parameters); await using var batch = new NpgsqlBatch(conn, main.Transaction); var statement = new NpgsqlBatchCommand(main.CommandText); foreach (NpgsqlParameter p in main.Parameters) statement.Parameters.Add(p.Clone()); batch.BatchCommands.Add(statement); batch.BatchCommands.Add(new NpgsqlBatchCommand(then)); await using var reader = await batch.ExecuteReaderAsync(cancellationToken); var first = new List(); var mapper1 = new RedbRowMapper(); while (await reader.ReadAsync(cancellationToken)) first.Add(mapper1.MapRow(reader)); var second = new List(); if (await reader.NextResultAsync(cancellationToken)) { var mapper2 = new RedbRowMapper(); while (await reader.ReadAsync(cancellationToken)) second.Add(mapper2.MapRow(reader)); } return (first, second); } catch (Exception ex) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } private async Task> QueryCoreAsync(NpgsqlConnection 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) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } private async Task QueryFirstOrDefaultCoreAsync(NpgsqlConnection 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) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } private async Task ExecuteScalarCoreAsync(NpgsqlConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); var result = await cmd.ExecuteScalarAsync(cancellationToken); return CoerceScalar(result); } private static T? CoerceScalar(object? result) { if (result == null || result == DBNull.Value) return default; // Handle nullable types var targetType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); // Direct cast if types match if (result.GetType() == targetType || targetType.IsAssignableFrom(result.GetType())) { return (T)result; } // Convert for numeric types etc. return (T)ChangeType(result, targetType); } /// /// , plus the two conversions Npgsql 10 took away. An untyped read /// of a date or time column (GetValue, ExecuteScalar) returns and /// since Npgsql 10, DateTime and TimeSpan before; neither implements IConvertible, so a /// caller asking for DateTime or TimeSpan, as it did on Npgsql 9, got InvalidCastException. redb's own SQL /// returns no date or time; the raw SQL of the caller can. /// internal static object ChangeType(object value, Type targetType) => value switch { DateOnly d when targetType == typeof(DateTime) => d.ToDateTime(TimeOnly.MinValue), TimeOnly t when targetType == typeof(TimeSpan) => t.ToTimeSpan(), _ => redb.Core.Utils.RedbDecimal.ChangeType(value, targetType) }; // === ORPHAN TRANSACTION HYGIENE === private const string OrphanRollbackFailureKey = "redb.OrphanTransactionRollbackFailure"; /// /// A command that failed can leave the session inside a transaction its own SQL text opened /// (a BEGIN in the text, then an error): an aborted transaction block this wrapper does not /// own, in which the scope's every later command and transaction is refused. It is rolled /// back here before the failure leaves, unless a transaction of this wrapper or an ambient /// one owns the session (its owner ends it). ROLLBACK outside a transaction is only a warning /// in PostgreSQL. The original exception always propagates; a rollback that fails as well is /// attached to it instead of replacing it. /// private async Task RollbackOrphanTransactionAsync(NpgsqlConnection conn, Exception failure) { if (_currentTransaction is { IsActive: true } || Transaction.Current != null || conn.State != System.Data.ConnectionState.Open) return; try { await using var cmd = conn.CreateCommand(); cmd.CommandText = "ROLLBACK"; // The failure may be the caller's own cancellation - the rollback must land regardless. await cmd.ExecuteNonQueryAsync(CancellationToken.None); } catch (Exception rollbackFailure) { failure.Data[OrphanRollbackFailureKey] = rollbackFailure.Message; } } /// Synchronous twin of . private void RollbackOrphanTransaction(NpgsqlConnection conn, Exception failure) { if (_currentTransaction is { IsActive: true } || Transaction.Current != null || conn.State != System.Data.ConnectionState.Open) return; try { using var cmd = conn.CreateCommand(); cmd.CommandText = "ROLLBACK"; cmd.ExecuteNonQuery(); } catch (Exception rollbackFailure) { failure.Data[OrphanRollbackFailureKey] = rollbackFailure.Message; } } // === 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, same session settings as the async // twins above. private NpgsqlConnection GetOpenConnection() { ThrowIfDisposed(); // 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, null); return (NpgsqlConnection)_ambientLease.Entry.Connection; } if (_connection == null) { _connection = _dataSource.OpenConnection(); NpgsqlDataSourceFactory.ApplySessionSettings(_dataSource, _connection); } else if (_connection.State != System.Data.ConnectionState.Open) { // Same healing as the async twin: a broken connector is replaced, not re-opened. try { _connection.Dispose(); } finally { _connection = null; } _connection = _dataSource.OpenConnection(); NpgsqlDataSourceFactory.ApplySessionSettings(_dataSource, _connection); } 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(NpgsqlConnection 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 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(NpgsqlConnection conn, string sql, object[] parameters) { using var cmd = CreateCommand(conn, sql, parameters); return CoerceScalar(cmd.ExecuteScalar()); } /// 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(NpgsqlConnection 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(); } /// 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(NpgsqlConnection 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; } } /// /// 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) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } private async Task ExecuteCoreAsync(NpgsqlConnection 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) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } private async Task> QueryScalarListCoreAsync(NpgsqlConnection 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(); var targetType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); while (await reader.ReadAsync(cancellationToken)) { if (reader.IsDBNull(0)) { results.Add(default!); } else { var value = reader.GetValue(0); results.Add((T)ChangeType(value, targetType)); } } return results; } // === TRANSACTION METHODS === /// /// Begin new transaction. /// public async Task BeginTransactionAsync(System.Data.IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default) { using var _guard = EnterCommand(); 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."); var conn = await GetOpenConnectionAsync(cancellationToken); var npgsqlTx = isolationLevel.HasValue ? await conn.BeginTransactionAsync(isolationLevel.Value, cancellationToken) // BR-1: the requested level : await conn.BeginTransactionAsync(cancellationToken); // the provider default, as always _currentTransaction = new NpgsqlRedbTransaction(npgsqlTx, () => _currentTransaction = null); return _currentTransaction; } // === 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 PostgreSQL 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) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } private async Task ExecuteJsonCoreAsync(NpgsqlConnection 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(); } /// /// with a statement before it and one after it, /// all three in one batch, so one round trip. and take no /// parameters and must return no rows (a DO block): the result is the JSON of . /// Outside an explicit transaction PostgreSQL runs the batch as one implicit transaction, so a transaction-local /// setting made by ends with the batch, also when fails. /// internal async Task ExecuteJsonBetweenAsync(string before, string sql, object[] parameters, string after, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { await using var main = CreateCommand(conn, sql, parameters); await using var batch = new NpgsqlBatch(conn, main.Transaction); batch.BatchCommands.Add(new NpgsqlBatchCommand(before)); var statement = new NpgsqlBatchCommand(main.CommandText); foreach (NpgsqlParameter p in main.Parameters) statement.Parameters.Add(p.Clone()); batch.BatchCommands.Add(statement); batch.BatchCommands.Add(new NpgsqlBatchCommand(after)); var result = await batch.ExecuteScalarAsync(cancellationToken); return result == null || result == DBNull.Value ? null : result.ToString(); } catch (Exception ex) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } /// /// 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) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } private async Task> ExecuteJsonListCoreAsync(NpgsqlConnection 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), /// NULL values included; "[]" when there are no rows. Behind RedbContextBase.QueryRowsAsJsonAsync. /// public async Task QueryRowsAsJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken) { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { 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); } catch (Exception ex) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } // === 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), // so Close/Reset never runs under a running command. The budget follows the // connection's own Command Timeout - a command may legally run that long. The LIVE // object is the source of truth (it can be changed programmatically); the string // is the fallback for a connection that was never opened. int commandTimeout; try { commandTimeout = _connection?.CommandTimeout ?? new NpgsqlConnectionStringBuilder(_dataSource.ConnectionString).CommandTimeout; } 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) 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; conn?.Dispose(); } } /// /// Convert @p0, @p1 parameter format to PostgreSQL $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 NpgsqlDataReader to objects. /// Supports multiple column name formats: /// - PostgreSQL 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; /// /// Map current row to object instance. /// public T MapRow(NpgsqlDataReader 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 value = reader.IsDBNull(i) ? null : reader.GetValue(i); if (value != null) { try { var targetType = slot.TargetType; // Special handling for DateTimeOffset (Npgsql returns DateTime for timestamptz) if (targetType == typeof(DateTimeOffset)) { if (value is DateTime dt) { slot.Assign(obj, new DateTimeOffset(dt, TimeSpan.Zero)); } else if (value is DateTimeOffset dto) { slot.Assign(obj, dto); } continue; } // A value already of the target type: Convert.ChangeType would return it unchanged. var convertedValue = value.GetType() == targetType ? value : NpgsqlRedbConnection.ChangeType(value, targetType); slot.Assign(obj, convertedValue); } catch { // Try direct assignment try { slot.Property.SetValue(obj, value); } catch { // Skip if cannot convert } } } } return obj; } } } Path: redb/redb.Postgres/Data/NpgsqlRedbContext.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.Postgres/Data/NpgsqlRedbContext.cs ---- using System; using Npgsql; using redb.Core.Data; namespace redb.Postgres.Data { /// /// PostgreSQL implementation of REDB context. /// Assembles all Npgsql components into single facade. /// public class NpgsqlRedbContext : RedbContextBase { private readonly NpgsqlRedbConnection _connection; private readonly NpgsqlKeyGenerator _keyGenerator; private readonly NpgsqlBulkOperations _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); /// /// Npgsql data source (for direct access if needed). /// public NpgsqlDataSource DataSource { get; } /// /// Create PostgreSQL context from data source. /// /// Npgsql data source (pooled connections). public NpgsqlRedbContext(NpgsqlDataSource dataSource) { DataSource = dataSource; _connection = new NpgsqlRedbConnection(dataSource); var domain = redb.Core.Models.Configuration.RedbServiceConfiguration.ComputeCacheDomain(dataSource.ConnectionString); _keyGenerator = new NpgsqlKeyGenerator(dataSource, domain, scopeConnection: () => _connection); _bulkOperations = new NpgsqlBulkOperations(_connection) { TimeoutSource = () => BulkInsertTimeout }; } /// /// Create PostgreSQL context from connection string. /// /// PostgreSQL connection string. public NpgsqlRedbContext(string connectionString) : this(NpgsqlDataSource.Create(NpgsqlDataSourceFactory.WithJitOff(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.Postgres/Data/NpgsqlRedbTransaction.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.Postgres/Data/NpgsqlRedbTransaction.cs ---- using Npgsql; using redb.Core.Data; using System; using System.Threading.Tasks; namespace redb.Postgres.Data { /// /// PostgreSQL implementation of IRedbTransaction using Npgsql. /// Connection-scoped: parent connection automatically uses this transaction. /// public class NpgsqlRedbTransaction : IRedbTransaction { private readonly NpgsqlTransaction _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 Npgsql transaction (for command assignment). /// internal NpgsqlTransaction NpgsqlTransaction => _transaction; /// /// Create new transaction wrapper. /// /// Underlying Npgsql transaction. /// Callback when transaction is disposed. public NpgsqlRedbTransaction(NpgsqlTransaction 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: Npgsql's NpgsqlConnection still holds a reference to // _transaction. Npgsql's pool reset (DISCARD ALL on acquire) usually // hides leaks of this shape, but the semantics should not depend on // pool-driver tolerance — speculatively rollback so the connection // returns clean, then re-throw so the caller still sees the original // exception. Both attempts are logged via [Diag-TX-LIFECYCLE-PG] so a // failure shape never goes silent. // Console.WriteLine($"[Diag-TX-LIFECYCLE-PG] 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-PG] Speculative rollback after failed commit ALSO FAILED: {rbEx.GetType().Name}: {rbEx.Message}. Pool may receive a dirty NpgsqlConnection (Npgsql's DISCARD ALL on next acquire is the only remaining mitigation)."); } IsActive = false; _onDispose(); throw; } Complete(committed: true); IsActive = false; // Clear the connection's `_currentTransaction` slot now so commands // issued between commit and dispose run against the autocommit // connection (Npgsql is more tolerant of cmd.Transaction=closedTx // than Microsoft.Data.Sqlite, but the semantics should not depend // on driver tolerance). _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 (ObjectDisposedException) { // The connector broke mid-command (e.g. a COPY torn down by a cancellation token) // and Npgsql disposed the transaction with it - the server has already rolled the // transaction back on disconnect. Treat the rollback as done: rethrowing here would // mask the original failure (the OCE) with a secondary ObjectDisposedException. IsActive = false; _onDispose(); } catch (Exception ex) { // Console.WriteLine( RollbackAsync FAILED: {ex.GetType().Name}: {ex.Message}. Npgsql's DISCARD ALL on next pool acquire is the only mitigation if the underlying state is dirty."); IsActive = false; _onDispose(); throw; } IsActive = false; _onDispose(); } /// /// Dispose transaction. /// If still active - rollback automatically. The catch CANNOT throw (Dispose contract), /// so a leaked NpgsqlConnection (autocommit=off at the driver layer) is mitigated by /// Npgsql's built-in DISCARD ALL on next pool acquire. /// public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; Complete(committed: false); // Auto-rollback if still active if (IsActive) { try { await _transaction.RollbackAsync(); } catch (Exception ex) { // Console.WriteLine($"[Diag-TX-LIFECYCLE-PG] DisposeAsync auto-rollback FAILED: {ex.GetType().Name}: {ex.Message}. Pool poisoning mitigated by Npgsql's DISCARD ALL 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.Postgres/Data/PostgresServerVersion.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.Postgres/Data/PostgresServerVersion.cs ---- using System; using System.Globalization; namespace redb.Postgres.Data; /// /// The lowest PostgreSQL server redb runs on, checked before any schema work. 15: the schema creates /// IX__list_items_unique with NULLS NOT DISTINCT, which older servers reject as a syntax error in the middle of /// the creation script. The service checks at initialization (), redb init before it /// sends the script. /// internal static class PostgresServerVersion { /// The lowest supported major version. public const int RequiredMajor = 15; /// Returns the server version as one integer (150004 for 15.4), on every server since 8.2. public const string Query = "SHOW server_version_num"; /// /// The message for a server older than , or null when the server is new enough. /// is the answer of . /// public static string? FindProblem(string? versionNum) { if (!int.TryParse(versionNum?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var number)) { return $"redb needs PostgreSQL {RequiredMajor} or newer, and the server version could not be read " + $"(server_version_num returned '{versionNum}')."; } if (number >= RequiredMajor * 10000) return null; return $"redb needs PostgreSQL {RequiredMajor} or newer; this server is PostgreSQL {Display(number)} " + $"(server_version_num {number}). Upgrade the server: the schema uses unique indexes with NULLS NOT " + "DISTINCT, which PostgreSQL has from version 15 on."; } /// Throws with the message of . public static void EnsureSupported(string? versionNum) { var problem = FindProblem(versionNum); if (problem != null) throw new NotSupportedException(problem); } // 10 and later: major * 10000 + minor. Before 10: major * 10000 + second * 100 + minor (90624 = 9.6.24). private static string Display(int number) => number >= 100000 ? $"{number / 10000}.{number % 10000}" : $"{number / 10000}.{number / 100 % 100}.{number % 100}"; } Path: redb/redb.Postgres/Extensions/PostgresOptionsExtensions.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.Postgres/Extensions/PostgresOptionsExtensions.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.Postgres.Data; using redb.Postgres.Providers; using redb.Postgres.Sql; namespace redb.Postgres.Extensions; /// /// PostgreSQL provider extensions for RedbOptionsBuilder. /// public static class PostgresOptionsExtensions { /// /// Configures REDB to use PostgreSQL as the database provider. /// For Pro version, use AddRedbPro() from redb.Postgres.Pro package. /// /// The options builder. /// PostgreSQL connection string. If null, must be set in Configure(). /// The options builder for chaining. /// /// services.AddRedb(options => options /// .UsePostgres("Host=localhost;Database=mydb;Username=user;Password=pass") /// .Configure(c => c.EnablePropsCache = true)); /// public static RedbOptionsBuilder UsePostgres( 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.Postgres.Pro package. Use AddRedbPro() from redb.Postgres.Pro.Extensions."); RegisterOpenSourceServices(services, config); }); return builder; } /// /// Registers OpenSource PostgreSQL services. /// Called by UsePostgres() and can be used by Pro version as fallback. /// public static void RegisterOpenSourceServices(IServiceCollection services, RedbServiceConfiguration config) { // DataSource and Context if (!string.IsNullOrEmpty(config.ConnectionString)) { // Factory registration hands OWNERSHIP to the container: disposing the provider disposes // the NpgsqlDataSource and closes its pool. The old instance-registration form left the // pool open forever - every container restart (module hot-reload, tests) stacked another // orphaned pool of idle sessions until the server-side pruner got them (2026-09-09). services.AddSingleton(_ => Data.NpgsqlDataSourceFactory.Create(config.ConnectionString, config.StringCollation, config.EnableLazyReferences)); services.AddScoped(sp => new NpgsqlRedbContext(sp.GetRequiredService()) { BulkInsertTimeout = config.BulkInsertTimeout }); } // Security services.AddScoped(sp => AmbientSecurityContext.GetOrCreateDefault()); // SQL Dialect. Constructed from the configuration rather than registered by type, so the // collation travels with the dialect instead of living in a process-wide static. services.AddSingleton(_ => new PostgreSqlDialect(config.StringCollation)); // 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.Postgres/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.Postgres/Extensions/PropertyInfoExtensions.cs ---- using System.Reflection; using System.Text.Json.Serialization; using redb.Core.Attributes; namespace redb.Postgres.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.Postgres/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.Postgres/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.Postgres.Providers; using redb.Core.Providers; using redb.Core.Serialization; namespace redb.Postgres.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.UsePostgres(connectionString)) from redb.Core.Extensions")] public static IServiceCollection AddRedbPostgres( 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 hands OWNERSHIP to the container: disposing the provider disposes // the NpgsqlDataSource and closes its pool. The old instance-registration form left the // pool open forever - every container restart (module hot-reload, tests) stacked another // orphaned pool of idle sessions until the server-side pruner got them (2026-09-09). services.AddSingleton(_ => Data.NpgsqlDataSourceFactory.Create(config.ConnectionString, config.StringCollation, config.EnableLazyReferences)); services.AddScoped(sp => new Data.NpgsqlRedbContext(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(_ => new Sql.PostgreSqlDialect(config.StringCollation)); // 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.UsePostgres(connectionString)) from redb.Core.Extensions")] public static IServiceCollection AddRedbPostgresFromConfig( 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 hands OWNERSHIP to the container: disposing the provider disposes // the NpgsqlDataSource and closes its pool. The old instance-registration form left the // pool open forever - every container restart (module hot-reload, tests) stacked another // orphaned pool of idle sessions until the server-side pruner got them (2026-09-09). services.AddSingleton(_ => Data.NpgsqlDataSourceFactory.Create(config.ConnectionString, config.StringCollation, config.EnableLazyReferences)); services.AddScoped(sp => new Data.NpgsqlRedbContext(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(_ => new Sql.PostgreSqlDialect(config.StringCollation)); // 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 hands OWNERSHIP to the container: disposing the provider disposes // the NpgsqlDataSource and closes its pool. The old instance-registration form left the // pool open forever - every container restart (module hot-reload, tests) stacked another // orphaned pool of idle sessions until the server-side pruner got them (2026-09-09). services.AddSingleton(_ => Data.NpgsqlDataSourceFactory.Create(configuration.ConnectionString, configuration.StringCollation, configuration.EnableLazyReferences)); services.AddScoped(sp => new Data.NpgsqlRedbContext(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.Postgres/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.Postgres/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.Postgres.Extensions { /// /// Extension methods for registering RedbService in DI container. /// public static class ServiceCollectionExtensions { /// /// Register RedbService with default configuration. /// [Obsolete("Use services.AddRedb() from redb.Postgres.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.Postgres.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.Postgres.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.Postgres.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.Postgres.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.Postgres.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.Postgres.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.Postgres/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.Postgres/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.Postgres.Providers { /// /// OpenSource implementation of lazy Props loading for PostgreSQL. /// 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 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.PostgreSqlDialect(); _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 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.Postgres/Providers/PostgresListProvider.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.Postgres/Providers/PostgresListProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Providers; using redb.Core.Providers.Base; using redb.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers { /// /// PostgreSQL implementation of IListProvider. /// Inherits all logic from ListProviderBase, provides PostgreSQL-specific SQL via PostgreSqlDialect. /// public class PostgresListProvider : ListProviderBase { /// /// Creates PostgreSQL list provider with default PostgreSqlDialect. /// /// Database context for executing queries /// Service configuration /// Scheme sync provider (for accessing domain-bound caches) /// Optional logger for diagnostics public PostgresListProvider( IRedbContext context, RedbServiceConfiguration configuration, ISchemeSyncProvider schemeSync, ILogger? logger = null) : base(context, configuration, new PostgreSqlDialect(), schemeSync, logger) { } } } Path: redb/redb.Postgres/Providers/PostgresMaintenanceProvider.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.Postgres/Providers/PostgresMaintenanceProvider.cs ---- using redb.Core.Data; using redb.Core.Providers.Base; using redb.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers { /// /// PostgreSQL maintenance provider. All logic lives in the base; this class only wires the /// dialect in (same shape as PostgresValidationProvider). /// public class PostgresMaintenanceProvider : MaintenanceProviderBase { public PostgresMaintenanceProvider(IRedbContext context, int analysisLimit, ILogger? logger = null) : base(context, new PostgreSqlDialect(), analysisLimit, logger) { } } } Path: redb/redb.Postgres/Providers/PostgresObjectStorageProvider.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.Postgres/Providers/PostgresObjectStorageProvider.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.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers { /// /// PostgreSQL implementation of ObjectStorageProvider. /// Inherits all business logic from ObjectStorageProviderBase, provides PostgreSQL-specific LazyPropsLoader. /// public class PostgresObjectStorageProvider : ObjectStorageProviderBase { /// /// Creates a new PostgresObjectStorageProvider instance. /// public PostgresObjectStorageProvider( 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 PostgreSqlDialect(), listProvider, logger, saveInterceptors) { } /// /// Creates PostgreSQL-specific LazyPropsLoader for lazy property loading. /// protected override ILazyPropsLoader CreateLazyPropsLoader() { return new LazyPropsLoader(Context, SchemeSyncProvider, Serializer, Configuration, ListProvider, Logger); } } } Path: redb/redb.Postgres/Providers/PostgresPermissionProvider.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.Postgres/Providers/PostgresPermissionProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers; /// /// PostgreSQL implementation of permission provider. /// Inherits all business logic from PermissionProviderBase. /// Only provides PostgreSQL-specific SQL dialect. /// /// IMPORTANT: Uses PostgreSQL function get_user_permissions_for_object() /// for efficient recursive permission calculation. /// /// Usage: /// services.AddScoped<IPermissionProvider, PostgresPermissionProvider>(); /// public class PostgresPermissionProvider : PermissionProviderBase { /// /// Creates a new PostgreSQL permission provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics public PostgresPermissionProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null) : base(context, securityContext, new PostgreSqlDialect(), logger) { } // All business logic is inherited from PermissionProviderBase. // PostgreSQL-specific SQL is provided by PostgreSqlDialect. // The critical method Permissions_GetEffectiveForObject() uses // PostgreSQL function get_user_permissions_for_object() for efficient // recursive permission calculation with inheritance. } Path: redb/redb.Postgres/Providers/PostgresQueryableProvider.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.Postgres/Providers/PostgresQueryableProvider.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.Postgres.Query; using redb.Core.Query.Parsing; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; namespace redb.Postgres.Providers { /// /// PostgreSQL implementation of IQueryableProvider. /// Inherits all logic from QueryableProviderBase, provides PostgreSQL-specific query providers. /// public class PostgresQueryableProvider : QueryableProviderBase { public PostgresQueryableProvider( 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 PostgresQueryProvider(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 PostgresTreeQueryProvider(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 PostgresTreeQueryProvider(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 PostgresTreeQueryProvider(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 PostgresTreeQueryable(treeQueryProvider, multiRootContext, filterParser, orderingParser); } protected override IRedbQueryable CreateMultiRootTreeQueryByIds( long schemeId, long? userId, bool checkPermissions, IEnumerable rootObjectIds, int? maxDepth) { var treeQueryProvider = new PostgresTreeQueryProvider(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 PostgresTreeQueryable(treeQueryProvider, multiRootContext, filterParser, orderingParser); } } } Path: redb/redb.Postgres/Providers/PostgresRoleProvider.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.Postgres/Providers/PostgresRoleProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers; /// /// PostgreSQL implementation of role provider. /// Inherits all business logic from RoleProviderBase. /// Only provides PostgreSQL-specific SQL dialect. /// /// Usage: /// services.AddScoped<IRoleProvider, PostgresRoleProvider>(); /// public class PostgresRoleProvider : RoleProviderBase { /// /// Creates a new PostgreSQL role provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics public PostgresRoleProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null) : base(context, securityContext, new PostgreSqlDialect(), logger) { } // All business logic is inherited from RoleProviderBase. // PostgreSQL-specific SQL is provided by PostgreSqlDialect. // Override virtual methods here for PostgreSQL-specific optimizations if needed. // For example, using RETURNING clause for insert operations. } Path: redb/redb.Postgres/Providers/PostgresSchemeSyncProvider.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.Postgres/Providers/PostgresSchemeSyncProvider.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.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers; /// /// PostgreSQL implementation of scheme synchronization provider. /// Inherits all logic from SchemeSyncProviderBase, provides PostgreSQL-specific SQL via PostgreSqlDialect. /// public class PostgresSchemeSyncProvider : SchemeSyncProviderBase { /// /// Creates PostgreSQL scheme sync provider with default PostgreSqlDialect. /// public PostgresSchemeSyncProvider( IRedbContext context, RedbServiceConfiguration? configuration = null, string? cacheDomain = null, ILogger? logger = null) : base(context, new PostgreSqlDialect(), 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); } } Path: redb/redb.Postgres/Providers/PostgresTreeProvider.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.Postgres/Providers/PostgresTreeProvider.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.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers; /// /// PostgreSQL implementation of tree provider. /// Inherits all logic from TreeProviderBase, provides PostgreSQL-specific SQL via PostgreSqlDialect. /// public class PostgresTreeProvider : TreeProviderBase { /// /// Creates PostgreSQL tree provider with default PostgreSqlDialect. /// public PostgresTreeProvider( 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 PostgreSqlDialect(), configuration, logger, saveInterceptors) { } } Path: redb/redb.Postgres/Providers/PostgresUserProvider.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.Postgres/Providers/PostgresUserProvider.cs ---- using redb.Core.Query; using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.Core.Security; using redb.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers; /// /// PostgreSQL implementation of user provider. /// Inherits all business logic from UserProviderBase. /// Only provides PostgreSQL-specific SQL dialect and password hasher. /// /// Usage: /// services.AddScoped<IUserProvider, PostgresUserProvider>(); /// public class PostgresUserProvider : UserProviderBase { /// /// Creates a new PostgreSQL user provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics /// /// Configured dialect. Optional so hand-construction keeps working, but DI supplies the /// singleton built from RedbServiceConfiguration, and that is how StringCollation /// reaches user search. This provider is the only one that needs it: its base class is the sole /// caller of FormatCaseInsensitiveLike. The other Postgres providers construct a bare /// dialect deliberately, because they use it only for pagination, quoting and literals. /// public PostgresUserProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null, ISqlDialect? dialect = null) : base(context, securityContext, dialect ?? new PostgreSqlDialect(), new BcryptPasswordHasher(), logger) { } /// /// Creates a new PostgreSQL user provider with custom password hasher. /// /// Database context for executing queries /// Security context for authorization /// Custom password hasher implementation /// Optional logger for diagnostics public PostgresUserProvider( IRedbContext context, IRedbSecurityContext securityContext, IPasswordHasher passwordHasher, ILogger? logger = null, ISqlDialect? dialect = null) : base(context, securityContext, dialect ?? new PostgreSqlDialect(), passwordHasher, logger) { } // All business logic is inherited from UserProviderBase. // PostgreSQL-specific SQL is provided by PostgreSqlDialect. // Password hashing defaults to BcryptPasswordHasher (a custom IPasswordHasher can be injected). } Path: redb/redb.Postgres/Providers/PostgresValidationProvider.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.Postgres/Providers/PostgresValidationProvider.cs ---- using redb.Core.Data; using redb.Core.Providers.Base; using redb.Postgres.Sql; using Microsoft.Extensions.Logging; namespace redb.Postgres.Providers { /// /// PostgreSQL implementation of validation provider. /// Inherits common logic from ValidationProviderBase. /// public class PostgresValidationProvider : ValidationProviderBase { /// /// Creates PostgreSQL validation provider. /// /// Database context for executing queries /// Optional logger for diagnostics public PostgresValidationProvider(IRedbContext context, ILogger? logger = null) : base(context, new PostgreSqlDialect(), logger) { } } } Path: redb/redb.Postgres/Query/PostgresQueryProvider.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.Postgres/Query/PostgresQueryProvider.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.Postgres.Query; /// /// PVT-backed terminal aggregations for free PostgreSQL. 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 PostgresQueryProvider { /// /// 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); var wrapped = "SELECT row_to_json(t)::text AS \"Value\" FROM (" + innerSql + ") t"; var jsonRow = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); 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 reads its one row through row_to_json. 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!; var invocation = "SELECT pvt_build_aggregate_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1::jsonb, $2::jsonb, 'flat', NULL::bigint[], NULL::int, true, true) 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.Postgres/Query/PostgresQueryProvider.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.Postgres/Query/PostgresQueryProvider.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.Postgres.Query; /// /// PVT-backed GroupBy + Window Functions for free PostgreSQL. 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 PostgresQueryProvider { /// 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, CancellationToken cancellationToken = default) { var sql = await BuildGroupedWindowSqlAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson); var jsonArray = await _context.ExecuteScalarAsync(sql, System.Array.Empty(), cancellationToken); 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(); // An aggregate the window sorts or partitions by need not be in the selector. It is then // computed inside the grouping under a private alias and left out of the result. var shownAggregates = aggList.ToList(); aggList = GroupedWindowSelect.WithHiddenAggregates(shownAggregates, windowList, partitionList, orderList); 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)); 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::jsonb, $2::jsonb, $3::jsonb, $4::jsonb, NULL::jsonb, NULL::integer, 0, 'flat', NULL::bigint[], NULL::integer, true, true) 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 + "."); var window = GroupedWindowSelect.Build( innerSql, groupList, aggList, shownAggregates, windowList, partitionList, orderList, QuoteIdent, rankingNeedsOrder: false); return "SELECT COALESCE(json_agg(row_to_json(t)), '[]'::json)::text AS \"Value\" FROM (" + window + ") t"; } private static string QuoteIdent(string identifier) { // Match PostgreSQL's standard double-quote identifier escaping. return "\"" + identifier.Replace("\"", "\"\"") + "\""; } } Path: redb/redb.Postgres/Query/PostgresQueryProvider.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.Postgres/Query/PostgresQueryProvider.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.Postgres.Query; /// /// PVT-backed GROUP BY for free PostgreSQL. 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 PostgresQueryProvider { /// 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, CancellationToken cancellationToken = default) { 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); var wrapped = "SELECT COALESCE(json_agg(row_to_json(t)), '[]'::json)::text AS \"Value\" FROM (" + innerSql + ") t"; var jsonArray = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); 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::jsonb, $2::jsonb, $3::jsonb, $4::jsonb, NULL::jsonb, NULL::integer, 0, 'flat', NULL::bigint[], NULL::integer, true, true) 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 PostgreSQL provider: pvt_build_array_groupby_sql of the module builds the /// grouping (and its HAVING); a window over the groups is written around it by . /// public override async Task ExecuteArrayGroupQueryAsync(ArrayGroupQuery query, CancellationToken cancellationToken = default) { var sql = await BuildArrayGroupSqlAsync(query, cancellationToken); var wrapped = "SELECT COALESCE(json_agg(row_to_json(t)), '[]'::json)::text AS \"Value\" FROM (" + sql + ") t"; var json = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); if (string.IsNullOrEmpty(json)) throw new InvalidOperationException("GroupByArray: the grouping returned no JSON array 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::text, $2::jsonb, $3::jsonb, $4::jsonb, $5::jsonb, NULL::jsonb, NULL::integer, 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.Postgres/Query/PostgresQueryProvider.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.Postgres/Query/PostgresQueryProvider.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.Postgres.Query; /// /// PVT-backed window functions for free PostgreSQL. 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 PostgresQueryProvider { /// 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, CancellationToken cancellationToken = default) { var innerSql = await BuildWindowInnerSqlAsync(schemeId, selectFields, windowFuncs, partitionBy, orderBy, filterJson, frameJson, take, skip); var wrapped = "SELECT COALESCE(json_agg(row_to_json(t)), '[]'::json)::text AS \"Value\" FROM (" + innerSql + ") t"; var jsonArray = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); 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::jsonb, $2::jsonb, NULL::jsonb, $3::integer, $4::integer, 'flat', NULL::bigint[], NULL::integer, true, true) 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 /// PostgreSQL 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"] = PostgresQueryProvider.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"] = PostgresQueryProvider.NormalizePvtFieldName(p.FieldPath, p.IsBaseField) }) .ToList(); var orderEntries = orderBy .Select(o => new Dictionary { ["field"] = PostgresQueryProvider.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"] = PostgresQueryProvider.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.Postgres/Query/PostgresQueryProvider.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.Postgres/Query/PostgresQueryProvider.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.Postgres.Sql; namespace redb.Postgres.Query; /// /// PostgreSQL query provider implementation. /// Inherits from QueryProviderBase and provides PostgreSQL-specific components. /// public partial class PostgresQueryProvider : QueryProviderBase { public PostgresQueryProvider( IRedbContext context, IRedbObjectSerializer serializer, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, ILogger? logger = null, ISchemeSyncProvider? schemeSync = null, ISqlDialect? dialect = null) : base(context, serializer, dialect ?? new PostgreSqlDialect(), lazyPropsLoader, configuration, logger, schemeSync) { } } Path: redb/redb.Postgres/Query/PostgresTreeQueryProvider.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.Postgres/Query/PostgresTreeQueryProvider.Pvt.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; 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.Postgres.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 PostgresTreeQueryProvider { /// /// 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 objectsJson = await ExecutePvtTreeAsync(context, route); var result = DeserializeTreeObjects(objectsJson); 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(*)::bigint 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::integer"; var limitArg = forCount || !context.Limit.HasValue ? "NULL" : context.Limit.Value.ToString(CultureInfo.InvariantCulture); var offsetArg = forCount ? "0" : (context.Offset ?? 0).ToString(CultureInfo.InvariantCulture); var treeIdsLiteral = route.TreeIds.Length == 0 ? "NULL::bigint[]" : "ARRAY[" + string.Join(",", route.TreeIds.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]::bigint[]"; // 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 // 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::jsonb" : "NULL::jsonb"; var invocation = "SELECT pvt_build_query_sql(" + context.SchemeId.ToString(CultureInfo.InvariantCulture) + ", $1::jsonb, " + limitArg + ", " + offsetArg + ", " + orderArg + ", " + maxDepth + ", " + (context.IsDistinct ? "true" : "false") + ", '" + route.SourceMode + "'" + ", " + treeIdsLiteral + ", " + (route.IncludeSeed ? "true" : "false") + ", true" // p_polymorphic=true matches Pro default + (distinctOnJson != null ? ", $3::jsonb" : "") + ") 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; } /// /// Wraps the inner _id list with the same jsonb_agg(jsonb_build_object(...)) /// shape produced by the legacy search_tree_objects_with_facets_base /// function and executes it. Returns the raw JSON array string. /// 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 = "SELECT jsonb_agg(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_unique', o._value_unique," + "'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" // The order of the inner query is carried explicitly: the inner query numbers its rows in its own order // (_ord, module 0.7.26). Aggregating over the join without ORDER BY kept it only while the planner happened // to choose a nested loop, and row_number() OVER () above the subquery relied on the plan reading it in order. + ") ORDER BY sub._ord)::text AS \"Value\"" + " FROM (" + inner + ") sub" + " JOIN _objects o ON o._id = sub._id"; 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.ExecuteScalarAsync(sql, new object[] { filterParam, orderByJson! }, cancellationToken); return await _context.ExecuteScalarAsync(sql, new object[] { filterParam }, cancellationToken); } /// /// 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 this /// provider no longer installs, so ToSqlStringAsync on a tree query failed with 42883. /// 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 System.Text.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(); } } Path: redb/redb.Postgres/Query/PostgresTreeQueryProvider.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.Postgres/Query/PostgresTreeQueryProvider.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.Postgres.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 PostgresTreeQueryProvider { /// /// 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"; var treeIdsLiteral = scopeRootIds == null || scopeRootIds.Length == 0 ? "NULL::bigint[]" : "ARRAY[" + string.Join(",", scopeRootIds.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]::bigint[]"; var maxDepth = searchDepth; var invocation = "SELECT pvt_build_query_sql(" + filter.TargetSchemeId.Value.ToString(CultureInfo.InvariantCulture) + ", $1::jsonb, NULL, 0, NULL::jsonb, " + maxDepth.ToString(CultureInfo.InvariantCulture) + ", false, '" + sourceMode + "', " + treeIdsLiteral + ", false, true) 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.Postgres/Query/PostgresTreeQueryProvider.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.Postgres/Query/PostgresTreeQueryProvider.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.Postgres.Sql; namespace redb.Postgres.Query; /// /// PostgreSQL tree query provider implementation. /// Inherits from TreeQueryProviderBase and provides PostgreSQL-specific components. /// public partial class PostgresTreeQueryProvider : TreeQueryProviderBase { public PostgresTreeQueryProvider( 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 PostgreSqlDialect(), cacheDomain, lazyPropsLoader, configuration, logger, schemeSync) { } /// /// Creates query provider for delegation. /// protected override IRedbQueryProvider CreateQueryProvider() { return new PostgresQueryProvider(_context, _serializer, _lazyPropsLoader, _configuration, _logger, _schemeSync); } /// /// Creates tree queryable instance. /// protected override IRedbQueryable CreateTreeQueryable(TreeQueryContext context) { return new PostgresTreeQueryable(this, context, _filterParser, _orderingParser); } } Path: redb/redb.Postgres/Query/PostgresTreeQueryable.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.Postgres/Query/PostgresTreeQueryable.cs ---- using redb.Core.Query; using redb.Core.Query.Base; using redb.Core.Query.FacetFilters; using redb.Core.Query.QueryExpressions; namespace redb.Postgres.Query; /// /// PostgreSQL tree queryable implementation. /// Inherits from TreeQueryableBase and provides PostgreSQL-specific components. /// public class PostgresTreeQueryable : TreeQueryableBase where TProps : class, new() { public PostgresTreeQueryable( 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 PostgresTreeQueryable(_treeProvider, context, _filterParser, _orderingParser); } } Path: redb/redb.Postgres/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.Postgres/README.md ---- # redb.Postgres PostgreSQL provider for **RedBase (REDB)** — Entity Database for .NET. [![NuGet](https://img.shields.io/nuget/v/redb.Postgres?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Postgres) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../LICENSE) ## What's inside - PostgreSQL-optimized SQL generation - Tree queries with recursive CTEs - Schema initialization (`redbPostgre.sql`) - Full LINQ-to-SQL translation - Depends on `redb.Core` and `Npgsql` ## Installation ```bash dotnet add package redb.Postgres ``` ## Setup ```csharp using redb.Core.Extensions; using redb.Postgres.Extensions; builder.Services.AddRedb(options => options .UsePostgres("Host=localhost;Port=5432;Database=mydb;Username=postgres;Password=pass")); ``` ## 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.Postgres/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.Postgres/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.Security; using redb.Core.Models.Contracts; using redb.Core.Models.Configuration; using redb.Postgres.Data; using redb.Postgres.Providers; using redb.Postgres.Sql; namespace redb.Postgres; /// /// PostgreSQL implementation of IRedbService. /// Inherits all common logic from RedbServiceBase. /// Only provides PostgreSQL-specific provider factories. /// public class RedbService : RedbServiceBase { private static readonly PostgreSqlDialect _dialect = new(); /// /// Creates a new PostgreSQL RedbService instance. /// public RedbService(IServiceProvider serviceProvider) : base(serviceProvider) { _postgresLogger = serviceProvider.GetService(typeof(ILogger)) as ILogger; } private readonly ILogger? _postgresLogger; // === POSTGRESQL-SPECIFIC IMPLEMENTATIONS === protected override string DatabaseTypeName => "PostgreSQL"; protected override ISqlDialect SqlDialect => _dialect; /// The indexes of a fresh PostgreSQL database of this build (PostgresIndexCatalog, generated and pinned by a test). protected override IReadOnlyList ExpectedIndexes => PostgresIndexCatalog.Base; /// CREATE INDEX CONCURRENTLY: reads and writes go on while it builds. protected override string IndexBuildStatement(Core.Models.RedbExpectedIndex index, bool online) => System.Text.RegularExpressions.Regex.Replace(index.CreateSql, @"^CREATE\s+(UNIQUE\s+)?INDEX\s+", m => m.Value.TrimEnd() + " CONCURRENTLY ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); /// The INVALID leftover of an interrupted build is dropped CONCURRENTLY as well. protected override string IndexDropStatement(Core.Models.RedbExpectedIndex index) => $"DROP INDEX CONCURRENTLY IF EXISTS \"{index.Name}\""; /// /// On a connection of its own: CONCURRENTLY refuses to run inside a transaction block, and a build on a large table /// runs past any command timeout of the connection string. /// protected override async Task ExecuteIndexDdlAsync(string sql, CancellationToken cancellationToken) { if (Context is not NpgsqlRedbContext npgsql) { await Context.ExecuteAsync(sql); return; } await using var connection = await npgsql.DataSource.OpenConnectionAsync(cancellationToken); await using var command = new Npgsql.NpgsqlCommand(sql, connection) { CommandTimeout = 0 }; await command.ExecuteNonQueryAsync(cancellationToken); } protected override string GetVersionSql => "SELECT version()"; protected override string GetDatabaseSizeSql => "SELECT pg_database_size(current_database())"; protected override string ContextNotRegisteredError => "IRedbContext is not registered in DI container. Add NpgsqlRedbContext to configuration."; // === PROVIDER FACTORIES === protected override ISchemeSyncProvider CreateSchemeSyncProvider( IRedbContext context, RedbServiceConfiguration config, string cacheDomain, ILogger? logger) => new PostgresSchemeSyncProvider(context, config, cacheDomain, logger); protected override IPermissionProvider CreatePermissionProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new PostgresPermissionProvider(context, securityContext, logger); protected override IUserProvider CreateUserProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new PostgresUserProvider(context, securityContext, ResolvePasswordHasher(), logger); protected override IRoleProvider CreateRoleProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new PostgresRoleProvider(context, securityContext, logger); protected override IListProvider CreateListProvider( IRedbContext context, RedbServiceConfiguration config, ISchemeSyncProvider schemeSync, ILogger? logger) => new PostgresListProvider(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 PostgresObjectStorageProvider(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 PostgresTreeProvider(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 PostgresQueryableProvider(context, serializer, schemeSync, securityContext, lazyPropsLoader, config, cacheDomain, logger); protected override IValidationProvider CreateValidationProvider( IRedbContext context, ILogger? logger) => new PostgresValidationProvider(context, logger); protected override Core.Providers.IMaintenanceProvider CreateMaintenanceProvider( IRedbContext context, int analysisLimit, ILogger? logger) => new Providers.PostgresMaintenanceProvider(context, analysisLimit, logger); // === DATABASE SCHEMA MANAGEMENT === /// protected override async Task TableExistsAsync(string tableName) { var sql = "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = @p0)"; return await Context.ExecuteScalarAsync(sql, tableName); } /// protected override string ReadEmbeddedSql() { var assembly = typeof(RedbService).Assembly; var resourceName = "redb.Postgres.sql.redb_init.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() { var assembly = typeof(RedbService).Assembly; var resourceName = "redb.Postgres.sql.v2-pvt.pvt_bundle.sql"; using var stream = assembly.GetManifestResourceStream(resourceName); if (stream is null) return null; using var reader = new StreamReader(stream); return reader.ReadToEnd(); } /// /// The module pass of the base class, then the step of /// (). /// protected override async Task EnsurePvtModuleDeployedAsync() { await EnsureServerSupportedAsync(); await base.EnsurePvtModuleDeployedAsync(); if (Configuration.CreateStringCollationIndex && Configuration.StringCollation is null) { _postgresLogger?.LogWarning( "CreateStringCollationIndex is on, but StringCollation is not set: there is no collation to build an index for."); return; } await EnsureStringCollationIndexAsync(); } /// /// The trigram index of . The free forms pivot the values of an /// object first and filter the pivoted value, so no trigram index ever serves their string search: with /// on, one Warning and nothing built. Pro with the /// planner on builds and checks the index. /// protected virtual Task EnsureStringCollationIndexAsync() { WarnStringCollationIndexHasNoEffect("free provider"); return Task.CompletedTask; } /// The Warning of on a tier that reads no trigram index. protected void WarnStringCollationIndexHasNoEffect(string tier) { if (!Configuration.CreateStringCollationIndex) return; _postgresLogger?.LogWarning( "CreateStringCollationIndex is on, but it has no effect on this tier ({Tier}): only Pro with EnablePvtPrefilter " + "on reads a trigram index for a string search. Nothing is built.", tier); } /// protected override async Task ExecuteSchemaScriptAsync(string sql) { await EnsureServerSupportedAsync(); await Context.ExecuteAsync(sql); } // Set once the server has passed the check: it is asked once per service, not at every module pass. private bool _serverSupported; /// /// Refuses a server older than PostgreSQL 15 () with one message naming both /// versions, before the creation script or the module pass reaches a statement the server cannot parse. /// private async Task EnsureServerSupportedAsync() { if (_serverSupported) return; PostgresServerVersion.EnsureSupported(await Context.ExecuteScalarAsync(PostgresServerVersion.Query)); _serverSupported = true; } /// protected override async Task OpenSchemaLockAsync(CancellationToken cancellationToken) { if (Context is not NpgsqlRedbContext npgsql) return SchemaLockHandle.None; return new AdvisoryLock(await npgsql.DataSource.OpenConnectionAsync(cancellationToken)); } /// /// The schema lock of PostgreSQL: a session advisory lock on a connection of its own, outside any transaction. /// Taken with pg_try_advisory_lock, never pg_advisory_lock: a backend blocked in pg_advisory_lock holds the /// snapshot of its statement, and CREATE INDEX CONCURRENTLY of the node that holds the lock waits for every such /// snapshot, so the two would wait for each other. Advisory locks are per database, so one key serves all of them. /// private sealed class AdvisoryLock(Npgsql.NpgsqlConnection connection) : SchemaLockHandle { // "redb_sch" in ASCII. private const long Key = 0x726564625F736368; private bool _held; public override string Name => $"pg_advisory_lock({Key})"; public override async Task TryAcquireAsync(CancellationToken cancellationToken) { await using var command = new Npgsql.NpgsqlCommand(_dialect.SchemaLock_TryAcquire(), connection); command.Parameters.Add(new Npgsql.NpgsqlParameter { Value = Key }); _held = (bool)(await command.ExecuteScalarAsync(cancellationToken))!; return _held; } public override async ValueTask DisposeAsync() { try { if (_held) { await using var command = new Npgsql.NpgsqlCommand(_dialect.SchemaLock_Release(), connection); command.Parameters.Add(new Npgsql.NpgsqlParameter { Value = Key }); await command.ExecuteScalarAsync(); } } finally { // Closing ends the session too, and the session takes its advisory locks with it. await connection.DisposeAsync(); } } } } Path: redb/redb.Postgres/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.Postgres/Utils/ValuesTopologicalSort.cs ---- using System.Collections.Generic; using System.Linq; using redb.Core.Data; using redb.Core.Models.Entities; namespace redb.Postgres.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.Postgres/redb.Postgres.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.Postgres/redb.Postgres.csproj ---- net10.0;net11.0 enable enable true $(NoWarn);CS1591 redb.Postgres REDB - Entity Database for .NET PostgreSQL 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;postgresql;postgres;linq;dotnet;typed-storage;cte;tree-query README.md redb.Postgres.sql.v2-pvt.pvt_bundle.sql System.IO.Path.GetFileName(i.ItemSpec), System.StringComparer.OrdinalIgnoreCase)); } // redb_init.sql is NOT sorted: its groups (main DDL, metadata cache, helpers, pvt) carry a // deliberate cross-group order that a filename sort destroys (review regression: a fresh // database died with `relation _structures does not exist`; caught by the fresh-install test). foreach (var item in items) { var path = item.ItemSpec; sb.AppendLine("-- ===== " + System.IO.Path.GetFileName(path) + " ====="); sb.AppendLine(System.IO.File.ReadAllText(path)); sb.AppendLine(); } System.IO.File.WriteAllText(OutputFile, sb.ToString()); ]]> Path: redb/redb.Postgres/sql/PostgreSqlDialect.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.Postgres/sql/PostgreSqlDialect.cs ---- using redb.Core.Query; using redb.Core.Utils; namespace redb.Postgres.Sql; /// /// PostgreSQL implementation of ISqlDialect. /// Uses CASE WHEN for PVT (tested - 15 ms on 15K objects!). /// public class PostgreSqlDialect : ISqlDialect { /// /// Collation attached to case-folding expressions, or null to leave SQL exactly as it was. /// Validated by before it reaches here. /// private readonly string? _stringCollation; /// Default construction: no collation, generated SQL is unchanged. public PostgreSqlDialect() : this(null) { } public PostgreSqlDialect(string? stringCollation) { if (!string.IsNullOrWhiteSpace(stringCollation)) { // Re-validated here rather than trusted: this constructor is public and is also // reachable from provider code that did not go through RedbServiceConfiguration. CollationNameValidator.Validate(stringCollation!); _stringCollation = stringCollation; } } public string ProviderName => "PostgreSQL"; /// /// (expr COLLATE "und-x-icu"). The parentheses are not decoration: without them /// COLLATE binds tighter than expected inside a larger expression and the clause can /// attach to the wrong operand. /// public string FoldCase(string expression) => _stringCollation is null ? expression : $"({expression} COLLATE {CollationNameValidator.Quote(_stringCollation)})"; public string FormatPagination(int? limit, int? offset) { var parts = new List(); if (limit.HasValue) parts.Add($"LIMIT {limit.Value}"); if (offset.HasValue && offset.Value > 0) parts.Add($"OFFSET {offset.Value}"); return string.Join(" ", parts); } 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) => $"(array_agg({dbColumn}) FILTER (WHERE _id_structure = {structureId}))[1] AS \"{alias}\""; public string FormatArrayContains(string column, string paramName) => $"{column} = ANY({paramName})"; public string GetDbTypeName(string redbType) => redbType switch { "Long" => "bigint", "String" => "text", "Boolean" => "boolean", "DateTime" => "timestamptz", "DateTimeOffset" => "timestamptz", "Double" => "double precision", "Numeric" => "numeric", "Guid" => "uuid", "ByteArray" => "bytea", _ => "text" }; public string FormatParameter(int index) => $"${index}"; public string QuoteIdentifier(string name) // PostgreSQL escapes a double quote by doubling it. Without this a name like // `a"b` closes the identifier and the rest becomes SQL (SQLI-PoC p.7). => "\"" + name.Replace("\"", "\"\"") + "\""; public string FormatCaseInsensitiveLike(string column, string parameter) => $"{FoldCase(column)} ILIKE {parameter}"; public string FormatDateTimeLiteral(DateTime dt) => $"'{DateTimeConverter.NormalizeForStorage(dt):yyyy-MM-ddTHH:mm:ss.ffffffZ}'::timestamptz"; public string FormatDateTimeOffsetLiteral(DateTimeOffset dto) => $"'{dto.UtcDateTime:yyyy-MM-ddTHH:mm:ss.ffffffZ}'::timestamptz"; public string FormatBinaryLiteral(byte[] value) => "'\\x" + Convert.ToHexString(value) + "'::bytea"; // ============================================================ // === 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"; /// /// CRITICAL: Uses PostgreSQL function get_user_permissions_for_object()! /// This function implements complex recursive permission logic. /// For MSSQL this must be replaced with CTE/JOIN query. /// public string Permissions_GetEffectiveForObject() => "SELECT * FROM get_user_permissions_for_object($1, $2)"; public string Permissions_GetEffectiveForObjects() => """ SELECT ids.id 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 unnest($1::bigint[]) AS ids(id) CROSS JOIN LATERAL get_user_permissions_for_object(ids.id, $2) p """; public string Permissions_SelectReadableObjectIds() => """ SELECT DISTINCT object_id FROM v_user_permissions WHERE user_id = $1 AND can_select = true """; 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 = ANY($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. Returns the FIRST match — email isn't enforced // unique at the schema level; callers that need uniqueness probe with their own // policy. Filters out soft-deleted rows (_enabled = false) so a stale row whose // address was anonymised by an admin update doesn't shadow a real new account. 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 = TRUE 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, $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 = $12 WHERE _id = $13 """; // _login is immutable per the protect_system_users trigger — soft-delete must NOT // touch it. Tombstoning happens on _name (mutable). Login slot stays occupied so // re-registration with the same login is blocked while the soft-deleted row exists; // freeing the login requires an explicit hard DELETE (separate admin operation). 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)"; // ON CONFLICT keeps the transaction alive: a raised unique violation would abort it and make the // follow-up SELECT fail with 25P02. 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 = $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, _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 set_config('redb.lazy_refs', CASE WHEN $1 = 1 THEN '1' ELSE '0' END, false)"; 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. 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 """; 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 """; public string Values_UpdateUnique() => "UPDATE _values SET _unique = $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 = $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)})"; // === SCHEMA LOCK === // Not part of ISqlDialect: the lock runs on a connection of its own (RedbService.OpenSchemaLockAsync), outside the // context. A session advisory lock, never waited for in the server (see RedbService.AdvisoryLock). /// One attempt at the session advisory lock of the schema; returns a boolean. Params: $1 = key (bigint). public string SchemaLock_TryAcquire() => "SELECT pg_try_advisory_lock($1)"; /// Releases the session advisory lock of the schema. Params: $1 = key (bigint). public string SchemaLock_Release() => "SELECT pg_advisory_unlock($1)"; // === ROOT STRUCTURE KEY === // A partial unique index over the root rows, written for PostgreSQL 14, which has no NULLS NOT DISTINCT. 15 is // the lowest supported server now; the index stays as databases have it. 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 pg_indexes WHERE schemaname = current_schema() AND indexname = '{RootKeyName}'"; public string Structures_CreateRootKey() => $"CREATE UNIQUE INDEX \"{RootKeyName}\" ON _structures (_id_scheme, _name) WHERE _id_parent IS NULL"; // === STRING COLLATION INDEX === // With StringCollation set, an ignore-case search reads (_String COLLATE "") ILIKE, which only a trigram // index over that same expression serves (see StringCollationIndex). /// /// Whether _values has a trigram index that serves (_String COLLATE "$1") ILIKE: a GIN index of one /// key column with opclass gin_trgm_ops over _string under collation $1. PostgreSQL stores /// (_String COLLATE "c") as the column itself with a collation of its own, not as an expression, so the key /// column is matched by attribute and collation. Matched by structure, not by name: an index made by hand under any /// name counts. Column Valid: NULL when there is none, false when every one is INVALID (an interrupted /// CONCURRENTLY build), true when one is usable. Column Ctype: the ctype of the database, which decides what /// pg_trgm takes for a letter (under C it finds no trigrams in a non-ASCII word, whatever the collation). /// The collation is resolved with to_regcollation(quote_ident($1)), the way the COLLATE "$1" of the /// search resolves it (search path, pg_catalog first), not by pg_collation.collname: a collation of the same /// name in another schema would match the name and still serve no search. Params: $1 = collation name. /// public string Values_StringCollationIndexState() => """ SELECT (SELECT bool_or(i.indisvalid) FROM pg_index i JOIN pg_class t ON t.oid = i.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace JOIN pg_class ic ON ic.oid = i.indexrelid JOIN pg_am am ON am.oid = ic.relam JOIN pg_opclass oc ON oc.oid = i.indclass[0] JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0] WHERE t.relname = '_values' AND n.nspname = current_schema() AND am.amname = 'gin' AND oc.opcname = 'gin_trgm_ops' AND i.indnkeyatts = 1 AND a.attname = '_string' AND i.indcollation[0] = to_regcollation(quote_ident($1))::oid) AS "Valid", (SELECT datctype FROM pg_database WHERE datname = current_database()) AS "Ctype" """; /// /// The statement that builds the index serving (_String COLLATE "collation") ILIKE under /// , CONCURRENTLY: it runs on a connection of its own, outside any /// transaction. The collation is a validated name (CollationNameValidator). /// public string Values_CreateStringCollationIndex(string collation) => $"CREATE INDEX CONCURRENTLY IF NOT EXISTS \"{StringCollationIndexName(collation)}\" " + $"ON _values USING gin ((_String COLLATE {CollationNameValidator.Quote(collation)}) gin_trgm_ops) " + "WHERE _String IS NOT NULL"; /// Drops an INVALID leftover of an interrupted build of . public string Values_DropStringCollationIndex(string collation) => $"DROP INDEX CONCURRENTLY IF EXISTS \"{StringCollationIndexName(collation)}\""; /// Whether the index named by exists and is INVALID. Params: $1 = index name. public string Values_StringCollationIndexInvalid() => """ SELECT NOT i.indisvalid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = $1 AND n.nspname = current_schema() """; /// The trigram operator classes; redb_init creates the extension, a database restored without it lacks them. public string Extension_CreateTrigram() => "CREATE EXTENSION IF NOT EXISTS pg_trgm"; /// /// IX__values__String_pattern_<slug>: the collation lowercased, every character other than a letter or a /// digit replaced by an underscore (und-x-icu gives IX__values__String_pattern_und_x_icu), cut to the /// 63 bytes PostgreSQL keeps of an identifier. The server cut longer names the same way when it built them, so an /// existing index keeps its name, and the look-up of an INVALID leftover finds it. Two collations that share their /// first 36 characters give one name; the cut stays, since a different form would rename indexes that exist. /// public string StringCollationIndexName(string collation) { const int identifierBytes = 63; // NAMEDATALEN - 1; the name is ASCII, one byte per character var slug = new System.Text.StringBuilder(collation.Length); foreach (var ch in collation.ToLowerInvariant()) slug.Append(char.IsAsciiLetterOrDigit(ch) ? ch : '_'); var name = "IX__values__String_pattern_" + slug; return name.Length > identifierBytes ? name[..identifierBytes] : name; } 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 """; public string? Structures_LockSubtree() => SubtreeCte + " SELECT s._id FROM _structures s JOIN t ON s._id = t._id FOR UPDATE OF s"; 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(*)::bigint 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 (PostgreSQL-specific) === // ============================================================ public string Schemes_SyncMetadataCache() => "SELECT sync_metadata_cache_for_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() => """ SELECT json_data FROM ( 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 ) subquery WHERE json_data IS NOT NULL """; public string Tree_SelectPolymorphicChildren() => """ SELECT o._id as ObjectId, o._id_scheme as SchemeId, get_object_json(o._id, 1)::text 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)::text 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 = ANY($1)"; public string Tree_DeleteObjectsByIds() => "DELETE FROM _objects WHERE _id = ANY($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::bigint IS NULL OR o._id_scheme = $2::bigint) 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::bigint IS NULL OR o._id_scheme = $2::bigint) ) 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 = ANY($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 = ANY($1) """; public string ObjectStorage_DeleteById() => "DELETE FROM _objects WHERE _id = $1"; public string ObjectStorage_DeleteByIds() => "DELETE FROM _objects WHERE _id = ANY($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, $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 = $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)::text"; public string ObjectStorage_GetObjectsJsonBulk() => """ SELECT get_object_json(id, $2)::text FROM unnest($1::bigint[]) AS id """; 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 = ANY($1) """; public string ObjectStorage_SelectSchemeIdsForObjects() => "SELECT _id as ObjectId, _id_scheme as SchemeId FROM _objects WHERE _id = ANY($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 = ANY($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 = ANY($1) " + "UNION ALL SELECT 0, NULL, s._structure_hash, s._id FROM _schemes s WHERE s._id = ANY($2)"; public string ObjectStorage_SelectIdHashPairs() => "SELECT _id as Id, _hash as Hash FROM _objects WHERE _id = ANY($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 = ANY($1) """; public string ObjectStorage_LockObjectsForUpdate() => "SELECT _id FROM _objects WHERE _id = ANY($1) ORDER BY _id FOR UPDATE"; 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 = ANY($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 === // ============================================================ public string Maintenance_Analyze(int analysisLimit) => "ANALYZE"; // pg_stat_user_indexes carries one combined scan counter (idx_scan) - it lands in Seeks; // Scans/Updates have no PostgreSQL counterpart. last_idx_scan exists from PG16 on, so it // is read defensively via to_jsonb of the row (older servers yield NULL, not an error). public string Maintenance_SelectIndexStats() => """ SELECT i.schemaname AS "Schema", c.relname AS "Table", i.indexrelname AS "Name", x.indisunique AS "IsUnique", (SELECT string_agg(a.attname, ',' ORDER BY k.ord) FROM unnest(x.indkey) WITH ORDINALITY AS k(attnum, ord) JOIN pg_attribute a ON a.attrelid = x.indrelid AND a.attnum = k.attnum WHERE k.ord <= x.indnkeyatts) AS "ColumnsCsv", (SELECT string_agg(a.attname, ',' ORDER BY k.ord) FROM unnest(x.indkey) WITH ORDINALITY AS k(attnum, ord) JOIN pg_attribute a ON a.attrelid = x.indrelid AND a.attnum = k.attnum WHERE k.ord > x.indnkeyatts) AS "IncludedColumnsCsv", x.indisprimary AS "IsPrimaryKey", EXISTS (SELECT 1 FROM pg_constraint con WHERE con.conindid = x.indexrelid AND con.contype IN ('p', 'u', 'x')) AS "IsUniqueConstraint", NULL::boolean AS "IsClustered", EXISTS (SELECT 1 FROM pg_constraint fk WHERE fk.contype = 'f' AND fk.conrelid = x.indrelid AND fk.conkey <@ x.indkey::smallint[]) AS "BacksForeignKey", pg_relation_size(i.indexrelid) AS "SizeBytes", GREATEST(ic.reltuples::bigint, 0) AS "EstimatedRows", i.idx_scan AS "Seeks", NULL::bigint AS "Scans", NULL::bigint AS "Updates", (to_jsonb(i) ->> 'last_idx_scan')::timestamptz AS "LastUsed" FROM pg_stat_user_indexes i JOIN pg_class c ON c.oid = i.relid JOIN pg_class ic ON ic.oid = i.indexrelid JOIN pg_index x ON x.indexrelid = i.indexrelid ORDER BY c.relname, i.indexrelname """; public string Maintenance_AnalyzeTable(string? schema, string table, int analysisLimit) => $"ANALYZE {QuoteIdentifier(schema ?? "public")}.{QuoteIdentifier(table)}"; public string Maintenance_SelectTableExists() => """ SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'p') AND c.relname = $1 AND n.nspname = COALESCE($2, 'public') """; public string Maintenance_SelectTableStats() => """ SELECT t.schemaname AS "Schema", t.relname AS "Table", GREATEST(c.reltuples::bigint, 0) AS "EstimatedRows", pg_table_size(c.oid) AS "DataSizeBytes", pg_indexes_size(c.oid) AS "IndexesSizeBytes", t.n_dead_tup AS "DeadRows", t.last_analyze AS "LastAnalyze", t.last_autoanalyze AS "LastAutoAnalyze", GREATEST(t.last_vacuum, t.last_autovacuum) AS "LastVacuum", (t.last_analyze IS NOT NULL OR t.last_autoanalyze IS NOT NULL) AS "HasStatistics" FROM pg_stat_user_tables t JOIN pg_class c ON c.oid = t.relid ORDER BY t.schemaname, t.relname """; public System.Collections.Generic.IReadOnlyList Maintenance_SelectTableStatsForms() => new[] { Maintenance_SelectTableStats() }; public string Maintenance_SelectStatisticsWindow() => """ SELECT COALESCE(pg_stat_get_db_stat_reset_time(oid), pg_postmaster_start_time()) AS "CountersSince", pg_is_in_recovery() AS "IsReplica" FROM pg_database WHERE datname = current_database() """; public string Maintenance_SelectIndexStatsNoSize() => Maintenance_SelectIndexStats(); // The index check: the indexes of the redb tables of the current schema. A key column is written by // pg_get_indexdef(index, n, true), which gives the column name or the expression; columns past indnkeyatts are the // INCLUDE list. indisvalid is false for an interrupted CREATE INDEX CONCURRENTLY. public string? Schema_SelectIndexShapes() => """ SELECT ic.relname AS "Name", t.relname AS "Table", x.indisunique AS "IsUnique", (SELECT string_agg(pg_get_indexdef(x.indexrelid, k.n, true), ',' ORDER BY k.n) FROM generate_series(1, x.indnkeyatts) AS k(n)) AS "KeyColumnsCsv", (SELECT string_agg(pg_get_indexdef(x.indexrelid, k.n, true), ',' ORDER BY k.n) FROM generate_series(x.indnkeyatts + 1, x.indnatts) AS k(n)) AS "IncludedColumnsCsv", x.indisvalid AS "IsValid" FROM pg_index x JOIN pg_class ic ON ic.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace WHERE n.nspname = current_schema() AND t.relname LIKE '\_%' AND NOT EXISTS (SELECT 1 FROM pg_constraint con WHERE con.conindid = x.indexrelid AND con.contype IN ('p', 'u', 'x')) """; // ============================================================ // === 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)::text"; public string LazyLoader_GetObjectJsonBatch() => @"SELECT id::bigint AS ""Id"", get_object_json(id, $2)::text AS ""JsonData"" FROM unnest($1::bigint[]) AS id"; 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 get_user_permissions_for_object($1, $2) WHERE can_select = true) as has_permission"; public string Query_SqlPreviewTemplate() => "SELECT {0}($1, $2::jsonb, $3, $4, $5::jsonb, $6, $7) as sql_preview"; /// /// PostgreSQL: 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"; /// /// PostgreSQL: 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"; /// /// PostgreSQL: Load objects by IDs as JSON using get_object_json function. /// public string Query_LoadObjectsByIdsSql(string idsString, int maxDepth) => $@"SELECT get_object_json(id, {maxDepth})::text as ""Value"" FROM unnest(ARRAY[{idsString}]) as id ORDER BY id"; public string Query_TreeSqlPreviewTemplate(string functionName) => $"SELECT {functionName}($1, $2, $3::jsonb, $4, $5, $6::jsonb, $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 Postgres) === // Two-step pipeline: ask DB to BUILD the inner _id-list SQL, // then wrap on the C# side with a materializer/COUNT/EXISTS. // The v2-pvt SQL module must be deployed (see redb.Postgres/sql/v2-pvt/). // Init-time check lives in RedbServiceBase.InitializeAsync using // Query_PvtModuleVersionFunction(). // ============================================================ 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 limitArg = limit.HasValue ? limit.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) : "NULL"; var offsetArg = offset.ToString(System.Globalization.CultureInfo.InvariantCulture); var maxDepthArg = maxDepth.ToString(System.Globalization.CultureInfo.InvariantCulture); var distinctArg = distinct ? "true" : "false"; var modeArg = sourceMode switch { "tree" => "'tree'", _ => "'flat'", }; string treeArg; if (treeIds is null || treeIds.Length == 0) { treeArg = "NULL::bigint[]"; } else { treeArg = "ARRAY[" + string.Join(",", treeIds.Select( i => i.ToString(System.Globalization.CultureInfo.InvariantCulture))) + "]::bigint[]"; } var distinctOnArg = hasDistinctOn ? "$3::jsonb" : "NULL::jsonb"; // 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 return "SELECT pvt_build_query_sql(" + schemeId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", $1::jsonb, " + limitArg + ", " + offsetArg + ", $2::jsonb, " + maxDepthArg + ", " + distinctArg + ", " + modeArg + ", " + treeArg + ", false" // p_include_seed + ", true" // p_polymorphic + ", " + distinctOnArg + ") AS \"Value\""; } // The inner query numbers its rows in its own order (_ord, module 0.7.26), restored after the join: a hash or merge // join keeps no order, and row_number() OVER () above the subquery relied on the plan reading it in order. 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 ({innerSql}) sub JOIN _objects o ON o._id = sub._id ORDER BY sub._ord """; public string? Query_WrapPvtWithCount(string innerSql) => $"SELECT count(*)::bigint AS \"Value\" FROM ({innerSql}) t"; public string? Query_WrapPvtWithExists(string innerSql) => $"SELECT EXISTS ({innerSql}) AS \"Value\""; public string? Query_WrapPvtWithIds(string innerSql) => $"SELECT t._id FROM (\n{innerSql}\n) t"; public string? Query_PvtModuleVersionFunction() => "pvt_module_version"; // Bump together with the literal in redb.Postgres/sql/v2-pvt/99_module_version.sql. public string? Query_PvtRequiredVersion() => "0.7.33"; // Created next to pvt_module_version() in 99_module_version.sql. public string? Query_PvtModuleCompatFunction() => "pvt_module_compat"; // ============================================================ // Native PVT projection orchestrator (pvt_build_projection_sql). // Mirrors the pvt_build_query_sql plumbing but the outer SELECT // yields the requested scalar columns. The C# layer wraps the // resulting SQL into a JSON-row shape via Query_WrapPvtProjectionRowsAsJson // so the existing materializer can consume it. // ============================================================ public string? Query_BuildPvtProjectionSqlFunction() => "pvt_build_projection_sql"; public string? Query_BuildPvtProjectionSqlInvocation( long schemeId, int? limit, int offset, int maxDepth, bool distinct, string sourceMode, long[]? treeIds, bool hasDistinctOn = false) { var limitArg = limit.HasValue ? limit.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) : "NULL"; var offsetArg = offset.ToString(System.Globalization.CultureInfo.InvariantCulture); var maxDepthArg = maxDepth.ToString(System.Globalization.CultureInfo.InvariantCulture); var distinctArg = distinct ? "true" : "false"; var modeArg = sourceMode switch { "tree" => "'tree'", _ => "'flat'", }; string treeArg; if (treeIds is null || treeIds.Length == 0) { treeArg = "NULL::bigint[]"; } else { treeArg = "ARRAY[" + string.Join(",", treeIds.Select( i => i.ToString(System.Globalization.CultureInfo.InvariantCulture))) + "]::bigint[]"; } var distinctOnArg = hasDistinctOn ? "$4::jsonb" : "NULL::jsonb"; // pvt_build_projection_sql signature: // p_scheme_id, p_projection, 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 return "SELECT pvt_build_projection_sql(" + schemeId.ToString(System.Globalization.CultureInfo.InvariantCulture) + ", $1::jsonb" + ", $2::jsonb, " + limitArg + ", " + offsetArg + ", $3::jsonb, " + maxDepthArg + ", " + distinctArg + ", " + modeArg + ", " + treeArg + ", false" // p_include_seed + ", true" // p_polymorphic + ", " + distinctOnArg + ") AS \"Value\""; } public string? Query_WrapPvtProjectionRowsAsJson(string innerSql, bool includeId) { // The inner projection SQL yields one column per projection entry. // We wrap it so each row becomes a JSON object shaped like a partial // RedbObject: {"id": <_id|0>, "properties": { ...projected scalar columns... }}. // ConvertFlatPropertiesToHierarchy on the C# side then turns dotted // aliases (e.g. "Address.City") into nested objects. if (includeId) { return $"SELECT (jsonb_build_object('id', t._id, 'properties', (to_jsonb(t) - '_id')))::text AS \"Value\" FROM ({innerSql}) t"; } // No _id column — every projected column is a property; id defaults to 0. return $"SELECT (jsonb_build_object('id', 0, 'properties', to_jsonb(t)))::text AS \"Value\" FROM ({innerSql}) t"; } // ============================================================ // === SOFT DELETE === // ============================================================ /// /// Calls mark_for_deletion function to soft-delete objects. /// Params: $1=objectIds (bigint[]), $2=userId (bigint), $3=trashParentId (bigint, nullable) /// Returns: trash_id, marked_count /// public string SoftDelete_MarkForDeletion() => "SELECT * FROM mark_for_deletion($1, $2, $3)"; /// /// Calls purge_trash function to physically delete objects from trash. /// Params: $1=trashId (bigint), $2=batchSize (integer) /// Returns: deleted_count, remaining_count /// public string SoftDelete_PurgeTrash() => "SELECT * FROM purge_trash($1, $2)"; /// /// Objects of a trash container referenced by live objects, with the referencing objects. /// Params: $1=trashId (bigint). 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 < NOW() - INTERVAL '1 minute' * $1 ) ) 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 = NOW() WHERE _id = $1 AND _id_scheme = -10 AND ( _value_string = 'pending' OR ( _value_string = 'running' AND _date_modify < NOW() - INTERVAL '1 minute' * $2 ) ) """; // ============================================================ // === METADATA CACHE WARMUP === // ============================================================ public string Warmup_AllMetadataCaches() => "SELECT scheme_id, structures_count, scheme_name FROM warmup_all_metadata_caches()"; } Path: redb/redb.Postgres/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.Postgres/sql/maintenance/free_value_indexes.sql ---- -- ===================================================================== -- REDB (PostgreSQL): value indexes for the FREE provider -- ===================================================================== -- The PVT module 0.7.14-0.7.16 retired the object-leading value indexes: the stock covering index -- IX__values__structure_object_lookup and the family (_id_structure, _id_object, ). Pro reads the -- covering index of its streams form instead (redb.Postgres.Pro/Sql/pvt_streams_indexes.sql), the free -- provider has no replacement for it. Measured on a copy of a production database (38 million values): -- one free query over a whole scheme went from 8.8 s to 18-20 s once they were gone. -- -- This file brings them back under names of their own (IX__values__free_*). The module drops the old -- names again on every change of its version; it neither drops nor checks 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: the seven indexes the module 0.7.13 dropped as duplicates. The leading columns of -- each are the leading columns of an index or UNIQUE constraint of the same table that stays, so they -- served no plan of their own. -- -- Price: every index here is updated on each save of a value. On 38 million values the covering one -- took about 1.7 GB, the partial ones less. Run the file only if free queries got slower. -- -- Nothing runs this file automatically. Run it yourself, once per database: -- psql -d -f free_value_indexes.sql -- Do not wrap it in a transaction: CONCURRENTLY cannot run inside one. Reads and writes go on while the -- indexes are built. Running it again is safe: an existing index is kept, an index left INVALID by an -- interrupted build is dropped first and built again. -- -- To remove them: -- DROP INDEX CONCURRENTLY IF EXISTS "IX__values__free_structure_object_lookup"; (and so on for each name below) -- ===================================================================== -- An interrupted CREATE INDEX CONCURRENTLY leaves an INVALID index, and IF NOT EXISTS would keep it. DO $$ DECLARE r record; BEGIN FOR r IN SELECT c.relname FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid AND i.indrelid = '_values'::regclass WHERE c.relname LIKE 'IX\_\_values\_\_free\_%' AND NOT i.indisvalid LOOP EXECUTE format('DROP INDEX %I', r.relname); END LOOP; END $$; -- 1. Values of a field by object, every scalar column but the string (was IX__values__structure_object_lookup) CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__free_structure_object_lookup" ON _values (_id_structure, _id_object, _Long, _DateTimeOffset, _Boolean, _Double, _Guid, _Numeric, _ListItem, _Object); -- 2. String value of a field by object (was IX__values__String_not_null). A btree entry is limited to about -- 2.7 kB, so longer strings stay out of the index; the length guard keeps an insert of such a string working. CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__free_string_by_object" ON _values (_id_structure, _id_object, _String) WHERE _String IS NOT NULL AND length(_String) < 2000; -- 3. Number, date and decimal value of a field by object (were IX__values__{Long,DateTimeOffset,Numeric}_not_null) CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__free_long_by_object" ON _values (_id_structure, _id_object, _Long) WHERE _Long IS NOT NULL; CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__free_datetimeoffset_by_object" ON _values (_id_structure, _id_object, _DateTimeOffset) WHERE _DateTimeOffset IS NOT NULL; CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__free_numeric_by_object" ON _values (_id_structure, _id_object, _Numeric) WHERE _Numeric IS NOT NULL; -- 4. Scalar (non-array) values of a field by object (was ix__values__array_null_structure) CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__free_array_null_structure" ON _values (_id_structure, _id_object, _Long) WHERE _array_index IS NULL; ANALYZE _values; Path: redb/redb.Postgres/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.Postgres/sql/maintenance/rebuild_objects_indexes_without_date_modify.sql ---- -- ===================================================================== -- REDB (PostgreSQL): bring three _objects indexes of an EXISTING database to the current schema -- ===================================================================== -- redbPostgre.sql no longer puts _date_modify into INCLUDE of these indexes. That file runs only -- on a new database, and CREATE INDEX IF NOT EXISTS does not change an index that already exists, -- so an existing database keeps the old definitions until this file is run. -- -- Why it matters: _date_modify changes on every save, so an index that carries it gets a new entry -- for every saved object. On a database 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: -- psql -d -f rebuild_objects_indexes_without_date_modify.sql -- Do not wrap it in a transaction: CONCURRENTLY cannot run inside one. -- -- Each index is built next to the old one, the old one is dropped, the new one takes its name. -- Reads and writes continue throughout. Each step needs free disk space for the new index. -- An interrupted build leaves an INVALID index named *_new; drop it and run the file again. -- A database that already has the new definitions only pays for one more rebuild. -- ===================================================================== -- 1. Descendants of an object CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__objects__parent_id_descendant_lookup_new" ON _objects (_id_parent, _id_scheme) INCLUDE (_id, _id_owner, _date_create) WHERE _id_parent IS NOT NULL; DROP INDEX CONCURRENTLY IF EXISTS "IX__objects__parent_id_descendant_lookup"; ALTER INDEX "IX__objects__parent_id_descendant_lookup_new" RENAME TO "IX__objects__parent_id_descendant_lookup"; -- 2. Tree queries sorted by creation date CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__objects__scheme_parent_date_create_new" ON _objects (_id_scheme, _id_parent, _date_create DESC) INCLUDE (_id, _id_owner); DROP INDEX CONCURRENTLY IF EXISTS "IX__objects__scheme_parent_date_create"; ALTER INDEX "IX__objects__scheme_parent_date_create_new" RENAME TO "IX__objects__scheme_parent_date_create"; -- 3. Tree queries filtered by owner or name CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__objects__scheme_parent_owner_new" ON _objects (_id_scheme, _id_parent) INCLUDE (_id, _id_owner, _date_create, _name) WHERE _id_parent IS NOT NULL; DROP INDEX CONCURRENTLY IF EXISTS "IX__objects__scheme_parent_owner"; ALTER INDEX "IX__objects__scheme_parent_owner_new" RENAME TO "IX__objects__scheme_parent_owner"; ANALYZE _objects; Path: redb/redb.Postgres/sql/maintenance/string_collation_index.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.Postgres/sql/maintenance/string_collation_index.sql ---- -- ===================================================================== -- REDB (PostgreSQL): trigram index for StringCollation -- ===================================================================== -- With StringCollation set (for example "und-x-icu"), Pro with the planner on (EnablePvtPrefilter, the default) -- runs an ignore-case string search (Contains, StartsWith, EndsWith with StringComparison.OrdinalIgnoreCase) as -- (_String COLLATE "") ILIKE '%x%' -- on _values. A collated operand cannot use the stock index IX__values__String_pattern: it is built over bare -- _String with the collation of the database. Without an index over the same expression such a search reads -- every row of _values. Nothing errors; the index just shows no reads. Pro start-up logs a Warning while the -- index is missing. The free provider, and Pro with the planner off, read no trigram index at all: they do not -- need this file. -- -- Check the ctype of the database first: -- SELECT datctype FROM pg_database WHERE datname = current_database(); -- UTF-8 ctype: plain ILIKE already folds every script; leaving StringCollation unset keeps the stock index -- serving the search, and this file is not needed. Ctype C or POSIX: pg_trgm builds no trigram from non-ASCII -- text, so this index serves patterns with ASCII letters only; a non-ASCII substring search stays a scan. -- -- This file builds that index for one collation. The collation is part of the index expression, so the index -- must match the configured StringCollation exactly: a different collation needs an index of its own. -- -- CreateStringCollationIndex = true has Pro build the same index (same name) at start-up. This file is for the -- installations that keep schema changes with the DBA (AutoApplyDatabaseUpgrades off, a role without the right). -- -- Run it yourself, once per database, with the value of StringCollation: -- psql -d -v collation=und-x-icu -f string_collation_index.sql -- Do not wrap it in a transaction: CONCURRENTLY cannot run inside one. Reads and writes go on while the index -- is built. Running it again is safe: an existing index is kept, an index left INVALID by an interrupted build -- is dropped first and built again. -- -- Price: a second GIN index on the largest table, updated on each save of a string value. Its size is close to -- that of IX__values__String_pattern. -- -- IX__values__String_pattern is still read by case-sensitive Contains / StartsWith / EndsWith (plain LIKE, no -- COLLATE). Drop it only if the project does no case-sensitive substring search; the statement is at the end of -- this file, commented out. -- ===================================================================== \set ON_ERROR_STOP on \if :{?collation} \else \echo 'Set the collation: psql -v collation= -f string_collation_index.sql' \quit \endif CREATE EXTENSION IF NOT EXISTS pg_trgm; -- The name start-up uses as well: IX__values__String_pattern_, cut to the -- 63 bytes PostgreSQL keeps of an identifier, so the INVALID look-up below compares the name the index really has. SELECT left('IX__values__String_pattern_' || regexp_replace(lower(:'collation'), '[^a-z0-9]', '_', 'g'), 63) AS ix_name \gset -- An interrupted CREATE INDEX CONCURRENTLY leaves an INVALID index, and IF NOT EXISTS would keep it. SELECT EXISTS ( SELECT 1 FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = :'ix_name' AND n.nspname = current_schema() AND NOT i.indisvalid ) AS ix_invalid \gset \if :ix_invalid DROP INDEX CONCURRENTLY IF EXISTS :"ix_name"; \endif CREATE INDEX CONCURRENTLY IF NOT EXISTS :"ix_name" ON _values USING gin ((_String COLLATE :"collation") gin_trgm_ops) WHERE _String IS NOT NULL; ANALYZE _values; -- Only if no case-sensitive substring search is left in the project (see the header): -- DROP INDEX CONCURRENTLY IF EXISTS "IX__values__String_pattern"; Path: redb/redb.Postgres/sql/migration_drop_deleted_objects.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.Postgres/sql/migration_drop_deleted_objects.sql ---- -- ===================================================== -- MIGRATION: Drop legacy _deleted_objects archive system -- Part of Background Deletion System migration -- ===================================================== -- This script removes the old _deleted_objects table and its trigger. -- The new soft-delete system uses @@__deleted scheme and trash containers. -- Run this script on existing databases to migrate to new system. -- ===================================================== -- 1. Drop the trigger first (depends on function) DROP TRIGGER IF EXISTS TR__objects__deleted_objects ON _objects; -- 2. Drop the archive function DROP FUNCTION IF EXISTS ftr__objects__deleted_objects(); -- 3. Drop the archive table DROP TABLE IF EXISTS _deleted_objects; -- 4. Add the @@__deleted scheme if not exists INSERT INTO _schemes (_id, _name, _alias, _type) VALUES (-10, '@@__deleted', 'Deleted Objects', -9223372036854775703) ON CONFLICT (_id) DO NOTHING; -- 5. Update validate_scheme_name function to allow @@ prefix -- (This is done by re-creating the function - see redbPostgre.sql) -- ===================================================== -- VERIFICATION -- ===================================================== -- After running this script, verify: -- SELECT * FROM _schemes WHERE _id = -10; -- Expected: @@__deleted scheme exists -- -- SELECT * FROM pg_trigger WHERE tgname = 'tr__objects__deleted_objects'; -- Expected: No rows (trigger removed) -- ===================================================== Path: redb/redb.Postgres/sql/redbPostgre.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.Postgres/sql/redbPostgre.sql ---- -- ===================================================== -- REDB PostgreSQL schema -- Creates the schema in an EMPTY database. A database that already holds it is left as it is: the guard below raises -- before any statement. An existing schema is upgraded by the service at start or with -- `redb schema --upgrade --provider postgres` (GetUpgradeScript), never by running this script again. -- Run by hand with psql, pass -v ON_ERROR_STOP=1: without it psql goes on past the guard's error, and the statements -- further down that are written to be repeated (the metadata cache table, triggers) run against the live database. -- The service and `redb init` send the whole script as one command, which stops at the first error and changes nothing. -- ===================================================== DO $$ BEGIN IF to_regclass('_types') IS NOT NULL THEN RAISE EXCEPTION 'redb: this database already holds the redb schema (table _types exists). The creation script runs on an empty database only and has changed nothing. Upgrade an existing schema with `redb schema --upgrade --provider postgres` or by starting the service; to start over, drop and create the database first.'; END IF; END $$; -- DROP SEQUENCE IF EXISTS global_identity; -- DROP VIEW IF EXISTS v_user_permissions; -- DROP VIEW IF EXISTS v_objects_json; -- DROP VIEW IF EXISTS v_schemes_definition; -- DROP FUNCTION IF EXISTS get_scheme_definition; -- DROP FUNCTION IF EXISTS get_object_json; -- DROP FUNCTION IF EXISTS search_objects_with_facets; -- DROP FUNCTION IF EXISTS get_facets; -- DROP FUNCTION IF EXISTS build_base_facet_conditions; -- DROP TABLE IF EXISTS _scheme_metadata_cache; -- DROP TABLE IF EXISTS _dependencies; -- DROP TABLE IF EXISTS _values; -- DROP TABLE IF EXISTS _permissions; -- DROP TABLE IF EXISTS _structures; -- DROP TABLE IF EXISTS _users_roles; -- DROP TABLE IF EXISTS _roles; -- DROP TABLE IF EXISTS _list_items; -- DROP TABLE IF EXISTS _lists; -- DROP TABLE IF EXISTS _links; -- DROP TABLE IF EXISTS _objects CASCADE; -- DROP TABLE IF EXISTS _users; -- DROP TABLE IF EXISTS _functions; -- DROP TABLE IF EXISTS _schemes; -- DROP TABLE IF EXISTS _types; -- DROP FUNCTION IF EXISTS validate_structure_name; -- DROP FUNCTION IF EXISTS validate_scheme_name; -- DROP FUNCTION IF EXISTS get_user_permissions_for_object; -- DROP FUNCTION IF EXISTS auto_create_node_permissions; CREATE TABLE _types( _id bigint NOT NULL, _name text NOT NULL UNIQUE, _db_type text NULL, _type text NULL, CONSTRAINT PK__types PRIMARY KEY (_id) ); CREATE TABLE _links( _id bigint NOT NULL, _id_1 bigint NOT NULL, _id_2 bigint NOT NULL, CONSTRAINT PK__links PRIMARY KEY (_id), CONSTRAINT IX__links UNIQUE (_id_1, _id_2), CONSTRAINT CK__links CHECK (_id_1<>_id_2) ); CREATE TABLE _lists( _id bigint NOT NULL, _name text NOT NULL, _alias text NULL, CONSTRAINT PK__lists PRIMARY KEY (_id), CONSTRAINT IX__lists_name UNIQUE (_name) ); CREATE TABLE _roles( _id bigint NOT NULL, _name text NOT NULL, _id_configuration bigint NULL, CONSTRAINT PK__roles PRIMARY KEY (_id), CONSTRAINT IX__roles UNIQUE (_name) ); CREATE TABLE _users( _id bigint NOT NULL, _login text NOT NULL UNIQUE, _password TEXT NOT NULL, _name text NOT NULL, _phone text NULL, _email text NULL, _date_register timestamptz DEFAULT now() NOT NULL, _date_dismiss timestamptz NULL, _enabled boolean DEFAULT true NOT NULL, _key bigint NULL, _code_int bigint NULL, _code_string text NULL, _code_guid uuid NULL, _note text NULL, _hash uuid NULL, _id_configuration bigint NULL, CONSTRAINT PK__users PRIMARY KEY (_id) ); CREATE TABLE _users_roles( _id bigint NOT NULL, _id_role bigint NOT NULL, _id_user bigint NOT NULL, CONSTRAINT PK__users_roles PRIMARY KEY (_id), 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 bigint NOT NULL, _id_parent bigint NULL, _name text NOT NULL, _alias text NULL, _name_space text NULL, _structure_hash uuid NULL, _tags varchar(450) NULL, -- V4: free-form marker for future / custom extensions ([RedbTags] or direct writes; 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 bigint NOT NULL DEFAULT -9223372036854775675, -- Scheme type: Class (default), Array, Dictionary, JsonDocument, XDocument CONSTRAINT PK__schemes PRIMARY KEY (_id), 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) ); CREATE TABLE _structures( _id bigint NOT NULL, _id_parent bigint NULL, _id_scheme bigint NOT NULL, _id_override bigint NULL, _id_type bigint NOT NULL, _id_list bigint NULL, _name text NOT NULL, _alias text NULL, _order bigint NULL, _readonly boolean NULL, _allow_not_null boolean NULL, _collection_type bigint NULL, -- Array/Dictionary type ID or NULL for non-collections _key_type bigint NULL, -- Key type for Dictionary fields _is_compress boolean NULL, _store_null boolean NULL, _unique boolean NULL, -- V4: field is a unique key within its scheme ([RedbUnique]) _unique_version bigint NULL, -- V4: UniqueKeyEncoder.Version the stored keys were computed with _unique_scope bigint NULL, -- S3: element-key scope of a collection key (NULL = default; 1 = Scheme elements; 2 = Collection elements) _lazy boolean NULL, -- V4 (LAZY Л2): lazy reference marker (virtual) _tags varchar(450) NULL, -- V4: free-form marker for future / custom extensions ([RedbTags] or direct writes; sync never wipes it) _renamed_from text NULL, -- previous names, oldest first, as a JSON array (RedbRename / RedbScheme.RenamedFrom); NULL = never renamed _default_value bytea NULL, _default_editor text NULL, CONSTRAINT PK__structure PRIMARY KEY (_id), 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 bigint NOT NULL, _id_scheme_1 bigint, _id_scheme_2 bigint NOT NULL, CONSTRAINT PK__dependencies PRIMARY KEY (_id), 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 bigint NOT NULL, _id_parent bigint NULL, _id_scheme bigint NOT NULL, _id_owner bigint NOT NULL, _id_who_change bigint NOT NULL, _date_create timestamptz DEFAULT now() NOT NULL, _date_modify timestamptz DEFAULT now() NOT NULL, _date_begin timestamptz NULL, _date_complete timestamptz NULL, _key bigint NULL, _name text NULL, _note text NULL, _hash uuid NULL, -- Value columns for RedbPrimitive (Props = primitive value stored directly) -- Replaces old _code_int, _code_string, _code_guid, _bool columns _value_long bigint NULL, -- was _code_int _value_string text NULL, -- identifiers/external keys; contract limit 450 (C#-enforced, owner decision 2026-09-02), long text belongs in _note _value_guid uuid NULL, -- was _code_guid _value_bool boolean NULL, -- was _bool _value_double float NULL, -- NEW _value_numeric NUMERIC(38, 18) NULL, -- NEW _value_datetime timestamptz NULL, -- NEW _value_bytes bytea NULL, -- NEW _value_unique varchar(440) NULL, -- V4: unique key within the scheme (UNIQUE stage 1); index below CONSTRAINT PK__objects PRIMARY KEY (_id), 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 bigint NOT NULL, _id_list bigint NOT NULL, _value text NULL, _alias text NULL, _id_object bigint NULL, CONSTRAINT PK__list_items PRIMARY KEY (_id), 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 ); -- NULLS NOT DISTINCT needs PostgreSQL 15, the lowest supported server: one NULL value per list. CREATE UNIQUE INDEX IX__list_items_unique ON _list_items (_id_list, _value) NULLS NOT DISTINCT; CREATE TABLE _values( _id bigint NOT NULL, _id_structure bigint NOT NULL, _id_object bigint NOT NULL, _String text NULL, _Long bigint NULL, _Guid uuid NULL, _Double float NULL, _DateTimeOffset timestamptz NULL, _Boolean boolean NULL, _ByteArray bytea NULL, _Numeric NUMERIC(38, 18) NULL, _ListItem bigint NULL, _Object bigint NULL, -- V4: unique-key hash of the typed value (UniqueKeyEncoder) for [RedbUnique] root scalars _unique uuid NULL, -- Fields for relational storage of collections (arrays, dictionaries, JSON/XML documents) _array_parent_id bigint NULL, -- Reference to parent element (for nested structures) _array_index text NULL, -- Key/index of element: '0','1','2' for arrays, string key for dictionaries CONSTRAINT PK__values PRIMARY KEY (_id), CONSTRAINT FK__values__objects FOREIGN KEY (_id_object) REFERENCES _objects (_id) ON DELETE CASCADE, -- DESIGN: ON DELETE CASCADE here intentionally mirrors the MSSQL -- TR__structures__cascade_values INSTEAD OF DELETE trigger -- (redb.MSSql/sql/redbMSSQL.sql ~L717). Both backends silently remove -- every _values row when a _structures row is deleted. Destructive -- structure deletion at runtime is gated by -- RedbServiceConfiguration.DefaultStrictDeleteExtra (default true, -- see README "Schema lifecycle and multi-version deployments"). 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) ); -- Comments for extended _values table for relational array support COMMENT ON TABLE _values IS 'Table for storing field values of objects. Supports relational arrays of all types (simple and Class fields) via _array_parent_id and _array_index'; COMMENT ON COLUMN _values._array_parent_id IS 'ID of parent element for array elements. NULL for regular (non-array) fields and root array elements'; COMMENT ON COLUMN _values._array_index IS 'Key/index of collection element (text). For arrays: ''0'',''1'',''2''. For dictionaries: string key. NULL for regular fields. For numeric sorting of arrays use ORDER BY _array_index::int'; COMMENT ON COLUMN _values._Numeric IS 'Exact decimal numbers for financial calculations. NUMERIC(38,18) provides lossless precision, unlike Double. Used for money, taxes, percentages where arithmetic accuracy is critical.'; COMMENT ON COLUMN _values._DateTimeOffset IS 'Date and time with timezone (timestamptz). PostgreSQL stores in UTC, converts on retrieval. Used for precise time moments: logs, transactions, events. Allows accurate reconstruction of event moment regardless of local timezone.'; COMMENT ON COLUMN _values._ListItem IS 'Reference to dictionary item (_list_items). FK without cascade delete - attempting to delete the linked list_item will cause integrity violation error. Used for ListItem type instead of storing ID in _Long.'; COMMENT ON COLUMN _values._Object IS 'Reference to object (_objects). FK without cascade delete - attempting to delete the linked object will cause integrity violation error. Used for Object type (redbObject) instead of storing ID in _Long.'; -- Comments for _schemes table COMMENT ON COLUMN _schemes._type IS 'Scheme type ID (FK to _types): Class (default), Array, Dictionary, JsonDocument, XDocument. Determines how Props are stored and serialized.'; -- Comments for _objects._value_* columns (RedbPrimitive support) -- These columns replace old _code_int, _code_string, _code_guid, _bool COMMENT ON COLUMN _objects._value_long IS 'Direct value for RedbPrimitive. Replaces _code_int.'; COMMENT ON COLUMN _objects._value_string IS 'Identifier / external-key value (RedbPrimitive). Contract limit 450 characters, enforced in C# on every provider; long text belongs in _note.'; COMMENT ON COLUMN _objects._value_guid IS 'Direct value for RedbPrimitive. Replaces _code_guid.'; COMMENT ON COLUMN _objects._value_bool IS 'Direct value for RedbPrimitive. Replaces _bool.'; COMMENT ON COLUMN _objects._value_double IS 'Direct value for RedbPrimitive. NEW column.'; COMMENT ON COLUMN _objects._value_numeric IS 'Direct value for RedbPrimitive. NEW column.'; COMMENT ON COLUMN _objects._value_datetime IS 'Direct value for RedbPrimitive. NEW column.'; COMMENT ON COLUMN _objects._value_bytes IS 'Direct value for RedbPrimitive. NEW column.'; -- Comments for _structures table COMMENT ON COLUMN _structures._collection_type IS 'Collection type ID (FK to _types): Array or Dictionary. NULL for non-collection fields. Replaces old _is_array boolean.'; COMMENT ON COLUMN _structures._key_type IS 'Key type ID for Dictionary fields (FK to _types). NULL for non-dictionary fields.'; COMMENT ON INDEX IX__list_items_unique IS 'Unique index on combination of dictionary + value with NULLS NOT DISTINCT. Prevents duplicate values in the same dictionary, including NULL (only one NULL per dictionary). Ensures strict integrity of dictionary data.'; CREATE TABLE _permissions( _id bigint NOT NULL, _id_role bigint NULL, _id_user bigint NULL, _id_ref bigint NOT NULL, _select boolean NULL, _insert boolean NULL, _update boolean NULL, _delete boolean NULL, CONSTRAINT PK__object_permissions PRIMARY KEY (_id), 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 bigint NOT NULL, _id_scheme bigint NOT NULL, _language varchar(50) NOT NULL, _name text NOT NULL, _body text NOT NULL, CONSTRAINT PK__functions PRIMARY KEY (_id), CONSTRAINT IX__functions_scheme_name UNIQUE (_id_scheme, _name), CONSTRAINT FK__functions__schemes FOREIGN KEY (_id_scheme) REFERENCES _schemes (_id) ); -- REMOVED (2026-10-12): "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-12): "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) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__permissions__ref" ON _permissions (_id_ref); CREATE INDEX IF NOT EXISTS "IX__values__objects" ON _values (_id_object) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__values__structures" ON _values (_id_structure) WITH (deduplicate_items=True); -- V4: uniqueness of [RedbUnique] fields. Covers keyed rows at ANY position (root scalars and -- S2 nested scalars; element keys join in S3) - the writer decides which rows carry a key, the -- partial form keeps the index to exactly those rows. INCLUDE makes the lookup index-only (P6). CREATE UNIQUE INDEX IF NOT EXISTS "UIX__values__structure_unique" ON _values (_id_structure, _unique) INCLUDE (_id_object) WHERE _unique IS NOT NULL; -- ============================================ -- REMOVED REDUNDANT INDEXES (migration_drop_redundant_indexes.sql) -- Reason: were covered by the composite index IX__values__structure_object_lookup (itself retired in 0.7.14, see "RETIRED" below) -- Facet search ALWAYS filters by (_id_structure, _id_object) BEFORE value -- ============================================ -- CREATE INDEX IF NOT EXISTS "IX__values__String" ON _values (_String) WITH (deduplicate_items=True); -- CREATE INDEX IF NOT EXISTS "IX__values__Long" ON _values (_Long) WITH (deduplicate_items=True); -- CREATE INDEX IF NOT EXISTS "IX__values__Guid" ON _values (_Guid) WITH (deduplicate_items=True); -- CREATE INDEX IF NOT EXISTS "IX__values__Double" ON _values (_Double) WITH (deduplicate_items=True); -- CREATE INDEX IF NOT EXISTS "IX__values__DateTimeOffset" ON _values (_DateTimeOffset) WITH (deduplicate_items=True); -- CREATE INDEX IF NOT EXISTS "IX__values__Boolean" ON _values (_Boolean) WITH (deduplicate_items=True); -- CREATE INDEX IF NOT EXISTS "IX__values__Numeric" ON _values (_Numeric) WITH (deduplicate_items=True); -- CREATE INDEX IF NOT EXISTS "IX__values__ListItem" ON _values (_ListItem) WITH (deduplicate_items=True); -- CREATE INDEX IF NOT EXISTS "IX__values__Object" ON _values (_Object) WITH (deduplicate_items=True); -- The two FK columns return in PARTIAL form (perf, 2026-09-10): _Object/_ListItem carry foreign -- keys, and without a leading index every DELETE of a referenced object or list item seq-scans -- the whole table for the FK check (measured ~5.9s on 8.7M rows; 0.5ms with the index). Partial -- WHERE IS NOT NULL keeps them nearly empty (16 kB on that same table), so writes barely pay - -- which is why the full-column form above stays retired. 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; -- Indexes for relational arrays of all types -- REMOVED (0.7.33): "IX__values__array_parent_id" (_array_parent_id) is the leading column of -- IX__values__array_parent_index below, which serves its lookups and the cascade of FK__values__array_parent. -- The module drops it on existing databases only where the wider index exists. -- REMOVED: _array_index is ALWAYS used together with _id_object + _id_structure -- CREATE INDEX IF NOT EXISTS "IX__values__array_index" ON _values (_array_index) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__values__array_parent_index" ON _values (_array_parent_id, _array_index) WITH (deduplicate_items=True); -- Index for Dictionary key lookups (text _array_index) CREATE INDEX IF NOT EXISTS "IX__values__array_key" ON _values (_id_structure, _array_index) WHERE _array_index IS NOT NULL; -- Unique indexes to ensure data integrity -- For ROOT fields (not arrays, not nested): structure + object must be unique 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; -- For BASE RECORDS OF NESTED ARRAYS: structure + object + parent must be unique 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; -- For array elements: structure + object + parent + index must be unique 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; -- Comments for created unique indexes COMMENT ON INDEX "UIX__values__structure_object" IS 'Ensures uniqueness: one value per structure+object for ROOT fields (not nested arrays)'; COMMENT ON INDEX "UIX__values__structure_object_parent" IS 'Ensures uniqueness: one base record per structure+object+parent for nested arrays'; COMMENT ON INDEX "UIX__values__structure_object_array_index" IS 'Ensures uniqueness: one element per structure+object+parent+position for elements of all arrays (including nested)'; CREATE INDEX IF NOT EXISTS "IX__list_items__id_list" ON _list_items (_id_list) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__list_items__objects" ON _list_items (_id_object) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__objects__objects" ON _objects (_id_parent) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__objects__schemes" ON _objects (_id_scheme) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__objects__users1" ON _objects (_id_owner) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__objects__users2" ON _objects (_id_who_change) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__objects__date_create" ON _objects (_date_create) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__objects__date_modify" ON _objects (_date_modify) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__objects__name" ON _objects (_name) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__users__name" ON _users (_name) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__objects__hash" ON _objects (_hash) WITH (deduplicate_items=True); -- Indexes for RedbPrimitive value columns (replaces old _code_* indexes) 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. 440 keeps the index entry under the -- MSSQL 900-byte house convention (parity of limits across providers); INCLUDE makes the key -- lookup index-only (P6). The trash (-10) is one more point of the same index - which is why -- mark_for_deletion nulls the key on the way in (decision 9). CREATE UNIQUE INDEX IF NOT EXISTS "UIX__objects__scheme_unique" ON _objects (_id_scheme, _value_unique) INCLUDE (_id) 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-12): "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) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__structures__structures" ON _structures (_id_parent) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__structures__schemes" ON _structures (_id_scheme) WITH (deduplicate_items=True); -- V4: lookup by the free-form _tags marker; partial - most structures carry no tags. CREATE INDEX IF NOT EXISTS "IX__structures__tags" ON _structures (_tags) WHERE _tags IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__structures__types" ON _structures (_id_type) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__structures__lists" ON _structures (_id_list) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__schemes__schemes" ON _schemes (_id_parent) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__schemes__structure_hash" ON _schemes (_structure_hash) WITH (deduplicate_items=True); CREATE INDEX IF NOT EXISTS "IX__schemes__type" ON _schemes (_type) WITH (deduplicate_items=True); -- REMOVED (2026-10-12): "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) WITH (deduplicate_items=True); -- Indexes for user and role configurations 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; -- Foreign keys for configurations (added after creating all tables) ALTER TABLE _users ADD CONSTRAINT FK_users_configuration FOREIGN KEY (_id_configuration) REFERENCES _objects(_id) ON DELETE SET NULL; ALTER TABLE _roles ADD CONSTRAINT FK_roles_configuration FOREIGN KEY (_id_configuration) REFERENCES _objects(_id) ON DELETE SET NULL; -- REMOVED (2026-10-16, PVT module 0.7.16): ix__values__array_null_structure (_id_structure, _id_object, _long) -- WHERE _array_index IS NULL. The value of a field next to its object is read from the covering index of the -- streams form; searching by value goes through IX__values__structure_long_object below. -- Index for quickly getting all nested fields by structure_id -- NOTE: _String removed from INCLUDE to prevent btree row overflow on large string values CREATE INDEX IF NOT EXISTS "IX__values__structure_parent_batch" ON _values (_id_structure, _array_parent_id) INCLUDE (_Long, _Double, _Boolean, _Guid) WHERE _array_parent_id IS NOT NULL; -- ============================================ -- OPTIMIZED INDEXES FOR FACETED SEARCH -- (Index Only Scan with INCLUDE - maximum performance) -- Tested EXPLAIN ANALYZE on Stage 41 - all Seq Scan eliminated! -- ============================================ -- 🔥 CRITICAL #1: Covering index for ORDER BY by structure name -- Eliminates: Seq Scan on _structures s (Filter: (_name)::text = 'Auction.Baskets') -- Cost reduction: 6.10 → 4.29 (-30%) -- One root field name once per scheme. IX__structures counts two NULL parents as distinct, so it does not hold -- for root structures; the index is partial because it was written for PostgreSQL 14, which has no NULLS NOT -- DISTINCT (15 is the lowest supported server now). Existing databases get it -- from RootStructureKey (redb.Core) at the next module upgrade. 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__name" ON _structures (_name) INCLUDE (_id, _id_type, _collection_type, _id_scheme) WITH (deduplicate_items=True); -- 🔥 CRITICAL #2: Covering index for searching structure by ID -- Eliminates: Seq Scan on _structures (Filter: _id = X) in InitPlan -- Eliminates: Seq Scan on _structures fs_1 (Filter: (_collection_type IS NULL) AND (_id = X)) -- Cost reduction: 6.10 → 4.29 (-30%) CREATE INDEX IF NOT EXISTS "IX__structures__id_lookup" ON _structures (_id) INCLUDE (_id_type, _name, _collection_type, _id_scheme) WITH (deduplicate_items=True); -- REMOVED (2026-10-12): "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. -- Extended partial index for non-collection structures -- Used in Nested Loop for fast search by _id with _collection_type IS NULL CREATE INDEX IF NOT EXISTS "IX__structures__not_collection_enhanced" ON _structures (_id, _name, _id_scheme, _id_type) WHERE _collection_type IS NULL; -- Index for collection fields (Array/Dictionary) CREATE INDEX IF NOT EXISTS "IX__structures__collection" ON _structures (_id, _id_scheme, _collection_type) WHERE _collection_type IS NOT NULL; -- Index for dictionaries with key type CREATE INDEX IF NOT EXISTS "IX__structures__key_type" ON _structures (_id, _id_scheme, _key_type) WHERE _key_type IS NOT NULL; -- Index for collection type lookups (Array/Dictionary fields) CREATE INDEX IF NOT EXISTS "IX__structures__collection_type" ON _structures (_collection_type) WHERE _collection_type IS NOT NULL; -- 🚀 Covering index for _values (object -> structure) -- Index Only Scan for EXISTS subqueries with value filtering -- INCLUDE allows filtering (_long > X) without accessing the table -- NOTE: _String excluded from INCLUDE — large text values (>2700 bytes) exceed btree row limit CREATE INDEX IF NOT EXISTS "IX__values__object_structure_lookup" ON _values (_id_object, _id_structure, _array_index) INCLUDE (_Long, _Double, _DateTimeOffset, _Boolean, _Guid, _Numeric, _ListItem, _Object) WITH (deduplicate_items=True); -- 🚀 Covering index for nested fields (Class) -- Index Only Scan for JOIN nested fields and ORDER BY subqueries -- INCLUDE eliminates table access for reading values -- NOTE: _String excluded from INCLUDE — large text values (>2700 bytes) exceed btree row limit CREATE INDEX IF NOT EXISTS "IX__values__object_array_null" ON _values (_id_object, _id_structure) INCLUDE (_Long, _Double, _DateTimeOffset, _Boolean, _Guid, _Numeric, _ListItem, _Object) WHERE _array_index IS NULL; -- ============================================ -- COMMENTS FOR OPTIMIZED INDEXES -- ============================================ COMMENT ON INDEX "IX__structures__name" IS '🔥 CRITICAL covering index for ORDER BY subqueries. Eliminates Seq Scan when searching structures by name (s._name = ''Field''). INCLUDE (_id, _id_type, _collection_type, _id_scheme) provides Index Only Scan without table access. Cost: 6.10 → 4.29 (-30%). Tested EXPLAIN ANALYZE Stage 41'; COMMENT ON INDEX "IX__structures__id_lookup" IS '🔥 CRITICAL covering index for InitPlan and EXISTS subqueries. Eliminates Seq Scan on Filter: (_id = X). INCLUDE contains all necessary fields for Index Only Scan. Covers InitPlan 2 and Nested Loop conditions. Cost: 6.10 → 4.29 (-30%). Tested EXPLAIN ANALYZE Stage 41'; COMMENT ON INDEX "IX__structures__not_collection_enhanced" IS 'Extended partial index for NON collection fields. Includes _id_type to eliminate additional JOINs in Nested Loop. Used when searching by _id with condition _collection_type IS NULL. Provides Index Only Scan'; COMMENT ON INDEX "IX__structures__collection" IS 'Partial index for collection fields (Array/Dictionary). Optimizes searching arrays and dictionaries by _collection_type'; COMMENT ON INDEX "IX__structures__collection_type" IS 'Index for fast search by collection type (Array or Dictionary). Used when analyzing schemes'; COMMENT ON INDEX "IX__values__array_key" IS 'Index for fast search by Dictionary key. Supports string keys for Dictionary'; COMMENT ON INDEX "IX__values__object_structure_lookup" IS '🚀 Covering index for EXISTS subqueries with value filtering. INCLUDE contains all value types for Index Only Scan. Updated: added _Numeric, _ListItem, _Object; _DateTime → _DateTimeOffset. Critical for faceted search with conditions on nested Class fields'; COMMENT ON INDEX "IX__values__object_array_null" IS '🚀 Covering index for non-array values. Optimizes JOIN nested Class fields and ORDER BY subqueries. INCLUDE contains all value types for reading without table access. Updated: added _Numeric, _ListItem, _Object; _DateTime → _DateTimeOffset. Partial index (_array_index IS NULL) reduces size by 30-40%'; -- ============================================ -- CRITICAL INDEXES FOR FACETED SEARCH -- ============================================ -- 1. Values by structure + object: RETIRED (2026-10-12, PVT module 0.7.14). -- The queries moved to the streams form, which reads values through -- IX__values__structure_object_scalar (redb.Postgres.Pro/Sql/pvt_streams_indexes.sql) and through the -- object-led indexes below; keeping this one as well meant two indexes of 1.7 GB each over the same -- rows on a 38M-row _values, both maintained on every write. Existing databases lose it when the -- module is re-applied (v2-pvt/00_module_init.sql). -- Measured on that database before retiring it: nothing got slower except the row prefilter over a -- dictionary item or a number, which fell back to IX__values__structures (27 -> 52 ms, 3 -> 7 ms). -- IF QUERIES GOT SLOWER AFTER THE UPGRADE, put it back - CONCURRENTLY, so that writes go on: -- CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__structure_object_lookup" -- ON _values (_id_structure, _id_object, _Long, _DateTimeOffset, _Boolean, _Double, _Guid, _Numeric, _ListItem, _Object); -- (_String is not in the key: a text value over ~2700 bytes does not fit a btree entry.) -- The module drops it again on its next version change, so tell us if you needed it. -- 2. 🌳 Tree queries CREATE INDEX IF NOT EXISTS "IX__objects__scheme_parent" ON _objects (_id_scheme, _id_parent, _id); -- 3. Arrays -- REMOVED (2026-10-12): "IX__values__object_structure_array_index" (_id_object, _id_structure, _array_index) -- WHERE _array_index IS NOT NULL. IX__values__object_structure_lookup has the same three key columns with no -- predicate and the values in INCLUDE, so it answers everything this one did. -- 4. Values found by value: (_id_structure, , _id_object), one per value column (PVT module 0.7.16). -- A filter on a field reads one range of its index and gets the objects that pass, instead of reading -- every object of the scheme. The value of a field next to a known object is read from the covering index -- of the streams form (IX__values__structure_object_scalar, redb.Postgres.Pro/Sql/pvt_streams_indexes.sql). -- Strings: the bound is in BYTES, the btree entry limit is on bytes (about 2.7 kB). -- _array_index is in INCLUDE: a query on a scalar field checks it as IS NULL, and without it every row the -- index found was looked up in the table for that check (29 ms -> 11 ms on 5 000 rows found). -- REMOVED (2026-10-16): the object-leading forms these replace, (_id_structure, _id_object, ): -- CREATE INDEX "IX__values__String_not_null" ON _values (_id_structure, _id_object, _String) WHERE _String IS NOT NULL AND length(_String) < 2000; -- 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) INCLUDE (_array_index) WHERE _String IS NOT NULL AND octet_length(_String) < 2000; CREATE INDEX IF NOT EXISTS "IX__values__structure_long_object" ON _values (_id_structure, _Long, _id_object) INCLUDE (_array_index) WHERE _Long IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_numeric_object" ON _values (_id_structure, _Numeric, _id_object) INCLUDE (_array_index) WHERE _Numeric IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_double_object" ON _values (_id_structure, _Double, _id_object) INCLUDE (_array_index) WHERE _Double IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_datetimeoffset_object" ON _values (_id_structure, _DateTimeOffset, _id_object) INCLUDE (_array_index) WHERE _DateTimeOffset IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_boolean_object" ON _values (_id_structure, _Boolean, _id_object) INCLUDE (_array_index) WHERE _Boolean IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_guid_object" ON _values (_id_structure, _Guid, _id_object) INCLUDE (_array_index) WHERE _Guid IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_listitem_object" ON _values (_id_structure, _ListItem, _id_object) INCLUDE (_array_index) WHERE _ListItem IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_object_object" ON _values (_id_structure, _Object, _id_object) INCLUDE (_array_index) WHERE _Object IS NOT NULL; -- 5. 🔍 Text search (requires pg_trgm) CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE INDEX IF NOT EXISTS "IX__values__String_pattern" ON _values USING gin (_String gin_trgm_ops) WHERE _String IS NOT NULL; -- 6. 🌳 Hierarchical queries (recursive CTE) CREATE INDEX IF NOT EXISTS "IX__objects__parent_scheme_id" ON _objects (_id_parent, _id_scheme, _id) WHERE _id_parent IS NOT NULL; -- 7. 🌲 Root objects CREATE INDEX IF NOT EXISTS "IX__objects__root_objects" ON _objects (_id_scheme, _id) WHERE _id_parent IS NULL; -- 7a. 🧬 Tree walk that needs the object hash (transparent cache). -- Analogue of IX__objects__id_parent in redbMSSQL.sql. 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 heap on every row. INCLUDE keeps _hash out -- of the key: it is not searched by, only returned. Verified on PostgreSQL 18.1 — -- the plan for SELECT _id, _hash, _id_scheme WHERE _id_parent = ? is Index Only Scan. -- No deduplicate_items here, matching the other indexes in this section. 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. CREATE INDEX IF NOT EXISTS "IX__objects__id_parent" ON _objects (_id_parent) INCLUDE (_id, _hash, _id_scheme) WHERE _id_parent IS NOT NULL; -- 8. 📅 Sorting by dates 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); -- 9. 🔤 Sorting by name CREATE INDEX IF NOT EXISTS "IX__objects__scheme_name" ON _objects (_id_scheme, _name, _id); -- CREATE INDEX IF NOT EXISTS ix__objects_parent_scheme -- ON _objects (_id_parent, _id_scheme) -- WHERE _id_parent IS NOT NULL; -- Comments for indexes COMMENT ON INDEX "IX__objects__scheme_parent" IS 'Composite index for fast filtering of objects by scheme and parent. CRITICAL for tree queries and searching direct children'; COMMENT ON INDEX "IX__values__structure_string_object" IS 'A string field searched by value: equality and ranges, and NOT NULL checks through the structure prefix'; COMMENT ON INDEX "IX__values__String_pattern" IS 'GIN index for fast text search via LIKE/ILIKE. Requires pg_trgm extension. Optimizes $contains, $startsWith, $endsWith, $matches (regex)'; COMMENT ON INDEX "IX__objects__parent_scheme_id" IS 'Partial index for fast recursive hierarchy traversal. Optimizes $hasAncestor, $hasDescendant, $level conditions'; COMMENT ON INDEX "IX__objects__root_objects" IS 'Partial index for fast search of root objects (without parent). Optimizes {"$isRoot": true} condition'; COMMENT ON INDEX "IX__objects__scheme_date_create" IS 'Composite index for fast sorting by creation date. Uses DESC to optimize ORDER BY _date_create DESC'; -- ==================================================================================================== -- CRITICAL INDEXES FOR OPTIMIZING WhereHasAncestor/WhereHasDescendant -- ==================================================================================================== -- 1. CRITICAL: Covering index for fast descendant search by ancestor -- _date_modify is deliberately NOT in INCLUDE (2026-10-12). It changes on every save, and an index that -- carries it gets a new entry for every saved object: on a database with frequent saves these indexes had -- grown to 700-1400 bytes per entry and shrank 10-20 times when rebuilt without it. Queries that go through -- them read the whole object row from the table anyway. CREATE INDEX IF NOT EXISTS "IX__objects__parent_id_descendant_lookup" ON _objects (_id_parent, _id_scheme) INCLUDE (_id, _id_owner, _date_create) WHERE _id_parent IS NOT NULL; COMMENT ON INDEX "IX__objects__parent_id_descendant_lookup" IS 'Covering index for fast search of all descendants of an object. INCLUDE allows getting basic fields without table access. Critical for optimized WhereHasAncestor (inverted logic). Index Only Scan speeds up queries 10-50x'; -- 2. IMPORTANT: Composite index for tree queries with date sorting CREATE INDEX IF NOT EXISTS "IX__objects__scheme_parent_date_create" ON _objects (_id_scheme, _id_parent, _date_create DESC) INCLUDE (_id, _id_owner); COMMENT ON INDEX "IX__objects__scheme_parent_date_create" IS 'Optimizes tree queries with sorting by creation date. Used in WhereHasAncestor + ORDER BY _date_create. INCLUDE for Index Only Scan'; -- 3. IMPORTANT: Composite index for reverse ancestor search CREATE INDEX IF NOT EXISTS "IX__objects__id_parent_scheme" ON _objects (_id, _id_parent, _id_scheme) WHERE _id_parent IS NOT NULL; COMMENT ON INDEX "IX__objects__id_parent_scheme" IS 'Accelerates reverse ancestor search (from descendant to parent). Used when building Parent/Children chains in ToTreeListAsync'; -- 4. MEDIUM PRIORITY: Covering index for search with filtering CREATE INDEX IF NOT EXISTS "IX__objects__scheme_parent_owner" ON _objects (_id_scheme, _id_parent) INCLUDE (_id, _id_owner, _date_create, _name) WHERE _id_parent IS NOT NULL; COMMENT ON INDEX "IX__objects__scheme_parent_owner" IS 'Covering index for tree queries with additional filtering by owner/name. Index Only Scan for complex WHERE conditions'; -- Index for nested Dictionary/Array field lookups via _array_parent_id -- Used by PRO PVT CTE for AddressBook[home].City queries CREATE INDEX IF NOT EXISTS "IX__values__parent_structure" ON _values (_array_parent_id, _id_structure) WHERE _array_parent_id IS NOT NULL; CREATE OR REPLACE FUNCTION public.get_scheme_definition( scheme_id bigint ) RETURNS json LANGUAGE 'plpgsql' COST 100 VOLATILE NOT LEAKPROOF AS $BODY$ DECLARE result_json json; scheme_json json; structures_json json; scheme_exists boolean; BEGIN -- Check if scheme exists SELECT EXISTS(SELECT 1 FROM _schemes WHERE _id = scheme_id) INTO scheme_exists; IF NOT scheme_exists THEN RETURN json_build_object('error', 'Scheme not found'); END IF; -- Get scheme information SELECT json_build_object( '_id', _s._id, '_id_parent', _s._id_parent, '_name', _s._name, '_alias', _s._alias, '_name_space', _s._name_space ) INTO scheme_json FROM _schemes _s WHERE _s._id = scheme_id; -- Get scheme structures (fields) SELECT json_agg( json_build_object( '_id', _st._id, '_id_parent', _st._id_parent, '_name', _st._name, '_alias', _st._alias, '_order', _st._order, '_type_name', _t._name, '_type_db_type', _t._db_type, '_type_dotnet_type', _t._type, '_readonly', _st._readonly, '_allow_not_null', _st._allow_not_null, '_collection_type', _st._collection_type, -- Array/Dictionary type ID or NULL '_key_type', _st._key_type, -- Key type for Dictionary '_is_compress', _st._is_compress, '_store_null', _st._store_null, '_id_list', _st._id_list, '_default_editor', _st._default_editor ) ORDER BY _st._order, _st._id ) INTO structures_json FROM _structures _st JOIN _types _t ON _t._id = _st._id_type WHERE _st._id_scheme = scheme_id; -- Build final JSON result_json := json_build_object( 'scheme', scheme_json, 'structures', COALESCE(structures_json, '[]'::json) ); RETURN result_json; END; $BODY$; -- View for selecting definitions of all schemes CREATE OR REPLACE VIEW v_schemes_definition AS SELECT _id as scheme_id, _name as scheme_name, _alias as scheme_alias, get_scheme_definition(_id) as scheme_definition FROM _schemes ORDER BY _id; CREATE SEQUENCE global_identity AS bigint START WITH 1000000 INCREMENT BY 1 MINVALUE 1000000 MAXVALUE 9223372036854775807; INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775709, 'Boolean', 'Boolean', 'boolean'); -- DateTime (C# type) -> DateTimeOffset (DB timestamptz) 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'); -- DateTimeOffset (C# type) -> DateTimeOffset (DB timestamptz) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775673, 'DateTimeOffset', 'DateTimeOffset', 'DateTimeOffset'); -- Numeric for exact decimal numbers (financial calculations) 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 (-9223372036854775702, 'Text', 'Text', 'string'); 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'); -- Additional simple types for REDB -- These can be added to extend functionality -- 1. Additional numeric types INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775699, 'Int', 'Long', 'int'); -- int (mapped to Long) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775698, 'Short', 'Long', 'short'); -- short (mapped to Long) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775697, 'Byte', 'Long', 'byte'); -- byte (mapped to Long) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775696, 'Float', 'Double', 'float'); -- float (mapped to Double) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775695, 'Decimal', 'Numeric', 'decimal'); -- decimal (mapped to Numeric for precision) -- 2. Additional string types INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775694, 'Char', 'String', 'char'); -- char (mapped to String) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775693, 'Url', 'String', 'string'); -- URL (validation via attributes) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775692, 'Email', 'String', 'string'); -- Email (validation via attributes) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775691, 'Phone', 'String', 'string'); -- Phone (validation via attributes) -- 3. Special types INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775690, 'Json', 'String', 'string'); -- JSON as string INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775689, 'Xml', 'String', 'string'); -- XML as string INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775688, 'Base64', 'String', 'string'); -- Base64 strings INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775687, 'Color', 'String', 'string'); -- Colors (hex, rgb) -- 4. Temporal types INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775686, 'DateOnly', 'DateTimeOffset', 'DateOnly'); -- .NET 6+ DateOnly, stored as a midnight reading in _DateTimeOffset INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775685, 'TimeOnly', 'Long', 'TimeOnly'); -- .NET 6+ TimeOnly (Ticks in _Long) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775684, 'TimeSpan', 'Long', 'TimeSpan'); -- TimeSpan (Ticks in _Long) -- 5. Enum support INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775683, 'Enum', 'String', 'Enum'); -- Enum (stored as string) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775682, 'EnumInt', 'Long', 'Enum'); -- Enum (stored as number) -- 6. Geographic types (for future expansion) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775681, 'Latitude', 'Double', 'double'); -- Latitude INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775680, 'Longitude', 'Double', 'double'); -- Longitude INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775679, 'GeoPoint', 'String', 'string'); -- Geographic point as JSON -- 7. File types INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775678, 'FilePath', 'String', 'string'); -- File path INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775677, 'FileName', 'String', 'string'); -- File name INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775676, 'MimeType', 'String', 'string'); -- MIME type INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775675, 'Class', 'Guid', 'Object'); -- Nested class type -- Collection and document types for RedbObject and Props fields INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775668, 'Array', 'Guid', 'Array'); -- For RedbObject/List and array fields in Props INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775667, 'Dictionary', 'Guid', 'Dictionary'); -- For RedbObject> and dict fields in Props INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775666, 'JsonDocument', 'Guid', 'JsonDocument'); -- For RedbObject (hierarchy via _array_parent_id) INSERT INTO _types (_id, _name, _db_type, _type) VALUES (-9223372036854775665, 'XDocument', 'Guid', 'XDocument'); -- For RedbObject (hierarchy via _array_parent_id) -- Comments for additional types COMMENT ON TABLE _types IS 'REDB data types table. Supports basic C# types and additional specialized types with validation'; -- Usage examples: -- 1. Int, Short, Byte - all mapped to Long for simplicity -- 2. Float - mapped to Double -- 3. Decimal - can be mapped to Double (precision loss) or Numeric (precision preserved) -- 4. Char - mapped to String -- 5. Url, Email, Phone - strings with additional application-level validation -- 6. Json, Xml - strings for storing structured data -- 7. DateOnly, TimeOnly, TimeSpan - special temporal types .NET 6+ -- 8. DateTime - for dates without timezone, DateTimeOffset - for dates with timezone -- 9. Enum - enumeration support (as string or number) -- 10. Geographic types - for location-based applications -- 11. File types - for working with files and media INSERT INTO _users (_id, _login, _password, _name, _phone, _email, _date_register, _date_dismiss, _enabled) VALUES (-1, 'default', '', 'default', NULL, NULL, CAST('2023-12-26T01:14:34.410' AS timestamptz), NULL, true); INSERT INTO _users (_id, _login, _password, _name, _phone, _email, _date_register, _date_dismiss, _enabled) VALUES (0, 'sys', '', 'sys', NULL, NULL, CAST('2023-12-26T01:14:34.410' AS timestamptz), NULL, true); INSERT INTO _users (_id, _login, _password, _name, _phone, _email, _date_register, _date_dismiss, _enabled) VALUES (1, 'admin', '', 'admin', NULL, NULL, CAST('2023-12-26T01:14:34.410' AS timestamptz), NULL, true); -- ===================================================== -- SOFT DELETE SYSTEM: Reserved scheme for deleted objects -- ===================================================== -- Scheme @@__deleted is used for soft-delete functionality -- Objects marked for deletion get _id_scheme = -10 -- Type = Object (-9223372036854775703) means no Props/structures INSERT INTO _schemes (_id, _name, _alias, _type) VALUES (-10, '@@__deleted', 'Deleted Objects', -9223372036854775703) ON CONFLICT (_id) DO NOTHING; -- for webApi dashboard -- Trigger for validating field names in _structures CREATE OR REPLACE FUNCTION validate_structure_name() RETURNS TRIGGER AS $$ DECLARE reserved_fields text[] := ARRAY[ '_id', '_id_parent', '_id_scheme', '_id_owner', '_id_who_change', '_date_create', '_date_modify', '_date_begin', '_date_complete', '_key', '_name', '_note', '_hash', '_value_long', '_value_string', '_value_guid', '_value_bool', '_value_double', '_value_numeric', '_value_datetime', '_value_bytes' ]; field_name text; BEGIN -- Check only on INSERT and UPDATE of _name field IF TG_OP = 'INSERT' OR (TG_OP = 'UPDATE' AND OLD._name IS DISTINCT FROM NEW._name) THEN field_name := LOWER(NEW._name); -- Check 1: Name must not match reserved fields of _objects IF field_name = ANY(reserved_fields) THEN RAISE EXCEPTION 'Field name "_name" cannot match system object fields: %', NEW._name USING ERRCODE = '23514', HINT = 'Use a different name, avoid: ' || array_to_string(reserved_fields, ', '); END IF; -- Check 2: Name must not start with a digit IF NEW._name ~ '^[0-9]' THEN RAISE EXCEPTION 'Field name "_name" cannot start with a digit: %', NEW._name USING ERRCODE = '23514', HINT = 'Field name must start with a letter or underscore'; END IF; -- Check 3: Name must follow C# naming rules (letters, digits, underscores) IF NEW._name !~ '^[a-zA-Z_][a-zA-Z0-9_]*$' THEN RAISE EXCEPTION 'Field name "_name" contains invalid characters: %', NEW._name USING ERRCODE = '23514', HINT = 'Name can only contain Latin letters, digits, underscores. Must start with letter or underscore'; END IF; -- Check 4: Name must not be empty or contain only spaces IF LENGTH(TRIM(NEW._name)) = 0 THEN RAISE EXCEPTION 'Field name "_name" cannot be empty' USING ERRCODE = '23514'; END IF; -- Check 5: Maximum name length (reasonable limit) IF LENGTH(NEW._name) > 64 THEN RAISE EXCEPTION 'Field name "_name" is too long (max 64 characters): %', NEW._name USING ERRCODE = '23514'; END IF; -- Check 6: C# reserved words, compared as written: C# keywords are case-sensitive, so Ref, Default or -- String are ordinary property names and only ref, default, string are refused (0.7.31). IF NEW._name = ANY(ARRAY[ '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' ]) THEN RAISE EXCEPTION 'Field name "_name" is a C# reserved word: %', NEW._name USING ERRCODE = '23514', HINT = 'Use a different name or add prefix/suffix'; END IF; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; -- Create trigger CREATE TRIGGER tr_validate_structure_name BEFORE INSERT OR UPDATE ON _structures FOR EACH ROW EXECUTE FUNCTION validate_structure_name(); -- Comments for trigger COMMENT ON FUNCTION validate_structure_name() IS 'Function for validating field names in _structures according to C# naming rules'; COMMENT ON TRIGGER tr_validate_structure_name ON _structures IS 'Trigger checks correctness of field names: prohibits system names, names starting with digits, special characters, and C# reserved words'; -- Trigger for validating scheme names in _schemes CREATE OR REPLACE FUNCTION validate_scheme_name() RETURNS TRIGGER AS $$ DECLARE scheme_name text; BEGIN -- Check only on INSERT and UPDATE of _name field IF TG_OP = 'INSERT' OR (TG_OP = 'UPDATE' AND OLD._name IS DISTINCT FROM NEW._name) THEN scheme_name := LOWER(NEW._name); -- Skip validation for system schemes (starting with @@) -- These are reserved for internal use (e.g. @@__deleted for soft-delete) IF NEW._name ~ '^@@' THEN RETURN NEW; END IF; -- Check 1: Name must not start with a digit IF NEW._name ~ '^[0-9]' THEN RAISE EXCEPTION 'Scheme name "_name" cannot start with a digit: %', NEW._name USING ERRCODE = '23514', HINT = 'Scheme name must start with a letter or underscore'; END IF; -- Check 2: Name must follow C# class naming rules (letters, digits, underscores, dots for namespace, + for nested classes) IF NEW._name !~ '^[a-zA-Z_][a-zA-Z0-9_.+]*$' THEN RAISE EXCEPTION 'Scheme name "_name" contains invalid characters: %', NEW._name USING ERRCODE = '23514', HINT = 'Name can only contain Latin letters, digits, underscores, dots and +. Must start with letter or underscore'; END IF; -- Check 3: Name must not end with a dot IF NEW._name ~ '\.$' THEN RAISE EXCEPTION 'Scheme name "_name" cannot end with a dot: %', NEW._name USING ERRCODE = '23514', HINT = 'Remove dot at the end of the name'; END IF; -- Check 4: Name must not contain two consecutive dots IF NEW._name ~ '\.\.' THEN RAISE EXCEPTION 'Scheme name "_name" cannot contain two consecutive dots: %', NEW._name USING ERRCODE = '23514', HINT = 'Use one dot to separate namespace parts'; END IF; -- Check 5: Name must not be empty or contain only spaces IF LENGTH(TRIM(NEW._name)) = 0 THEN RAISE EXCEPTION 'Scheme name "_name" cannot be empty' USING ERRCODE = '23514'; END IF; -- Check 6: Maximum name length (reasonable limit) IF LENGTH(NEW._name) > 128 THEN RAISE EXCEPTION 'Scheme name "_name" is too long (max 128 characters): %', NEW._name USING ERRCODE = '23514'; END IF; -- Check 7: C# reserved words (check each part after splitting by dots or +) IF EXISTS ( SELECT 1 FROM regexp_split_to_table(LOWER(NEW._name), '[.+]') AS part WHERE part = ANY(ARRAY[ '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' ]) ) THEN RAISE EXCEPTION 'Scheme name "_name" contains C# reserved word: %', NEW._name USING ERRCODE = '23514', HINT = 'Use a different name or add prefix/suffix to the problematic part'; END IF; -- Check 8: Each part (separated by dots or +) must be a valid identifier IF EXISTS ( SELECT 1 FROM regexp_split_to_table(NEW._name, '[.+]') AS part WHERE LENGTH(TRIM(part)) = 0 OR part ~ '^[0-9]' OR part !~ '^[a-zA-Z_][a-zA-Z0-9_]*$' ) THEN RAISE EXCEPTION 'Scheme name "_name" contains invalid namespace part: %', NEW._name USING ERRCODE = '23514', HINT = 'Each part between dots/+ must be a valid C# identifier'; END IF; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; -- Create trigger for schemes CREATE TRIGGER tr_validate_scheme_name BEFORE INSERT OR UPDATE ON _schemes FOR EACH ROW EXECUTE FUNCTION validate_scheme_name(); -- Comments for scheme trigger COMMENT ON FUNCTION validate_scheme_name() IS 'Function for validating scheme names in _schemes according to C# class and namespace naming rules'; COMMENT ON TRIGGER tr_validate_scheme_name ON _schemes IS 'Trigger checks correctness of scheme names: C# class naming rules, namespace support via dots, reserved words'; -- Function for building facets (faceted search) -- Function for faceted search of objects with filtering (REFACTORED MODULAR VERSION) -- Function to get user permissions for a specific object CREATE OR REPLACE FUNCTION get_user_permissions_for_object( p_object_id bigint, p_user_id bigint DEFAULT NULL -- now optional for use in trigger ) RETURNS TABLE( object_id bigint, user_id bigint, permission_source_id bigint, permission_type varchar, _id_role bigint, _id_user bigint, can_select boolean, can_insert boolean, can_update boolean, can_delete boolean ) AS $$ BEGIN -- System user (id=0) has full rights to everything IF p_user_id = 0 THEN RETURN QUERY SELECT p_object_id as object_id, 0::bigint as user_id, 0::bigint as permission_source_id, 'system'::varchar as permission_type, NULL::bigint as _id_role, 0::bigint as _id_user, true as can_select, true as can_insert, true as can_update, true as can_delete; RETURN; END IF; RETURN QUERY WITH RECURSIVE permission_search AS ( -- Step 1: Start with target object SELECT p_object_id as object_id, p_object_id as current_search_id, o._id_parent, 0 as level, EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = p_object_id) as has_permission FROM _objects o WHERE o._id = p_object_id UNION ALL -- Step 2: If NO permission - go to 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 = false -- continue only if NO permission ), -- Take first found permission for object object_permission AS ( SELECT DISTINCT ON (ps.object_id) ps.object_id, p._id as permission_id, p._id_user, p._id_role, p._select, p._insert, p._update, p._delete, ps.level, ps.current_search_id as permission_source_id FROM permission_search ps JOIN _permissions p ON p._id_ref = ps.current_search_id WHERE ps.has_permission = true ORDER BY ps.object_id, ps.level -- closest to object ), -- Add global rights as fallback (_id_ref = 0) global_permission AS ( SELECT p_object_id 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, -- low priority 0 as permission_source_id FROM _permissions p WHERE p._id_ref = 0 ), -- Combine specific and global rights all_permissions AS ( SELECT * FROM object_permission UNION ALL SELECT * FROM global_permission ), -- Take first by priority (specific > global) final_permission AS ( SELECT DISTINCT ON (object_id) * FROM all_permissions ORDER BY object_id, level -- specific rights have smaller level ) -- Result: for user permissions - directly, for role permissions - via users_roles SELECT fp.object_id, CASE WHEN p_user_id IS NULL THEN NULL -- if user_id not provided for trigger WHEN fp._id_user IS NOT NULL THEN fp._id_user -- direct user permission ELSE ur._id_user -- via role END as user_id, fp.permission_source_id, CASE WHEN fp._id_user IS NOT NULL THEN 'user'::varchar ELSE 'role'::varchar 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_permission fp LEFT JOIN _users_roles ur ON ur._id_role = fp._id_role -- only for role permissions WHERE p_user_id IS NULL OR (fp._id_user = p_user_id OR ur._id_user = p_user_id); -- if user_id NULL - all permissions, otherwise filter END; $$ LANGUAGE plpgsql; -- Comment for function to get permissions for object COMMENT ON FUNCTION get_user_permissions_for_object(bigint, bigint) IS 'Function to get effective permissions for a specific object considering hierarchical inheritance and priorities (user > role). If user_id = NULL, returns first found permission without filtering by user (for use in triggers)'; -- Trigger function for automatically creating permissions when creating node objects CREATE OR REPLACE FUNCTION auto_create_node_permissions() RETURNS TRIGGER AS $$ DECLARE source_permission RECORD; BEGIN -- Process only INSERT of new objects with parent IF TG_OP = 'INSERT' AND NEW._id_parent IS NOT NULL THEN -- Check if parent already has permission IF EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = NEW._id_parent) THEN RETURN NEW; -- Parent already has permission, do nothing END IF; -- Use modified function WITHOUT user_id to search for source permission SELECT * INTO source_permission FROM get_user_permissions_for_object(NEW._id_parent, NULL) LIMIT 1; -- If found source permission - create permission for parent IF FOUND THEN INSERT INTO _permissions ( _id, _id_role, _id_user, _id_ref, _select, _insert, _update, _delete ) VALUES ( nextval('global_identity'), source_permission._id_role, source_permission._id_user, NEW._id_parent, -- create permission for parent source_permission.can_select, source_permission.can_insert, source_permission.can_update, source_permission.can_delete ); END IF; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; -- Create trigger on _objects table CREATE TRIGGER tr_auto_create_node_permissions AFTER INSERT ON _objects FOR EACH ROW EXECUTE FUNCTION auto_create_node_permissions(); -- Comments for trigger COMMENT ON FUNCTION auto_create_node_permissions() IS 'Trigger function for automatically creating permissions for parent objects when child objects appear. Creates permission only if parent doesn''t have one yet, inheriting from nearest ancestor with permission'; COMMENT ON TRIGGER tr_auto_create_node_permissions ON _objects IS 'Trigger automatically creates permission for an object when a child object is added to it, if it doesn''t already have its own permission. Speeds up permission search by reducing recursion depth'; CREATE VIEW v_user_permissions AS WITH RECURSIVE permission_search AS ( -- Step 1: Each object searches for its 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 - go to 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 = false -- continue only if NO permission ), -- Take first found permission for each object object_permissions AS ( SELECT DISTINCT ON (ps.object_id) ps.object_id, p._id as permission_id, p._id_user, p._id_role, p._select, p._insert, p._update, p._delete, ps.level FROM permission_search ps JOIN _permissions p ON p._id_ref = ps.current_search_id WHERE ps.has_permission = true ORDER BY ps.object_id, ps.level -- closest to object ), -- 🚀 NEW: Add global rights as virtual records with object_id = 0 global_permissions AS ( SELECT 0 as object_id, -- virtual object for global rights p._id as permission_id, p._id_user, p._id_role, p._select, p._insert, p._update, p._delete, 999 as level -- low priority FROM _permissions p WHERE p._id_ref = 0 -- global rights ), -- Combine specific and global rights all_permissions AS ( SELECT * FROM object_permissions UNION ALL SELECT * FROM global_permissions ), -- Take first by priority (specific > global) final_permissions AS ( SELECT DISTINCT ON (object_id) * FROM all_permissions ORDER BY object_id, level -- specific rights have smaller level ) -- Result: for user permissions - directly, for role permissions - via users_roles SELECT fp.object_id, CASE WHEN fp._id_user IS NOT NULL THEN fp._id_user -- direct user permission ELSE ur._id_user -- via role END as user_id, fp.permission_id, CASE WHEN fp._id_user IS NOT NULL THEN 'user'::varchar ELSE 'role'::varchar END as permission_type, fp._id_role, 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 -- only for role permissions WHERE fp._id_user IS NOT NULL OR ur._id_user IS NOT NULL; -- has user -- 🔐 TRIGGER FOR PROTECTING SYSTEM USERS -- Prohibits deletion of system users with ID 0, 1, -1 -- IDs 0 (sys), -1 (default): fully immutable (no changes allowed) -- Login (_login) is immutable for ALL users -- Trigger function CREATE OR REPLACE FUNCTION protect_system_users() RETURNS TRIGGER AS $$ BEGIN -- Check DELETE operation IF TG_OP = 'DELETE' THEN -- Prohibit deletion of system users IF OLD._id IN (0, 1, -1) THEN RAISE EXCEPTION 'Cannot delete system user with ID %', OLD._id; END IF; RETURN OLD; END IF; -- Check UPDATE operation IF TG_OP = 'UPDATE' THEN -- Prohibit changing ID (just in case) IF OLD._id != NEW._id THEN RAISE EXCEPTION 'Cannot change user ID'; END IF; -- IDs 0 (sys) and -1 (default): fully immutable, no changes allowed IF OLD._id IN (0, -1) THEN IF OLD._login != NEW._login OR OLD._password != NEW._password OR OLD._name != NEW._name OR COALESCE(OLD._phone, '') != COALESCE(NEW._phone, '') OR COALESCE(OLD._email, '') != COALESCE(NEW._email, '') OR OLD._enabled != NEW._enabled OR COALESCE(OLD._note, '') != COALESCE(NEW._note, '') THEN RAISE EXCEPTION 'Cannot modify system user with ID %', OLD._id; END IF; END IF; -- Login is immutable for ALL users IF OLD._login != NEW._login THEN RAISE EXCEPTION 'Cannot change user login'; END IF; RETURN NEW; END IF; -- For INSERT nothing to check RETURN NEW; END; $$ LANGUAGE plpgsql; -- Create trigger on _users table DROP TRIGGER IF EXISTS tr_protect_system_users ON _users; CREATE TRIGGER tr_protect_system_users BEFORE UPDATE OR DELETE ON _users FOR EACH ROW EXECUTE FUNCTION protect_system_users(); -- Comments for trigger COMMENT ON FUNCTION protect_system_users() IS 'Protects system users (ID -1, 0) from any modification, prohibits login change for all users'; COMMENT ON TRIGGER tr_protect_system_users ON _users IS 'Trigger protecting system users and login immutability'; -- Disable trigger (keeps trigger definition but prevents execution) ALTER TABLE _objects DISABLE TRIGGER tr_auto_create_node_permissions; -- View current value --SHOW shared_buffers; -- Change (requires PostgreSQL restart) -- ALTER SYSTEM SET shared_buffers = '2GB'; -- Schemes for TrueSight.Models INSERT INTO _permissions (_id, _id_user, _id_ref, _select, _insert, _update, _delete) VALUES ( nextval('global_identity'), -- Permission record ID 0, -- ID of sys user 0, -- _id_ref = 0 means "all objects" true, -- _select = allow reading true, -- _insert = allow creation true, -- _update = allow modification true -- _delete = allow deletion ); INSERT INTO _permissions (_id, _id_user, _id_ref, _select, _insert, _update, _delete) VALUES ( nextval('global_identity'), -- Permission record ID 1, -- ID of sys user 0, -- _id_ref = 0 means "all objects" true, -- _select = allow reading true, -- _insert = allow creation true, -- _update = allow modification true -- _delete = allow deletion ); Path: redb/redb.Postgres/sql/redb_metadata_cache.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.Postgres/sql/redb_metadata_cache.sql ---- -- ============================================================ -- METADATA CACHE: Solution for repeated JOIN problem -- ============================================================ -- Goal: Avoid repeated JOIN _structures ← _types in each query -- Approach: UNLOGGED TABLE + automatic synchronization via triggers on _structure_hash -- Advantages: -- ✅ No recursion problems (indexes created once) -- ✅ Works with connection pooling (global table) -- ✅ Automatic invalidation (triggers on _schemes._structure_hash) -- ✅ No changes in C# code required -- ✅ Minimal cache rebuilds (only on actual schema changes) -- ============================================================ -- 1️⃣ Create metadata cache (ALL fields from _structures + fields from _types) DROP TABLE IF EXISTS _scheme_metadata_cache CASCADE; CREATE TABLE _scheme_metadata_cache ( --<-- UNLOGGED TABLE IF NEEDED -- Identifiers _scheme_id bigint NOT NULL, _structure_id bigint NOT NULL, _parent_structure_id bigint, _id_override bigint, -- Names and aliases _name text NOT NULL, _alias text, -- Structure type _type_id bigint NOT NULL, _list_id bigint, type_name text NOT NULL, db_type text NOT NULL, type_semantic text NOT NULL, -- Scheme type (Class/Array/Dictionary/JsonDocument/XDocument) _scheme_type bigint, scheme_type_name text, -- Structure attributes _order bigint, _collection_type bigint, -- NULL = not a collection, otherwise collection type ID (Array/Dictionary) collection_type_name text, -- Collection type name _key_type bigint, -- Key type for Dictionary key_type_name text, -- Key type name _readonly boolean, _allow_not_null boolean, _is_compress boolean, _store_null boolean, _unique boolean, -- V4: unique key flag ([RedbUnique]) _unique_version bigint, -- V4: encoder version of the stored keys _unique_scope bigint, -- S3: element-key scope of a collection key _lazy boolean, -- V4 (LAZY Л2): lazy reference marker _tags varchar(450), -- V4: free-form marker mirrored from _structures -- Default values _default_value bytea, _default_editor text ); -- 2️⃣ Indexes for fast search 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; -- 3) sync_metadata_cache_for_scheme is MODULE-OWNED since V4: it carries the cache column list, -- which must reach EXISTING databases when _structures gains a column. It lives in -- v2-pvt/29_metadata_cache_sync.sql and rides the versioned bundle (redb_init.sql includes it -- for fresh databases). The triggers below call it by name at run time. -- 4️⃣ Trigger on _structure_hash change in _schemes -- 🔥 KEY IDEA: Track ONLY hash changes, not every INSERT/UPDATE in _structures! CREATE OR REPLACE FUNCTION sync_metadata_cache_on_hash_change() RETURNS TRIGGER AS $$ BEGIN -- Check if _structure_hash changed IF (TG_OP = 'UPDATE' AND OLD._structure_hash IS DISTINCT FROM NEW._structure_hash) THEN -- Hash changed → rebuild cache for this scheme PERFORM sync_metadata_cache_for_scheme(NEW._id); RAISE NOTICE 'Metadata cache rebuilt for scheme_id=% due to structure_hash change (old=%, new=%)', NEW._id, OLD._structure_hash, NEW._structure_hash; ELSIF (TG_OP = 'INSERT' AND NEW._structure_hash IS NOT NULL) THEN -- New scheme with hash → create cache PERFORM sync_metadata_cache_for_scheme(NEW._id); RAISE NOTICE 'Metadata cache created for new scheme_id=% (hash=%)', NEW._id, NEW._structure_hash; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; DROP TRIGGER IF EXISTS trg_sync_metadata_cache_on_hash_change ON _schemes; CREATE TRIGGER trg_sync_metadata_cache_on_hash_change AFTER INSERT OR UPDATE ON _schemes FOR EACH ROW EXECUTE FUNCTION sync_metadata_cache_on_hash_change(); -- 5️⃣ Trigger on DELETE of scheme CREATE OR REPLACE FUNCTION cleanup_metadata_cache_on_scheme_delete() RETURNS TRIGGER AS $$ BEGIN DELETE FROM _scheme_metadata_cache WHERE _scheme_id = OLD._id; RAISE NOTICE 'Metadata cache cleared for deleted scheme_id=%', OLD._id; RETURN OLD; END; $$ LANGUAGE plpgsql; DROP TRIGGER IF EXISTS trg_cleanup_metadata_cache_on_scheme_delete ON _schemes; CREATE TRIGGER trg_cleanup_metadata_cache_on_scheme_delete AFTER DELETE ON _schemes FOR EACH ROW EXECUTE FUNCTION cleanup_metadata_cache_on_scheme_delete(); -- 6️⃣ Trigger on type changes (invalidates entire cache) -- 🔥 When _types change → all schemes must rebuild CREATE OR REPLACE FUNCTION invalidate_all_metadata_caches() RETURNS TRIGGER AS $$ BEGIN TRUNCATE _scheme_metadata_cache; RAISE NOTICE 'All metadata caches invalidated due to _types change'; RETURN NEW; END; $$ LANGUAGE plpgsql; DROP TRIGGER IF EXISTS trg_invalidate_all_caches ON _types; CREATE TRIGGER trg_invalidate_all_caches AFTER UPDATE OR DELETE ON _types FOR EACH STATEMENT EXECUTE FUNCTION invalidate_all_metadata_caches(); -- 7) warmup_all_metadata_caches is MODULE-OWNED since V4 — see v2-pvt/29_metadata_cache_sync.sql -- (same reason as sync_metadata_cache_for_scheme above). -- 8️⃣ Cache consistency check function CREATE OR REPLACE FUNCTION check_metadata_cache_consistency() RETURNS TABLE( scheme_id bigint, scheme_name text, cached_count bigint, actual_count bigint, is_consistent boolean ) AS $$ BEGIN RETURN QUERY SELECT s._id as scheme_id, s._name::text as scheme_name, COALESCE(cache_stats.cached_count, 0) as cached_count, COALESCE(actual_stats.actual_count, 0) as actual_count, (COALESCE(cache_stats.cached_count, 0) = COALESCE(actual_stats.actual_count, 0)) as is_consistent FROM _schemes s LEFT JOIN ( SELECT _scheme_id, COUNT(*) as cached_count FROM _scheme_metadata_cache GROUP BY _scheme_id ) cache_stats ON cache_stats._scheme_id = s._id LEFT JOIN ( SELECT _id_scheme, COUNT(*) as actual_count FROM _structures GROUP BY _id_scheme ) actual_stats ON actual_stats._id_scheme = s._id ORDER BY s._id; END; $$ LANGUAGE plpgsql; COMMENT ON FUNCTION check_metadata_cache_consistency() IS 'Checks metadata cache consistency. Returns discrepancies between cache and actual data. Usage: SELECT * FROM check_metadata_cache_consistency() WHERE NOT is_consistent; '; COMMENT ON TABLE _scheme_metadata_cache IS 'Metadata cache for schemes to optimize queries. Automatically synchronized via triggers on _schemes._structure_hash. Note: Use UNLOGGED TABLE for better performance if replication is not needed (cleared after crash). Invalidation strategy: ✅ _schemes._structure_hash changed → rebuild cache for scheme (trigger) ✅ _schemes deleted → delete scheme cache (trigger) ✅ _types changed → clear entire cache (TRUNCATE trigger) Cache warmup: ✅ warmup_all_metadata_caches() warms up ALL schemes (including those without _structure_hash) ✅ Auto-filling in functions (get_object_json, get_facets) as fallback '; -- ============================================================ -- READY! Now use in queries: -- -- INSTEAD OF: -- FROM _structures s -- JOIN _types t ON t._id = s._id_type -- WHERE s._id_scheme = object_scheme_id -- -- USE: -- FROM _scheme_metadata_cache c -- WHERE c._scheme_id = object_scheme_id -- -- AVAILABLE FIELDS: -- _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 (scheme type: Class/Array/Dictionary/JsonDocument/XDocument) -- _order, _collection_type, collection_type_name (collection type: Array/Dictionary/NULL) -- _key_type, key_type_name (key type for Dictionary) -- _readonly, _allow_not_null, _is_compress, _store_null -- _default_value, _default_editor -- -- COLLECTION CHECK (instead of _is_array): -- _collection_type IS NOT NULL = this is a collection (array or dictionary) -- _collection_type IS NULL = not a collection -- ============================================================ Path: redb/redb.Postgres/sql/redb_migrations.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.Postgres/sql/redb_migrations.sql ---- -- ===================================================== -- REDB Pro: Таблица истории миграций (PostgreSQL) -- ===================================================== CREATE TABLE IF NOT EXISTS _migrations ( _id BIGSERIAL PRIMARY KEY, _migration_id TEXT NOT NULL, -- уникальный ID миграции "OrderProps_TotalPrice_v1" _scheme_id BIGINT NOT NULL REFERENCES _schemes(_id) ON DELETE CASCADE, _structure_id BIGINT REFERENCES _structures(_id) ON DELETE SET NULL, -- NULL = вся схема _property_name TEXT, -- имя свойства (для логов) _expression_hash TEXT, -- MD5 от Expression для детекции изменений _migration_type TEXT NOT NULL, -- ComputedFrom, TypeChange, DefaultValue, Transform _applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), _applied_by TEXT, -- кто применил (user/system) _sql_executed TEXT, -- SQL который был выполнен (для аудита) _affected_rows INT, -- сколько записей затронуто _duration_ms INT, -- время выполнения _dry_run BOOLEAN NOT NULL DEFAULT FALSE, -- это был dry-run? CONSTRAINT uq_migration_scheme UNIQUE(_scheme_id, _migration_id) ); -- Индексы для быстрого поиска CREATE INDEX IF NOT EXISTS idx_migrations_scheme ON _migrations(_scheme_id); CREATE INDEX IF NOT EXISTS idx_migrations_applied ON _migrations(_applied_at DESC); COMMENT ON TABLE _migrations IS 'История применённых миграций данных (Pro feature)'; COMMENT ON COLUMN _migrations._migration_id IS 'Уникальный ID миграции в формате SchemeType_PropertyName_vN'; COMMENT ON COLUMN _migrations._expression_hash IS 'MD5 хеш Expression для детекции изменений'; COMMENT ON COLUMN _migrations._sql_executed IS 'SQL запрос для аудита и отладки'; Path: redb/redb.Postgres/sql/redb_save_json_objects.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.Postgres/sql/redb_save_json_objects.sql ---- -- ============================================================ -- SAVE OBJECT FROM JSON (Postgres) -- Inverse of get_object_json: JSON → _objects + _values -- Strategy: DeleteInsert (delete all _values, then insert new) -- ============================================================ -- Input format: same JSON structure as produced by get_object_json() -- -- Two functions (mirroring read architecture): -- save_object_json(jsonb) → bigint [mirror of get_object_json] -- save_hierarchical_properties(...) [mirror of build_hierarchical_properties_optimized] -- -- Supported field types (all branches from build_hierarchical_properties_optimized): -- 1. Array of Class (type_semantic='Object', _is_array) -- 2. Array of _RObject refs (type_semantic='_RObject', _is_array) -- 3. Array of primitives (String/Long/Double/Guid/Boolean/Numeric/DateTime/ByteArray/ListItem) -- 4. Dictionary of Class (type_semantic='Object', _is_dictionary) -- 5. Dictionary of _RObject (type_semantic='_RObject', _is_dictionary) -- 6. Dictionary of primitives -- 7. Single _RObject ref (type_name='Object', type_semantic='_RObject') -- 8. Class field (type_semantic='Object', marker _Guid) -- 9. ListItem (db_type='ListItem', or Long backward-compat) -- 10. Primitive scalars (String/Long/Double/Guid/Boolean/Numeric/DateTime/ByteArray) -- ============================================================ -- Drop existing functions (handle signature changes on re-deploy) DROP FUNCTION IF EXISTS save_object_json(jsonb); DROP FUNCTION IF EXISTS save_hierarchical_properties(bigint, bigint, bigint, jsonb, bigint); -- ============================================================ -- 1. RECURSIVE PROPERTY WRITER -- Mirror of build_hierarchical_properties_optimized (reader) -- Walks _scheme_metadata_cache, extracts values from JSON, -- INSERTs into _values with correct column routing -- ============================================================ CREATE OR REPLACE FUNCTION save_hierarchical_properties( p_object_id bigint, -- owning object _id p_parent_structure_id bigint, -- NULL for root level, structure _id for nested Class p_scheme_id bigint, -- scheme _id (for metadata cache lookup) p_properties_json jsonb, -- JSON object: {"Name":"Alice","Tags":[...],"Address":{...}} p_parent_value_id bigint DEFAULT NULL -- NULL for root, parent _values._id for nested ) RETURNS void LANGUAGE 'plpgsql' AS $BODY$ DECLARE structure_record RECORD; field_json jsonb; v_value_id bigint; v_head_id bigint; v_element_id bigint; v_element jsonb; v_nested_id bigint; v_idx integer; v_dict_entry RECORD; BEGIN -- Ensure metadata cache is populated (mirrors read function) IF NOT EXISTS(SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = p_scheme_id LIMIT 1) THEN PERFORM sync_metadata_cache_for_scheme(p_scheme_id); END IF; -- Walk structures for this level -- Same query & ordering as build_hierarchical_properties_optimized FOR structure_record IN SELECT c._structure_id as structure_id, c._name as field_name, c._collection_type as collection_type, c._collection_type = -9223372036854775668 as _is_array, -- Array type ID c._collection_type = -9223372036854775667 as _is_dictionary, -- Dictionary type ID c.type_name, c.db_type, c.type_semantic FROM _scheme_metadata_cache c WHERE c._scheme_id = p_scheme_id AND ((p_parent_structure_id IS NULL AND c._parent_structure_id IS NULL) OR (p_parent_structure_id IS NOT NULL AND c._parent_structure_id = p_parent_structure_id)) ORDER BY c._order, c._structure_id LOOP -- Extract field value from JSON by structure name field_json := p_properties_json -> structure_record.field_name; -- Skip if field not present (SQL NULL) or JSON null IF field_json IS NULL OR field_json = 'null'::jsonb THEN CONTINUE; END IF; -- ================================================================ -- DISPATCH BY TYPE -- Mirrors the CASE tree in build_hierarchical_properties_optimized -- ================================================================ IF structure_record._is_array THEN -- ======================================================== -- ARRAY FIELDS (branches 1-3) -- ======================================================== IF jsonb_typeof(field_json) != 'array' THEN CONTINUE; -- type mismatch guard END IF; -- Insert head record: marker "this array property exists" -- Read side: base_array_value_id IS NULL → property is null (not []) v_head_id := nextval('global_identity'); INSERT INTO _values (_id, _id_structure, _id_object, _array_index, _array_parent_id) VALUES (v_head_id, structure_record.structure_id, p_object_id, NULL, p_parent_value_id); -- Empty array [] → head record alone (read returns []) IF jsonb_array_length(field_json) = 0 THEN CONTINUE; END IF; -- ----- Branch 1: Array of Class fields ----- -- Mirror: build_hierarchical_properties_optimized recursion per element IF structure_record.type_semantic = 'Object' THEN FOR v_idx IN 0..jsonb_array_length(field_json) - 1 LOOP v_element := field_json -> v_idx; IF v_element IS NULL OR v_element = 'null'::jsonb THEN CONTINUE; END IF; -- Insert element record (_array_index = index, _array_parent_id = head) v_element_id := nextval('global_identity'); INSERT INTO _values (_id, _id_structure, _id_object, _array_index, _array_parent_id) VALUES (v_element_id, structure_record.structure_id, p_object_id, v_idx::text, v_head_id); -- Recurse into child properties of this array element IF jsonb_typeof(v_element) = 'object' THEN PERFORM save_hierarchical_properties( p_object_id, structure_record.structure_id, -- parent structure = array structure p_scheme_id, v_element, v_element_id -- children's _array_parent_id → this element ); END IF; END LOOP; -- ----- Branch 2: Array of Object references (_RObject) ----- -- Mirror: get_object_json(v._Object, max_depth - 1) per element ELSIF structure_record.type_semantic = '_RObject' THEN FOR v_idx IN 0..jsonb_array_length(field_json) - 1 LOOP v_element := field_json -> v_idx; -- Resolve: full object JSON → recursive save; number → ID directly IF jsonb_typeof(v_element) = 'object' THEN v_nested_id := save_object_json(v_element); ELSIF v_element IS NOT NULL AND v_element != 'null'::jsonb THEN v_nested_id := (v_element #>> '{}')::bigint; ELSE v_nested_id := NULL; END IF; v_element_id := nextval('global_identity'); INSERT INTO _values ( _id, _id_structure, _id_object, _Object, _array_index, _array_parent_id ) VALUES ( v_element_id, structure_record.structure_id, p_object_id, v_nested_id, v_idx::text, v_head_id ); END LOOP; -- ----- Branch 3: Array of primitive types ----- -- Mirror: to_jsonb(v._String) / to_jsonb(v._Long) / ... per element ELSE FOR v_idx IN 0..jsonb_array_length(field_json) - 1 LOOP v_element := field_json -> v_idx; v_element_id := nextval('global_identity'); INSERT INTO _values ( _id, _id_structure, _id_object, _array_index, _array_parent_id, _String, _Long, _Guid, _Double, _Numeric, _DateTimeOffset, _Boolean, _ByteArray, _ListItem ) VALUES ( v_element_id, structure_record.structure_id, p_object_id, v_idx::text, v_head_id, -- Route value to correct column based on db_type CASE WHEN structure_record.db_type = 'String' THEN v_element #>> '{}' END, CASE WHEN structure_record.db_type = 'Long' AND jsonb_typeof(v_element) != 'object' THEN (v_element #>> '{}')::bigint END, CASE WHEN structure_record.db_type = 'Guid' THEN (v_element #>> '{}')::uuid END, CASE WHEN structure_record.db_type = 'Double' THEN (v_element #>> '{}')::float END, CASE WHEN structure_record.db_type = 'Numeric' THEN (v_element #>> '{}')::numeric END, CASE WHEN structure_record.db_type IN ('DateTimeOffset', 'DateTime') THEN (v_element #>> '{}')::timestamptz END, CASE WHEN structure_record.db_type = 'Boolean' THEN (v_element #>> '{}')::boolean END, CASE WHEN structure_record.db_type = 'ByteArray' THEN decode(v_element #>> '{}', 'base64') END, -- _ListItem: ListItem type OR Long backward-compat (Long field with ListItem JSON) CASE WHEN structure_record.db_type = 'ListItem' THEN CASE WHEN jsonb_typeof(v_element) = 'object' THEN (v_element ->> 'id')::bigint ELSE (v_element #>> '{}')::bigint END WHEN structure_record.db_type = 'Long' AND jsonb_typeof(v_element) = 'object' THEN (v_element ->> 'id')::bigint END ); END LOOP; END IF; ELSIF structure_record._is_dictionary THEN -- ======================================================== -- DICTIONARY FIELDS (branches 4-6) -- ======================================================== IF jsonb_typeof(field_json) != 'object' THEN CONTINUE; -- type mismatch guard END IF; -- Insert head record (marker: "this dictionary property exists") v_head_id := nextval('global_identity'); INSERT INTO _values (_id, _id_structure, _id_object, _array_index, _array_parent_id) VALUES (v_head_id, structure_record.structure_id, p_object_id, NULL, p_parent_value_id); -- Empty dict {} → head record alone (read returns {}); jsonb_each yields zero rows -- ----- Branch 4: Dictionary of Class fields ----- -- Mirror: build_hierarchical_properties_optimized recursion per entry IF structure_record.type_semantic = 'Object' THEN FOR v_dict_entry IN SELECT * FROM jsonb_each(field_json) LOOP v_element_id := nextval('global_identity'); INSERT INTO _values (_id, _id_structure, _id_object, _array_index, _array_parent_id) VALUES (v_element_id, structure_record.structure_id, p_object_id, v_dict_entry.key, v_head_id); IF jsonb_typeof(v_dict_entry.value) = 'object' THEN PERFORM save_hierarchical_properties( p_object_id, structure_record.structure_id, p_scheme_id, v_dict_entry.value, v_element_id ); END IF; END LOOP; -- ----- Branch 5: Dictionary of Object references (_RObject) ----- -- Mirror: get_object_json(v._Object, max_depth - 1) per entry ELSIF structure_record.type_semantic = '_RObject' THEN FOR v_dict_entry IN SELECT * FROM jsonb_each(field_json) LOOP IF jsonb_typeof(v_dict_entry.value) = 'object' THEN v_nested_id := save_object_json(v_dict_entry.value); ELSIF v_dict_entry.value IS NOT NULL AND v_dict_entry.value != 'null'::jsonb THEN v_nested_id := (v_dict_entry.value #>> '{}')::bigint; ELSE v_nested_id := NULL; END IF; v_element_id := nextval('global_identity'); INSERT INTO _values ( _id, _id_structure, _id_object, _Object, _array_index, _array_parent_id ) VALUES ( v_element_id, structure_record.structure_id, p_object_id, v_nested_id, v_dict_entry.key, v_head_id ); END LOOP; -- ----- Branch 6: Dictionary of primitive types ----- -- Mirror: jsonb_object_agg(key, to_jsonb(v._String / v._Long / ...)) ELSE FOR v_dict_entry IN SELECT * FROM jsonb_each(field_json) LOOP v_element_id := nextval('global_identity'); INSERT INTO _values ( _id, _id_structure, _id_object, _array_index, _array_parent_id, _String, _Long, _Guid, _Double, _Numeric, _DateTimeOffset, _Boolean, _ByteArray, _ListItem ) VALUES ( v_element_id, structure_record.structure_id, p_object_id, v_dict_entry.key, v_head_id, CASE WHEN structure_record.db_type = 'String' THEN v_dict_entry.value #>> '{}' END, CASE WHEN structure_record.db_type = 'Long' THEN (v_dict_entry.value #>> '{}')::bigint END, CASE WHEN structure_record.db_type = 'Guid' THEN (v_dict_entry.value #>> '{}')::uuid END, CASE WHEN structure_record.db_type = 'Double' THEN (v_dict_entry.value #>> '{}')::float END, CASE WHEN structure_record.db_type = 'Numeric' THEN (v_dict_entry.value #>> '{}')::numeric END, CASE WHEN structure_record.db_type IN ('DateTimeOffset', 'DateTime') THEN (v_dict_entry.value #>> '{}')::timestamptz END, CASE WHEN structure_record.db_type = 'Boolean' THEN (v_dict_entry.value #>> '{}')::boolean END, CASE WHEN structure_record.db_type = 'ByteArray' THEN decode(v_dict_entry.value #>> '{}', 'base64') END, CASE WHEN structure_record.db_type = 'ListItem' THEN CASE WHEN jsonb_typeof(v_dict_entry.value) = 'object' THEN (v_dict_entry.value ->> 'id')::bigint ELSE (v_dict_entry.value #>> '{}')::bigint END END ); END LOOP; END IF; ELSIF structure_record.type_name = 'Object' AND structure_record.type_semantic = '_RObject' THEN -- ======================================================== -- Branch 7: SINGLE OBJECT REFERENCE -- Mirror: get_object_json(current_value_record._Object, max_depth - 1) -- ======================================================== IF jsonb_typeof(field_json) = 'object' THEN -- Full nested object JSON → save recursively, get ID v_nested_id := save_object_json(field_json); ELSE -- Numeric ID reference v_nested_id := (field_json #>> '{}')::bigint; END IF; v_value_id := nextval('global_identity'); INSERT INTO _values (_id, _id_structure, _id_object, _Object, _array_parent_id) VALUES (v_value_id, structure_record.structure_id, p_object_id, v_nested_id, p_parent_value_id); ELSIF structure_record.type_semantic = 'Object' THEN -- ======================================================== -- Branch 8: CLASS FIELD (nested class with child properties) -- Mirror: WHEN _Guid IS NULL THEN NULL ELSE build_hierarchical_... -- ======================================================== IF jsonb_typeof(field_json) != 'object' THEN CONTINUE; -- class fields must be JSON objects END IF; -- Insert marker record with _Guid (read checks: _Guid IS NULL → class is null) v_value_id := nextval('global_identity'); INSERT INTO _values (_id, _id_structure, _id_object, _Guid, _array_parent_id) VALUES (v_value_id, structure_record.structure_id, p_object_id, gen_random_uuid(), p_parent_value_id); -- Recurse: save child properties under this class structure PERFORM save_hierarchical_properties( p_object_id, structure_record.structure_id, -- children are under this structure in _scheme_metadata_cache p_scheme_id, field_json, v_value_id -- children's _array_parent_id → this marker record ); ELSE -- ======================================================== -- Branches 9-10: PRIMITIVE SCALAR FIELDS + LISTITEM -- Mirror: to_jsonb(v._String) / to_jsonb(v._Long) / build_listitem_jsonb / ... -- ======================================================== v_value_id := nextval('global_identity'); -- Branch 9: ListItem (db_type='ListItem', or Long backward-compat with ListItem JSON) IF structure_record.db_type = 'ListItem' OR (structure_record.db_type = 'Long' AND jsonb_typeof(field_json) = 'object') THEN INSERT INTO _values (_id, _id_structure, _id_object, _ListItem, _array_parent_id) VALUES (v_value_id, structure_record.structure_id, p_object_id, (field_json ->> 'id')::bigint, p_parent_value_id); -- Branch 10: Standard primitive types ELSE INSERT INTO _values ( _id, _id_structure, _id_object, _array_parent_id, _String, _Long, _Guid, _Double, _Numeric, _DateTimeOffset, _Boolean, _ByteArray ) VALUES ( v_value_id, structure_record.structure_id, p_object_id, p_parent_value_id, CASE WHEN structure_record.db_type = 'String' THEN field_json #>> '{}' END, CASE WHEN structure_record.db_type = 'Long' THEN (field_json #>> '{}')::bigint END, CASE WHEN structure_record.db_type = 'Guid' THEN (field_json #>> '{}')::uuid END, CASE WHEN structure_record.db_type = 'Double' THEN (field_json #>> '{}')::float END, CASE WHEN structure_record.db_type = 'Numeric' THEN (field_json #>> '{}')::numeric END, CASE WHEN structure_record.db_type IN ('DateTimeOffset', 'DateTime') THEN (field_json #>> '{}')::timestamptz END, CASE WHEN structure_record.db_type = 'Boolean' THEN (field_json #>> '{}')::boolean END, CASE WHEN structure_record.db_type = 'ByteArray' THEN decode(field_json #>> '{}', 'base64') END ); END IF; END IF; END LOOP; END; $BODY$; -- ============================================================ -- 2. MAIN ENTRY POINT -- Mirror of get_object_json (reader) -- JSON → UPSERT _objects → DELETE _values → save properties -- ============================================================ CREATE OR REPLACE FUNCTION save_object_json( p_json_data jsonb ) RETURNS bigint LANGUAGE 'plpgsql' AS $BODY$ DECLARE v_object_id bigint; v_scheme_id bigint; v_properties jsonb; v_exists boolean; BEGIN -- Extract required fields v_object_id := (p_json_data ->> 'id')::bigint; v_scheme_id := (p_json_data ->> 'scheme_id')::bigint; IF v_scheme_id IS NULL THEN RAISE EXCEPTION 'save_object_json: scheme_id is required'; END IF; -- Verify scheme exists IF NOT EXISTS(SELECT 1 FROM _schemes WHERE _id = v_scheme_id) THEN RAISE EXCEPTION 'save_object_json: scheme_id=% not found', v_scheme_id; END IF; -- Generate new ID for new objects (id = 0 or absent) IF v_object_id IS NULL OR v_object_id = 0 THEN v_object_id := nextval('global_identity'); END IF; -- Check if object already exists SELECT EXISTS(SELECT 1 FROM _objects WHERE _id = v_object_id) INTO v_exists; IF v_exists THEN -- ===== UPDATE existing object ===== -- Mirror: base fields from get_object_json output -- Note: _date_create is preserved (not updated) UPDATE _objects SET _id_scheme = v_scheme_id, _id_parent = (p_json_data ->> 'parent_id')::bigint, _id_owner = COALESCE((p_json_data ->> 'owner_id')::bigint, _id_owner), _id_who_change = COALESCE((p_json_data ->> 'who_change_id')::bigint, _id_who_change), _name = p_json_data ->> 'name', _note = p_json_data ->> 'note', _key = (p_json_data ->> 'key')::bigint, _hash = (p_json_data ->> 'hash')::uuid, _date_modify = now(), _date_begin = (p_json_data ->> 'date_begin')::timestamptz, _date_complete = (p_json_data ->> 'date_complete')::timestamptz, _value_long = (p_json_data ->> 'value_long')::bigint, _value_string = p_json_data ->> 'value_string', _value_guid = (p_json_data ->> 'value_guid')::uuid, _value_bool = (p_json_data ->> 'value_bool')::boolean, _value_double = (p_json_data ->> 'value_double')::float, _value_numeric = (p_json_data ->> 'value_numeric')::numeric, _value_datetime = (p_json_data ->> 'value_datetime')::timestamptz, _value_bytes = decode(p_json_data ->> 'value_bytes', 'base64') WHERE _id = v_object_id; -- DeleteInsert strategy: remove all old values before inserting new DELETE FROM _values WHERE _id_object = v_object_id; ELSE -- ===== INSERT new object ===== INSERT INTO _objects ( _id, _id_scheme, _id_parent, _id_owner, _id_who_change, _name, _note, _key, _hash, _date_create, _date_modify, _date_begin, _date_complete, _value_long, _value_string, _value_guid, _value_bool, _value_double, _value_numeric, _value_datetime, _value_bytes ) VALUES ( v_object_id, v_scheme_id, (p_json_data ->> 'parent_id')::bigint, COALESCE((p_json_data ->> 'owner_id')::bigint, 1), COALESCE((p_json_data ->> 'who_change_id')::bigint, 1), p_json_data ->> 'name', p_json_data ->> 'note', (p_json_data ->> 'key')::bigint, (p_json_data ->> 'hash')::uuid, COALESCE((p_json_data ->> 'date_create')::timestamptz, now()), now(), (p_json_data ->> 'date_begin')::timestamptz, (p_json_data ->> 'date_complete')::timestamptz, (p_json_data ->> 'value_long')::bigint, p_json_data ->> 'value_string', (p_json_data ->> 'value_guid')::uuid, (p_json_data ->> 'value_bool')::boolean, (p_json_data ->> 'value_double')::float, (p_json_data ->> 'value_numeric')::numeric, (p_json_data ->> 'value_datetime')::timestamptz, decode(p_json_data ->> 'value_bytes', 'base64') ); END IF; -- Save properties if present (not null, not JSON null) v_properties := p_json_data -> 'properties'; IF v_properties IS NOT NULL AND v_properties != 'null'::jsonb THEN PERFORM save_hierarchical_properties( v_object_id, NULL, -- root level (no parent structure) v_scheme_id, v_properties, NULL -- root level (no parent value) ); END IF; RETURN v_object_id; END; $BODY$; -- ============================================================ -- DOCUMENTATION -- ============================================================ COMMENT ON FUNCTION save_hierarchical_properties(bigint, bigint, bigint, jsonb, bigint) IS 'Recursive property writer — inverse of build_hierarchical_properties_optimized. Walks _scheme_metadata_cache for the given scheme, extracts values from the properties JSON, and INSERTs into _values with correct column routing based on db_type. Handles all 10 field type branches: Arrays (Class / _RObject / primitives) with head+element records Dictionaries (Class / _RObject / primitives) with head+keyed-element records Single Object references (_RObject) — recursive save_object_json for nested objects Class fields — marker record with _Guid + recursive child properties ListItem — extract id from JSON object Primitives — type-based column routing (String/_Long/_Guid/_Double/etc.) Mutual recursion: _RObject fields call save_object_json for nested objects.'; COMMENT ON FUNCTION save_object_json(jsonb) IS 'Save object from JSON — inverse of get_object_json. Strategy: DeleteInsert (UPDATE/INSERT _objects, DELETE all _values, INSERT new _values). Input: JSON in exactly the same format as produced by get_object_json(). Supports: New objects (id=0 or absent): generates ID via nextval(global_identity) Existing objects (id>0): UPDATE base fields, DELETE+re-INSERT values All property types: scalars, arrays, dictionaries, Class fields, Object references Nested objects in _RObject fields: saved recursively via mutual recursion Returns: object _id (bigint).'; Path: redb/redb.Postgres/sql/redb_structure_tree.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.Postgres/sql/redb_structure_tree.sql ---- -- ==================================================================================================== -- FUNCTIONS FOR WORKING WITH SCHEME STRUCTURE TREE -- ==================================================================================================== -- Supports hierarchical navigation through structures: parent → children → descendants -- Solves flat structure search problems in SaveAsync -- ==================================================================================================== -- MAIN FUNCTION: Build scheme structure tree (SIMPLE APPROACH) -- SIMPLE AND CLEAR LOGIC: get current layer → for each structure get children recursively CREATE OR REPLACE FUNCTION get_scheme_structure_tree( scheme_id bigint, parent_id bigint DEFAULT NULL, max_depth integer DEFAULT 10 ) RETURNS jsonb LANGUAGE 'plpgsql' COST 100 VOLATILE NOT LEAKPROOF AS $BODY$ DECLARE result jsonb := '[]'::jsonb; structure_record RECORD; children_json jsonb; BEGIN -- Protection from infinite recursion IF max_depth <= 0 THEN RETURN jsonb_build_array(jsonb_build_object('error', 'Max recursion depth reached')); END IF; -- Check scheme existence IF NOT EXISTS(SELECT 1 FROM _schemes WHERE _id = scheme_id) THEN RETURN jsonb_build_array(jsonb_build_object('error', 'Scheme not found')); END IF; -- AUTOMATIC CACHE CHECK AND FILL IF NOT EXISTS(SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = scheme_id LIMIT 1) THEN PERFORM sync_metadata_cache_for_scheme(scheme_id); -- Auto-fill without NOTICE (use warmup_all_metadata_caches() for explicit warmup) END IF; -- SIMPLE LOGIC: Get structures of CURRENT LEVEL -- OPTIMIZATION: Use _scheme_metadata_cache instead of JOIN _structures ← _types FOR structure_record IN SELECT c._structure_id as _id, c._name, c._order, c._collection_type IS NOT NULL as _is_array, -- _collection_type != NULL = array/dict c._collection_type, c._store_null, c._allow_not_null, c.type_name, c.db_type, c.type_semantic FROM _scheme_metadata_cache c WHERE c._scheme_id = scheme_id AND ((parent_id IS NULL AND c._parent_structure_id IS NULL) OR (parent_id IS NOT NULL AND c._parent_structure_id = parent_id)) ORDER BY c._order, c._structure_id LOOP -- CHECK IF STRUCTURE HAS CHILDREN IF EXISTS(SELECT 1 FROM _structures WHERE _id_scheme = scheme_id AND _id_parent = structure_record._id) THEN -- RECURSIVELY get children (simple function call!) children_json := get_scheme_structure_tree(scheme_id, structure_record._id, max_depth - 1); ELSE -- No children - empty array children_json := '[]'::jsonb; END IF; -- ADD STRUCTURE TO RESULT (simple construction) result := result || jsonb_build_array( jsonb_build_object( 'structure_id', structure_record._id, 'name', structure_record._name, 'order', structure_record._order, 'is_array', structure_record._is_array, -- For compatibility 'collection_type', structure_record._collection_type, -- New collection type 'store_null', structure_record._store_null, 'allow_not_null', structure_record._allow_not_null, 'type_name', structure_record.type_name, 'db_type', structure_record.db_type, 'type_semantic', structure_record.type_semantic, 'children', children_json -- Recursively obtained children ) ); END LOOP; RETURN result; END; $BODY$; -- HELPER FUNCTION: Get only direct child structures CREATE OR REPLACE FUNCTION get_structure_children( scheme_id bigint, parent_id bigint ) RETURNS jsonb LANGUAGE 'plpgsql' COST 50 VOLATILE NOT LEAKPROOF AS $BODY$ BEGIN -- AUTOMATIC CACHE CHECK AND FILL IF NOT EXISTS(SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = scheme_id LIMIT 1) THEN PERFORM sync_metadata_cache_for_scheme(scheme_id); -- Auto-fill without NOTICE (use warmup_all_metadata_caches() for explicit warmup) END IF; -- OPTIMIZATION: Use _scheme_metadata_cache instead of JOIN _structures ← _types RETURN ( SELECT COALESCE(jsonb_agg( jsonb_build_object( 'structure_id', c._structure_id, 'name', c._name, 'order', c._order, 'is_array', c._collection_type IS NOT NULL, -- For compatibility 'collection_type', c._collection_type, -- New collection type 'type_name', c.type_name, 'db_type', c.db_type, 'type_semantic', c.type_semantic ) ORDER BY c._order, c._structure_id ), '[]'::jsonb) FROM _scheme_metadata_cache c WHERE c._scheme_id = scheme_id AND c._parent_structure_id = parent_id ); END; $BODY$; -- DIAGNOSTIC FUNCTION: Validate structure tree for redundancy CREATE OR REPLACE FUNCTION validate_structure_tree( scheme_id bigint ) RETURNS jsonb LANGUAGE 'plpgsql' COST 100 VOLATILE NOT LEAKPROOF AS $BODY$ DECLARE validation_result jsonb; excessive_structures jsonb; orphaned_structures jsonb; circular_references jsonb; BEGIN -- 1. Find excessive structures (structures without values connections) SELECT jsonb_agg( jsonb_build_object( 'structure_id', s._id, 'name', s._name, 'parent_name', parent_s._name, 'issue', 'No values found - possibly excessive structure' ) ) INTO excessive_structures FROM _structures s LEFT JOIN _structures parent_s ON parent_s._id = s._id_parent LEFT JOIN _values v ON v._id_structure = s._id WHERE s._id_scheme = scheme_id AND v._id IS NULL -- No values for this structure AND s._id_parent IS NOT NULL; -- Only child structures -- 2. Find orphaned structures (parent doesn't exist) SELECT jsonb_agg( jsonb_build_object( 'structure_id', s._id, 'name', s._name, 'parent_id', s._id_parent, 'issue', 'Parent structure does not exist' ) ) INTO orphaned_structures FROM _structures s WHERE s._id_scheme = scheme_id AND s._id_parent IS NOT NULL AND NOT EXISTS(SELECT 1 FROM _structures parent_s WHERE parent_s._id = s._id_parent); -- 3. Simple check for circular references (structure references itself via chain) WITH RECURSIVE cycle_check AS ( SELECT _id, _id_parent, ARRAY[_id] as path, false as has_cycle FROM _structures WHERE _id_scheme = scheme_id AND _id_parent IS NOT NULL UNION ALL SELECT s._id, s._id_parent, cc.path || s._id, s._id = ANY(cc.path) FROM _structures s JOIN cycle_check cc ON cc._id_parent = s._id WHERE NOT cc.has_cycle AND array_length(cc.path, 1) < 50 ) SELECT jsonb_agg( jsonb_build_object( 'structure_id', _id, 'path', path, 'issue', 'Circular reference detected' ) ) INTO circular_references FROM cycle_check WHERE has_cycle; -- Form final report validation_result := jsonb_build_object( 'scheme_id', scheme_id, 'validation_date', NOW(), 'excessive_structures', COALESCE(excessive_structures, '[]'::jsonb), 'orphaned_structures', COALESCE(orphaned_structures, '[]'::jsonb), 'circular_references', COALESCE(circular_references, '[]'::jsonb), 'total_structures', (SELECT COUNT(*) FROM _structures WHERE _id_scheme = scheme_id), 'is_valid', (excessive_structures IS NULL AND orphaned_structures IS NULL AND circular_references IS NULL) ); RETURN validation_result; END; $BODY$; -- FUNCTION: Get all structure descendants (flat list) CREATE OR REPLACE FUNCTION get_structure_descendants( scheme_id bigint, parent_id bigint ) RETURNS jsonb LANGUAGE 'plpgsql' COST 100 VOLATILE NOT LEAKPROOF AS $BODY$ BEGIN RETURN ( WITH RECURSIVE descendants AS ( -- Direct child structures SELECT _id, _name, _id_parent, 0 as level FROM _structures WHERE _id_scheme = scheme_id AND _id_parent = parent_id UNION ALL -- Recursively all descendants SELECT s._id, s._name, s._id_parent, d.level + 1 FROM _structures s JOIN descendants d ON d._id = s._id_parent WHERE s._id_scheme = scheme_id AND d.level < 10 ) SELECT COALESCE(jsonb_agg( jsonb_build_object( 'structure_id', _id, 'name', _name, 'parent_id', _id_parent, 'level', level ) ORDER BY level, _id ), '[]'::jsonb) FROM descendants ); END; $BODY$; -- Comments for structure tree functions COMMENT ON FUNCTION get_scheme_structure_tree(bigint, bigint, integer) IS 'Build complete scheme structure tree with hierarchy. Supports recursion depth limit. Used by PostgresSchemeSyncProvider for correct structure traversal in SaveAsync.'; COMMENT ON FUNCTION get_structure_children(bigint, bigint) IS 'Get only direct child structures without recursion. Fast function for simple tree navigation cases.'; COMMENT ON FUNCTION validate_structure_tree(bigint) IS 'Structure tree diagnostics: find excessive structures, orphaned references, circular dependencies. Helps identify issues like with Address.Details.Tags1.'; COMMENT ON FUNCTION get_structure_descendants(bigint, bigint) IS 'Get all structure descendants in flat format with nesting level indication. Useful for analyzing deep hierarchies.'; Path: redb/redb.Postgres/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.Postgres/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() in 99_module_version.sql (applied LAST). -- -- This file must be applied FIRST. It performs two 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 — pvt_module_version() included, which is -- why the version is recreated LAST, in 99_module_version.sql: a -- failure anywhere in between leaves no version, and the next start -- applies the bundle again. -- ===================================================================== -- ---------- Guard: a newer module is never taken back ---------- -- An older package never puts its module over a newer one. Start-up does not apply this script then; -- the guard stops a hand run of an older script (GetUpgradeScript(), redb schema --upgrade) before it -- changes anything, with the sentence of RedbSchemaNewerException. A version that does not read as -- numbers is not newer. _own is the version 99_module_version.sql stamps (a test holds them equal). -- psql goes on after an error unless told to stop: run the script with -v ON_ERROR_STOP=1. DO $$ DECLARE _own constant text := '0.7.33'; _deployed text; _core text; _compat text; _package text; BEGIN IF to_regprocedure('pvt_module_version()') IS NULL THEN RETURN; END IF; EXECUTE 'SELECT pvt_module_version()' INTO _deployed; _core := split_part(coalesce(_deployed, ''), '-', 1); IF _core !~ '^[0-9]{1,9}(\.[0-9]{1,9}){1,3}$' OR string_to_array(_core, '.')::int[] <= string_to_array(_own, '.')::int[] THEN RETURN; END IF; IF to_regprocedure('pvt_module_compat()') IS NOT NULL THEN EXECUTE 'SELECT pvt_module_compat()' INTO _compat; END IF; _package := CASE WHEN position('|' IN coalesce(_compat, '')) > 0 THEN nullif(split_part(_compat, '|', 2), '') END; RAISE EXCEPTION 'The PostgreSQL database carries the redb module %, newer than % of this package, and %. Upgrade the redb packages of this application; the database was left unchanged.', _deployed, _own, CASE WHEN _package IS NULL THEN 'it does not state which packages it serves' ELSE 'it needs redb packages from ' || _package || ' on' END USING ERRCODE = 'object_not_in_prerequisite_state'; END $$; -- ---------- 0. Schema upgrades (idempotent, run on every redeploy) ---------- -- DDL for columns added after a database was created. The base DDL in -- redbPostgre.sql stays the source of truth for fresh databases; this block -- is the delivery to existing ones (SCHEMA_DELIVERY plan, V4). Every -- statement is a no-op once applied. -- 0.7.29: TimeOnly and TimeSpan are stored as Ticks in _Long (they were text, which compared wrong past a day and -- below zero). The type rows and their copy in the metadata cache say Long from now on; values already stored as -- text are not converted (UPGRADING.md gives the statement for a database that wants them). UPDATE _types SET _db_type = 'Long' WHERE _id IN (-9223372036854775685, -9223372036854775684) AND _db_type <> 'Long'; UPDATE _scheme_metadata_cache SET db_type = 'Long' WHERE _type_id IN (-9223372036854775685, -9223372036854775684) AND db_type <> 'Long'; -- 0.7.31: the field-name trigger compares C# keywords as written, not in lower case. C# keywords are case-sensitive, so -- Ref, Default or String are ordinary property names; they were refused at scheme sync ("is a C# reserved word"). -- The same body as in redbPostgre.sql, which a new database gets; this puts it into an existing one. CREATE OR REPLACE FUNCTION validate_structure_name() RETURNS TRIGGER AS $$ DECLARE reserved_fields text[] := ARRAY[ '_id', '_id_parent', '_id_scheme', '_id_owner', '_id_who_change', '_date_create', '_date_modify', '_date_begin', '_date_complete', '_key', '_name', '_note', '_hash', '_value_long', '_value_string', '_value_guid', '_value_bool', '_value_double', '_value_numeric', '_value_datetime', '_value_bytes' ]; field_name text; BEGIN -- Check only on INSERT and UPDATE of _name field IF TG_OP = 'INSERT' OR (TG_OP = 'UPDATE' AND OLD._name IS DISTINCT FROM NEW._name) THEN field_name := LOWER(NEW._name); -- Check 1: Name must not match reserved fields of _objects IF field_name = ANY(reserved_fields) THEN RAISE EXCEPTION 'Field name "_name" cannot match system object fields: %', NEW._name USING ERRCODE = '23514', HINT = 'Use a different name, avoid: ' || array_to_string(reserved_fields, ', '); END IF; -- Check 2: Name must not start with a digit IF NEW._name ~ '^[0-9]' THEN RAISE EXCEPTION 'Field name "_name" cannot start with a digit: %', NEW._name USING ERRCODE = '23514', HINT = 'Field name must start with a letter or underscore'; END IF; -- Check 3: Name must follow C# naming rules (letters, digits, underscores) IF NEW._name !~ '^[a-zA-Z_][a-zA-Z0-9_]*$' THEN RAISE EXCEPTION 'Field name "_name" contains invalid characters: %', NEW._name USING ERRCODE = '23514', HINT = 'Name can only contain Latin letters, digits, underscores. Must start with letter or underscore'; END IF; -- Check 4: Name must not be empty or contain only spaces IF LENGTH(TRIM(NEW._name)) = 0 THEN RAISE EXCEPTION 'Field name "_name" cannot be empty' USING ERRCODE = '23514'; END IF; -- Check 5: Maximum name length (reasonable limit) IF LENGTH(NEW._name) > 64 THEN RAISE EXCEPTION 'Field name "_name" is too long (max 64 characters): %', NEW._name USING ERRCODE = '23514'; END IF; -- Check 6: C# reserved words, compared as written: C# keywords are case-sensitive, so Ref, Default or -- String are ordinary property names and only ref, default, string are refused (0.7.31). IF NEW._name = ANY(ARRAY[ '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' ]) THEN RAISE EXCEPTION 'Field name "_name" is a C# reserved word: %', NEW._name USING ERRCODE = '23514', HINT = 'Use a different name or add prefix/suffix'; END IF; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; -- V4 (UNIQUE stage 2): [RedbUnique] key metadata and the key hash column. ALTER TABLE _structures ADD COLUMN IF NOT EXISTS _unique boolean NULL; ALTER TABLE _structures ADD COLUMN IF NOT EXISTS _unique_version bigint NULL; ALTER TABLE _values ADD COLUMN IF NOT EXISTS _unique uuid NULL; -- S2 (subtree-unique plan, 0.7.7): 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. DO $$ BEGIN IF EXISTS (SELECT 1 FROM pg_indexes WHERE schemaname = 'public' AND indexname = 'UIX__values__structure_unique' AND indexdef LIKE '%_array_parent_id%') THEN DROP INDEX "UIX__values__structure_unique"; END IF; END $$; CREATE UNIQUE INDEX IF NOT EXISTS "UIX__values__structure_unique" ON _values (_id_structure, _unique) INCLUDE (_id_object) WHERE _unique IS NOT NULL; ALTER TABLE _scheme_metadata_cache ADD COLUMN IF NOT EXISTS _unique boolean NULL; ALTER TABLE _scheme_metadata_cache ADD COLUMN IF NOT EXISTS _unique_version bigint NULL; -- V4 (LAZY Л2): the lazy-reference marker, read from `virtual` at synchronisation. ALTER TABLE _structures ADD COLUMN IF NOT EXISTS _lazy boolean NULL; ALTER TABLE _scheme_metadata_cache ADD COLUMN IF NOT EXISTS _lazy boolean NULL; UPDATE _scheme_metadata_cache c SET _lazy = s._lazy FROM _structures s WHERE s._id = c._structure_id AND c._lazy IS DISTINCT FROM s._lazy; -- V4 (UNIQUE stage 1): the object key column and its unique index. ALTER TABLE _objects ADD COLUMN IF NOT EXISTS _value_unique varchar(440) NULL; CREATE UNIQUE INDEX IF NOT EXISTS "UIX__objects__scheme_unique" ON _objects (_id_scheme, _value_unique) INCLUDE (_id) WHERE _value_unique IS NOT NULL; -- S3 (subtree-unique plan, 0.7.8): element-key scope of collection keys, and the free-form -- _tags marker on schemes and structures (future / custom extensions; sync never wipes it). ALTER TABLE _structures ADD COLUMN IF NOT EXISTS _unique_scope bigint NULL; ALTER TABLE _structures ADD COLUMN IF NOT EXISTS _tags varchar(450) NULL; ALTER TABLE _schemes ADD COLUMN IF NOT EXISTS _tags varchar(450) NULL; CREATE INDEX IF NOT EXISTS "IX__structures__tags" ON _structures (_tags) WHERE _tags IS NOT NULL; ALTER TABLE _scheme_metadata_cache ADD COLUMN IF NOT EXISTS _unique_scope bigint NULL; ALTER TABLE _scheme_metadata_cache ADD COLUMN IF NOT EXISTS _tags varchar(450) NULL; UPDATE _scheme_metadata_cache c SET _unique_scope = s._unique_scope, _tags = s._tags FROM _structures s WHERE s._id = c._structure_id AND (c._unique_scope IS DISTINCT FROM s._unique_scope OR c._tags IS DISTINCT FROM s._tags); -- 0.7.27: the previous names of renamed structures and schemes ([RedbRename], RedbScheme.RenamedFrom), oldest -- first, as a JSON array; read by the sync to stop a class older than the rename. ALTER TABLE _structures ADD COLUMN IF NOT EXISTS _renamed_from text NULL; ALTER TABLE _schemes ADD COLUMN IF NOT EXISTS _renamed_from text NULL; -- 0.7.32: 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. NULL counts as 0. ALTER TABLE _schemes ADD COLUMN IF NOT EXISTS _version integer NULL; -- FK-column indexes of _values (perf, 2026-09-10): _Object/_ListItem carry foreign keys, and -- without a leading index every DELETE of a referenced object or list item seq-scans the whole -- table for the FK check. Partial form keeps them 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; -- Index cleanup (0.7.13, 2026-10-12): indexes another index of the same table fully replaces. They -- were removed from redbPostgre.sql, but that file only ever runs CREATE INDEX IF NOT EXISTS on a -- new database, so an existing one keeps them until they are dropped here. -- IX__values__object_structure_array_index - same key as IX__values__object_structure_lookup, -- which has no predicate and carries the values in INCLUDE. -- ix__objects_parent_scheme - commented out of the schema long ago; left behind on older -- databases. Same key and predicate as IX__objects__parent_id_descendant_lookup. -- the rest - a single column that is the leading column of a UNIQUE constraint or of a wider -- index with the same predicate. -- DROP INDEX takes a short exclusive lock on the table; none of these is read by any plan that -- the replacing index cannot serve. DROP INDEX IF EXISTS "IX__values__object_structure_array_index"; DROP INDEX IF EXISTS ix__objects_parent_scheme; DROP INDEX IF EXISTS "IX__functions__schemes"; DROP INDEX IF EXISTS "IX__permissions__roles"; DROP INDEX IF EXISTS "IX__dependencies__schemes_1"; DROP INDEX IF EXISTS "IX__users_roles__roles"; DROP INDEX IF EXISTS "IX__structures__not_collection"; -- 0.7.33: IX__values__array_parent_id (_array_parent_id) is the leading column of IX__values__array_parent_index -- (_array_parent_id, _array_index), which serves the same lookups and the ON DELETE CASCADE of FK__values__array_parent. -- It is dropped only where such a wider index exists: a database created by an old version may lack -- array_parent_index, and the cascade must keep an index. Drop by name only; the other index must be a valid, -- non-partial btree whose first column is _array_parent_id. DO $$ DECLARE _parent smallint; BEGIN IF to_regclass('"IX__values__array_parent_id"') IS NULL THEN RETURN; END IF; SELECT a.attnum INTO _parent FROM pg_attribute a WHERE a.attrelid = '_values'::regclass AND a.attname = '_array_parent_id'; IF EXISTS ( SELECT 1 FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid JOIN pg_am m ON m.oid = c.relam WHERE i.indrelid = '_values'::regclass AND c.relname <> 'IX__values__array_parent_id' AND m.amname = 'btree' AND i.indisvalid AND i.indpred IS NULL AND i.indkey[0] = _parent) THEN DROP INDEX "IX__values__array_parent_id"; END IF; END $$; -- Stock value index retired (0.7.14, 2026-10-12). It and the covering index of the streams form -- (IX__values__structure_object_scalar, redb.Postgres.Pro/Sql/pvt_streams_indexes.sql) were two -- indexes of the same size over the same rows; the queries read the covering one and the -- object-led ones. Measured before retiring it: only the row prefilter over a dictionary item or -- a number got slower, falling back to IX__values__structures (27 -> 52 ms, 3 -> 7 ms). -- IF QUERIES GOT SLOWER AFTER THIS UPGRADE, put it back, CONCURRENTLY so that writes go on: -- CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__structure_object_lookup" -- ON _values (_id_structure, _id_object, _Long, _DateTimeOffset, _Boolean, _Double, _Guid, _Numeric, _ListItem, _Object); -- This file drops it again whenever the module version changes, so report the case. DROP INDEX IF EXISTS "IX__values__structure_object_lookup"; -- Value-leading indexes (0.7.16, 2026-10-16): a filter on a field finds its objects by value. Measured on -- 100 000 employees: three matching rows 6 ms -> 0 ms, 5 % of the scheme 36 -> 10 ms, with the streams form -- that pushes the filter down. They replace the object-leading forms (_id_structure, _id_object, ), -- which only served reading the value of a known object; the covering index of the streams form does that. -- Built inside the module transaction, so not CONCURRENTLY: writes to _values wait while they are built, about -- a minute per index on 38 million rows. Created before the old ones are dropped, so no moment is left without. -- IF QUERIES GOT SLOWER AFTER THIS UPGRADE (the aggregate form, with EnablePvtPrefilter off, read the old ones), -- these bring the old ones back; the module drops them again on its next version change, so report the case: -- CREATE INDEX "IX__values__String_not_null" ON _values (_id_structure, _id_object, _String) WHERE _String IS NOT NULL AND length(_String) < 2000; -- 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; -- An index of one of these names whose definition differs in anything (key columns or their order, INCLUDE, the -- WHERE clause, uniqueness) or that is invalid (an interrupted CREATE INDEX CONCURRENTLY) is dropped and built -- again below: IF NOT EXISTS alone would keep it. A development build of 0.7.15 left them without INCLUDE. DO $$ DECLARE r record; BEGIN FOR r IN SELECT c.relname FROM (VALUES ('IX__values__structure_string_object', 'USING btree (_id_structure, _string, _id_object) INCLUDE (_array_index) WHERE ((_string IS NOT NULL) AND (octet_length(_string) < 2000))'), ('IX__values__structure_long_object', 'USING btree (_id_structure, _long, _id_object) INCLUDE (_array_index) WHERE (_long IS NOT NULL)'), ('IX__values__structure_numeric_object', 'USING btree (_id_structure, _numeric, _id_object) INCLUDE (_array_index) WHERE (_numeric IS NOT NULL)'), ('IX__values__structure_double_object', 'USING btree (_id_structure, _double, _id_object) INCLUDE (_array_index) WHERE (_double IS NOT NULL)'), ('IX__values__structure_datetimeoffset_object', 'USING btree (_id_structure, _datetimeoffset, _id_object) INCLUDE (_array_index) WHERE (_datetimeoffset IS NOT NULL)'), ('IX__values__structure_boolean_object', 'USING btree (_id_structure, _boolean, _id_object) INCLUDE (_array_index) WHERE (_boolean IS NOT NULL)'), ('IX__values__structure_guid_object', 'USING btree (_id_structure, _guid, _id_object) INCLUDE (_array_index) WHERE (_guid IS NOT NULL)'), ('IX__values__structure_listitem_object', 'USING btree (_id_structure, _listitem, _id_object) INCLUDE (_array_index) WHERE (_listitem IS NOT NULL)'), ('IX__values__structure_object_object', 'USING btree (_id_structure, _object, _id_object) INCLUDE (_array_index) WHERE (_object IS NOT NULL)') ) x(name, def) JOIN pg_class c ON c.relname = x.name JOIN pg_index i ON i.indexrelid = c.oid AND i.indrelid = '_values'::regclass WHERE NOT i.indisvalid OR i.indisunique OR substring(pg_get_indexdef(c.oid) from 'USING .*') IS DISTINCT FROM x.def LOOP EXECUTE format('DROP INDEX %I', r.relname); END LOOP; END $$; CREATE INDEX IF NOT EXISTS "IX__values__structure_string_object" ON _values (_id_structure, _String, _id_object) INCLUDE (_array_index) WHERE _String IS NOT NULL AND octet_length(_String) < 2000; CREATE INDEX IF NOT EXISTS "IX__values__structure_long_object" ON _values (_id_structure, _Long, _id_object) INCLUDE (_array_index) WHERE _Long IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_numeric_object" ON _values (_id_structure, _Numeric, _id_object) INCLUDE (_array_index) WHERE _Numeric IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_double_object" ON _values (_id_structure, _Double, _id_object) INCLUDE (_array_index) WHERE _Double IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_datetimeoffset_object" ON _values (_id_structure, _DateTimeOffset, _id_object) INCLUDE (_array_index) WHERE _DateTimeOffset IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_boolean_object" ON _values (_id_structure, _Boolean, _id_object) INCLUDE (_array_index) WHERE _Boolean IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_guid_object" ON _values (_id_structure, _Guid, _id_object) INCLUDE (_array_index) WHERE _Guid IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_listitem_object" ON _values (_id_structure, _ListItem, _id_object) INCLUDE (_array_index) WHERE _ListItem IS NOT NULL; CREATE INDEX IF NOT EXISTS "IX__values__structure_object_object" ON _values (_id_structure, _Object, _id_object) INCLUDE (_array_index) WHERE _Object IS NOT NULL; DROP INDEX IF EXISTS "IX__values__String_not_null"; DROP INDEX IF EXISTS "IX__values__Long_not_null"; DROP INDEX IF EXISTS "IX__values__DateTimeOffset_not_null"; DROP INDEX IF EXISTS "IX__values__Numeric_not_null"; DROP INDEX IF EXISTS ix__values__array_null_structure; -- ---------- 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; -- NOTE: get_object_json() is now OWNED by this module (defined in -- 08_core_object_json.sql), so it is no longer guarded as an external -- prerequisite — it is (re)created later in the same bundle. This lets -- its bug fixes ride the versioned auto-redeploy. -- 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 $$; -- ---------- 3a. Unicode-aware case folding ----------------------------- -- Case folding in PostgreSQL is driven by the collation's ctype. A database -- created with LC_CTYPE=C folds ASCII and nothing else, so on such a database -- 'Привет' ILIKE '%привет%' -> false -- lower('Привет') -> 'Привет' -- while the same statements are correct on a database created with a real -- locale. The fix is to attach an explicit collation to the operand. -- -- The collation name arrives through a GUC rather than a function parameter. -- That is deliberate: every entry point of this module (pvt_build_query_sql and -- friends) would otherwise need an extra argument threaded through five layers, -- which is a signature change on each. The GUC costs nothing at the call sites -- and the C# provider sets it once per connection. -- -- Unset GUC means unchanged behaviour, byte for byte, which is what makes this -- safe to deploy to a database whose owner never asked for it. -- -- STABLE, not IMMUTABLE: the result depends on a run-time setting. CREATE OR REPLACE FUNCTION pvt_fold_case(p_expr text) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_collation text; BEGIN -- The second argument makes a missing setting return NULL instead of raising. v_collation := btrim(coalesce(current_setting('redb.string_collation', true), '')); IF v_collation = '' THEN RETURN p_expr; END IF; -- quote_ident is the escaping, not decoration: the name is an identifier and -- therefore cannot be a bound parameter, so it is concatenated into SQL text. -- It doubles embedded quotes, which neutralises an injected name. RETURN '(' || p_expr || ' COLLATE ' || quote_ident(v_collation) || ')'; END; $BODY$; COMMENT ON FUNCTION pvt_fold_case(text) IS 'Wraps a text expression in COLLATE when redb.string_collation is set, so ILIKE/LOWER/UPPER fold every script and not just ASCII. Returns the expression untouched when the GUC is unset.'; -- ---------- pvt_like_escape: make a sugar operand LITERAL under LIKE/ILIKE ---------- -- BR-7 (2026-09-02): $startsWith/$endsWith/$contains (+IgnoreCase; field, class-field, dict, -- array and expression sugar) splice their operand into a LIKE pattern. The operand is a -- LITERAL by contract: '%'/'_' must not act as wildcards and a backslash must not act as -- LIKE's own escape character (PostgreSQL's default escape). The raw $like/$ilike/$matches -- operators do NOT pass through here - their pattern belongs to the caller. CREATE OR REPLACE FUNCTION pvt_like_escape(p_v text) RETURNS text LANGUAGE sql IMMUTABLE PARALLEL SAFE RETURNS NULL ON NULL INPUT AS $$ SELECT replace(replace(replace(p_v, '\', '\\'), '%', '\%'), '_', '\_') $$; COMMENT ON FUNCTION pvt_like_escape(text) IS 'Escapes LIKE metacharacters (backslash, %, _) so a sugar operand matches literally. BR-7 2026-09-02.'; -- ---------- 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).'; Path: redb/redb.Postgres/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.Postgres/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_unique' THEN '_value_unique' WHEN 'ValueUnique' THEN '_value_unique' WHEN '_value_unique' THEN '_value_unique' 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.Postgres/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.Postgres/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.Postgres/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.Postgres/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.Postgres/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.Postgres/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 -- TimeSpan and TimeOnly are Ticks in _Long (db_type Long): the Long branch compares them. IF 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 := pvt_like_escape(operator_value) || '%'; WHEN '$endsWith' THEN pattern := '%' || pvt_like_escape(operator_value); WHEN '$contains' THEN pattern := '%' || pvt_like_escape(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 := pvt_like_escape(operator_value) || '%'; WHEN '$endsWithIgnoreCase' THEN pattern := '%' || pvt_like_escape(operator_value); WHEN '$containsIgnoreCase' THEN pattern := '%' || pvt_like_escape(operator_value) || '%'; END CASE; RETURN format('%s ILIKE %L', pvt_fold_case('fv._String'), 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' = '_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' = '_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 )', pvt_like_escape(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 )', '%' || pvt_like_escape(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 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 -- 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, TimeOnly: as Long (their Ticks in _Long) 📅 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.'; Path: redb/redb.Postgres/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.Postgres/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, '%' || pvt_like_escape(operator_value) || '%') WHEN '$containsIgnoreCase' THEN format('%s ILIKE %L', pvt_fold_case(format('%I.%I', table_alias, sql_field_name)), '%' || pvt_like_escape(operator_value) || '%') WHEN '$startsWith' THEN format('%I.%I LIKE %L', table_alias, sql_field_name, pvt_like_escape(operator_value) || '%') WHEN '$startsWithIgnoreCase' THEN format('%s ILIKE %L', pvt_fold_case(format('%I.%I', table_alias, sql_field_name)), pvt_like_escape(operator_value) || '%') WHEN '$endsWith' THEN format('%I.%I LIKE %L', table_alias, sql_field_name, '%' || pvt_like_escape(operator_value)) WHEN '$endsWithIgnoreCase' THEN format('%s ILIKE %L', pvt_fold_case(format('%I.%I', table_alias, sql_field_name)), '%' || pvt_like_escape(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', '%' || pvt_like_escape(dict_op_value) || '%') WHEN '$startsWith' THEN format('dv._String LIKE %L', pvt_like_escape(dict_op_value) || '%') WHEN '$endsWith' THEN format('dv._String LIKE %L', '%' || pvt_like_escape(dict_op_value)) WHEN '$containsIgnoreCase' THEN format('%s ILIKE %L', pvt_fold_case('dv._String'), '%' || pvt_like_escape(dict_op_value) || '%') WHEN '$startsWithIgnoreCase' THEN format('%s ILIKE %L', pvt_fold_case('dv._String'), pvt_like_escape(dict_op_value) || '%') WHEN '$endsWithIgnoreCase' THEN format('%s ILIKE %L', pvt_fold_case('dv._String'), '%' || pvt_like_escape(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.Postgres/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.Postgres/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.Postgres/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.Postgres/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.Postgres/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.Postgres/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_unique', o._value_unique, '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.Postgres/sql/v2-pvt/08_core_object_json.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.Postgres/sql/v2-pvt/08_core_object_json.sql ---- -- ===================================================================== -- 08_core_object_json.sql — object<->JSON materializer (core, module-owned) -- --------------------------------------------------------------------- -- The whole object->JSON materializer (get_object_json + get_objects_json + -- build_hierarchical_properties_optimized + build_listitem_jsonb) lives in the -- v2-pvt module, not the core init, so that its bug fixes ride the versioned -- auto-redeploy: bumping pvt_module_version() re-applies this file to existing -- databases via EnsurePvtModuleDeployedAsync, without re-running the full -- redb_init.sql (skipped once _schemes exists). -- -- Definition order matters: get_object_json (plpgsql) is defined BEFORE -- get_objects_json (LANGUAGE sql), whose body references it and is validated -- at CREATE time. -- ===================================================================== DROP VIEW IF EXISTS v_objects_json; DROP FUNCTION IF EXISTS get_object_json; DROP FUNCTION IF EXISTS build_listitem_jsonb; -- Drop old signatures with jsonb parameter (before optimization to _values[]) DROP FUNCTION IF EXISTS build_hierarchical_properties_optimized(bigint, bigint, bigint, jsonb, integer, integer, bigint); DROP FUNCTION IF EXISTS build_hierarchical_properties_optimized(bigint, bigint, bigint, jsonb, integer, text, bigint); -- Drop new signature with _values[] array (if exists) DROP FUNCTION IF EXISTS build_hierarchical_properties_optimized(bigint, bigint, bigint, _values[], integer, text, bigint); -- ===== HELPER: Build ListItem JSON (DRY - used in multiple places) ===== -- The model's keys (RedbListItem: id, id_list, value, alias, id_object). The linked object travels as its -- id; until 0.7.11 it was built in full under "object", a key the deserializer ignores, and the item was -- written as "idList" without "id_object". max_depth stays for the callers. CREATE OR REPLACE FUNCTION build_listitem_jsonb( listitem_id bigint, max_depth integer DEFAULT 10 ) RETURNS jsonb LANGUAGE 'plpgsql' COST 10 STABLE AS $BODY$ BEGIN IF listitem_id IS NULL THEN RETURN NULL; END IF; RETURN (SELECT jsonb_build_object( 'id', li._id, 'id_list', li._id_list, 'value', li._value, 'alias', li._alias, 'id_object', li._id_object ) FROM _list_items li WHERE li._id = listitem_id); END; $BODY$; -- ===== OPTIMIZED FUNCTIONS ===== -- Optimized function for building hierarchical properties with preloaded values array -- 🚀 OPTIMIZATION: Uses _values[] array instead of jsonb - all data in memory, no repeated table queries CREATE OR REPLACE FUNCTION build_hierarchical_properties_optimized( object_id bigint, parent_structure_id bigint, object_scheme_id bigint, all_values _values[], -- 🚀 Array of _values records instead of jsonb max_depth integer DEFAULT 10, array_index text DEFAULT NULL, -- Text to support Dictionary string keys parent_value_id bigint DEFAULT NULL -- ID of parent element for nested arrays ) RETURNS jsonb LANGUAGE 'plpgsql' COST 100 VOLATILE NOT LEAKPROOF AS $BODY$ DECLARE result_json jsonb := '{}'::jsonb; structure_record RECORD; current_value_record _values; -- 🚀 Typed record instead of jsonb field_value jsonb; base_array_value_id bigint; -- ID of base array record for recursion BEGIN -- Protection against infinite recursion for Class fields (hierarchical structures) -- IMPORTANT: This function is for Class fields (Address.Street, Contacts[].Email) -- max_depth is NOT checked here - Class fields are always loaded completely! -- max_depth is controlled only in get_object_json() for Object references (_RObject) IF max_depth < -100 THEN -- Protection against anomalous recursion (practically impossible) RETURN jsonb_build_object('error', 'Max recursion depth reached for hierarchical fields'); END IF; -- 🔥 AUTOMATIC CACHE CHECK AND POPULATION IF NOT EXISTS(SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = object_scheme_id LIMIT 1) THEN -- Cache is empty for this scheme → populate automatically PERFORM sync_metadata_cache_for_scheme(object_scheme_id); -- Auto-population without NOTICE (use warmup_all_metadata_caches() for explicit warmup) END IF; -- Collect all structures for given parent_structure_id (NO JOIN with _values!) -- 🚀 OPTIMIZATION: Use _scheme_metadata_cache instead of JOIN _structures ← _types FOR structure_record IN SELECT c._structure_id as structure_id, c._name as field_name, c._collection_type as collection_type, -- NULL = scalar, Array ID = array, Dictionary ID = dictionary c._collection_type = -9223372036854775668 as _is_array, -- Array type ID c._collection_type = -9223372036854775667 as _is_dictionary, -- Dictionary type ID c.type_name, c.db_type, c.type_semantic, COALESCE(c._lazy, false) as _lazy -- V4 (LAZY Л2) 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)) ORDER BY c._order, c._structure_id LOOP -- 🚀 OPTIMIZATION: Search value from preloaded array using unnest() IF parent_value_id IS NOT NULL THEN -- For nested fields inside array/dictionary elements - find by _array_parent_id SELECT v.* INTO current_value_record FROM unnest(all_values) AS v WHERE v._id_structure = structure_record.structure_id AND v._array_parent_id = parent_value_id LIMIT 1; ELSIF array_index IS NOT NULL THEN -- For array/dictionary elements - find value with specific array_index SELECT v.* INTO current_value_record FROM unnest(all_values) AS v WHERE v._id_structure = structure_record.structure_id AND v._array_index = array_index LIMIT 1; ELSE -- For regular fields or root fields - find first match by structure_id SELECT v.* INTO current_value_record FROM unnest(all_values) AS v WHERE v._id_structure = structure_record.structure_id AND v._array_index IS NULL LIMIT 1; END IF; -- ✅ Get ID of base array record for recursion base_array_value_id := NULL; -- Reset before each field IF structure_record._is_array = true OR structure_record._is_dictionary = true THEN -- Find base array/dictionary record from preloaded data IF parent_value_id IS NULL THEN -- Root array/dictionary: _array_parent_id must be NULL SELECT v._id INTO base_array_value_id FROM unnest(all_values) AS v WHERE v._id_structure = structure_record.structure_id AND v._array_index IS NULL AND v._array_parent_id IS NULL LIMIT 1; ELSE -- Nested array/dictionary: _array_parent_id must match parent_value_id SELECT v._id INTO base_array_value_id FROM unnest(all_values) AS v WHERE v._id_structure = structure_record.structure_id AND v._array_index IS NULL AND v._array_parent_id = parent_value_id LIMIT 1; END IF; END IF; -- Determine field value based on its type and preloaded data field_value := CASE -- If this is an array - process relationally through _array_index WHEN structure_record._is_array = true THEN CASE -- No head record = array property is null (not empty []) WHEN base_array_value_id IS NULL THEN NULL -- Array of Class fields - build from relational data recursively WHEN structure_record.type_semantic = 'Object' THEN ( WITH array_elements AS ( -- Find all array elements with their indices from preloaded data SELECT v._array_index, -- Safe numeric sorting: only for numeric indices (Array), text keys (Dictionary) sort as 0 CASE WHEN v._array_index ~ '^[0-9]+$' THEN v._array_index::int ELSE 0 END as array_index_int, v._id as element_value_id, v._array_parent_id, -- "null must be null" (V-1) + R-1 legacy tolerance: a null -- element is a row WITHOUT _Guid AND WITHOUT children (a true -- null never has children); a class missing its legacy hash -- but having children still reads as an object. CASE WHEN v._Guid IS NULL THEN CASE WHEN EXISTS (SELECT 1 FROM unnest(all_values) c WHERE c._array_parent_id = v._id) THEN build_hierarchical_properties_optimized( object_id, structure_record.structure_id, object_scheme_id, all_values, max_depth, v._array_index, v._id) ELSE 'null'::jsonb END ELSE build_hierarchical_properties_optimized( object_id, structure_record.structure_id, object_scheme_id, all_values, -- 🚀 Pass array, not jsonb max_depth, v._array_index, v._id ) END as element_json FROM unnest(all_values) AS v -- 🚀 From memory array WHERE v._id_structure = structure_record.structure_id AND v._array_index IS NOT NULL AND (base_array_value_id IS NULL OR v._array_parent_id = base_array_value_id) ORDER BY array_index_int, v._array_index -- numeric first, then text ) SELECT CASE WHEN COUNT(*) = 0 THEN '[]'::jsonb -- Empty array = [] ELSE jsonb_agg(element_json ORDER BY array_index_int) END FROM array_elements ) -- Arrays of primitive types (String, Long, Boolean, etc.) - relationally ELSE ( SELECT CASE WHEN COUNT(*) = 0 THEN '[]'::jsonb -- Empty array = [] ELSE jsonb_agg( CASE -- Object references (_RObject) - check by type_semantic WHEN structure_record.type_semantic = '_RObject' AND v._Object IS NOT NULL THEN -- V4 (LAZY Л2): a virtual reference with the session flag on is a stub (depth 0) get_object_json(v._Object, CASE WHEN structure_record._lazy AND current_setting('redb.lazy_refs', true) = '1' THEN 0 ELSE max_depth - 1 END) WHEN structure_record.db_type = 'String' THEN to_jsonb(v._String) WHEN structure_record.db_type = 'Long' THEN -- If _ListItem is filled, process as ListItem (for backward compatibility) CASE WHEN v._ListItem IS NOT NULL THEN build_listitem_jsonb(v._ListItem, max_depth) ELSE to_jsonb(v._Long) END WHEN structure_record.db_type = 'Guid' THEN to_jsonb(v._Guid) WHEN structure_record.db_type = 'Double' THEN to_jsonb(v._Double) WHEN structure_record.db_type = 'Numeric' THEN to_jsonb(v._Numeric) WHEN structure_record.db_type = 'DateTimeOffset' THEN to_jsonb(v._DateTimeOffset) WHEN structure_record.db_type = 'Boolean' THEN to_jsonb(v._Boolean) WHEN structure_record.db_type = 'ListItem' THEN build_listitem_jsonb(v._ListItem, max_depth) WHEN structure_record.db_type = 'ByteArray' THEN to_jsonb(encode(v._ByteArray, 'base64')) ELSE NULL -- Safe sorting: numeric for Array, text for Dictionary END ORDER BY CASE WHEN v._array_index ~ '^[0-9]+$' THEN v._array_index::int ELSE 0 END, v._array_index ) END FROM unnest(all_values) AS v -- 🚀 From memory array WHERE v._id_structure = structure_record.structure_id AND v._array_index IS NOT NULL AND (base_array_value_id IS NULL OR v._array_parent_id = base_array_value_id) ) END -- Dictionary fields - return JSON object with keys WHEN structure_record._is_dictionary = true THEN CASE -- No head record = dictionary property is null (not empty {}) WHEN base_array_value_id IS NULL THEN NULL -- Dictionary of RedbObject references (_RObject) WHEN structure_record.type_semantic = '_RObject' THEN ( SELECT CASE WHEN COUNT(*) = 0 THEN '{}'::jsonb -- Empty dictionary = {} ELSE jsonb_object_agg( v._array_index, -- Key as JSON key CASE WHEN v._Object IS NOT NULL THEN get_object_json(v._Object, CASE WHEN structure_record._lazy AND current_setting('redb.lazy_refs', true) = '1' THEN 0 ELSE max_depth - 1 END) ELSE NULL END ) END FROM unnest(all_values) AS v WHERE v._id_structure = structure_record.structure_id AND v._array_index IS NOT NULL AND (base_array_value_id IS NULL OR v._array_parent_id = base_array_value_id) ) -- Dictionary of Class fields WHEN structure_record.type_semantic = 'Object' THEN ( SELECT CASE WHEN COUNT(*) = 0 THEN '{}'::jsonb -- Empty dictionary = {} ELSE jsonb_object_agg( v._array_index, -- Key as JSON key build_hierarchical_properties_optimized( object_id, structure_record.structure_id, object_scheme_id, all_values, max_depth, NULL, -- array_index = NULL for nested Class fields! v._id -- parent_value_id = element record ID ) ) END FROM unnest(all_values) AS v WHERE v._id_structure = structure_record.structure_id AND v._array_index IS NOT NULL AND (base_array_value_id IS NULL OR v._array_parent_id = base_array_value_id) ) -- Dictionary of primitive types ELSE ( SELECT CASE WHEN COUNT(*) = 0 THEN '{}'::jsonb -- Empty dictionary = {} ELSE jsonb_object_agg( v._array_index, -- Key as JSON key CASE WHEN structure_record.db_type = 'String' THEN to_jsonb(v._String) WHEN structure_record.db_type = 'Long' THEN to_jsonb(v._Long) WHEN structure_record.db_type = 'Guid' THEN to_jsonb(v._Guid) WHEN structure_record.db_type = 'Double' THEN to_jsonb(v._Double) WHEN structure_record.db_type = 'Numeric' THEN to_jsonb(v._Numeric) WHEN structure_record.db_type = 'DateTimeOffset' THEN to_jsonb(v._DateTimeOffset) WHEN structure_record.db_type = 'Boolean' THEN to_jsonb(v._Boolean) ELSE NULL END ) END FROM unnest(all_values) AS v WHERE v._id_structure = structure_record.structure_id AND v._array_index IS NOT NULL AND (base_array_value_id IS NULL OR v._array_parent_id = base_array_value_id) ) END -- Regular fields (not arrays or dictionaries) -- Object reference to another object WHEN structure_record.type_name = 'Object' AND structure_record.type_semantic = '_RObject' THEN CASE WHEN current_value_record._Object IS NOT NULL THEN get_object_json(current_value_record._Object, CASE WHEN structure_record._lazy AND current_setting('redb.lazy_refs', true) = '1' THEN 0 ELSE max_depth - 1 END) ELSE NULL END -- Class field with hierarchical child fields WHEN structure_record.type_semantic = 'Object' THEN CASE WHEN current_value_record._Guid IS NULL THEN NULL -- Class field is truly NULL - don't build object ELSE build_hierarchical_properties_optimized( object_id, structure_record.structure_id, object_scheme_id, all_values, -- 🚀 Pass array, not jsonb max_depth, -- Don't decrease max_depth for Class fields! NULL, -- array_index = NULL for nested Class fields current_value_record._id -- IMPORTANT: pass ID of current Class field record! ) END -- Primitive types - direct access to typed record fields (no JSON parsing!) -- Check _id IS NOT NULL to verify record was found (prevents jsonb null instead of SQL NULL) WHEN structure_record.db_type = 'String' THEN CASE WHEN current_value_record._id IS NOT NULL THEN to_jsonb(current_value_record._String) ELSE NULL END WHEN structure_record.db_type = 'Long' THEN -- If _ListItem is filled, process as ListItem (for backward compatibility) CASE WHEN current_value_record._ListItem IS NOT NULL THEN -- This is ListItem saved in old schema with db_type=Long build_listitem_jsonb(current_value_record._ListItem, max_depth) WHEN current_value_record._id IS NOT NULL THEN to_jsonb(current_value_record._Long) ELSE NULL END WHEN structure_record.db_type = 'Guid' THEN CASE WHEN current_value_record._id IS NOT NULL THEN to_jsonb(current_value_record._Guid) ELSE NULL END WHEN structure_record.db_type = 'Double' THEN CASE WHEN current_value_record._id IS NOT NULL THEN to_jsonb(current_value_record._Double) ELSE NULL END WHEN structure_record.db_type = 'Numeric' THEN CASE WHEN current_value_record._id IS NOT NULL THEN to_jsonb(current_value_record._Numeric) ELSE NULL END WHEN structure_record.db_type = 'DateTimeOffset' THEN CASE WHEN current_value_record._id IS NOT NULL THEN to_jsonb(current_value_record._DateTimeOffset) ELSE NULL END WHEN structure_record.db_type = 'Boolean' THEN CASE WHEN current_value_record._id IS NOT NULL THEN to_jsonb(current_value_record._Boolean) ELSE NULL END WHEN structure_record.db_type = 'ListItem' OR current_value_record._ListItem IS NOT NULL THEN -- Process as ListItem if db_type=ListItem OR if _ListItem is filled (backward compatibility) CASE WHEN current_value_record._ListItem IS NOT NULL THEN build_listitem_jsonb(current_value_record._ListItem, max_depth) ELSE NULL END WHEN structure_record.db_type = 'ByteArray' THEN CASE WHEN current_value_record._ByteArray IS NOT NULL THEN to_jsonb(encode(current_value_record._ByteArray, 'base64')) ELSE NULL END ELSE NULL END; -- Add field to result only if value is not NULL IF field_value IS NOT NULL THEN result_json := result_json || jsonb_build_object(structure_record.field_name, field_value); END IF; END LOOP; RETURN result_json; END; $BODY$; -- OPTIMIZED function for getting object in JSON format with preloaded values array -- 🚀 OPTIMIZATION: Loads all _values into typed array - no JSON parsing overhead CREATE OR REPLACE FUNCTION get_object_json( 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[]; -- 🚀 Typed array instead of jsonb BEGIN -- Check if object exists - return NULL if not found SELECT EXISTS(SELECT 1 FROM _objects WHERE _id = object_id AND _id_scheme <> -10) INTO object_exists; IF NOT object_exists THEN RETURN NULL; END IF; -- Check recursion depth IF max_depth <= 0 THEN -- max_depth = 0: return ONLY base fields WITHOUT properties 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_unique', o._value_unique, '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', replace(encode(o._value_bytes, 'base64'), chr(10), ''), '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; -- Collect base object info + get scheme_id 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_unique', o._value_unique, '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', replace(encode(o._value_bytes, 'base64'), chr(10), ''), '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; -- 🚀 OPTIMIZATION: Load ALL values into typed array - single query, no JSON overhead SELECT array_agg(v) INTO all_values FROM _values v WHERE v._id_object = object_id; -- No _values at all = properties is null (not fake empty {}) IF all_values IS NULL THEN result_json := base_info || jsonb_build_object('properties', NULL); RETURN result_json; END IF; -- Use optimized function with preloaded values array SELECT build_hierarchical_properties_optimized( object_id, NULL, object_scheme_id, COALESCE(all_values, ARRAY[]::_values[]), -- 🚀 Pass typed array max_depth, NULL, -- array_index = NULL for root fields NULL -- parent_value_id = NULL for root level ) INTO properties_info; -- Combine base info with properties result_json := base_info || jsonb_build_object('properties', COALESCE(properties_info, '{}'::jsonb)); RETURN result_json; END; $BODY$; -- BULK-OPTIMIZED VIEW for batch object retrieval in JSON format -- CREATE OR REPLACE VIEW v_objects_json AS -- WITH -- -- Stage 1: BULK load values (optimal - GROUP BY only by ID) -- all_values AS ( -- SELECT -- o._id, -- COALESCE( -- jsonb_object_agg( -- v._id_structure::text, -- jsonb_build_object( -- '_String', v._String, -- '_Long', v._Long, -- '_Guid', v._Guid, -- '_Double', v._Double, -- '_DateTimeOffset', v._DateTimeOffset, -- '_Boolean', v._Boolean, -- '_ByteArray', v._ByteArray, -- '_array_parent_id', v._array_parent_id, -- '_array_index', v._array_index -- ) -- ) FILTER (WHERE v._id IS NOT NULL), -- '{}'::jsonb -- ) as all_values_json -- FROM _objects o -- LEFT JOIN _values v ON v._id_object = o._id -- GROUP BY o._id -- GROUP BY only by ID (fast!) -- ), -- -- Stage 2: Join with _objects fields and build JSON -- objects_with_json AS ( -- SELECT -- o.*, -- All _objects fields with single asterisk (efficient) -- -- Full object JSON with properties -- jsonb_build_object( -- 'id', o._id, -- 'name', o._name, -- 'scheme_id', o._id_scheme, -- 'scheme_name', s._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, -- 'hash', o._hash, -- 'properties', -- build_hierarchical_properties_optimized( -- o._id, -- NULL, -- o._id_scheme, -- av.all_values_json, -- Use preloaded data -- 10, -- NULL -- array_index = NULL for root fields -- ) -- ) as object_json -- FROM _objects o -- JOIN _schemes s ON s._id = o._id_scheme -- JOIN all_values av ON av._id = o._id -- JOIN with preloaded values -- ) -- SELECT * FROM objects_with_json ORDER BY _id; -- -- Comments for OPTIMIZED functions and VIEWs for object retrieval -- COMMENT ON VIEW v_objects_json IS 'MAXIMALLY OPTIMIZED VIEW for object retrieval. Two-stage architecture: 1) BULK _values aggregation with GROUP BY only by _id (fast!) 2) JOIN ready data with _objects via o.* (efficient). Returns ALL original _objects fields as columns PLUS full JSON with properties. Avoids heavy GROUP BY on 17 fields. Perfect for integration and API. Supports hierarchical Class fields.'; COMMENT ON FUNCTION build_hierarchical_properties_optimized(bigint, bigint, bigint, _values[], integer, text, bigint) IS 'Optimized function for recursive building of hierarchical JSON structure with preloaded _values[] array. OPTIMIZATION: Uses typed _values[] array instead of jsonb - all data in memory, no repeated table queries! IMPORTANT: max_depth is NOT decreased for Class fields - they are always loaded completely as part of object structure. max_depth controls ONLY the depth of Object references (_RObject) in get_object_json(). Supports: Relational arrays of Class fields Nested arrays (arrays inside array elements) via array_index and parent_value_id NO JOIN with _values in loop - uses unnest() from memory array! 5-10x faster for objects with arrays due to zero table queries.'; COMMENT ON FUNCTION get_object_json(bigint, integer) IS 'OPTIMIZED function for getting object in JSON format with SMART recursion depth: max_depth = 0: only base fields WITHOUT properties (fast) max_depth >= 1: base fields + properties OPTIMIZATION: Loads ALL _values into typed array - single query, no JSON parsing overhead! IMPORTANT: max_depth controls depth of Object references (_RObject): - Object references are called with max_depth-1 - Class fields (Address, Contacts) are ALWAYS loaded COMPLETELY (max_depth not decreased) - ListItem._id_object also called with max_depth-1 (like regular Object references) Supports: Hierarchical Class fields (Address.Street, Contacts[].Email) - always fully Object references (_RObject) - controlled depth via max_depth ListItem with _id_object (base fields of linked object) Relational arrays of all types Optimal for objects with 10+ fields and arrays.'; -- ============================================================================ -- BULK get_objects_json: single-pass batch loader for many object IDs. -- ---------------------------------------------------------------------------- -- Replaces the legacy "unnest($1::bigint[]) + get_object_json(id, N)" pattern -- used by C# LazyPropsLoader.LoadPropsForManyAsync. The legacy pattern made -- one full plpgsql invocation per object (EXISTS + base SELECT + _values -- SELECT, then recursion), producing 3*N round-trips. This bulk variant does -- one scan of _objects, one scan of _values grouped by _id_object, then a -- single LEFT JOIN that materializes hierarchical properties per row inside -- one execution plan. -- ============================================================================ DROP FUNCTION IF EXISTS get_objects_json(bigint[], integer) CASCADE; CREATE OR REPLACE FUNCTION get_objects_json( p_ids bigint[], p_max_depth integer DEFAULT 10 ) RETURNS TABLE("Id" bigint, "JsonData" text) LANGUAGE 'sql' COST 200 VOLATILE AS $BODY$ WITH bases AS ( SELECT o._id, o._id_scheme, 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_unique', o._value_unique, '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', replace(encode(o._value_bytes, 'base64'), chr(10), ''), 'hash', o._hash ) AS base FROM _objects o JOIN _schemes sc ON sc._id = o._id_scheme WHERE o._id = ANY(p_ids) ), grouped_values AS ( SELECT v._id_object AS oid, array_agg(v) AS vs FROM _values v WHERE v._id_object = ANY(p_ids) GROUP BY v._id_object ) SELECT b._id AS "Id", ( b.base || jsonb_build_object( 'properties', CASE WHEN p_max_depth <= 0 THEN NULL WHEN g.vs IS NULL THEN NULL ELSE COALESCE( build_hierarchical_properties_optimized( b._id, NULL, b._id_scheme, g.vs, p_max_depth, NULL, NULL ), '{}'::jsonb ) END ) )::text AS "JsonData" FROM bases b LEFT JOIN grouped_values g ON g.oid = b._id; $BODY$; COMMENT ON FUNCTION get_objects_json(bigint[], integer) IS 'Bulk JSON materializer for a set of object IDs. Single-plan replacement for "SELECT get_object_json(id, N) FROM unnest($1::bigint[])". Aggregates _values once with GROUP BY _id_object, joins to _objects + _schemes, then calls build_hierarchical_properties_optimized per row from in-memory array. Returns rows compatible with the C# ObjectJsonResult DTO ("Id", "JsonData"). Honors max_depth = 0 (base fields only, properties=null) and absent _values rows (properties=null) the same way as get_object_json.'; -- ===== SIMPLE VIEW FOR OBJECTS WITH JSON ===== -- Drop existing view if exists DROP VIEW IF EXISTS v_objects_json; -- COMMENTED OUT: v_objects_json is inefficient for bulk operations (calls get_object_json for each row) -- For LoadAsync direct SELECT from _objects + LoadPropsForManyAsync (LAZY) or get_object_json batch via unnest (EAGER) is used -- -- Simple view: all _objects fields + JSON via get_object_json -- CREATE VIEW v_objects_json AS -- SELECT -- o.*, -- All _objects fields as is -- get_object_json(o._id, 10) as object_json -- JSON representation of object -- FROM _objects o; -- COMMENT ON VIEW v_objects_json IS 'Simple view for object retrieval: all _objects fields + full JSON via get_object_json. Convenient for viewing and debugging.'; Path: redb/redb.Postgres/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.Postgres/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.Postgres/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.Postgres/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 '_Long' -- Ticks WHEN 'TimeOnly' THEN '_Long' -- Ticks 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.Postgres/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.Postgres/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 o._id AS _id_object, p., ... -- FROM _objects o -- LEFT JOIN ( -- SELECT v._id_object, -- -- FROM _values v -- WHERE v._id_structure = ANY(ARRAY[, , ...]::bigint[]) -- AND v._id_object IN (SELECT o._id FROM _objects o WHERE ) -- GROUP BY v._id_object -- ) p ON p._id_object = o._id -- WHERE -- o._id_scheme = [AND ] -- -- [AND o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree))] -- ) -- 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, o._value_unique'; 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_where 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 ------- -- Always LEFT: an object that stores no value (a null field has no row) is still an object of the source, and -- counts, groups (under NULL) and lists like any other. v_join_kind := 'LEFT JOIN'; -- ------- 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 = ANY(ARRAY(SELECT _id FROM _pvt_tree))' ELSE 'o._id = ANY(ARRAY(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 = ANY(ARRAY(SELECT _id FROM _pvt_tree))'; ELSIF p_source_mode = 'tree_roots' THEN IF v_seed_arr IS NOT NULL THEN -- Root-scoped: WhereRoots() on TreeQuery(rootObj) means the root of THIS tree — the seed -- object itself — not every _id_parent IS NULL object in the scheme. v_cte_parts := v_cte_parts || ( '_pvt_tree(_id, depth) AS (' || E'\n SELECT o._id, 0 FROM _objects o WHERE o._id = ANY(' || v_seed_arr || ')' || E'\n)'); ELSE 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 || E'\n)'); END IF; v_tree_filter := 'o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree))'; ELSIF p_source_mode = 'tree_leaves' THEN IF v_seed_arr IS NOT NULL THEN -- Root-scoped: leaves of THIS subtree, not every scheme leaf (the cross-tree leak). -- Descend from the seed root(s), then keep only childless descendants (depth > 0 drops -- the container root itself). 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 := 'o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree WHERE depth > 0))' || ' AND NOT EXISTS (SELECT 1 FROM _objects c WHERE c._id_parent = o._id)'; ELSE 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)' || E'\n)'); v_tree_filter := 'o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree))'; END IF; 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 = ANY(ARRAY(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: the objects of the source (scheme + base pushdown + -- tree restriction) LEFT JOIN their _values rows of the requested -- structures, grouped by a single column (_id_object). An object with -- no such row keeps its row with NULL columns. -- The outer SELECT must JOIN _objects to expose base columns. -- Eligible iff: narrow flag set, no force_outer, 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_where := format( '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); -- The pivot of the value rows (p), and every object of the source joined to it: an object with no row for any -- requested structure (every field null) keeps its pivot row with NULL columns. Without the outer join it was -- lost, and with it a group, a count, a list row. Pivoting first and joining after is the faster form: the -- pivot grouped straight from _objects LEFT JOIN _values took 975 ms against 810-900 on 100 000 objects. v_inner_pivot := E'SELECT\n o._id AS _id_object' || CASE WHEN array_length(v_pivot_aliases, 1) IS NOT NULL THEN ', p.' || array_to_string(v_pivot_aliases, ', p.') ELSE '' END || E'\n FROM _objects o' || E'\n LEFT JOIN (' || E'\n 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 (SELECT o._id FROM _objects o WHERE ' || v_objects_where || ')' || E'\n GROUP BY v._id_object' || E'\n ) p ON p._id_object = o._id' || E'\n WHERE ' || v_objects_where; 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 LEFT JOIN _values v` GROUP BY 21 base cols) used for null-checks, tree mode, and nested-dict groups; narrow Pro-shape (`FROM _objects o LEFT JOIN _values v ON ... AND _id_structure=ANY(...) 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.Postgres/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.Postgres/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 / _value_unique / _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(). No such item is FALSE, not NULL (0.7.30): -- a missing list or NULL items without a match, so $not of it holds there (!Roles.Any(...)). v_parts := v_parts || (CASE v_op_norm WHEN '$eq' THEN format('COALESCE(%L%s = ANY(%s), FALSE)', 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 -- Only the case-INSENSITIVE half is folded. $like is case-sensitive by -- definition, and attaching a collation to it would cost the index for -- no behavioural gain. v_parts := v_parts || format('%s %s %L', CASE v_op_norm WHEN '$like' THEN v_col ELSE pvt_fold_case(v_col) END, 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, pvt_like_escape(v_op_val #>> '{}') || '%'); ELSIF v_op_norm = '$endswith' THEN v_parts := v_parts || format('%s LIKE %L', v_col, '%' || pvt_like_escape(v_op_val #>> '{}')); ELSIF v_op_norm = '$contains' THEN v_parts := v_parts || format('%s LIKE %L', v_col, '%' || pvt_like_escape(v_op_val #>> '{}') || '%'); ELSIF v_op_norm = '$startswithignorecase' THEN v_parts := v_parts || format('%s ILIKE %L', pvt_fold_case(v_col), pvt_like_escape(v_op_val #>> '{}') || '%'); ELSIF v_op_norm = '$endswithignorecase' THEN v_parts := v_parts || format('%s ILIKE %L', pvt_fold_case(v_col), '%' || pvt_like_escape(v_op_val #>> '{}')); ELSIF v_op_norm = '$containsignorecase' THEN v_parts := v_parts || format('%s ILIKE %L', pvt_fold_case(v_col), '%' || pvt_like_escape(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, pvt_like_escape(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, '%' || pvt_like_escape(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.Postgres/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.Postgres/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.Postgres/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.Postgres/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$; -- ---------- internal helper: place of NULL of one sort key ------------- -- LINQ puts null first ascending and last descending, and so do Pro, SQL -- Server and SQLite; PostgreSQL does the opposite unless told (v0.7.28: -- the module left it to PostgreSQL, so Free PostgreSQL alone put objects -- without a value last ascending). An explicit "nulls" of the entry wins. -- A base column of the object (kind = base) is never NULL and keeps the -- bare direction, as in Pro: NULLS FIRST on an ascending key would stop -- PostgreSQL from reading the order off its index (a page by _id). CREATE OR REPLACE FUNCTION _pvt_order_nulls( p_elem jsonb, p_fields jsonb, p_dir text ) RETURNS text LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_nulls text := lower(COALESCE(p_elem->>'nulls', '')); v_field text; BEGIN IF v_nulls = 'first' THEN RETURN ' NULLS FIRST'; END IF; IF v_nulls = 'last' THEN RETURN ' NULLS LAST'; END IF; IF NOT (p_elem ? '$expr') THEN v_field := COALESCE(p_elem->>'field', p_elem->>'field_path'); IF p_fields -> v_field ->> 'kind' = 'base' THEN RETURN ''; END IF; END IF; RETURN CASE WHEN p_dir = 'desc' THEN ' NULLS LAST' ELSE ' NULLS FIRST' END; 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; oel jsonb; dir text; parts text[] := ARRAY[]::text[]; v_col text; v_keys text[] := ARRAY[]::text[]; v_key_part text; BEGIN -- ---------- DISTINCT ON prefix -------------------------------- -- PostgreSQL requires every DISTINCT ON expression to appear at -- the head of ORDER BY. A key takes the direction of the p_order -- entry for the same expression (OrderByDescending(k).DistinctBy(k) -- comes back descending), ASC when p_order has none; that p_order -- entry is then skipped below so the key is not ordered twice. -- v0.7.17: the key used to be forced ASC. 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); v_key_part := v_col || ' ASC' || _pvt_order_nulls(elem, p_fields, 'asc'); IF p_order IS NOT NULL AND jsonb_typeof(p_order) = 'array' THEN FOR oel IN SELECT value FROM jsonb_array_elements(p_order) LOOP IF _pvt_compile_order_col(oel, p_fields, p_base_prefix) = v_col THEN dir := lower(COALESCE(oel->>'dir', oel->>'direction', 'asc')); v_key_part := v_col || ' ' || upper(dir) || _pvt_order_nulls(oel, p_fields, dir); EXIT; END IF; END LOOP; END IF; parts := parts || v_key_part; v_keys := v_keys || v_col; 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')); 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); IF v_col = ANY(v_keys) THEN CONTINUE; -- already at the head as a DISTINCT ON key END IF; parts := parts || (v_col || ' ' || upper(dir) || _pvt_order_nulls(elem, p_fields, dir)); 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 prepended (PostgreSQL DISTINCT ON requirement) with the direction of the matching p_order entry, ASC when there is none. Returns empty string when both p_order and p_distinct_on are empty.'; Path: redb/redb.Postgres/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.Postgres/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.Postgres/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.Postgres/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, and the "filter" of an aggregate ({"$count":"*","filter":...}). FOR k, v IN SELECT key, value FROM jsonb_each(p_node) LOOP IF left(k, 1) <> '$' AND k <> 'filter' 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; -- Folded for the same reason ILIKE is: UPPER/LOWER take their case mapping from -- the collation's ctype, so on a C-ctype database lower('Привет') is a no-op. -- These back .ToLower()/.ToUpper() in LINQ, and leaving them unfolded while -- fixing ILIKE would let a search match a row that a comparison then rejects. IF lower(v_op_key) = '$upper' THEN RETURN 'UPPER(' || pvt_fold_case(v_a) || ')'; END IF; IF lower(v_op_key) = '$lower' THEN RETURN 'LOWER(' || pvt_fold_case(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 -- Only the case-insensitive half is folded; $like is case-sensitive by definition. RETURN '(' || CASE WHEN v_op = '$like' THEN v_l ELSE pvt_fold_case(v_l) END || 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; v_ci boolean; BEGIN v_ci := right(v_op, length('ignorecase')) = 'ignorecase'; v_kw := CASE WHEN v_ci THEN ' ILIKE ' ELSE ' LIKE ' END; v_lit := CASE WHEN v_op IN ('$contains', '$containsignorecase') THEN quote_literal('%' || pvt_like_escape(v_pat) || '%') WHEN v_op IN ('$startswith', '$startswithignorecase') THEN quote_literal(pvt_like_escape(v_pat) || '%') WHEN v_op IN ('$endswith', '$endswithignorecase') THEN quote_literal('%' || pvt_like_escape(v_pat)) END; RETURN '(' || CASE WHEN v_ci THEN pvt_fold_case(v_l) ELSE v_l END || 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.Postgres/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.Postgres/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.Postgres/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.Postgres/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); -- WhereLevel of a tree query that starts from nodes: the level counts from them (the start is 0, its children 1), -- as the maxDepth of the same query and Pro count it. The walk CTE _pvt_tree carries that depth; a node reached from -- two starts keeps the first depth. Returns the HAVING condition on min(depth) for a $level value (a number or an -- operator object such as {"$gte": 2}). CREATE OR REPLACE FUNCTION pvt_seed_level_having(p_level jsonb) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $BODY$ DECLARE v_parts text := ''; v_op text; v_key text; v_val text; BEGIN IF jsonb_typeof(p_level) = 'number' THEN RETURN 'min(depth) = ' || (p_level #>> '{}')::integer::text; END IF; IF jsonb_typeof(p_level) <> 'object' THEN RAISE EXCEPTION 'pvt_seed_level_having: $level expects a number or an operator object, got %', p_level; END IF; FOR v_key, v_val IN SELECT key, value FROM jsonb_each_text(p_level) LOOP v_op := CASE v_key WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' WHEN '$eq' THEN '=' WHEN '$ne' THEN '<>' END; IF v_op IS NULL THEN RAISE EXCEPTION 'pvt_seed_level_having: unsupported $level operator %', v_key; END IF; v_parts := v_parts || CASE WHEN v_parts = '' THEN '' ELSE ' AND ' END || 'min(depth) ' || v_op || ' ' || v_val::integer::text; END LOOP; RETURN CASE WHEN v_parts = '' THEN 'TRUE' ELSE v_parts END; END; $BODY$; -- The _ord column of pvt_build_query_sql: the position of the row in the order of the query, its ORDER BY and the -- object id after it. The caller wraps the statement as a derived table and sorts by _ord: a subquery keeps no order -- by the standard, and row_number() OVER () above it relied on the plan reading the rows in that order. -- p_order_sql is the ORDER BY clause of the statement (pvt_build_order_conditions, empty when none). CREATE OR REPLACE FUNCTION pvt_ord_column(p_order_sql text, p_id_ref text) RETURNS text LANGUAGE sql IMMUTABLE AS $BODY$ SELECT 'row_number() OVER (' || CASE WHEN COALESCE(btrim(p_order_sql, E' \n'), '') = '' THEN 'ORDER BY ' || p_id_ref ELSE btrim(p_order_sql, E' \n') || ', ' || p_id_ref END || ') AS _ord'; $BODY$; -- A DISTINCT statement numbered around it: the window would make every row distinct inside it. DISTINCT orders by -- the id alone (PostgreSQL keeps an ORDER BY of a DISTINCT SELECT to its select list), so the id gives the position. CREATE OR REPLACE FUNCTION pvt_ord_over_distinct(p_distinct_sql text) RETURNS text LANGUAGE sql IMMUTABLE AS $BODY$ SELECT 'SELECT _dist._id, row_number() OVER (ORDER BY _dist._id) AS _ord FROM (' || E'\n' || p_distinct_sql || E'\n) _dist'; $BODY$; 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; v_seed_level jsonb; v_level_sql text; v_select text; v_id_ref text; 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; -- 0. WhereLevel below start nodes counts from them: it leaves the filter and becomes a condition on the walk -- depth (step 6). Without start nodes (the whole scheme) the level stays absolute, counted from the root. IF p_source_mode IN ('tree', 'tree_descendants', 'tree_children', 'tree_roots', 'tree_leaves') AND p_tree_ids IS NOT NULL AND array_length(p_tree_ids, 1) IS NOT NULL AND jsonb_typeof(p_filter) = 'object' AND p_filter ? '$level' THEN v_seed_level := p_filter -> '$level'; p_filter := p_filter - '$level'; 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; v_select := 'SELECT ' || CASE WHEN p_distinct THEN 'DISTINCT ' ELSE '' END || pvt_build_distinct_on_select(p_distinct_on, v_fields, 'o.') || 'o._id' || CASE WHEN p_distinct THEN '' ELSE ', ' || pvt_ord_column(v_order_sql, 'o._id') END || ' 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; RETURN CASE WHEN p_distinct THEN pvt_ord_over_distinct(v_select) ELSE v_select END; 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; IF v_seed_level IS NOT NULL THEN -- The node id stays outside the subquery, so it binds to the outer row in the wide shape too. v_level_sql := CASE WHEN v_narrow THEN 'o.' ELSE '' END || '_id = ANY(ARRAY(SELECT _id FROM _pvt_tree GROUP BY _id HAVING ' || pvt_seed_level_having(v_seed_level) || '))'; v_where_sql := CASE WHEN v_where_sql = 'TRUE' THEN v_level_sql ELSE '(' || v_where_sql || ') AND ' || v_level_sql 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. -- Every statement returns _id and _ord (see pvt_ord_column); a DISTINCT one is numbered around it. v_id_ref := CASE WHEN v_narrow THEN 'o._id' ELSE '_pvt_cte._id' END; v_select := E'SELECT ' || CASE WHEN p_distinct THEN 'DISTINCT ' ELSE '' END || pvt_build_distinct_on_select(p_distinct_on, v_fields, CASE WHEN v_narrow THEN 'o.' ELSE '' END) || v_id_ref || ' AS _id' || CASE WHEN p_distinct THEN '' ELSE ', ' || pvt_ord_column(v_order_sql, v_id_ref) END || ' FROM _pvt_cte' || CASE WHEN v_narrow THEN E'\nJOIN _objects o ON o._id = _pvt_cte._id_object' ELSE '' END || CASE WHEN v_where_sql = 'TRUE' THEN '' ELSE E'\nWHERE ' || v_where_sql END || v_order_sql || v_paging; IF p_distinct THEN -- The WITH stays in front of the numbering SELECT; the DISTINCT statement becomes its derived table. RETURN v_cte_sql || E'\n' || pvt_ord_over_distinct(v_select); END IF; RETURN v_cte_sql || E'\n' || v_select; 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.Postgres/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.Postgres/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.Postgres/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.Postgres/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_aliases text := ''; 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'); v_inline_aliases := v_inline_aliases || ', p.' || quote_ident(v_fname); IF (v_fmeta->>'list_item_prop') IN ('Value', 'Alias') THEN v_inline_li_join := true; END IF; END LOOP; -- The pivot of the value rows (p), and every object of the scheme joined to it: an object with no row for -- the grouped fields (a null key has no row) is grouped under NULL. An inner join here dropped it, and with -- it the NULL group. Same form as the narrow CTE of pvt_build_cte_sql. v_inline_sql := E'SELECT\n o._id' || v_inline_aliases || E'\n FROM _objects o' || E'\n LEFT JOIN (SELECT v._id_object' || v_inline_cols || E'\n FROM _values v' || CASE WHEN v_inline_li_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_inline_sids || ']::bigint[])' || E'\n AND v._array_index IS NULL' || E'\n AND v._id_object IN (SELECT o._id FROM _objects o 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 GROUP BY v._id_object) p ON p._id_object = o._id' || 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; 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.Postgres/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.Postgres/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.Postgres/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.Postgres/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.Postgres/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.Postgres/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.Postgres/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.Postgres/sql/v2-pvt/26_pvt_array_groupby.sql ---- -- ===================================================================== -- 26_pvt_array_groupby.sql -- --------------------------------------------------------------------- -- GROUP BY over the elements of an array (GroupByArray of the free provider). -- -- pvt_build_array_groupby_sql( -- p_scheme_id bigint, -- p_array_path text, -- path to the array through classes and arrays: -- -- 'Contacts', 'Contacts.Metadata', 'HomeAddress.Building.Amenities' -- p_filter jsonb, -- optional condition on the owning objects (PVT shape) -- p_group_by jsonb, -- non-empty array of {field, alias} -- p_aggregations jsonb, -- optional array of {field, func, alias, filter?} -- p_having jsonb, -- optional boolean expression ($and/$or/$not, comparisons, -- -- $isnull/$notnull, $count/$sum/$avg/$min/$max, $field, $const) -- p_order jsonb, -- optional [{field, asc?}] over outer aliases -- p_limit integer, -- p_offset integer -- ) RETURNS text -- -- A field is a path inside the element ('Type', 'Address.City') or '$element', the element itself -- of an array of simple values. A func is COUNT, SUM, AVG, MIN or MAX; COUNT of '*' with a filter is -- the count of the elements that satisfy it. -- -- Shape (the same in the SQL Server module, the SQLite extension and the Pro builder): -- SELECT , FROM ( -- SELECT -- FROM (SELECT DISTINCT _id FROM () _filt) f -- with a condition -- JOIN _objects o ON o._id = f._id AND o._id_scheme = -- JOIN _values arr ON arr._id_object = f._id AND arr._id_structure = -- AND arr._array_index IS NOT NULL -- LEFT JOIN _values eN ON eN._array_parent_id = ._id AND eN._id_structure = -- AND eN._array_parent_id IS NOT NULL -- ) elements GROUP BY [HAVING ...] -- Without a condition the elements are read off the structure of the array. The elements of the -- last array of the path are found by its structure alone: intermediate levels are not joined. -- -- Everything it cannot answer raises: a path that is not an array, a dictionary in the path, a field -- the elements do not have, '$element' on an array of classes, a field of an array of simple values, -- a collection or a class named as a value, an unknown '$' token, an unknown func. -- ===================================================================== DROP FUNCTION IF EXISTS pvt_build_array_groupby_sql(bigint, text, jsonb, jsonb, jsonb, jsonb, jsonb, integer, integer); -- The column of one element path, with the joins it needs. p_joins maps "|" -- to {alias, parent, sid}; the function returns {col, db_type, joins}. CREATE OR REPLACE FUNCTION pvt_array_element_ref( p_scheme_id bigint, p_array_path text, p_arr_sid bigint, p_arr_db_type text, p_is_class boolean, p_path text, p_joins jsonb ) RETURNS jsonb LANGUAGE plpgsql STABLE AS $BODY$ DECLARE v_segments text[]; v_i integer; v_parent bigint := p_arr_sid; v_alias text := 'arr'; v_key text; v_row record; v_col text; v_joins jsonb := COALESCE(p_joins, '{}'::jsonb); BEGIN IF p_path = '$element' THEN IF p_is_class THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "$element" names the element itself, but the elements of "%" are classes; name a field of the element', p_array_path; END IF; v_col := pvt_db_type_to_value_column(p_arr_db_type); IF v_col IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: the elements of "%" are stored as %, which cannot be grouped or aggregated', p_array_path, p_arr_db_type; END IF; RETURN jsonb_build_object('col', 'arr.' || v_col, 'db_type', p_arr_db_type, 'joins', v_joins); END IF; IF left(p_path, 1) = '$' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" is not a field of the elements of "%"', p_path, p_array_path; END IF; IF NOT p_is_class THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: the elements of "%" are simple values and have no field "%"; use the element itself', p_array_path, p_path; END IF; v_segments := string_to_array(p_path, '.'); FOR v_i IN 1 .. array_length(v_segments, 1) LOOP SELECT c._structure_id, c.db_type, c.type_name, c.collection_type_name INTO v_row FROM _scheme_metadata_cache c WHERE c._scheme_id = p_scheme_id AND c._name = v_segments[v_i] AND c._parent_structure_id = v_parent; IF v_row._structure_id IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" is not a field of the elements of "%"', array_to_string(v_segments[1:v_i], '.'), p_array_path; END IF; IF v_row.collection_type_name IS NOT NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" is a collection inside the element of "%"; group the inner collection instead', array_to_string(v_segments[1:v_i], '.'), p_array_path; END IF; IF v_i < array_length(v_segments, 1) AND v_row.type_name <> 'Class' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" is a value, not a class with fields', array_to_string(v_segments[1:v_i], '.'); END IF; IF v_i = array_length(v_segments, 1) AND v_row.type_name = 'Class' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" is a class; a key or aggregate reads a stored value', p_path; END IF; v_key := v_alias || '|' || v_row._structure_id::text; IF v_joins ? v_key THEN v_alias := v_joins -> v_key ->> 'alias'; ELSE v_joins := v_joins || jsonb_build_object(v_key, jsonb_build_object( 'alias', 'e' || ((SELECT count(*) FROM jsonb_object_keys(v_joins)) + 1)::text, 'parent', v_alias, 'sid', v_row._structure_id)); v_alias := v_joins -> v_key ->> 'alias'; END IF; v_parent := v_row._structure_id; END LOOP; v_col := pvt_db_type_to_value_column(v_row.db_type); IF v_col IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" is stored as %, which cannot be grouped or aggregated', p_path, v_row.db_type; END IF; RETURN jsonb_build_object('col', v_alias || '.' || v_col, 'db_type', v_row.db_type, 'joins', v_joins); END; $BODY$; 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_segment text; v_row record; v_arr record; v_parent bigint := NULL; v_is_class boolean; v_paths text[] := ARRAY[]::text[]; v_path text; v_ref jsonb; v_joins jsonb := '{}'::jsonb; v_fields_map jsonb := '{}'::jsonb; v_inner_select text[] := ARRAY[]::text[]; v_join_sql text := ''; v_entry jsonb; v_alias text; v_func text; v_field text; 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_from text; v_filter_sql 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; -- ---- the array: every segment exists, none is a dictionary, the last one is an array FOREACH v_segment IN ARRAY string_to_array(p_array_path, '.') LOOP SELECT c._structure_id, c.db_type, c.type_name, c.collection_type_name INTO v_row FROM _scheme_metadata_cache c WHERE c._scheme_id = p_scheme_id AND c._name = v_segment AND ((v_parent IS NULL AND c._parent_structure_id IS NULL) OR c._parent_structure_id = v_parent); IF v_row._structure_id IS NULL THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" of the array path "%" is not a field of scheme %', v_segment, p_array_path, p_scheme_id; END IF; IF v_row.collection_type_name = 'Dictionary' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" in the array path "%" is a dictionary; dictionaries are not supported in the array path', v_segment, p_array_path; END IF; v_parent := v_row._structure_id; v_arr := v_row; END LOOP; IF v_arr.collection_type_name IS DISTINCT FROM 'Array' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: "%" is not an array', p_array_path; END IF; v_is_class := v_arr.type_name = 'Class'; -- ---- every element path the statement reads: keys, aggregate operands and conditions, HAVING FOR v_entry IN SELECT value FROM jsonb_array_elements(p_group_by) LOOP v_field := v_entry->>'field'; IF v_field IS NULL OR v_field = '' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: group_by entry missing "field"'; END IF; v_paths := v_paths || v_field; END LOOP; IF p_aggregations IS NOT NULL AND jsonb_typeof(p_aggregations) = 'array' THEN FOR v_entry IN SELECT value FROM jsonb_array_elements(p_aggregations) LOOP v_field := COALESCE(v_entry->>'field', '*'); IF v_field <> '*' THEN v_paths := v_paths || v_field; END IF; IF v_entry ? 'filter' THEN v_paths := v_paths || ARRAY(SELECT n FROM pvt_expr_field_names(v_entry->'filter') n WHERE n IS NOT NULL); END IF; END LOOP; END IF; IF p_having IS NOT NULL AND jsonb_typeof(p_having) = 'object' AND p_having <> '{}'::jsonb THEN v_paths := v_paths || ARRAY(SELECT n FROM pvt_expr_field_names(p_having) n WHERE n IS NOT NULL); END IF; FOR v_path IN SELECT DISTINCT unnest(v_paths) LOOP v_ref := pvt_array_element_ref(p_scheme_id, p_array_path, v_arr._structure_id, v_arr.db_type, v_is_class, v_path, v_joins); v_joins := v_ref -> 'joins'; v_inner_select := v_inner_select || format('%s AS %I', v_ref->>'col', v_path); v_fields_map := v_fields_map || jsonb_build_object(v_path, jsonb_build_object('kind', 'props', 'db_type', v_ref->>'db_type')); END LOOP; SELECT string_agg(format( E'\nLEFT JOIN _values %s ON %s._array_parent_id = %s._id AND %s._id_structure = %s AND %s._array_parent_id IS NOT NULL', j.value->>'alias', j.value->>'alias', j.value->>'parent', j.value->>'alias', j.value->>'sid', j.value->>'alias'), '' ORDER BY substr(j.value->>'alias', 2)::integer) INTO v_join_sql FROM jsonb_each(v_joins) j; v_join_sql := COALESCE(v_join_sql, ''); -- ---- keys FOR v_entry IN SELECT value FROM jsonb_array_elements(p_group_by) LOOP v_field := v_entry->>'field'; v_alias := COALESCE(v_entry->>'alias', v_field); IF v_alias = ANY(v_alias_seen) THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: duplicate alias "%"', v_alias; END IF; v_select_parts := v_select_parts || (quote_ident(v_field) || ' AS ' || quote_ident(v_alias)); v_group_parts := v_group_parts || quote_ident(v_field); v_alias_seen := v_alias_seen || v_alias; END LOOP; -- ---- aggregates IF p_aggregations IS NOT NULL AND jsonb_typeof(p_aggregations) = 'array' THEN FOR v_entry IN SELECT value FROM jsonb_array_elements(p_aggregations) LOOP v_field := COALESCE(v_entry->>'field', '*'); v_func := upper(COALESCE(v_entry->>'func', '')); v_alias := COALESCE(v_entry->>'alias', v_func); IF v_func NOT IN ('COUNT', 'SUM', 'AVG', 'MIN', 'MAX') THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: unknown aggregate function "%"', v_entry->>'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_entry ? 'filter' THEN IF v_func <> 'COUNT' OR v_field <> '*' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: only COUNT(*) takes a filter ("%")', v_alias; END IF; v_select_parts := v_select_parts || ( 'COUNT(CASE WHEN ' || pvt_build_bool_expr(v_entry->'filter', v_fields_map, '') || ' THEN 1 END) AS ' || quote_ident(v_alias)); ELSIF v_field = '*' THEN IF v_func <> 'COUNT' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: % needs a field ("%")', v_func, v_alias; END IF; v_select_parts := v_select_parts || ('COUNT(*) AS ' || quote_ident(v_alias)); ELSE v_select_parts := v_select_parts || (v_func || '(' || quote_ident(v_field) || ') AS ' || quote_ident(v_alias)); END IF; v_alias_seen := v_alias_seen || v_alias; END LOOP; END IF; IF p_having IS NOT NULL AND jsonb_typeof(p_having) = 'object' AND p_having <> '{}'::jsonb THEN v_having_sql := E'\nHAVING ' || pvt_build_bool_expr(p_having, v_fields_map, ''); END IF; -- ---- ORDER BY / paging over the outer aliases IF p_order IS NOT NULL AND jsonb_typeof(p_order) = 'array' AND jsonb_array_length(p_order) > 0 THEN FOR v_entry IN SELECT value FROM jsonb_array_elements(p_order) LOOP v_alias := v_entry->>'field'; IF v_alias IS NULL OR v_alias = '' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: order entry missing "field"'; END IF; -- Null first ascending, last descending, as LINQ and the other engines (v0.7.28; PostgreSQL's own -- order is the opposite). The keys are outputs of the grouping: no index reads them in order. v_ord_parts := v_ord_parts || (quote_ident(v_alias) || CASE WHEN COALESCE((v_entry->>'asc')::boolean, true) THEN ' ASC NULLS FIRST' ELSE ' DESC NULLS LAST' 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; -- ---- source of the elements 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); IF v_filter_sql IS NULL OR v_filter_sql = '' THEN RAISE EXCEPTION 'pvt_build_array_groupby_sql: the condition on the objects did not compile'; END IF; v_from := format( E'FROM (SELECT DISTINCT _id FROM (%s) _filt) f\nJOIN _objects o ON o._id = f._id AND o._id_scheme = %s\nJOIN _values arr ON arr._id_object = f._id AND arr._id_structure = %s AND arr._array_index IS NOT NULL%s', v_filter_sql, p_scheme_id, v_arr._structure_id, v_join_sql); ELSE v_from := format( E'FROM _values arr\nJOIN _objects o ON o._id = arr._id_object AND o._id_scheme = %s%s\nWHERE arr._id_structure = %s AND arr._array_index IS NOT NULL', p_scheme_id, v_join_sql, v_arr._structure_id); END IF; RETURN format( E'SELECT %s\nFROM (\nSELECT %s\n%s\n) elements\nGROUP BY %s%s%s', array_to_string(v_select_parts, ', '), array_to_string(v_inner_select, ', '), v_from, 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 over the elements of an array (path through classes and arrays). Element fields, nested classes of the element and $element of an array of simple values are joined by _array_parent_id; COUNT(*) takes a filter; HAVING through pvt_build_bool_expr. Raises on every form it cannot answer.'; Path: redb/redb.Postgres/sql/v2-pvt/27_migrate_structure_type.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.Postgres/sql/v2-pvt/27_migrate_structure_type.sql ---- -- ============================================================ -- HELPER FUNCTION: get_value_column -- Returns the _values column name for a given type name -- ============================================================ -- DROP FUNCTION IF EXISTS public.get_value_column(text); CREATE OR REPLACE FUNCTION public.get_value_column(p_type_name text) RETURNS text LANGUAGE 'plpgsql' IMMUTABLE AS $BODY$ BEGIN RETURN CASE LOWER(p_type_name) WHEN 'string' THEN '_string' WHEN 'text' THEN '_string' WHEN 'mimetype' THEN '_string' WHEN 'filepath' THEN '_string' WHEN 'filename' THEN '_string' WHEN 'long' THEN '_long' WHEN 'int' THEN '_long' WHEN 'short' THEN '_long' WHEN 'byte' THEN '_long' WHEN 'object' THEN '_object' WHEN 'double' THEN '_double' WHEN 'float' THEN '_double' WHEN 'boolean' THEN '_boolean' WHEN 'datetime' THEN '_datetimeoffset' WHEN 'datetimeoffset' THEN '_datetimeoffset' WHEN 'dateonly' THEN '_datetimeoffset' WHEN 'timeonly' THEN '_long' -- Ticks, as TimeSpan WHEN 'timespan' THEN '_long' WHEN 'guid' THEN '_guid' WHEN 'bytearray' THEN '_bytearray' WHEN 'numeric' THEN '_numeric' WHEN 'listitem' THEN '_listitem' ELSE NULL END; END; $BODY$; COMMENT ON FUNCTION public.get_value_column(text) IS 'Returns the _values column name for a given REDB type name. Examples: SELECT get_value_column(''String''); -- returns ''_string'' SELECT get_value_column(''Long''); -- returns ''_long'''; -- ============================================================ -- FUNCTION: public.migrate_structure_type(bigint, text, text, boolean) -- ============================================================ -- DROP FUNCTION IF EXISTS public.migrate_structure_type(bigint, text, text, boolean); CREATE OR REPLACE FUNCTION public.migrate_structure_type( p_structure_id bigint, p_old_type_name text, p_new_type_name text, p_dry_run boolean DEFAULT false) RETURNS TABLE(affected_rows integer, success_count integer, error_count integer, errors text) LANGUAGE 'plpgsql' COST 100 VOLATILE PARALLEL UNSAFE ROWS 1000 AS $BODY$ DECLARE v_source_col TEXT; v_target_col TEXT; v_affected_rows INT := 0; v_success_count INT := 0; v_has_collision BOOLEAN; v_conversion_sql TEXT; BEGIN -- Get column names v_source_col := get_value_column(p_old_type_name); v_target_col := get_value_column(p_new_type_name); -- Type validation IF v_source_col IS NULL THEN RETURN QUERY SELECT 0, 0, 0, format('Unknown source type: %s', p_old_type_name); RETURN; END IF; IF v_target_col IS NULL THEN RETURN QUERY SELECT 0, 0, 0, format('Unknown target type: %s', p_new_type_name); RETURN; END IF; -- Same columns - migration not needed (e.g., Int->Long both in _Long) IF v_source_col = v_target_col THEN RETURN QUERY SELECT 0, 0, 0, NULL::TEXT; RETURN; END IF; -- Check if structure exists IF NOT EXISTS (SELECT 1 FROM _structures WHERE _id = p_structure_id) THEN RETURN QUERY SELECT 0, 0, 0, format('Structure %s not found', p_structure_id); RETURN; END IF; -- Count affected rows EXECUTE format( 'SELECT COUNT(*) FROM _values WHERE _id_structure = $1 AND %I IS NOT NULL', v_source_col ) INTO v_affected_rows USING p_structure_id; -- Dry run - only counting IF p_dry_run THEN RETURN QUERY SELECT v_affected_rows, 0, 0, NULL::TEXT; RETURN; END IF; -- ======================================== -- COLLISION CHECK (key point!) -- If target is filled and source is empty - data was already migrated manually -- ======================================== EXECUTE format( 'SELECT EXISTS( SELECT 1 FROM _values WHERE _id_structure = $1 AND %I IS NOT NULL AND %I IS NULL LIMIT 1 )', v_target_col, v_source_col ) INTO v_has_collision USING p_structure_id; IF v_has_collision THEN RETURN QUERY SELECT v_affected_rows, 0, v_affected_rows, format('TYPE_MIGRATION_COLLISION: Data already in %s but _id_type = %s. Fix manually: UPDATE _structures SET _id_type = (SELECT _id FROM _types WHERE _name = ''%s'') WHERE _id = %s', v_target_col, p_old_type_name, p_new_type_name, p_structure_id); RETURN; END IF; -- No data to migrate IF v_affected_rows = 0 THEN RETURN QUERY SELECT 0, 0, 0, NULL::TEXT; RETURN; END IF; -- ======================================== -- CONVERSION MATRIX -- ======================================== v_conversion_sql := NULL; -- STRING -> * IF v_source_col = '_string' THEN IF v_target_col = '_long' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::bigint, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL AND %I ~ ''^-?[0-9]+$''', v_target_col, v_source_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_double' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::double precision, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL AND %I ~ ''^-?[0-9]+\.?[0-9]*$''', v_target_col, v_source_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_numeric' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::numeric, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL AND %I ~ ''^-?[0-9]+\.?[0-9]*$''', v_target_col, v_source_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_boolean' THEN -- The IN-list is repeated as a predicate on purpose. Without it the CASE fell through to -- NULL for anything unrecognised while the same statement cleared the source column, so a -- value like 'maybe' was DESTROYED — and counted as a success, because success is measured -- by rows updated. Every other text conversion here is guarded; this one was not. v_conversion_sql := format( 'UPDATE _values SET %I = CASE WHEN LOWER(%I) IN (''true'', ''1'', ''yes'', ''t'', ''y'') THEN TRUE ELSE FALSE END, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL AND LOWER(%I) IN (''true'', ''1'', ''yes'', ''t'', ''y'', ''false'', ''0'', ''no'', ''f'', ''n'')', v_target_col, v_source_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_datetimeoffset' THEN -- Guarded like the numeric branches, and like MSSQL's TRY_CAST. A bare ::timestamptz raised -- on the first unparseable row and aborted the whole migration, so one bad value blocked -- every good one — and the failure arrived as a raw SQL error rather than a report. v_conversion_sql := format( 'UPDATE _values SET %I = %I::timestamptz, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL AND %I ~ ''^\d{4}-\d{2}-\d{2}''', v_target_col, v_source_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_guid' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::uuid, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL AND %I ~* ''^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$''', v_target_col, v_source_col, v_source_col, v_source_col, v_source_col); END IF; -- LONG -> * ELSIF v_source_col = '_long' THEN IF v_target_col = '_string' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::text, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_double' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::double precision, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_numeric' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::numeric, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_boolean' THEN v_conversion_sql := format( 'UPDATE _values SET %I = (%I != 0), %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_datetimeoffset' THEN v_conversion_sql := format( 'UPDATE _values SET %I = to_timestamp(%I), %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); END IF; -- DOUBLE -> * ELSIF v_source_col = '_double' THEN IF v_target_col = '_string' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::text, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_long' THEN v_conversion_sql := format( 'UPDATE _values SET %I = ROUND(%I)::bigint, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_numeric' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::numeric, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); END IF; -- NUMERIC -> * ELSIF v_source_col = '_numeric' THEN IF v_target_col = '_string' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::text, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_long' THEN v_conversion_sql := format( 'UPDATE _values SET %I = ROUND(%I)::bigint, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_double' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::double precision, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); END IF; -- BOOLEAN -> * ELSIF v_source_col = '_boolean' THEN IF v_target_col = '_string' THEN v_conversion_sql := format( 'UPDATE _values SET %I = CASE WHEN %I THEN ''true'' ELSE ''false'' END, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_long' THEN v_conversion_sql := format( 'UPDATE _values SET %I = CASE WHEN %I THEN 1 ELSE 0 END, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); END IF; -- DATETIMEOFFSET -> * ELSIF v_source_col = '_datetimeoffset' THEN IF v_target_col = '_string' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::text, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); ELSIF v_target_col = '_long' THEN v_conversion_sql := format( 'UPDATE _values SET %I = EXTRACT(EPOCH FROM %I)::bigint, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); END IF; -- GUID -> * ELSIF v_source_col = '_guid' THEN IF v_target_col = '_string' THEN v_conversion_sql := format( 'UPDATE _values SET %I = %I::text, %I = NULL WHERE _id_structure = $1 AND %I IS NOT NULL', v_target_col, v_source_col, v_source_col, v_source_col); END IF; END IF; -- Conversion not supported IF v_conversion_sql IS NULL THEN RETURN QUERY SELECT v_affected_rows, 0, v_affected_rows, format('Conversion %s -> %s not supported', p_old_type_name, p_new_type_name); RETURN; END IF; -- Execute migration EXECUTE v_conversion_sql USING p_structure_id; GET DIAGNOSTICS v_success_count = ROW_COUNT; -- V4 (P3): a SQL-side writer does not know the canonical form - the keys of the touched rows -- are released; scheme synchronisation recomputes them (rows with a value and no key are its -- trigger). NULL takes rows OUT of uniqueness instead of faking it. -- AFTER the ROW_COUNT capture: the migration's own success count must not measure this UPDATE. UPDATE _values SET _unique = NULL WHERE _id_structure = p_structure_id AND _unique IS NOT NULL; RETURN QUERY SELECT v_affected_rows, v_success_count, v_affected_rows - v_success_count, NULL::TEXT; END; $BODY$; COMMENT ON FUNCTION public.migrate_structure_type(bigint, text, text, boolean) IS 'Atomic data migration when changing structure type. Parameters: p_structure_id - structure ID in _structures p_old_type_name - old type name (String, Long, Double, etc.) p_new_type_name - new type name p_dry_run - TRUE for test run without changes Returns: affected_rows - total rows with data success_count - successfully migrated error_count - failed to migrate errors - error text (NULL if success) Returns TYPE_MIGRATION_COLLISION error if data is already in target column. Examples: SELECT * FROM migrate_structure_type(12345, ''String'', ''Long'', TRUE); -- dry run SELECT * FROM migrate_structure_type(12345, ''String'', ''Long'', FALSE); -- execute'; Path: redb/redb.Postgres/sql/v2-pvt/28_migrate_dateonly_db_type.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.Postgres/sql/v2-pvt/28_migrate_dateonly_db_type.sql ---- -- ===================================================== -- MIGRATION: DateOnly gets db_type 'DateTimeOffset' (PostgreSQL) -- ===================================================== -- DateOnly was seeded with _db_type = 'DateTime', a value no other type uses and -- no JSON projection knows about: get_object_json switches on _db_type and has -- branches for 'DateTimeOffset', 'String', 'Long', ... but none for 'DateTime'. -- The column was written correctly and then dropped on the way out, so every -- DateOnly property materialised as 0001-01-01 on every provider. -- -- Retyping it to 'DateTimeOffset' routes it through the branch that already -- exists everywhere — JSON projections, PVT builders and the SQLite native -- extension — with no change to any SQL function and no PVT version bump. -- Storage is unchanged: the value already lives in _values._DateTimeOffset as -- midnight of that date. -- -- Idempotent. Run on existing databases; new ones get the right value from -- redbPostgre.sql. -- ===================================================== UPDATE _types SET _db_type = 'DateTimeOffset' WHERE _id = -9223372036854775686 -- DateOnly AND _db_type <> 'DateTimeOffset'; -- The scheme metadata cache copies _db_type, so every scheme with a DateOnly field must be -- resynced after the retype. That resync lives at the TAIL of 29_metadata_cache_sync.sql, not -- here (BR-5): a top-level call in this file is planned by a FRESH database before the 29th -- file has created the function - 42883, and the whole generated redb_init.sql died mid-way. -- Lived-in databases kept the previous version of the function (00 does not drop it) and never -- noticed, which is why the defect hid until the first truly fresh install. -- ===================================================== -- VERIFICATION -- ===================================================== -- SELECT _name, _db_type, _type FROM _types WHERE _id = -9223372036854775686; -- expected: DateOnly | DateTimeOffset | DateOnly Path: redb/redb.Postgres/sql/v2-pvt/29_metadata_cache_sync.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.Postgres/sql/v2-pvt/29_metadata_cache_sync.sql ---- -- ============================================================ -- METADATA CACHE SYNC — module-owned since V4 -- ============================================================ -- sync_metadata_cache_for_scheme and warmup_all_metadata_caches carry the -- column list of _scheme_metadata_cache. A new _structures column (V4: -- _unique, _unique_version) must appear in that list on EXISTING databases, -- and sql/redb_metadata_cache.sql lands only in redb_init.sql — fresh -- databases only. So the two functions ride the versioned bundle, exactly -- like get_object_json (08_core_object_json.sql): their fixes and column -- lists redeploy whenever pvt_module_version() disagrees with the build. -- -- The cache TABLE, its indexes and the triggers stay in -- sql/redb_metadata_cache.sql: the triggers call these functions by name at -- run time, so recreating the functions here is enough. Column additions to -- the table itself go through the "0. Schema upgrades" block of -- 00_module_init.sql. -- ============================================================ DROP FUNCTION IF EXISTS sync_metadata_cache_for_scheme(bigint); DROP FUNCTION IF EXISTS warmup_all_metadata_caches(); CREATE OR REPLACE FUNCTION sync_metadata_cache_for_scheme(target_scheme_id bigint) RETURNS void AS $$ BEGIN -- Remove old scheme data DELETE FROM _scheme_metadata_cache WHERE _scheme_id = target_scheme_id; -- Insert current data (with support for collection types and scheme type) 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, -- Scheme type scht._name, -- Scheme type name s._order, s._collection_type, -- Collection type (Array/Dictionary/NULL) ct._name, -- Collection type name s._key_type, -- Key type for Dictionary kt._name, -- Key type name s._readonly, s._allow_not_null, s._is_compress, s._store_null, s._unique, -- V4: unique key flag ([RedbUnique]) s._unique_version, -- V4: encoder version of the stored keys s._unique_scope, -- S3: element-key scope of a collection key s._lazy, -- V4 (LAZY Л2): lazy reference marker s._tags, -- V4: free-form marker 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 -- Scheme type LEFT JOIN _types ct ON ct._id = s._collection_type -- Collection type LEFT JOIN _types kt ON kt._id = s._key_type -- Key type WHERE s._id_scheme = target_scheme_id; -- NOTICE removed to avoid spam during mass warmup -- Use warmup_all_metadata_caches() to get statistics END; $$ LANGUAGE plpgsql; -- Warmup function (for application startup or after crash) CREATE OR REPLACE FUNCTION warmup_all_metadata_caches() RETURNS TABLE(scheme_id bigint, structures_count bigint, scheme_name text, structure_hash uuid) AS $$ BEGIN TRUNCATE _scheme_metadata_cache; -- Rebuild cache for ALL schemes (removed filter for _structure_hash) PERFORM sync_metadata_cache_for_scheme(s._id) FROM _schemes s; -- Return statistics for ALL schemes RETURN QUERY SELECT s._id as scheme_id, COUNT(c._structure_id) as structures_count, s._name::text as scheme_name, s._structure_hash as structure_hash FROM _schemes s LEFT JOIN _scheme_metadata_cache c ON c._scheme_id = s._id GROUP BY s._id, s._name, s._structure_hash ORDER BY s._id; END; $$ LANGUAGE plpgsql; COMMENT ON FUNCTION warmup_all_metadata_caches() IS 'Warms up metadata cache for ALL schemes (including schemes without _structure_hash). Recommended to call: 1. On application startup 2. After PostgreSQL crash (UNLOGGED TABLE is cleared) 3. After schema migrations Returns statistics: scheme_id → number of structures for all schemes. Usage: SELECT * FROM warmup_all_metadata_caches(); UPDATED: Now warms up ALL schemes, not only those with _structure_hash IS NOT NULL. This eliminates auto-filling of cache on every query to v_objects_json. '; -- ===================================================== -- Repair pass moved here from 28_migrate_dateonly_db_type.sql (BR-5): the cache copies _db_type, -- so every scheme with a DateOnly field is resynced after the retype in 28. It must run AFTER the -- function above exists - in 28 a fresh database planned the call before this file had created it -- and the whole init died with 42883; here it holds for any history, dump-restored databases -- included. Idempotent and cheap: only schemes that actually have a DateOnly structure. -- ===================================================== SELECT sync_metadata_cache_for_scheme(s._id) FROM _schemes s WHERE EXISTS (SELECT 1 FROM _structures st WHERE st._id_scheme = s._id AND st._id_type = -9223372036854775686); Path: redb/redb.Postgres/sql/v2-pvt/30_soft_delete.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.Postgres/sql/v2-pvt/30_soft_delete.sql ---- -- ===================================================== -- SOFT DELETE FUNCTIONS FOR POSTGRESQL - module-owned since V4 -- ===================================================== -- Moved from sql/redb_soft_delete.sql: that location lands only in -- redb_init.sql, i.e. fresh databases. mark_for_deletion now also releases -- unique keys (_values._unique = NULL, UNIQUE plan decision 9), and that -- change must reach existing databases - so the functions ride the -- versioned bundle. Part of Background Deletion System. -- ===================================================== -- Drop existing functions if any DROP FUNCTION IF EXISTS mark_for_deletion(bigint[], bigint); DROP FUNCTION IF EXISTS mark_for_deletion(bigint[], bigint, bigint); DROP FUNCTION IF EXISTS purge_trash(bigint, integer); -- ===================================================== -- FUNCTION: mark_for_deletion -- Marks objects for deletion by moving them under a trash container -- Creates trash container, finds all descendants via CTE, updates parent and scheme -- All operations in single transaction (atomic) -- p_trash_parent_id: optional parent for trash container (NULL = root level) -- ===================================================== CREATE OR REPLACE FUNCTION mark_for_deletion( p_object_ids bigint[], p_user_id bigint, p_trash_parent_id bigint DEFAULT NULL ) RETURNS TABLE(trash_id bigint, marked_count bigint) AS $$ DECLARE v_trash_id bigint; v_count bigint; BEGIN -- 1. Create Trash container object with @@__deleted scheme -- Progress fields: _value_long=total, _key=deleted, _value_string=status INSERT INTO _objects ( _id, _id_scheme, _id_parent, _id_owner, _id_who_change, _name, _date_create, _date_modify, _value_long, _key, _value_string ) VALUES ( nextval('global_identity'), -10, -- @@__deleted scheme p_trash_parent_id, -- user-specified parent or NULL p_user_id, p_user_id, '__TRASH__' || p_user_id || '_' || extract(epoch from now())::bigint, NOW(), NOW(), 0, -- _value_long = total (will be updated after count) 0, -- _key = deleted 'pending' -- _value_string = status ) RETURNING _id INTO v_trash_id; -- 2. CTE: find all objects and their descendants recursively -- 3. UPDATE: move all found objects under Trash container and change scheme WITH RECURSIVE all_descendants AS ( -- Start with requested objects SELECT _id FROM _objects WHERE _id = ANY(p_object_ids) AND _id_scheme != -10 -- skip already deleted UNION ALL -- Recursively find children SELECT o._id FROM _objects o INNER JOIN all_descendants d ON o._id_parent = d._id WHERE o._id_scheme != -10 -- skip already deleted ) UPDATE _objects SET _id_parent = v_trash_id, _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 = NOW() WHERE _id IN (SELECT _id FROM all_descendants) -- On the target row, so it is checked again on the version a concurrent soft delete committed while this -- one waited for the row lock: without it the object moved into a second trash and was counted. AND _id_scheme != -10; GET DIAGNOSTICS v_count = ROW_COUNT; -- V4 (UNIQUE, decision 9): a soft-deleted object releases its keys, whole and at once. -- Without this the trash scheme (-10) acts as one more uniqueness namespace and a repeated -- or cross-scheme delete fails on the unique index. Same transaction as the move above: -- there is no window where the object is in the trash but its key is still taken. UPDATE _values SET _unique = NULL WHERE _unique IS NOT NULL AND _id_object IN (SELECT _id FROM _objects WHERE _id_parent = v_trash_id AND _id_scheme = -10); -- 4. Update trash container with total count UPDATE _objects SET _value_long = v_count WHERE _id = v_trash_id; -- 5. Return trash container ID and count of marked objects RETURN QUERY SELECT v_trash_id, v_count; END; $$ LANGUAGE plpgsql; COMMENT ON FUNCTION mark_for_deletion(bigint[], bigint, bigint) IS 'Marks objects for soft-deletion. Creates a trash container, moves all specified objects and their descendants under it with scheme=@@__deleted. Returns (trash_id, marked_count). p_trash_parent_id: optional parent ID for trash container (NULL = root level). Atomic operation - all or nothing.'; -- ===================================================== -- FUNCTION: purge_trash -- Physically deletes objects from a trash container in batches -- ON DELETE CASCADE handles _values deletion automatically -- Updates progress in trash container (_key=deleted, _value_string=status) -- After all children deleted, removes the trash container itself -- -- References (_values._Object, a foreign key with no ON DELETE action): -- * a reference held by an object that is itself in the trash dies with the purge - the -- referencing value row is removed first, so the order containers are purged in never matters; -- * an object referenced by a LIVE object is skipped, never deleted and never unlinked (nulling -- a live reference would hide the caller's bug inside another object's data). When nothing -- but such objects is left, the container is marked 'failed': the background worker stops -- claiming it, and the caller learns which references hold it. -- ===================================================== CREATE OR REPLACE FUNCTION purge_trash( p_trash_id bigint, p_batch_size integer DEFAULT 10 ) RETURNS TABLE(deleted_count bigint, remaining_count bigint) AS $$ DECLARE v_batch bigint[]; v_deleted bigint; v_remaining bigint; BEGIN -- Update status to 'running' if it was 'pending' UPDATE _objects SET _value_string = 'running', _date_modify = NOW() WHERE _id = p_trash_id AND _value_string = 'pending'; -- The batch: objects of this container that no live object references SELECT COALESCE(array_agg(c._id), ARRAY[]::bigint[]) INTO v_batch FROM ( SELECT o._id FROM _objects o WHERE o._id_parent = p_trash_id AND NOT EXISTS ( SELECT 1 FROM _values v INNER JOIN _objects r ON r._id = v._id_object WHERE v._Object = o._id AND r._id_scheme <> -10) LIMIT p_batch_size ) c; -- References to the batch held by trashed objects go first. Restricted to trashed holders on -- purpose: a live reference written after the batch was chosen makes the delete below fail -- loudly instead of being removed here. DELETE FROM _values v USING _objects r WHERE v._Object = ANY(v_batch) AND r._id = v._id_object AND r._id_scheme = -10; -- Delete the batch (CASCADE handles its own _values) DELETE FROM _objects WHERE _id = ANY(v_batch); GET DIAGNOSTICS v_deleted = ROW_COUNT; -- Count remaining objects in this trash SELECT COUNT(*) INTO v_remaining FROM _objects WHERE _id_parent = p_trash_id; -- Update progress in trash container. An empty batch while objects remain = every one of them -- is referenced by a live object: 'failed', no longer claimed by the background worker. A batch -- that deleted nothing is another purger's work - the rows went between choosing the batch and -- deleting it - and the container stays 'running': the next batch takes what is left. UPDATE _objects SET _key = _key + v_deleted, _value_string = CASE WHEN v_remaining = 0 THEN 'completed' WHEN cardinality(v_batch) = 0 THEN 'failed' ELSE 'running' END, _date_modify = NOW() WHERE _id = p_trash_id; -- If no more children, delete the trash container itself IF v_remaining = 0 THEN DELETE FROM _objects WHERE _id = p_trash_id; END IF; RETURN QUERY SELECT v_deleted, v_remaining; END; $$ LANGUAGE plpgsql; COMMENT ON FUNCTION purge_trash(bigint, integer) IS 'Physically deletes objects from a trash container in batches. p_trash_id: ID of the trash container created by mark_for_deletion. p_batch_size: Number of objects to delete per call (default 10). Returns (deleted_count, remaining_count). When remaining=0, trash container is also deleted. Objects referenced by live objects are skipped; deleted_count = 0 with remaining_count > 0 means only such objects are left, and the container is marked failed. Call repeatedly until remaining_count = 0 or deleted_count = 0.'; Path: redb/redb.Postgres/sql/v2-pvt/99_module_version.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.Postgres/sql/v2-pvt/99_module_version.sql ---- -- ===================================================================== -- v2-pvt module version (PostgreSQL) -- ===================================================================== -- This file is applied LAST on purpose. The version function is what the -- C# client compares on start-up to decide whether the module must be -- (re)applied, so it must come into existence only after every other file -- of the module has succeeded. Step 2 of 00_module_init.sql drops every -- pvt_* function, this one included; a failure anywhere in the middle of -- the bundle therefore leaves the database with NO version function, the -- next start treats the module as missing and applies the bundle again. -- With the function created first (as it was until 0.6.8) a mid-bundle -- failure left the NEW version next to the OLD functions, and nothing ever -- retried. -- ===================================================================== -- ---------- 3. Module compatibility function --------------------------- -- What this module still serves: '|'. A package whose module -- is older than this one never puts its own module back: it starts when its -- version is not below the first part, and stops otherwise, naming the -- package version from the second part. Raise the first part only when a -- change breaks the C# of older packages (a dropped or renamed function, a -- changed signature, a column the old code reads); never lower it. -- Created before the version function: a module that reports a version -- always has this function too. CREATE OR REPLACE FUNCTION pvt_module_compat() RETURNS text LANGUAGE sql IMMUTABLE AS $BODY$ SELECT '0.7.25|4.8.0'::text; $BODY$; -- ---------- 4. 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.7.14 - the stock value index IX__values__structure_object_lookup is retired (2026-10-12): -- dropped from existing databases (00_module_init.sql), no longer created on new ones -- (redbPostgre.sql). The statement that brings it back is kept in both files. No function changed. -- 0.7.13 - index cleanup (2026-10-12): seven indexes that another index of the same table fully -- replaces are dropped from existing databases (00_module_init.sql) and no longer created on -- new ones (redbPostgre.sql). No function changed; the bump exists so that existing databases -- re-run the module and lose the redundant indexes. -- 0.7.12 - purge_trash marks 'failed' on an empty batch, not on a batch that deleted nothing -- (2026-09-16): a batch chosen here and deleted by a concurrent purger meanwhile - the -- background worker beside a caller's PurgeTrashAsync, another node - failed the container with -- nothing blocking it, and the caller got RedbObjectReferencedException naming no referrer. -- 0.7.11 - list item JSON in the model's shape (2026-09-15): build_listitem_jsonb writes -- {id, id_list, value, alias, id_object}. It wrote {id, idList, value, alias, object}: the model -- reads id_list / id_object, so every load lost the list link and the object link of the items, -- and the linked object was built in full for a key the deserializer ignores. -- 0.7.10 - purge_trash and references (trash review, 2026-09-14): a reference held by a trashed -- object is removed with the purge instead of failing it on the foreign key; an object -- referenced by a live object is skipped, and a container left with nothing else is marked -- 'failed' instead of being retried forever. -- 0.7.9 - soft delete resets _objects._hash (full-object hash, 2026-09-11): the trash move -- changes parent and key outside the save path; a props-cache copy must not outlive it. -- 0.7.8 - block 0: S3 - _structures._unique_scope (element-key scope), _tags on schemes, -- structures and the metadata cache (free-form marker), IX__structures__tags; -- sync_metadata_cache_for_scheme carries the two new columns. -- 0.7.7 - block 0: UIX__values__structure_unique recreated without the positional filter -- (S2, subtree-unique plan): nested scalar keys carry _array_parent_id, the old predicate -- kept them out of the index, so their uniqueness silently never fired. -- 0.7.6 - block 0: 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 seq-scanned the -- whole _values for the FK check (perf finding, 2026-09-10). -- 0.7.5 - root value_bytes emitted as base64 (was bytea hex; bug report BUG_BYTES �3.2). -- 0.7.4 - Р-1 (2026-09-03): legacy-толерантность - null-элемент класса определяется -- как «без _Guid И без детей»; класс без исторического хеша с детьми читается. -- 0.7.3 - В-1 «null должен быть null» (2026-09-03): null-элемент коллекции классов -- (строка без _Guid) эмитится JSON-null, а не пустым объектом. -- 0.7.2 - BR-7 (2026-09-02): pvt_like_escape() - the operand of every LIKE/ILIKE sugar -- operator (field, class-field, dict, array, expression) is a LITERAL now; the raw -- $like/$ilike/$matches operators keep the caller's pattern. -- 0.7.1 - V4 LAZY L2 (lazy references): -- * block 0: _structures._lazy and _scheme_metadata_cache._lazy (the virtual marker). -- * 29: the metadata cache carries the marker. -- * 08 get_object_json: a reference whose structure is _lazy emits the base-fields -- stub (depth 0) when the session GUC redb.lazy_refs = '1' - regardless of depth. -- 0.6.11 - V4 byte[] scalar storage (B1): -- * get_object_json: the ByteArray emit decoded _ByteArray::text as base64, -- but bytea::text is hex ('\x...') - error 22023 on the first reachable -- value. Now encode(v._ByteArray, 'base64') directly (2 sites in 08). -- 0.6.10 - V4 unique keys, stage 1 (UNIQUE_STRING_KEY_PLAN, Э1): -- * block "0. Schema upgrades": _objects._value_unique varchar(440) and the partial -- unique index UIX__objects__scheme_unique (INCLUDE _id). -- * get_object_json and the PVT base-field surface emit and filter the column -- (07/08/12/13/01), so the key behaves exactly like _value_string. -- * mark_for_deletion (30_soft_delete.sql) also releases the object key on the way -- into the trash (decision 9). -- 0.6.9 - V4 unique keys, stage 2 (UNIQUE_STRING_KEY_PLAN, Э2): -- * block "0. Schema upgrades" opens 00_module_init.sql: _structures._unique, -- _structures._unique_version, _values._unique uuid, the partial unique index -- UIX__values__structure_unique, and the same two columns on _scheme_metadata_cache - -- the delivery of DDL to existing databases (SCHEMA_DELIVERY plan, work S.1). -- * 29_metadata_cache_sync.sql: sync_metadata_cache_for_scheme and -- warmup_all_metadata_caches move in from sql/redb_metadata_cache.sql - they carry -- the cache column list, which otherwise reaches fresh databases only. -- * 30_soft_delete.sql: mark_for_deletion and purge_trash move in from -- sql/redb_soft_delete.sql; mark_for_deletion now releases unique keys -- (_values._unique = NULL) in the same transaction (decision 9). -- 0.6.8 — version function moved to 99_module_version.sql, applied LAST: -- a failure in the middle of the bundle used to leave the NEW version next -- to the OLD functions, and the next start saw no mismatch. Now the -- function is dropped with the rest in step 2 and recreated only after -- every other file succeeded. No behaviour change on a healthy deploy. -- 0.6.7 — the DateOnly seed correction joins the module: -- * 28_migrate_dateonly_db_type.sql moved in from sql/. DateOnly was seeded -- with _db_type = 'DateTime', a value get_object_json has no branch for, -- so every DateOnly property materialised as 0001-01-01. The correction -- was written but lived in sql/, which lands only in redb_init.sql and is -- applied when the tables are absent — so it reached new databases and no -- existing one. Nothing else applied it: it was dead on arrival. -- * Idempotent by construction (AND _db_type <> 'DateTimeOffset'), which it -- has to be: the bundle is reapplied on every version change. -- 0.6.6 — migrate_structure_type joins the module, and its text conversions -- are guarded: -- * 27_migrate_structure_type.sql moved in from sql/. It used to ship only -- in redb_init.sql, which is applied to fresh databases only, so a fix to -- it never reached an existing one. Living in the module means the -- version check redeploys it like everything else here. -- * String -> Boolean destroyed unrecognised values: the CASE fell through -- to NULL while the same statement cleared _String, and the row counted -- as a success. Now predicated on the accepted token list, so anything -- else stays put and lands in error_count. -- * String -> DateTimeOffset and String -> Guid were bare casts that raised -- on the first bad row and aborted the whole migration. Now guarded, as -- the numeric branches always were and as MSSQL's TRY_CAST already did. -- 0.6.5 — Unicode-aware case folding for the Free query path: -- * new pvt_fold_case(text): wraps an expression in COLLATE when the -- redb.string_collation GUC is set, and returns it untouched otherwise. -- Case folding is driven by the database ctype, so on a database created -- with LC_CTYPE=C the ILIKE/LOWER/UPPER family folds ASCII only and -- 'Привет' ILIKE '%привет%' is false. The GUC is set by the C# provider -- per connection, which keeps every existing function signature intact. -- * applied in 13_pvt_condition.sql and 17_pvt_expr.sql at every ILIKE, -- and at $lower/$upper, so the three operations cannot disagree. -- 0.6.4 — Scoped WhereLeaves()/WhereRoots() cross-tree leak fix: -- * 12_pvt_cte_builder.sql tree_leaves/tree_roots now honour the seed as a -- SUBTREE ROOT (descend, then apply the leaf/root predicate) instead of an -- exact-id membership, so TreeQuery(rootObj).WhereLeaves() returns the leaves -- of that subtree — not every leaf in the scheme. -- 0.6.3 — Soft-delete read-path fix + object-json materializer ownership: -- * The whole object->JSON materializer (get_object_json, get_objects_json, -- build_hierarchical_properties_optimized, build_listitem_jsonb) moved -- from core (redb_json_objects.sql, now deleted) into the module -- (08_core_object_json.sql) so its fixes auto-redeploy to existing -- databases via the version check (full redb_init.sql is not re-run -- once _schemes exists). -- * get_object_json() now treats soft-deleted objects -- (_id_scheme = -10, @@__deleted) as non-existent: a nested -- _Object reference to a trashed object resolves to NULL instead -- of materializing the tombstone. The _values pointer stays -- intact, so soft-delete remains reversible. -- 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. -- 0.7.16 - block 0: value-leading indexes (_id_structure, , _id_object) for every value column -- replace the object-leading IX__values__{String,Long,DateTimeOffset,Numeric}_not_null and -- ix__values__array_null_structure (2026-10-16), with _array_index in INCLUDE. Restore statements: -- 00_module_init.sql. (0.7.15 was a development build of the same, without the INCLUDE.) -- 0.7.17 - pvt_build_order_conditions: a DISTINCT ON key takes the direction of its p_order entry instead of -- ASC (OrderByDescending(k).DistinctBy(k) came back ascending), and that entry is not repeated. -- 0.7.33 - IX__values__array_parent_id is dropped where IX__values__array_parent_index (or another plain btree led by -- _array_parent_id) exists (00_module_init.sql). No function changed. -- 0.7.32 - _schemes._version (00_module_init.sql): the version of the Props class last synchronised; the sync deletes -- a structure or changes its type only for a class of a higher version. No function changed. -- 0.7.31 - validate_structure_name() (00_module_init.sql, block 0): C# keywords are compared as written, so a field named -- Ref, Default or String passes and only ref, default, string are refused; it compared in lower case. -- 0.7.30 - pvt_build_field_condition: $eq of an array path (Roles[].Value == x, from Any) is FALSE where no item -- matches, also for a missing list, so its $not (!Roles.Any(r => r.Value == x)) returns those objects. -- 0.7.29 - TimeOnly and TimeSpan as Ticks in _Long: _types and the metadata cache say Long (00_module_init.sql), -- the ::interval branches of pvt_build_inner_condition are gone, pvt_db_type_to_value_column maps both to -- _Long, get_value_column (27) maps TimeOnly to _long (it went to _datetimeoffset). Stored text values -- are not converted. -- 0.7.28 - pvt_build_order_conditions (_pvt_order_nulls) and pvt_build_array_groupby_sql: a sort key that can be -- empty spells out NULLS FIRST ascending and NULLS LAST descending, as LINQ, Pro, SQL Server and SQLite put -- null; PostgreSQL's own order put the objects without a value last ascending. A base column of the -- object keeps the bare direction, so a page by _id still reads its index (2026-11-19). -- 0.7.27 - _structures._renamed_from and _schemes._renamed_from (00_module_init.sql): the previous names the sync -- records when it applies a rename ([RedbRename], RedbScheme.RenamedFrom). No function changed. -- 0.7.26 - pvt_build_query_sql returns _ord next to _id, the position of the row in the order of the query -- (pvt_ord_column, pvt_ord_over_distinct), and the caller sorts by it: row_number() OVER () above the -- ordered subquery relied on the plan reading the rows in that order (2026-11-15). -- 0.7.25 - mark_for_deletion: the move into the trash checks again that the object is not in the trash yet; a -- concurrent soft delete of the same object moved it into a second trash and counted it (2026-11-14). -- 0.7.24 - pvt_module_compat(): what this module still serves, read by packages whose module is older; they leave a -- newer module in place instead of putting their own back (2026-11-14). No other function changed. -- 0.7.23 - tree sources: the walk restricts the objects as o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree ...)) instead of -- an IN subquery. Since the pivot starts from the objects the walk is read twice, and the recursive CTE, -- estimated at a few hundred rows, became the inner side of nested loops: a Props filter over a -- 100 thousand node subtree ran for minutes; now 0.75 s (2026-11-02). -- 0.7.22 - pvt_build_query_sql: WhereLevel of a tree query that starts from nodes counts from them (pvt_seed_level_having -- over the walk depth), as maxDepth and Pro do; it counted from the root of the whole tree (2026-11-02). -- 0.7.21 - the pivot starts from the objects in every shape (LEFT JOIN _values): an object that stores no value -- for the fields a statement reads (a null field has no row) kept no pivot row, and lists, counts, -- groups (the NULL group) and windows lost it; the inline pivot of pvt_build_groupby_sql -- likewise (2026-11-02). -- 0.7.18 - pvt_build_array_groupby_sql (GroupByArray): array paths through classes and arrays (an inner array -- of an element), '$element' of an array of simple values, fields of classes inside the element, -- COUNT(*) with a filter, elements reached from the ids of the filtered objects, element fields joined -- by _array_parent_id alone with _array_parent_id IS NOT NULL; every form it cannot answer raises -- instead of joining a field to the wrong row (2026-11-02). RETURN '0.7.33'; 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).'; DO $$ BEGIN RAISE NOTICE 'v2-pvt module init OK, version: %', pvt_module_version(); END $$; Path: redb/redb.Postgres/sql/v2-pvt/99_smoke_auto.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.Postgres/sql/v2-pvt/99_smoke_auto.sql ---- -- ===================================================================== -- 99_smoke_auto.sql -- --------------------------------------------------------------------- -- Automated PVT smoke runner. Iterates a static table of (scheme_alias, -- label, filter_json) cases, builds the SQL via pvt_build_query_sql -- and EXECUTEs it inside a count(*) wrapper. Reports OK/FAIL per case -- through RAISE NOTICE, raises at the end if any case failed. -- -- Designed against the redb.Examples model corpus (Employee, Person, -- City, ProjectMetrics, Department). Schemes are looked up by -- _schemes._alias first, then by suffix match on _schemes._name. -- Missing schemes are reported as SKIP and do not fail the run. -- -- Usage (from psql): -- \i redb.Postgres/sql/v2-pvt/99_smoke_auto.sql -- ===================================================================== DO $SMOKE$ DECLARE v_scheme_name text; v_scheme_id bigint; v_label text; v_filter jsonb; v_order jsonb; v_sql text; v_count bigint; v_pass int := 0; v_fail int := 0; v_skip int := 0; v_msg text; v_cases text[][] := ARRAY[ -- Employee -------------------------------------------------------- ['redb.Tests.Integration.Models.EmployeeProps', 'eq string', '{"FirstName":{"$eq":"Ivan"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'shorthand eq', '{"LastName":"Doe"}'], ['redb.Tests.Integration.Models.EmployeeProps', 'ne string', '{"FirstName":{"$ne":"Ivan"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'in string', '{"Department":{"$in":["IT","HR"]}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'nin string', '{"Department":{"$nin":["Sales"]}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'range int', '{"Age":{"$gte":18,"$lte":65}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'numeric gt decimal', '{"Salary":{"$gt":1000}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'numeric lt decimal', '{"Salary":{"$lt":1000000}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'numeric range', '{"Salary":{"$gte":0,"$lte":1000000}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'null check', '{"EmployeeCode":{"$null":true}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'notNull check', '{"EmployeeCode":{"$notNull":true}}'], ['redb.Tests.Integration.Models.EmployeeProps', '$exists true', '{"EmployeeCode":{"$exists":true}}'], ['redb.Tests.Integration.Models.EmployeeProps', '$exists false', '{"EmployeeCode":{"$exists":false}}'], ['redb.Tests.Integration.Models.EmployeeProps', '$isNull true', '{"EmployeeCode":{"$isNull":true}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'startsWith', '{"FirstName":{"$startsWith":"A"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'endsWith', '{"LastName":{"$endsWith":"ov"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'contains', '{"Position":{"$contains":"eng"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'containsIgnoreCase', '{"Position":{"$containsIgnoreCase":"ENG"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'startsWithIgnoreCase', '{"FirstName":{"$startsWithIgnoreCase":"a"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'endsWithIgnoreCase', '{"LastName":{"$endsWithIgnoreCase":"OV"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'like', '{"FirstName":{"$like":"A%"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'ilike', '{"FirstName":{"$ilike":"a%"}}'], ['redb.Tests.Integration.Models.EmployeeProps', '$and+$or', '{"$and":[{"Age":{"$gt":18}},{"$or":[{"Department":{"$eq":"IT"}},{"Department":{"$eq":"HR"}}]}]}'], ['redb.Tests.Integration.Models.EmployeeProps', '$or top-level', '{"$or":[{"Department":"IT"},{"Department":"HR"}]}'], ['redb.Tests.Integration.Models.EmployeeProps', '$not', '{"$not":{"Age":{"$lt":18}}}'], ['redb.Tests.Integration.Models.EmployeeProps', '$not + $and', '{"$not":{"$and":[{"Age":{"$lt":18}},{"Department":"IT"}]}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'multi-field AND merge', '{"Department":"IT","Age":{"$gt":18}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'date gt', '{"HireDate":{"$gt":"2020-01-01T00:00:00Z"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'date lte', '{"HireDate":{"$lte":"2030-01-01T00:00:00Z"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'date range', '{"HireDate":{"$gte":"2000-01-01T00:00:00Z","$lt":"2030-01-01T00:00:00Z"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'base 0$:Id eq', '{"0$:Id":{"$gt":0}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'base 0$:Name eq', '{"0$:Name":{"$startsWith":"E"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'base _id range', '{"_id":{"$gt":0}}'], -- B1 base-pushdown semantics ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown _date_create gte', '{"_date_create":{"$gte":"2000-01-01T00:00:00Z"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown base+props AND', '{"_id":{"$gt":0},"FirstName":{"$startsWith":"A"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown $and explicit', '{"$and":[{"_id":{"$gt":0}},{"Department":"IT"}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown $or all-base', '{"$or":[{"_id":{"$lt":10}},{"_id":{"$gt":100}}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown $or mixed (stays)', '{"$or":[{"_id":{"$lt":10}},{"FirstName":"Ivan"}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown $not base', '{"$not":{"_id":{"$lt":0}}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown $not mixed (stays)','{"$not":{"$and":[{"_id":{"$gt":0}},{"FirstName":"Ivan"}]}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown nested $and+$or', '{"$and":[{"_id":{"$gt":0}},{"$or":[{"Department":"IT"},{"Department":"HR"}]}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'pushdown 0$:Name+props', '{"0$:Name":{"$startsWith":"E"},"Age":{"$gt":0}}'], -- B2 expression engine: arithmetic, functions, expression-form predicates ['redb.Tests.Integration.Models.EmployeeProps', 'expr arithmetic gt', '{"$gt":[{"$add":[{"$field":"Age"},{"$const":1}]},{"$const":18}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr mul base pushdown', '{"$lt":[{"$mul":[{"$field":"_id"},{"$const":2}]},{"$const":1000000}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr upper eq', '{"$eq":[{"$upper":[{"$field":"FirstName"}]},{"$const":"IVAN"}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr concat ilike', '{"$ilike":[{"$concat":[{"$field":"FirstName"},{"$const":" "},{"$field":"LastName"}]},{"$const":"%van%"}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr coalesce eq', '{"$eq":[{"$coalesce":[{"$field":"Department"},{"$const":"none"}]},{"$const":"IT"}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr between base push', '{"$between":[{"$field":"_id"},{"$const":0},{"$const":1000000}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr in props', '{"$in":[{"$field":"Department"},["IT","HR","R&D"]]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr nin base push', '{"$nin":[{"$field":"_id"},[-1,-2,-3]]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr length gt', '{"$gt":[{"$length":[{"$field":"FirstName"}]},{"$const":0}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr abs sub', '{"$lt":[{"$abs":[{"$sub":[{"$field":"Age"},{"$const":30}]}]},{"$const":1000}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr min max', '{"$lt":[{"$min":[{"$field":"Age"},{"$const":100}]},{"$max":[{"$field":"Age"},{"$const":0}]}]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr null base push', '{"$null":{"$field":"_id_parent"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr notNull props', '{"$notNull":{"$field":"FirstName"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr $contains sugar', '{"$contains":[{"$field":"FirstName"},"a"]}'], ['redb.Tests.Integration.Models.EmployeeProps', 'expr $startsWith sugar', '{"$startsWith":[{"$field":"LastName"},"S"]}'], -- Arrays + .$length / .$count + array ops ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayContains', '{"Skills":{"$arrayContains":"C#"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayCount eq', '{"Skills":{"$arrayCount":3}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayCount 0', '{"Skills":{"$arrayCount":0}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayCountGt', '{"Skills":{"$arrayCountGt":2}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayCountGte', '{"Skills":{"$arrayCountGte":1}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayCountLt', '{"Skills":{"$arrayCountLt":10}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayCountLte', '{"Skills":{"$arrayCountLte":5}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayAny true', '{"Skills":{"$arrayAny":true}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayAny false', '{"Skills":{"$arrayAny":false}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayEmpty false', '{"Skills":{"$arrayEmpty":false}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayEmpty true', '{"Skills":{"$arrayEmpty":true}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayFirst', '{"Skills":{"$arrayFirst":"C#"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayLast', '{"Skills":{"$arrayLast":"SQL"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayAt index=1', '{"Skills":{"$arrayAt":{"index":1,"value":"Python"}}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayAt index=0', '{"Skills":{"$arrayAt":{"index":0,"value":"C#"}}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayStartsWith', '{"Skills":{"$arrayStartsWith":"C"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayEndsWith', '{"Skills":{"$arrayEndsWith":"L"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array $arrayMatches', '{"Skills":{"$arrayMatches":"%QL%"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array int $arraySum', '{"SkillLevels":{"$arraySum":10}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array int $arrayMin', '{"SkillLevels":{"$arrayMin":1}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array int $arrayMax', '{"SkillLevels":{"$arrayMax":5}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array int $arrayAvg', '{"SkillLevels":{"$arrayAvg":3}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'array int $arrayCount', '{"SkillLevels":{"$arrayCount":3}}'], ['redb.Tests.Integration.Models.EmployeeProps', '.$length gt', '{"Skills.$length":{"$gt":0}}'], ['redb.Tests.Integration.Models.EmployeeProps', '.$length eq 0', '{"Skills.$length":{"$eq":0}}'], ['redb.Tests.Integration.Models.EmployeeProps', '.$count gte', '{"Skills.$count":{"$gte":1}}'], ['redb.Tests.Integration.Models.EmployeeProps', '.$count int gt', '{"SkillLevels.$count":{"$gt":0}}'], -- Dictionaries ['redb.Tests.Integration.Models.EmployeeProps', 'dict ContainsKey simple', '{"PhoneDirectory.ContainsKey":"work"}'], ['redb.Tests.Integration.Models.EmployeeProps', 'dict ContainsKey home', '{"PhoneDirectory.ContainsKey":"home"}'], ['redb.Tests.Integration.Models.EmployeeProps', 'dict indexer simple', '{"PhoneDirectory[work]":{"$eq":"+7-000-0000000"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'dict indexer notNull', '{"PhoneDirectory[work]":{"$notNull":true}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'dict nested .City', '{"OfficeLocations[Moscow].City":{"$eq":"Moscow"}}'], ['redb.Tests.Integration.Models.EmployeeProps', 'dict nested .Street', '{"OfficeLocations[Moscow].Street":{"$notNull":true}}'], -- Person (ListItem accessors) ['redb.Tests.Integration.Models.PersonProps', 'eq Name (props)', '{"Name":{"$eq":"Alice"}}'], ['redb.Tests.Integration.Models.PersonProps', 'Age range', '{"Age":{"$gte":18,"$lte":99}}'], ['redb.Tests.Integration.Models.PersonProps', 'Email contains', '{"Email":{"$contains":"@"}}'], -- NB: shorthand '{"Status":"Active"}' is intentionally NOT covered: -- ListItem field stores _listitem (bigint ID). Scalar .Value/.Alias -- in WHERE compare as text against the dereferenced -- _list_items._value/_alias column (Free PG LINQ passes string -- literals; Pro pre-resolves to id on the client side). ['redb.Tests.Integration.Models.PersonProps', 'ListItem Status.Value eq', '{"Status.Value":{"$eq":"Active"}}'], ['redb.Tests.Integration.Models.PersonProps', 'ListItem Status.Alias eq', '{"Status.Alias":{"$eq":"active"}}'], ['redb.Tests.Integration.Models.PersonProps', 'ListItem Status.Id', '{"Status.Id":{"$gt":0}}'], ['redb.Tests.Integration.Models.PersonProps', 'ListItem Roles[].Value in', '{"Roles[].Value":{"$in":["admin","user"]}}'], ['redb.Tests.Integration.Models.PersonProps', 'ListItem Roles[].Value nin', '{"Roles[].Value":{"$nin":["guest"]}}'], -- ProjectMetrics ['redb.Tests.Integration.Models.ProjectMetricsProps', 'numeric range Budget', '{"Budget":{"$gte":0}}'], ['redb.Tests.Integration.Models.ProjectMetricsProps', 'TasksCompleted gte', '{"TasksCompleted":{"$gte":0}}'], ['redb.Tests.Integration.Models.ProjectMetricsProps', 'BugsFixed gte', '{"BugsFixed":{"$gte":0}}'], ['redb.Tests.Integration.Models.ProjectMetricsProps', 'TeamSize range', '{"TeamSize":{"$gte":1,"$lte":1000}}'], ['redb.Tests.Integration.Models.ProjectMetricsProps', 'tech $arrayContains', '{"Technologies":{"$arrayContains":"PostgreSQL"}}'], ['redb.Tests.Integration.Models.ProjectMetricsProps', 'tech $arrayAny', '{"Technologies":{"$arrayAny":true}}'], ['redb.Tests.Integration.Models.ProjectMetricsProps', 'tech .$length gt', '{"Technologies.$length":{"$gt":0}}'], ['redb.Tests.Integration.Models.ProjectMetricsProps', 'tech $arrayStartsWith','{"Technologies":{"$arrayStartsWith":"P"}}'], ['redb.Tests.Integration.Models.ProjectMetricsProps', 'ProjectId gt', '{"ProjectId":{"$gt":0}}'], -- City ['redb.Tests.Integration.Models.CityProps', 'bool true', '{"IsCapital":{"$eq":true}}'], ['redb.Tests.Integration.Models.CityProps', 'bool false', '{"IsCapital":{"$eq":false}}'], ['redb.Tests.Integration.Models.CityProps', 'coords $arrayCount', '{"Coordinates":{"$arrayCount":2}}'], ['redb.Tests.Integration.Models.CityProps', 'coords $arrayAt 0', '{"Coordinates":{"$arrayAt":{"index":0,"value":55.7558}}}'], ['redb.Tests.Integration.Models.CityProps', 'coords .$length eq', '{"Coordinates.$length":{"$eq":2}}'], ['redb.Tests.Integration.Models.CityProps', 'population gt', '{"Population":{"$gt":1000}}'], ['redb.Tests.Integration.Models.CityProps', 'population range', '{"Population":{"$gte":0,"$lt":50000000}}'], ['redb.Tests.Integration.Models.CityProps', 'region startsWith', '{"Region":{"$startsWith":"M"}}'], ['redb.Tests.Integration.Models.CityProps', 'name in', '{"Name":{"$in":["Moscow","Paris"]}}'], -- Department (tree-style scheme) ['redb.Tests.Integration.Models.DepartmentProps', 'eq bool', '{"IsActive":{"$eq":true}}'], ['redb.Tests.Integration.Models.DepartmentProps', 'name startsWith', '{"Name":{"$startsWith":"IT"}}'], ['redb.Tests.Integration.Models.DepartmentProps', 'name like', '{"Name":{"$like":"%"}}'], ['redb.Tests.Integration.Models.DepartmentProps', 'code contains', '{"Code":{"$contains":"-"}}'], ['redb.Tests.Integration.Models.DepartmentProps', 'budget range', '{"Budget":{"$gte":0}}'], ['redb.Tests.Integration.Models.DepartmentProps', 'description notNull', '{"Description":{"$notNull":true}}'] ]; i int; v_total int; v_dump boolean := COALESCE(current_setting('pvt.dump_sql', true), '0') IN ('1','on','true','TRUE'); BEGIN RAISE NOTICE '----------------------------------------------------------'; RAISE NOTICE 'pvt smoke run starting, module version: %', pvt_module_version(); IF v_dump THEN RAISE NOTICE 'dump_sql mode is ON (pvt.dump_sql) -- SQL for every case will be printed'; END IF; RAISE NOTICE '----------------------------------------------------------'; v_total := COALESCE(array_length(v_cases, 1), 0); FOR i IN 1..v_total LOOP v_scheme_name := v_cases[i][1]; v_label := v_cases[i][2]; -- Each filter is a JSON literal; parse defensively. BEGIN v_filter := v_cases[i][3]::jsonb; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [% / %] bad filter JSON: %', v_scheme_name, v_label, v_msg; CONTINUE; END; -- Scheme lookup: exact match on _name (full CLR type name, as stored by C# InitializeAsync). SELECT _id INTO v_scheme_id FROM _schemes WHERE _name = v_scheme_name LIMIT 1; IF v_scheme_id IS NULL THEN v_skip := v_skip + 1; RAISE NOTICE 'SKIP [% / %] scheme not found', v_scheme_name, v_label; CONTINUE; END IF; BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => v_filter); IF v_dump THEN RAISE NOTICE E'----- DUMP [% / %] -----\nFILTER: %\nSQL:\n%', v_scheme_name, v_label, v_filter::text, v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [% / %] rows=%', v_scheme_name, v_label, v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [% / %] %', v_scheme_name, v_label, v_msg; END; END LOOP; -- Order / paging / tree shape smoke ----------------------------------- -- (Run only if Employee scheme exists so we know we are connected to -- a database with the example data layout.) SELECT _id INTO v_scheme_id FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.EmployeeProps' LIMIT 1; IF v_scheme_id IS NOT NULL THEN v_order := '[{"field":"Age","dir":"desc","nulls":"last"}]'::jsonb; BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_order => v_order, p_limit => 10, p_offset => 0); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / order+limit] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / order+limit] %', v_msg; END; v_order := '[{"field":"LastName","dir":"asc","nulls":"first"},{"field":"FirstName","dir":"asc"}]'::jsonb; BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_order => v_order, p_limit => 25, p_offset => 5); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / order multi+offset] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / order multi+offset] %', v_msg; END; v_order := '[{"field":"0$:Id","dir":"desc"}]'::jsonb; BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"Age":{"$gte":18}}'::jsonb, p_order => v_order, p_limit => 5); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / filter+order by base Id] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / filter+order by base Id] %', v_msg; END; -- Pro-parity ORDER BY $expr: arithmetic on a pivot prop. v_order := '[{"$expr":{"$mul":[{"$field":"Age"},{"$const":2}]},"dir":"desc"}]'::jsonb; BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_order => v_order, p_limit => 5); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; IF v_sql !~* 'ORDER BY \(.*Age.* \* 2\)' THEN RAISE EXCEPTION 'expected ORDER BY (Age * 2) in SQL, got: %', v_sql; END IF; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / order $expr arith Age*2 desc] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / order $expr arith Age*2 desc] %', v_msg; END; -- Pro-parity ORDER BY $expr: function call on a pivot prop. v_order := '[{"$expr":{"$upper":{"$field":"FirstName"}},"dir":"asc","nulls":"last"}]'::jsonb; BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_order => v_order, p_limit => 5); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; IF v_sql !~* 'ORDER BY UPPER\(.*FirstName.*\) ASC NULLS LAST' THEN RAISE EXCEPTION 'expected ORDER BY UPPER(FirstName) ASC NULLS LAST in SQL, got: %', v_sql; END IF; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / order $expr UPPER(FirstName)] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / order $expr UPPER(FirstName)] %', v_msg; END; -- Pro-parity ORDER BY $expr: mixed function + arithmetic on base column. v_order := '[{"$expr":{"$add":[{"$length":{"$field":"_name"}},{"$const":1}]},"dir":"desc"}]'::jsonb; BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_order => v_order, p_limit => 5); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; IF v_sql !~* 'ORDER BY \(LENGTH\(.*_name.*\) \+ 1\) DESC' THEN RAISE EXCEPTION 'expected ORDER BY (LENGTH(_name) + 1) DESC in SQL, got: %', v_sql; END IF; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / order $expr LENGTH(_name)+1 desc] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / order $expr LENGTH(_name)+1 desc] %', v_msg; END; -- Pro-parity DISTINCT: plain dedup over an Employee subset. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"Age":{"$gte":18}}'::jsonb, p_distinct => true, p_limit => 5); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; IF v_sql !~* 'SELECT DISTINCT ' THEN RAISE EXCEPTION 'expected SELECT DISTINCT in SQL, got: %', v_sql; END IF; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / DISTINCT] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / DISTINCT] %', v_msg; END; -- Pro-parity DISTINCT ON: dedup by a pivot field, with ORDER BY user keys. v_order := '[{"field":"_id","dir":"desc"}]'::jsonb; BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_order => v_order, p_limit => 10, p_distinct_on => '[{"field":"Age"}]'::jsonb); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; IF v_sql !~* 'DISTINCT ON \(.*"Age".*\)' THEN RAISE EXCEPTION 'expected DISTINCT ON ("Age") in SQL, got: %', v_sql; END IF; IF v_sql !~* 'ORDER BY .*"Age" ASC NULLS FIRST, .*o\._id DESC' THEN RAISE EXCEPTION 'expected DISTINCT-ON key auto-prepended ASC NULLS FIRST in ORDER BY, got: %', v_sql; END IF; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / DISTINCT ON (Age) + order _id desc] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / DISTINCT ON (Age) + order _id desc] %', v_msg; END; -- Pro-parity DISTINCT ON $expr: dedup by UPPER(FirstName). BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_order => NULL, p_limit => 10, p_distinct_on => '[{"$expr":{"$upper":{"$field":"FirstName"}}}]'::jsonb); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; IF v_sql !~* 'DISTINCT ON \(UPPER\(.*"FirstName".*\)\)' THEN RAISE EXCEPTION 'expected DISTINCT ON (UPPER("FirstName")) in SQL, got: %', v_sql; END IF; IF v_sql !~* 'ORDER BY UPPER\(.*"FirstName".*\) ASC NULLS FIRST' THEN RAISE EXCEPTION 'expected DISTINCT-ON $expr auto-prepended ASC NULLS FIRST in ORDER BY, got: %', v_sql; END IF; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / DISTINCT ON $expr UPPER(FirstName)] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / DISTINCT ON $expr UPPER(FirstName)] %', v_msg; END; -- Pro-parity: DISTINCT + DISTINCT ON together must raise. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_distinct => true, p_distinct_on => '[{"field":"Age"}]'::jsonb); v_fail := v_fail + 1; RAISE NOTICE 'FAIL [Employee / DISTINCT + DISTINCT ON guard] expected exception, got SQL: %', v_sql; EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; IF v_msg ~* 'mutually exclusive' THEN v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / DISTINCT + DISTINCT ON guard] raised: %', v_msg; ELSE v_fail := v_fail + 1; RAISE NOTICE 'FAIL [Employee / DISTINCT + DISTINCT ON guard] wrong exception: %', v_msg; END IF; END; END IF; -- Tree-mode smoke on Department -------------------------------------- SELECT _id INTO v_scheme_id FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.DepartmentProps' LIMIT 1; IF v_scheme_id IS NOT NULL THEN DECLARE v_root bigint; BEGIN SELECT _id INTO v_root FROM _objects WHERE _id_scheme = v_scheme_id AND _id_parent IS NULL LIMIT 1; -- Fallback: when no Department objects exist, seed=-1 exercises all -- tree-mode SQL generators; all queries return 0 rows, no errors. v_root := COALESCE(v_root, -1); v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_source_mode => 'tree', p_tree_ids => ARRAY[v_root]::bigint[], p_max_depth => 5); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree depth=5] rows=%', v_count; v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_source_mode => 'tree', p_tree_ids => ARRAY[v_root]::bigint[], p_max_depth => 1); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree depth=1] rows=%', v_count; v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"IsActive":{"$eq":true}}'::jsonb, p_source_mode => 'tree', p_tree_ids => ARRAY[v_root]::bigint[], p_max_depth => 10); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree + filter] rows=%', v_count; -- New tree-modes coverage (Pro parity bite) ---------- v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_source_mode => 'tree_descendants', p_tree_ids => ARRAY[v_root]::bigint[], p_include_seed=> false); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree_descendants exclude seed] rows=%', v_count; v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_source_mode => 'tree_children', p_tree_ids => ARRAY[v_root]::bigint[]); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree_children] rows=%', v_count; v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_source_mode => 'tree_roots'); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree_roots] rows=%', v_count; v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_source_mode => 'tree_leaves'); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree_leaves] rows=%', v_count; -- tree_ancestors only makes sense from a non-root seed. DECLARE v_leaf_id bigint; BEGIN SELECT _id INTO v_leaf_id FROM _objects WHERE _id_scheme = v_scheme_id AND _id_parent IS NOT NULL LIMIT 1; IF v_leaf_id IS NOT NULL THEN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_source_mode => 'tree_ancestors', p_tree_ids => ARRAY[v_leaf_id]::bigint[]); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree_ancestors from non-root] rows=%', v_count; ELSE v_skip := v_skip + 1; RAISE NOTICE 'SKIP [Department / tree_ancestors] no non-root object found'; END IF; END; -- Hierarchical DSL operators (legacy free parity) ---- v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$isRoot":true}'::jsonb); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / $isRoot] rows=%', v_count; v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$isLeaf":true}'::jsonb); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / $isLeaf] rows=%', v_count; v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => ('{"$childrenOf":' || v_root::text || '}')::jsonb); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / $childrenOf root] rows=%', v_count; v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$level":{"$gte":0}}'::jsonb); EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / $level>=0] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Department / tree depth=5] %', v_msg; END; END IF; -- =============================================================== -- Extended scalar ops on Employee (Pro-parity + free extras). -- =============================================================== SELECT _id INTO v_scheme_id FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.EmployeeProps' LIMIT 1; IF v_scheme_id IS NOT NULL THEN -- $year over a base date column. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$gte":[{"$year":{"$field":"HireDate"}},{"$const":2000}]}'::jsonb, p_limit => 5); IF v_sql !~* 'EXTRACT\(YEAR FROM' THEN RAISE EXCEPTION 'expected EXTRACT(YEAR FROM ...) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / $year EXTRACT] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / $year EXTRACT] %', v_msg; END; -- $trimStart over a props string. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$eq":[{"$trimStart":{"$field":"FirstName"}},{"$const":"Ivan"}]}'::jsonb, p_limit => 5); IF v_sql !~* 'LTRIM\(' THEN RAISE EXCEPTION 'expected LTRIM(...) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / $trimStart LTRIM] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / $trimStart LTRIM] %', v_msg; END; -- $substring (3-arg). BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$eq":[{"$substring":[{"$field":"FirstName"},{"$const":1},{"$const":3}]},{"$const":"Iva"}]}'::jsonb, p_limit => 5); IF v_sql !~* 'SUBSTRING\(.+ FROM .+ FOR ' THEN RAISE EXCEPTION 'expected SUBSTRING(... FROM ... FOR ...) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / $substring] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / $substring] %', v_msg; END; -- $replace. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$eq":[{"$replace":[{"$field":"FirstName"},{"$const":"a"},{"$const":"A"}]},{"$const":"IvAn"}]}'::jsonb, p_limit => 5); IF v_sql !~* 'REPLACE\(' THEN RAISE EXCEPTION 'expected REPLACE(...) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / $replace] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / $replace] %', v_msg; END; -- $power. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$lt":[{"$power":[{"$field":"Age"},{"$const":2}]},{"$const":1000000}]}'::jsonb, p_limit => 5); IF v_sql !~* 'POWER\(' THEN RAISE EXCEPTION 'expected POWER(...) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / $power] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / $power] %', v_msg; END; -- $dateAdd: HireDate + 30 days. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$gt":[{"$dateAdd":["day",{"$field":"HireDate"},{"$const":30}]},{"$const":"2000-01-01T00:00:00Z"}]}'::jsonb, p_limit => 5); IF v_sql !~* 'INTERVAL ''1 day' THEN RAISE EXCEPTION 'expected INTERVAL ''1 day'' in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / $dateAdd day] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / $dateAdd day] %', v_msg; END; -- $if conditional: salary >= 100000 then "High" else "Normal". BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$eq":[{"$if":[{"$gte":[{"$field":"Salary"},{"$const":100000}]},{"$const":"High"},{"$const":"Normal"}]},{"$const":"Normal"}]}'::jsonb, p_limit => 5); IF v_sql !~* '\(CASE WHEN ' THEN RAISE EXCEPTION 'expected (CASE WHEN ... in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / $if] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / $if] %', v_msg; END; -- $case: bucket Age into groups. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"$eq":[{"$case":[{"when":{"$lt":[{"$field":"Age"},{"$const":18}]},"then":{"$const":"minor"}},{"when":{"$lt":[{"$field":"Age"},{"$const":65}]},"then":{"$const":"adult"}},{"else":{"$const":"senior"}}]},{"$const":"adult"}]}'::jsonb, p_limit => 5); IF v_sql !~* '\(CASE WHEN .* WHEN .* ELSE' THEN RAISE EXCEPTION 'expected multi-arm CASE in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / $case multi-arm] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / $case multi-arm] %', v_msg; END; -- =============================================================== -- Terminal aggregations: pvt_build_aggregate_sql. -- =============================================================== -- COUNT(*) over filtered set. BEGIN v_sql := pvt_build_aggregate_sql( p_scheme_id => v_scheme_id, p_filter => '{"Age":{"$gte":18}}'::jsonb, p_aggregations => '[{"alias":"total","$count":"*"}]'::jsonb); IF v_sql !~* 'COUNT\(\*\) AS "?total"?' THEN RAISE EXCEPTION 'expected COUNT(*) AS total in SQL, got: %', v_sql; END IF; EXECUTE v_sql INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / agg COUNT(*)] total=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / agg COUNT(*)] %', v_msg; END; -- SUM + AVG + MIN + MAX over Age. BEGIN v_sql := pvt_build_aggregate_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_aggregations => '[ {"alias":"sum_age","$sum":{"$field":"Age"}}, {"alias":"avg_age","$avg":{"$field":"Age"}}, {"alias":"min_age","$min":{"$field":"Age"}}, {"alias":"max_age","$max":{"$field":"Age"}} ]'::jsonb); IF v_sql !~* 'SUM\(' OR v_sql !~* 'AVG\(' OR v_sql !~* 'MIN\(' OR v_sql !~* 'MAX\(' THEN RAISE EXCEPTION 'expected SUM/AVG/MIN/MAX in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT 1 FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / agg SUM+AVG+MIN+MAX over Age]'; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / agg SUM+AVG+MIN+MAX over Age] %', v_msg; END; -- C# emit shape (TASK-16): batch with Count(*)+Sum+Avg+Min+Max + -- a filter, mirroring exactly what PostgresQueryProvider.Aggregation -- serializes from AggregateRequest[]. Locks the C#/SQL contract. BEGIN v_sql := pvt_build_aggregate_sql( p_scheme_id => v_scheme_id, p_filter => '{"Position":{"$eq":"Developer"}}'::jsonb, p_aggregations => '[ {"alias":"_agg_1","$count":"*"}, {"alias":"sum_salary","$sum":{"$field":"Salary"}}, {"alias":"avg_salary","$avg":{"$field":"Salary"}}, {"alias":"min_salary","$min":{"$field":"Salary"}}, {"alias":"max_salary","$max":{"$field":"Salary"}} ]'::jsonb); IF v_sql !~* 'COUNT\(\*\) AS "?_agg_1"?' OR v_sql !~* 'SUM\(' OR v_sql !~* 'AVG\(' OR v_sql !~* 'MIN\(' OR v_sql !~* 'MAX\(' THEN RAISE EXCEPTION 'expected Count+Sum+Avg+Min+Max projection, got: %', v_sql; END IF; EXECUTE 'SELECT 1 FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / agg C# emit shape batch+filter]'; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / agg C# emit shape batch+filter] %', v_msg; END; -- COUNT DISTINCT (free extra over Pro). BEGIN v_sql := pvt_build_aggregate_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_aggregations => '[{"alias":"unique_depts","$count":{"$field":"Department"},"distinct":true}]'::jsonb); IF v_sql !~* 'COUNT\(DISTINCT' THEN RAISE EXCEPTION 'expected COUNT(DISTINCT ...) in SQL, got: %', v_sql; END IF; EXECUTE v_sql INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / agg COUNT DISTINCT] unique=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / agg COUNT DISTINCT] %', v_msg; END; -- COUNT with FILTER clause (free extra: per-aggregate WHERE). BEGIN v_sql := pvt_build_aggregate_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_aggregations => '[{"alias":"adults","$count":"*","filter":{"$gte":[{"$field":"Age"},{"$const":18}]}}]'::jsonb); IF v_sql !~* 'COUNT\(\*\) FILTER \(WHERE' THEN RAISE EXCEPTION 'expected COUNT(*) FILTER (WHERE ...) in SQL, got: %', v_sql; END IF; EXECUTE v_sql INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / agg COUNT FILTER] adults=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / agg COUNT FILTER] %', v_msg; END; -- Pure-base aggregation: Shape A shortcut (no CTE). BEGIN v_sql := pvt_build_aggregate_sql( p_scheme_id => v_scheme_id, p_filter => '{"_id":{"$gt":0}}'::jsonb, p_aggregations => '[{"alias":"total","$count":"*"}]'::jsonb); IF v_sql ~* 'WITH _pvt_cte' THEN RAISE EXCEPTION 'expected Shape A (no CTE) for pure-base aggregation, got: %', v_sql; END IF; EXECUTE v_sql INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / agg Shape A pure-base] total=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / agg Shape A pure-base] %', v_msg; END; -- =============================================================== -- GROUP BY: pvt_build_groupby_sql + HAVING (free over Pro). -- =============================================================== -- Single key + COUNT. BEGIN v_sql := pvt_build_groupby_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_group_by => '[{"field":"Department"}]'::jsonb, p_aggregations => '[{"alias":"cnt","$count":"*"}]'::jsonb); IF v_sql !~* 'GROUP BY ' THEN RAISE EXCEPTION 'expected GROUP BY in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / GROUP BY Department + COUNT] groups=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / GROUP BY Department + COUNT] %', v_msg; END; -- Multi-key GROUP BY + multiple aggregates + ORDER BY + LIMIT. BEGIN v_sql := pvt_build_groupby_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_group_by => '[{"field":"Department"},{"field":"Position"}]'::jsonb, p_aggregations => '[ {"alias":"cnt","$count":"*"}, {"alias":"avg_salary","$avg":{"$field":"Salary"}} ]'::jsonb, p_order => '[{"$expr":{"$count":"*"},"dir":"desc"}]'::jsonb, p_limit => 10); IF v_sql !~* 'GROUP BY .+, ' THEN RAISE EXCEPTION 'expected multi-key GROUP BY in SQL, got: %', v_sql; END IF; IF v_sql !~* 'ORDER BY COUNT\(\*\) DESC' THEN RAISE EXCEPTION 'expected ORDER BY COUNT(*) DESC in SQL, got: %', v_sql; END IF; IF v_sql !~* 'LIMIT 10' THEN RAISE EXCEPTION 'expected LIMIT 10, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / GROUP BY multi + ORDER agg + LIMIT] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / GROUP BY multi + ORDER agg + LIMIT] %', v_msg; END; -- GROUP BY + HAVING (free over Pro). BEGIN v_sql := pvt_build_groupby_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_group_by => '[{"field":"Department"}]'::jsonb, p_aggregations => '[{"alias":"cnt","$count":"*"}]'::jsonb, p_having => '{"$gt":[{"$count":"*"},{"$const":1}]}'::jsonb); IF v_sql !~* 'HAVING ' THEN RAISE EXCEPTION 'expected HAVING in SQL, got: %', v_sql; END IF; IF v_sql !~* 'HAVING \(COUNT\(\*\) > 1\)' THEN RAISE EXCEPTION 'expected HAVING (COUNT(*) > 1) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / GROUP BY + HAVING COUNT>1] groups=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / GROUP BY + HAVING COUNT>1] %', v_msg; END; -- GROUP BY $expr key (free: arbitrary expression as group key). BEGIN v_sql := pvt_build_groupby_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_group_by => '[{"$expr":{"$year":{"$field":"HireDate"}},"alias":"yr"}]'::jsonb, p_aggregations => '[{"alias":"cnt","$count":"*"}]'::jsonb); IF v_sql !~* 'EXTRACT\(YEAR FROM .+\)(::integer)? AS "?yr"?' THEN RAISE EXCEPTION 'expected EXTRACT(YEAR FROM ...) AS yr in SQL, got: %', v_sql; END IF; IF v_sql !~* 'GROUP BY EXTRACT\(YEAR FROM' THEN RAISE EXCEPTION 'expected GROUP BY EXTRACT(YEAR FROM ...) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / GROUP BY $expr $year(HireDate)] groups=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / GROUP BY $expr $year(HireDate)] %', v_msg; END; -- C# emit shape (TASK-17): batch GROUP BY with multi-key and Count+Avg+Sum -- mirroring exactly what PostgresQueryProvider.Grouping serializes from -- GroupFieldRequest[] + AggregateRequest[]. Locks the C#/SQL contract. BEGIN v_sql := pvt_build_groupby_sql( p_scheme_id => v_scheme_id, p_filter => '{"Position":{"$eq":"Developer"}}'::jsonb, p_group_by => '[{"field":"Department","alias":"dept"},{"field":"Position","alias":"pos"}]'::jsonb, p_aggregations => '[ {"alias":"_agg_1","$count":"*"}, {"alias":"avg_salary","$avg":{"$field":"Salary"}}, {"alias":"sum_salary","$sum":{"$field":"Salary"}} ]'::jsonb); IF v_sql !~* 'GROUP BY ' THEN RAISE EXCEPTION 'expected GROUP BY in SQL, got: %', v_sql; END IF; IF v_sql !~* 'COUNT\(\*\) AS "?_agg_1"?' THEN RAISE EXCEPTION 'expected COUNT(*) AS _agg_1, got: %', v_sql; END IF; IF v_sql !~* 'AVG\(' OR v_sql !~* 'SUM\(' THEN RAISE EXCEPTION 'expected AVG and SUM in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / groupby C# emit shape multi-key+filter] groups=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / groupby C# emit shape multi-key+filter] %', v_msg; END; -- =============================================================== -- Window functions: pvt_build_window_sql. -- =============================================================== -- ROW_NUMBER OVER (ORDER BY Age DESC). BEGIN v_sql := pvt_build_window_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_select => '[ {"field":"_id"}, {"field":"Age"}, {"alias":"rn","$expr":{"$over":{"func":"row_number","order_by":[{"field":"Age","dir":"desc"}]}}} ]'::jsonb, p_limit => 10); IF v_sql !~* 'ROW_NUMBER\(\) OVER \(ORDER BY ' THEN RAISE EXCEPTION 'expected ROW_NUMBER() OVER (ORDER BY ...) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / window ROW_NUMBER ORDER BY Age desc] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / window ROW_NUMBER] %', v_msg; END; -- SUM(Salary) OVER (PARTITION BY Department). BEGIN v_sql := pvt_build_window_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_select => '[ {"field":"_id"}, {"field":"Department"}, {"alias":"dept_total","$expr":{"$over":{"func":"sum","args":[{"$field":"Salary"}],"partition_by":[{"field":"Department"}]}}} ]'::jsonb, p_limit => 20); IF v_sql !~* 'SUM\(.+\) OVER \(PARTITION BY ' THEN RAISE EXCEPTION 'expected SUM(...) OVER (PARTITION BY ...) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / window SUM OVER PARTITION BY Dept] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / window SUM PARTITION BY] %', v_msg; END; -- LAG(Age, 1, 0) OVER (PARTITION BY Department ORDER BY Age) -- + explicit frame ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. BEGIN v_sql := pvt_build_window_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_select => '[ {"field":"_id"}, {"alias":"prev_age","$expr":{"$over":{ "func":"lag", "args":[{"$field":"Age"},{"$const":1},{"$const":0}], "partition_by":[{"field":"Department"}], "order_by":[{"field":"Age","dir":"asc"}] }}}, {"alias":"running_sum","$expr":{"$over":{ "func":"sum", "args":[{"$field":"Salary"}], "partition_by":[{"field":"Department"}], "order_by":[{"field":"_id","dir":"asc"}], "frame":{"type":"rows","start":"unbounded_preceding","end":"current_row"} }}} ]'::jsonb, p_limit => 10); IF v_sql !~* 'LAG\(' THEN RAISE EXCEPTION 'expected LAG(...) in SQL, got: %', v_sql; END IF; IF v_sql !~* 'ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW' THEN RAISE EXCEPTION 'expected ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / window LAG + SUM with ROWS frame] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / window LAG + SUM frame] %', v_msg; END; -- NTILE(4) over Age (free: ranking quartiles). BEGIN v_sql := pvt_build_window_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_select => '[ {"field":"_id"}, {"alias":"quartile","$expr":{"$over":{"func":"ntile","args":[{"$const":4}],"order_by":[{"field":"Age","dir":"asc"}]}}} ]'::jsonb, p_limit => 10); IF v_sql !~* 'NTILE\(4\)' THEN RAISE EXCEPTION 'expected NTILE(4) in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / window NTILE(4)] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / window NTILE(4)] %', v_msg; END; -- C# emit shape (TASK-18): combined plain-field selects + SUM OVER -- (PARTITION BY ... ORDER BY ... ROWS frame) mirroring exactly what -- PostgresQueryProvider.Window serializes from WindowFieldRequest[] + -- WindowFuncRequest[] with global partition_by / order_by / frame / -- take. Locks the C#/SQL contract. BEGIN v_sql := pvt_build_window_sql( p_scheme_id => v_scheme_id, p_filter => '{"Position":{"$eq":"Developer"}}'::jsonb, p_select => '[ {"field":"_id"}, {"field":"Department"}, {"alias":"running_sum","$expr":{"$over":{ "func":"sum", "args":[{"$field":"Salary"}], "partition_by":[{"field":"Department"}], "order_by":[{"field":"Age","dir":"asc"}], "frame":{"type":"rows","start":"unbounded_preceding","end":"current_row"} }}} ]'::jsonb, p_limit => 25, p_offset => 0); IF v_sql !~* 'SUM\(' THEN RAISE EXCEPTION 'expected SUM in SQL, got: %', v_sql; END IF; IF v_sql !~* 'PARTITION BY ' THEN RAISE EXCEPTION 'expected PARTITION BY in SQL, got: %', v_sql; END IF; IF v_sql !~* 'ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW' THEN RAISE EXCEPTION 'expected ROWS frame in SQL, got: %', v_sql; END IF; IF v_sql !~* 'LIMIT 25' THEN RAISE EXCEPTION 'expected LIMIT 25 in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / window C# emit shape SUM OVER + frame + filter] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / window C# emit shape SUM OVER + frame + filter] %', v_msg; END; END IF; -- =============================================================== -- Tree-variant of GROUP BY (Department): COUNT per parent. -- =============================================================== SELECT _id INTO v_scheme_id FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.DepartmentProps' LIMIT 1; IF v_scheme_id IS NOT NULL THEN DECLARE v_root bigint; BEGIN SELECT _id INTO v_root FROM _objects WHERE _id_scheme = v_scheme_id AND _id_parent IS NULL LIMIT 1; -- Fallback: when no Department objects exist, seed=-1 exercises the -- groupby SQL generator; query returns 0 rows, no errors. v_root := COALESCE(v_root, -1); BEGIN v_sql := pvt_build_groupby_sql( p_scheme_id => v_scheme_id, p_filter => NULL, p_group_by => '[{"field":"_id_parent"}]'::jsonb, p_aggregations => '[{"alias":"cnt","$count":"*"}]'::jsonb, p_source_mode => 'tree_descendants', p_tree_ids => ARRAY[v_root]::bigint[], p_max_depth => 5); IF v_sql !~* 'WITH _pvt_tree' AND v_sql !~* 'RECURSIVE' THEN RAISE EXCEPTION 'expected tree-mode CTE in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / tree_descendants GROUP BY _id_parent + COUNT] groups=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Department / tree GROUP BY] %', v_msg; END; END; END IF; -- =================================================================== -- Projections: pvt_build_projection_sql. -- =================================================================== DECLARE v_emp_id bigint; BEGIN SELECT _id INTO v_emp_id FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.EmployeeProps' LIMIT 1; v_scheme_id := v_emp_id; END; IF v_scheme_id IS NOT NULL THEN -- Bare fields. BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[{"field":"FirstName"},{"field":"Age"}]'::jsonb, p_limit => 5); IF v_sql !~* 'AS "?FirstName"?' OR v_sql !~* 'AS "?Age"?' THEN RAISE EXCEPTION 'expected FirstName/Age aliases, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection bare fields] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection bare fields] %', v_msg; END; -- Base + props mixed with explicit aliases. BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[ {"field":"_id","alias":"id"}, {"field":"FirstName","alias":"name"}, {"field":"Salary","alias":"sal"} ]'::jsonb, p_order => '[{"field":"Salary","dir":"desc"}]'::jsonb, p_limit => 3); IF v_sql !~* 'AS "?id"?' OR v_sql !~* 'AS "?name"?' OR v_sql !~* 'AS "?sal"?' THEN RAISE EXCEPTION 'expected id/name/sal aliases, got: %', v_sql; END IF; IF v_sql !~* 'ORDER BY' THEN RAISE EXCEPTION 'expected ORDER BY in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection mixed base+props + order + limit] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection mixed base+props + order + limit] %', v_msg; END; -- $expr projection: computed column $year(HireDate). BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[ {"field":"FirstName"}, {"alias":"hire_year","$expr":{"$year":{"$field":"HireDate"}}} ]'::jsonb, p_limit => 5); IF v_sql !~* 'EXTRACT\(YEAR FROM .+\) AS "?hire_year"?' THEN RAISE EXCEPTION 'expected EXTRACT(YEAR FROM ...) AS hire_year, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $expr $year] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $expr $year] %', v_msg; END; -- $expr projection: $case ternary (free over Pro: Pro NotSupported). BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[ {"field":"FirstName"}, {"alias":"kind","$expr":{"$case":[ {"when":{"$gt":[{"$field":"Age"},{"$const":18}]}, "then":{"$const":"adult"}}, {"else":{"$const":"minor"}} ]}} ]'::jsonb, p_limit => 10); IF v_sql !~* 'CASE WHEN .+ THEN .+ ELSE .+ END' THEN RAISE EXCEPTION 'expected CASE WHEN ... THEN ... ELSE ... END, got: %', v_sql; END IF; IF v_sql !~* 'AS "?kind"?' THEN RAISE EXCEPTION 'expected AS kind, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $expr $case] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $expr $case] %', v_msg; END; -- $expr projection: $coalesce (free over Pro: Pro NotSupported on ??). BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[ {"alias":"display","$expr":{"$coalesce":[{"$field":"FirstName"},{"$const":"n/a"}]}} ]'::jsonb, p_limit => 5); IF v_sql !~* 'COALESCE\(' THEN RAISE EXCEPTION 'expected COALESCE(...), got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $coalesce] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $coalesce] %', v_msg; END; -- $expr projection: $concat (n-ary). BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[ {"alias":"label","$expr":{"$concat":[{"$field":"FirstName"},{"$const":" / "},{"$field":"Department"}]}} ]'::jsonb, p_limit => 5); IF v_sql !~* ' \|\| ' THEN RAISE EXCEPTION 'expected || concat operator, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $concat] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $concat] %', v_msg; END; -- Computed expression with filter + paging + DISTINCT. BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[{"field":"Department"}]'::jsonb, p_filter => '{"Salary":{"$gt":0}}'::jsonb, p_distinct => true, p_limit => 50); IF v_sql !~* 'SELECT DISTINCT' THEN RAISE EXCEPTION 'expected SELECT DISTINCT, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection DISTINCT + filter] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection DISTINCT + filter] %', v_msg; END; -- DISTINCT ON (Department) ordered by Salary desc. BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[{"field":"Department"},{"field":"FirstName"},{"field":"Salary"}]'::jsonb, p_distinct_on => '[{"field":"Department"}]'::jsonb, p_order => '[{"field":"Salary","dir":"desc"}]'::jsonb); IF v_sql !~* 'SELECT DISTINCT ON' THEN RAISE EXCEPTION 'expected SELECT DISTINCT ON, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection DISTINCT ON Department] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection DISTINCT ON Department] %', v_msg; END; -- Pure-base shortcut (Shape A): only _id requested. BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[{"field":"_id"}]'::jsonb, p_limit => 3); IF v_sql ~* '_pvt_cte' THEN RAISE EXCEPTION 'expected Shape A (no CTE) for pure-base projection, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection Shape A pure-base] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection Shape A pure-base] %', v_msg; END; -- $cast: explicit cast (free-only; Pro has no Convert.To* mapping). BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[ {"alias":"age_str","$expr":{"$cast":["text",{"$field":"Age"}]}} ]'::jsonb, p_limit => 3); IF v_sql !~* '::text' THEN RAISE EXCEPTION 'expected ::text cast, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $cast] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $cast] %', v_msg; END; -- Duplicate alias must raise. BEGIN BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[{"field":"FirstName","alias":"x"},{"field":"Age","alias":"x"}]'::jsonb); RAISE EXCEPTION 'expected duplicate-alias error, but no exception raised'; EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; IF v_msg NOT ILIKE '%duplicate alias%' THEN RAISE EXCEPTION 'unexpected error message: %', v_msg; END IF; END; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection duplicate alias rejected]'; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection duplicate alias rejected] %', v_msg; END; -- Empty projection must raise. BEGIN BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_scheme_id, p_projection => '[]'::jsonb); RAISE EXCEPTION 'expected empty-projection error, but no exception raised'; EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; IF v_msg NOT ILIKE '%non-empty%' THEN RAISE EXCEPTION 'unexpected error message: %', v_msg; END IF; END; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection empty array rejected]'; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection empty array rejected] %', v_msg; END; END IF; -- Tree-mode projection (descendants). DECLARE v_dep_scheme bigint; v_root2 bigint; BEGIN SELECT _id INTO v_dep_scheme FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.DepartmentProps' LIMIT 1; SELECT _id INTO v_root2 FROM _objects WHERE _id_scheme = v_dep_scheme AND _id_parent IS NULL LIMIT 1; -- Fallback: when no Department objects exist, seed=-1 exercises the -- projection SQL generator; query returns 0 rows, no errors. v_root2 := COALESCE(v_root2, -1); IF v_dep_scheme IS NOT NULL THEN BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_dep_scheme, p_projection => '[{"field":"_id"},{"field":"_id_parent"},{"field":"Name"}]'::jsonb, p_source_mode => 'tree_descendants', p_tree_ids => ARRAY[v_root2]::bigint[], p_max_depth => 5); IF v_sql !~* 'WITH _pvt_tree' AND v_sql !~* 'RECURSIVE' THEN RAISE EXCEPTION 'expected tree-mode CTE in SQL, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Department / projection tree_descendants] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Department / projection tree_descendants] %', v_msg; END; END IF; END; -- =================================================================== -- New $expr operators: trig, $log10, $now/$today/$utcNow, -- $dateTrunc, $regexReplace and predicate-side $regex/$iregex/$fts. -- All free-only (Pro has none of these mapped). -- =================================================================== DECLARE v_emp_id bigint; BEGIN SELECT _id INTO v_emp_id FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.EmployeeProps' LIMIT 1; IF v_emp_id IS NULL THEN v_skip := v_skip + 1; RAISE NOTICE 'SKIP [Employee / new $expr ops] no Employee scheme'; ELSE -- $sin / $cos / $tan / $log10 BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_emp_id, p_projection => '[ {"alias":"s","$expr":{"$sin":{"$const":0}}}, {"alias":"c","$expr":{"$cos":{"$const":0}}}, {"alias":"t","$expr":{"$tan":{"$const":0}}}, {"alias":"l","$expr":{"$log10":{"$const":1000}}} ]'::jsonb, p_limit => 1); IF v_sql !~* 'SIN\(' OR v_sql !~* 'COS\(' OR v_sql !~* 'TAN\(' OR v_sql !~* 'LOG\(' THEN RAISE EXCEPTION 'expected SIN/COS/TAN/LOG, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $sin $cos $tan $log10] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $sin $cos $tan $log10] %', v_msg; END; -- $now / $today / $utcNow BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_emp_id, p_projection => '[ {"alias":"now_ts","$expr":{"$now":[]}}, {"alias":"today", "$expr":{"$today":[]}}, {"alias":"utc_ts", "$expr":{"$utcNow":[]}} ]'::jsonb, p_limit => 1); IF v_sql !~* 'NOW\(\)' OR v_sql !~* 'CURRENT_DATE' THEN RAISE EXCEPTION 'expected NOW() and CURRENT_DATE, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $now $today $utcNow] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $now $today $utcNow] %', v_msg; END; -- $dateTrunc("month", HireDate) BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_emp_id, p_projection => '[ {"alias":"hire_month","$expr":{"$dateTrunc":["month",{"$field":"HireDate"}]}} ]'::jsonb, p_limit => 3); IF v_sql !~* 'DATE_TRUNC\(''month''' THEN RAISE EXCEPTION 'expected DATE_TRUNC(''month'',...), got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $dateTrunc month] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $dateTrunc month] %', v_msg; END; -- $regexReplace BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_emp_id, p_projection => '[ {"alias":"clean","$expr":{"$regexReplace":[{"$field":"FirstName"},{"$const":"[aeiou]"},{"$const":"_"}]}} ]'::jsonb, p_limit => 3); IF v_sql !~* 'REGEXP_REPLACE\(' THEN RAISE EXCEPTION 'expected REGEXP_REPLACE(...), got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $regexReplace] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $regexReplace] %', v_msg; END; -- $regex predicate via $expr filter (pvt_build_expr_predicate path). BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_emp_id, p_filter => '{"$expr":{"$iregex":[{"$field":"FirstName"},{"$const":"^[a-z]+$"}]}}'::jsonb); IF v_sql !~* ' ~\* ' THEN RAISE EXCEPTION 'expected ~* operator, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / filter $iregex via $expr] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / filter $iregex via $expr] %', v_msg; END; -- $regex shorthand on field. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_emp_id, p_filter => '{"FirstName":{"$regex":"^[A-Z]"}}'::jsonb); IF v_sql !~* ' ~ ''' THEN RAISE EXCEPTION 'expected ~ operator with literal, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / filter $regex shorthand] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / filter $regex shorthand] %', v_msg; END; -- $fts predicate (multi-field, object form). BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_emp_id, p_filter => '{"$expr":{"$fts":{"query":{"$const":"ivan or john"},"fields":[{"$field":"FirstName"},{"$field":"LastName"}],"language":"simple"}}}'::jsonb); IF v_sql !~* 'to_tsvector\(' OR v_sql !~* 'websearch_to_tsquery\(' OR v_sql !~* '@@' THEN RAISE EXCEPTION 'expected to_tsvector + websearch_to_tsquery + @@, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / filter $fts multi-field] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / filter $fts multi-field] %', v_msg; END; -- $fts shorthand on a single field. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_emp_id, p_filter => '{"FirstName":{"$fts":"ivan"}}'::jsonb); IF v_sql !~* 'to_tsvector\(' OR v_sql !~* 'websearch_to_tsquery\(' THEN RAISE EXCEPTION 'expected FTS via to_tsvector / websearch_to_tsquery, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / filter $fts shorthand] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / filter $fts shorthand] %', v_msg; END; -- $padLeft / $indexOf already wired earlier — quick smoke. BEGIN v_sql := pvt_build_projection_sql( p_scheme_id => v_emp_id, p_projection => '[ {"alias":"padded","$expr":{"$padLeft":[{"$field":"FirstName"},{"$const":10},{"$const":"*"}]}}, {"alias":"pos", "$expr":{"$indexOf":[{"$field":"FirstName"},{"$const":"a"}]}} ]'::jsonb, p_limit => 2); IF v_sql !~* 'LPAD\(' OR v_sql !~* 'POSITION\(' THEN RAISE EXCEPTION 'expected LPAD/POSITION, got: %', v_sql; END IF; EXECUTE 'SELECT count(*) FROM (' || v_sql || ') _t' INTO v_count; v_pass := v_pass + 1; RAISE NOTICE 'OK [Employee / projection $padLeft + $indexOf] rows=%', v_count; EXCEPTION WHEN OTHERS THEN v_fail := v_fail + 1; GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT; RAISE NOTICE 'FAIL [Employee / projection $padLeft + $indexOf] %', v_msg; END; END IF; END; RAISE NOTICE '----------------------------------------------------------'; RAISE NOTICE 'pvt smoke summary: % passed, % failed, % skipped', v_pass, v_fail, v_skip; RAISE NOTICE '----------------------------------------------------------'; IF v_fail > 0 THEN RAISE EXCEPTION 'pvt smoke: % case(s) failed (see NOTICE lines above)', v_fail; END IF; END $SMOKE$; -- ===================================================================== -- SQL inspection: dump a few generated queries verbatim so you can see -- both the base-pushdown predicate inside the CTE (`WHERE o._id_scheme -- = X AND `) and the residual outer `WHERE` over the CTE. -- Runs even if the smoke above raised --- wrap separately. -- ===================================================================== DO $INSPECT$ DECLARE v_scheme_id bigint; v_sql text; v_dump text; v_inspect jsonb[]; v_labels text[]; v_tag text; v_has_cte boolean; v_has_narrow_grp boolean; v_has_narrow_join boolean; v_has_wide_join boolean; v_shape_fail_cnt int := 0; i int; BEGIN SELECT _id INTO v_scheme_id FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.EmployeeProps' LIMIT 1; IF v_scheme_id IS NULL THEN RAISE NOTICE 'inspect: Employee scheme not found, skipping SQL dump'; RETURN; END IF; -- Each label is tagged with the expected outer shape so we can -- assert it programmatically. Recognized prefixes: -- SHAPE_A: no CTE, plain SELECT over _objects. -- NARROW: Pro-shape pivot CTE (`GROUP BY v._id_object`) + outer -- `JOIN _objects o ON o._id = _pvt_cte._id_object`. -- WIDE: legacy wide CTE (`INNER|LEFT JOIN _values v ON -- v._id_object = o._id` + 21-col GROUP BY). v_labels := ARRAY[ 'SHAPE_A: pure base _id>0 (expect no CTE, no _values)', 'SHAPE_A: pure base $or all-base (expect no CTE)', 'SHAPE_A: pure base $not (expect no CTE)', 'SHAPE_A: empty filter (expect just SELECT _id FROM _objects o WHERE _id_scheme=X)', 'NARROW: base+props AND (pushdown _id, residual FirstName)', 'SHAPE_A: $or all-base (full pushdown, residual NULL)', 'NARROW: $or mixed base/props (no pushdown, stays in outer WHERE)', 'NARROW: expr arithmetic on props (residual UPPER+Age etc.)', 'SHAPE_A: expr in base (full pushdown -- expect SHAPE A)', 'WIDE: NULL props (LEFT JOIN to catch missing _values rows)', 'NARROW: NOT NULL props ($notNull is satisfied by INNER JOIN)', 'NARROW: simple dict ContainsKey (PhoneDirectory[work])', 'NARROW: simple dict indexer eq (PhoneDirectory[work] = ...)', 'NARROW: scalar prop eq (FirstName=Ivan)', 'NARROW: scalar prop + base AND (FirstName + _id range)', 'NARROW: ORDER BY base only on prop query (Age desc)' ]; v_inspect := ARRAY[ '{"_id":{"$gt":0}}'::jsonb, '{"$or":[{"_id":{"$lt":10}},{"_id":{"$gt":100}}]}'::jsonb, '{"$not":{"_id":{"$gt":1000000}}}'::jsonb, '{}'::jsonb, '{"_id":{"$gt":0},"FirstName":{"$startsWith":"A"}}'::jsonb, '{"$or":[{"_id":{"$lt":10}},{"_id":{"$gt":100}}]}'::jsonb, '{"$or":[{"_id":{"$lt":10}},{"FirstName":"Ivan"}]}'::jsonb, '{"$gt":[{"$add":[{"$field":"Age"},{"$const":1}]},{"$const":18}]}'::jsonb, '{"$between":[{"$field":"_id"},{"$const":0},{"$const":1000000}]}'::jsonb, '{"EmployeeCode":{"$null":true}}'::jsonb, '{"EmployeeCode":{"$notNull":true}}'::jsonb, '{"PhoneDirectory.ContainsKey":"work"}'::jsonb, '{"PhoneDirectory[work]":{"$eq":"+7-000-0000000"}}'::jsonb, '{"FirstName":"Ivan"}'::jsonb, '{"FirstName":{"$startsWith":"A"},"_id":{"$gt":0}}'::jsonb, '{"Age":{"$gt":18}}'::jsonb ]; FOR i IN 1..array_length(v_inspect, 1) LOOP BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => v_inspect[i], p_limit => 5); RAISE NOTICE E'----- INSPECT [%] -----\nFILTER: %\nSQL:\n%', v_labels[i], v_inspect[i]::text, v_sql; -- ---- Shape assertion driven by the label prefix -------- v_tag := split_part(v_labels[i], ':', 1); v_has_cte := position('WITH ' IN v_sql) > 0 OR position('WITH _pvt_cte' IN v_sql) > 0 OR position('WITH RECURSIVE' IN v_sql) > 0; v_has_narrow_grp := position('GROUP BY v._id_object' IN v_sql) > 0; v_has_narrow_join := position('JOIN _objects o ON o._id = _pvt_cte._id_object' IN v_sql) > 0; v_has_wide_join := position('JOIN _values v ON v._id_object = o._id' IN v_sql) > 0; IF v_tag = 'SHAPE_A' THEN IF v_has_cte THEN v_shape_fail_cnt := v_shape_fail_cnt + 1; RAISE NOTICE 'SHAPE-FAIL [%]: expected SHAPE_A (no CTE) but got CTE', v_labels[i]; END IF; ELSIF v_tag = 'NARROW' THEN IF NOT (v_has_narrow_grp AND v_has_narrow_join) OR v_has_wide_join THEN v_shape_fail_cnt := v_shape_fail_cnt + 1; RAISE NOTICE 'SHAPE-FAIL [%]: expected NARROW shape (GROUP BY v._id_object + JOIN _objects o ON _pvt_cte._id_object, no wide _values JOIN)', v_labels[i]; END IF; ELSIF v_tag = 'WIDE' THEN IF NOT v_has_wide_join OR v_has_narrow_grp THEN v_shape_fail_cnt := v_shape_fail_cnt + 1; RAISE NOTICE 'SHAPE-FAIL [%]: expected WIDE shape (JOIN _values v ON v._id_object = o._id)', v_labels[i]; END IF; END IF; EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'INSPECT [%] FAILED: %', v_labels[i], SQLERRM; v_shape_fail_cnt := v_shape_fail_cnt + 1; END; END LOOP; -- ---- Tree-mode narrow assertion ------------------------------------ -- Tree pushdown (Pro CHANGELOG 2.0.1 parity): when source_mode=tree -- the recursive `_pvt_tree` CTE is still emitted, but its -- restriction (`o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree))`) must be -- folded into the narrow IN-subquery rather than appended to a -- wide JOIN WHERE. We assert both signatures appear together and -- that the wide _values JOIN does NOT. BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_scheme_id, p_filter => '{"FirstName":{"$startsWith":"A"}}'::jsonb, p_limit => 5, p_source_mode => 'tree', p_tree_ids => ARRAY[v_scheme_id]::bigint[]); RAISE NOTICE E'----- INSPECT [NARROW: tree-mode pushdown (_pvt_tree folded into IN-subquery)] -----\nFILTER: %\nSQL:\n%', '{"FirstName":{"$startsWith":"A"}} +tree', v_sql; IF position('WITH RECURSIVE' IN v_sql) = 0 OR position('GROUP BY v._id_object' IN v_sql) = 0 OR position('o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree))' IN v_sql) = 0 OR position('JOIN _values v ON v._id_object = o._id' IN v_sql) > 0 THEN v_shape_fail_cnt := v_shape_fail_cnt + 1; RAISE NOTICE 'SHAPE-FAIL [NARROW: tree-mode pushdown]: expected WITH RECURSIVE _pvt_tree + narrow GROUP BY + tree filter folded into IN-subquery, no wide _values JOIN'; END IF; EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'INSPECT [NARROW: tree-mode pushdown] FAILED: %', SQLERRM; v_shape_fail_cnt := v_shape_fail_cnt + 1; END; -- ---- Tree-modes family assertion (5 CTE shapes) -------------------- -- For each explicit tree mode we assert the right CTE shape: -- tree_descendants / tree_ancestors -> WITH RECURSIVE -- tree_children / tree_roots / tree_leaves -> non-recursive WITH -- In every case the narrow pivot must be selected (no wide -- _values JOIN) and the tree restriction folded into the -- ANY-array (`o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree...`). DECLARE v_tree_labels text[]; v_tree_modes text[]; v_recursive boolean[]; v_root bigint; v_dep_scheme bigint; j int; BEGIN SELECT _id INTO v_dep_scheme FROM _schemes WHERE _name = 'redb.Tests.Integration.Models.DepartmentProps' LIMIT 1; SELECT _id INTO v_root FROM _objects WHERE _id_scheme = v_dep_scheme AND _id_parent IS NULL LIMIT 1; IF v_dep_scheme IS NULL OR v_root IS NULL THEN RAISE NOTICE 'inspect: Department scheme/root not found, skipping tree-modes assertion'; ELSE v_tree_labels := ARRAY[ 'NARROW: tree_descendants (recursive walk DOWN)', 'NARROW: tree_children (single-level, non-recursive)', 'NARROW: tree_roots (_id_parent IS NULL, non-recursive)', 'NARROW: tree_leaves (no children, non-recursive)', 'NARROW: tree_ancestors (recursive walk UP)' ]; v_tree_modes := ARRAY[ 'tree_descendants', 'tree_children', 'tree_roots', 'tree_leaves', 'tree_ancestors' ]; v_recursive := ARRAY[true, false, false, false, true]; FOR j IN 1..array_length(v_tree_modes, 1) LOOP BEGIN v_sql := pvt_build_query_sql( p_scheme_id => v_dep_scheme, p_filter => '{"IsActive":{"$eq":true}}'::jsonb, p_limit => 5, p_source_mode => v_tree_modes[j], p_tree_ids => ARRAY[v_root]::bigint[]); RAISE NOTICE E'----- INSPECT [%] -----\nMODE: %\nSQL:\n%', v_tree_labels[j], v_tree_modes[j], v_sql; v_has_cte := position('WITH ' IN v_sql) > 0; v_has_narrow_grp := position('GROUP BY v._id_object' IN v_sql) > 0; v_has_wide_join := position('JOIN _values v ON v._id_object = o._id' IN v_sql) > 0; IF NOT v_has_cte OR NOT v_has_narrow_grp OR v_has_wide_join OR position('o._id = ANY(ARRAY(SELECT _id FROM _pvt_tree' IN v_sql) = 0 OR (v_recursive[j] AND position('WITH RECURSIVE' IN v_sql) = 0) OR (NOT v_recursive[j] AND position('WITH RECURSIVE' IN v_sql) > 0) THEN v_shape_fail_cnt := v_shape_fail_cnt + 1; RAISE NOTICE 'SHAPE-FAIL [%]: expected % CTE + narrow GROUP BY + IN(_pvt_tree) fold, no wide _values JOIN', v_tree_labels[j], CASE WHEN v_recursive[j] THEN 'WITH RECURSIVE' ELSE 'non-recursive WITH' END; END IF; EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'INSPECT [%] FAILED: %', v_tree_labels[j], SQLERRM; v_shape_fail_cnt := v_shape_fail_cnt + 1; END; END LOOP; END IF; END; IF v_shape_fail_cnt > 0 THEN RAISE EXCEPTION 'pvt inspect: % shape assertion(s) failed (see SHAPE-FAIL NOTICE lines above)', v_shape_fail_cnt; END IF; END $INSPECT$; Path: redb/redb.Postgres/sql/v2-pvt/99_smoke_tests.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.Postgres/sql/v2-pvt/99_smoke_tests.sql ---- -- ===================================================================== -- 99_smoke_tests.sql -- --------------------------------------------------------------------- -- Ручные smoke-тесты v2-pvt. Все SELECT'ы закомментированы — файл -- безопасно деплоить как есть. Скопируй нужный сниппет в psql и -- замени плейсхолдеры / / на -- реальные id из своей БД. -- -- НОВАЯ АРХИТЕКТУРА (v0.1.0): -- * SQL-сторона отдаёт ТОЛЬКО строку SQL (pvt_build_query_sql). -- * Никакого RETURN NEXT / jsonb_agg внутри pvt-функций нет. -- * Материализацию (get_object_json, COUNT, EXISTS, projection) -- накладывает клиентский слой (C# / Python / Go). -- * Здесь демонстрируются оба round-trip'а — фаза build и фаза exec. -- ===================================================================== /* -- 0. Module version check ---------------------------------------------- SELECT pvt_module_version(); -- 1. Фаза build — простой $eq на скалярном поле ----------------------- SELECT pvt_build_query_sql( p_scheme_id => , p_filter => jsonb_build_object('Name', jsonb_build_object('$eq', 'Acme')) ); -- 2. Range + IN + sort + paging — фаза build --------------------------- SELECT pvt_build_query_sql( p_scheme_id => , p_filter => '{ "$and": [ { "Age": { "$gte": 18, "$lte": 65 } }, { "Status": { "$in": ["active","trial"] } } ] }'::jsonb, p_order => '[{"field":"Age","dir":"desc","nulls":"last"}]'::jsonb, p_limit => 50, p_offset => 0 ); -- 3. NULL-check — выбирает LEFT JOIN внутри CTE ------------------------ SELECT pvt_build_query_sql( p_scheme_id => , p_filter => '{ "MiddleName": { "$null": true } }'::jsonb ); -- 4. Логические $or + $not -------------------------------------------- SELECT pvt_build_query_sql( p_scheme_id => , p_filter => '{ "$or": [ { "Name": { "$ilike": "%foo%" } }, { "$not": { "Age": { "$lt": 10 } } } ] }'::jsonb ); -- 5. Tree mode (descendant scan) -------------------------------------- SELECT pvt_build_query_sql( p_scheme_id => , p_filter => NULL, p_source_mode => 'tree', p_tree_ids => ARRAY[]::bigint[], p_max_depth => 5 ); -- 6. Фаза execute — full materialization (имитация C#-обёртки) -------- DO $$ DECLARE v_inner text; v_wrapped text; v_row jsonb; BEGIN v_inner := pvt_build_query_sql( , jsonb_build_object('Name', jsonb_build_object('$startsWith', 'A')), 5, 0, NULL, NULL, false, 'flat', NULL ); v_wrapped := 'SELECT get_object_json(t._id, 3) FROM (' || v_inner || ') t'; RAISE NOTICE 'wrapped SQL: %', v_wrapped; FOR v_row IN EXECUTE v_wrapped LOOP RAISE NOTICE 'row: %', v_row; END LOOP; END $$; -- 7. COUNT-обёртка (то же, что C# делает через ExecuteScalarAsync) WITH inner_sql AS ( SELECT pvt_build_query_sql( , jsonb_build_object('Status', jsonb_build_object('$eq', 'active')), NULL, 0, NULL, NULL, false, 'flat', NULL ) AS sql_text ) SELECT 'SELECT count(*) FROM (' || sql_text || ') t' AS count_sql FROM inner_sql; -- 8. EXISTS-обёртка --------------------------------------------------- WITH inner_sql AS ( SELECT pvt_build_query_sql( , jsonb_build_object('Email', jsonb_build_object('$eq', 'a@b.c')), 1, 0, NULL, NULL, false, 'flat', NULL ) AS sql_text ) SELECT 'SELECT EXISTS (' || sql_text || ')' AS exists_sql FROM inner_sql; */ DO $$ BEGIN RAISE NOTICE 'v2-pvt smoke-tests file loaded (all statements are commented out).'; END $$; Path: redb/redb.Postgres/sql/v2-pvt/_bundle.ps1 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.Postgres/sql/v2-pvt/_bundle.ps1 ---- # ===================================================================== # _bundle.ps1 # --------------------------------------------------------------------- # Конкатенирует все *.sql из текущей папки v2-pvt (по числовому префиксу: # 00, 01, ..., 20, 99) в один файл pvt_bundle.sql. Удобно для деплоя: # psql -h -U -d -v ON_ERROR_STOP=1 -f pvt_bundle.sql # # Игнорирует: # - подпапки (deprecated/); # - сам этот скрипт и любые *.ps1; # - 99_smoke_tests.sql (по умолчанию НЕ включается; чтобы включить — флаг -IncludeSmoke); # - pvt_bundle.sql (если уже лежит рядом — перезаписывается). # # Использование: # ./_bundle.ps1 # ./_bundle.ps1 -IncludeSmoke # ./_bundle.ps1 -OutFile pvt_full.sql -IncludeSmoke # ===================================================================== param( [string]$OutFile = 'pvt_bundle.sql', [switch]$IncludeSmoke ) $ErrorActionPreference = 'Stop' $here = Split-Path -Parent $MyInvocation.MyCommand.Path Set-Location $here $files = Get-ChildItem -Path $here -Filter '*.sql' -File | Where-Object { $_.Name -ne $OutFile } | Where-Object { $IncludeSmoke -or ($_.Name -ne '99_smoke_tests.sql' -and $_.Name -ne '99_smoke_auto.sql') } | Sort-Object { $_.Name.ToUpperInvariant() } -Culture "" if (-not $files) { throw "No *.sql files to bundle in $here" } $outPath = Join-Path $here $OutFile $utf8NoBom = New-Object System.Text.UTF8Encoding($false) $header = @" -- ===================================================================== -- pvt_bundle.sql — AUTO-GENERATED, DO NOT EDIT BY HAND -- --------------------------------------------------------------------- -- Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz') -- Generator: redb.Postgres/sql/v2-pvt/_bundle.ps1 -- Source files: $($files.Count) (alphabetical by numeric prefix) -- Include smoke tests: $IncludeSmoke -- -- To re-generate, run from this folder: -- pwsh ./_bundle.ps1 # без smoke -- pwsh ./_bundle.ps1 -IncludeSmoke # вместе со смоук-тестами -- -- To deploy: -- psql -h -U -d -v ON_ERROR_STOP=1 -f $OutFile -- ===================================================================== "@ $sb = [System.Text.StringBuilder]::new() [void]$sb.Append($header) foreach ($f in $files) { [void]$sb.AppendLine() [void]$sb.AppendLine('-- =====================================================================') [void]$sb.AppendLine("-- >>> BEGIN FILE: $($f.Name)") [void]$sb.AppendLine('-- =====================================================================') $content = [System.IO.File]::ReadAllText($f.FullName, $utf8NoBom) [void]$sb.Append($content) if (-not $content.EndsWith("`n")) { [void]$sb.AppendLine() } [void]$sb.AppendLine('-- =====================================================================') [void]$sb.AppendLine("-- <<< END FILE: $($f.Name)") [void]$sb.AppendLine('-- =====================================================================') } [System.IO.File]::WriteAllText($outPath, $sb.ToString(), $utf8NoBom) Write-Host "Bundled $($files.Count) file(s) into:" -ForegroundColor Green Write-Host " $outPath" -ForegroundColor Green Write-Host "" Write-Host "Files included:" -ForegroundColor Cyan $files | ForEach-Object { Write-Host (" " + $_.Name) } Path: redb/redb.Postgres/sql/v2-pvt/_fork-legacy-helpers.ps1 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.Postgres/sql/v2-pvt/_fork-legacy-helpers.ps1 ---- # ===================================================================== # _fork-legacy-helpers.ps1 # --------------------------------------------------------------------- # One-shot script that forks 8 helper functions from legacy SQL into # the v2-pvt module under the pvt_* prefix. # # Usage (from repo root): # pwsh redb.Postgres/sql/v2-pvt/_fork-legacy-helpers.ps1 # # Idempotent: overwrites target files every run. # Does NOT touch legacy SQL files. # ===================================================================== [CmdletBinding()] param( [string]$RepoRoot = (Resolve-Path "$PSScriptRoot/../../..").Path, [string]$ForkDate = '2026-05-18' ) $ErrorActionPreference = 'Stop' $facets = Join-Path $RepoRoot 'redb.Postgres/sql/redb_facets_search.sql' $lazy = Join-Path $RepoRoot 'redb.Postgres/sql/redb_lazy_loading_search.sql' $outDir = Join-Path $RepoRoot 'redb.Postgres/sql/v2-pvt' if (-not (Test-Path $facets)) { throw "Source not found: $facets" } if (-not (Test-Path $lazy)) { throw "Source not found: $lazy" } $facetsLines = Get-Content -LiteralPath $facets $lazyLines = Get-Content -LiteralPath $lazy # Cross-reference replacements applied to every forked function body. # Order matters only if patterns overlap — these do not. $nameMap = @( @{ From = '_normalize_base_field_name'; To = 'pvt_normalize_base_field_name' } @{ From = '_parse_field_path'; To = 'pvt_parse_field_path' } @{ From = '_get_listitem_field_type_info';To = 'pvt_get_listitem_field_type_info' } @{ From = '_find_structure_info'; To = 'pvt_find_structure_info' } @{ From = '_build_inner_condition'; To = 'pvt_build_inner_condition' } @{ From = '_build_single_facet_condition';To = 'pvt_build_single_facet_condition' } @{ From = 'build_hierarchical_conditions';To = 'pvt_build_hierarchical_conditions' } @{ From = 'get_object_base_fields'; To = 'pvt_get_object_base_fields' } ) # Note on order: `_get_listitem_field_type_info` shares no overlapping # substring with other From values; `build_hierarchical_conditions` is # matched without the leading underscore by design (legacy uses no # underscore prefix for it). To avoid partial matches we apply with # word-boundary regex below. function Apply-NameMap { param([string[]]$Lines) $text = ($Lines -join "`n") foreach ($m in $nameMap) { # Word-boundary replacement; \b matches start/end of identifier. $pattern = '(?