Bundle: redb / redb.MSSql (redb.MSSql.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.MSSql/Data/SqlBulkOperations.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.MSSql/Data/SqlBulkOperations.cs ---- using Microsoft.Data.SqlClient; using redb.Core.Data; using redb.Core.Models.Entities; using System.Data; using System.Text; namespace redb.MSSql.Data; /// /// MS SQL Server implementation of IBulkOperations using SqlBulkCopy. /// Much faster than individual INSERTs for large datasets. /// public class SqlBulkOperations : IBulkOperations { private readonly IRedbConnection _db; /// /// Create bulk operations handler. /// Uses the same connection as the context for transaction consistency. /// public SqlBulkOperations(IRedbConnection db) { _db = db ?? throw new ArgumentNullException(nameof(db)); } /// The timeout of one SqlBulkCopy, read at each load; the context hands its BulkInsertTimeout in. internal Func TimeoutSource { get; init; } = static () => null; /// /// Sets from the configured timeout, rounded up to whole seconds /// ( is the driver's "no limit"); null keeps the driver's 30 seconds, which the /// connection string's Command Timeout does not reach. /// internal static void ApplyTimeout(SqlBulkCopy bulkCopy, TimeSpan? timeout) { if (timeout is { } value) bulkCopy.BulkCopyTimeout = (int)Math.Min(int.MaxValue, Math.Ceiling(value.TotalSeconds)); } /// /// Up to this many rows an insert runs as parameterized multi-row INSERT statements, above it through SqlBulkCopy. /// /// The foreign keys of a bulk load (_values._id_object, _objects._id_parent to PK__objects) /// are validated by a plan built for a load of unknown size, which reads PK__objects beyond the keys the load /// names and waits for the rows of concurrent writers: two writers that each hold their own new object wait for /// each other's, a deadlock between saves of different objects. An INSERT of a few rows validates by a seek per key /// and touches only the rows it references. A larger load keeps SqlBulkCopy: measured on SQL Server 2022, the /// statements are faster up to a few hundred rows (one object of about 70 values, 50 objects of 4 values) and /// slower from several hundred (10 objects, about 700 values), where compiling statements of 2000 parameters /// outweighs the bulk load. /// /// internal const int InsertByStatementMaxRows = 250; // SQL Server allows 2100 parameters per command. private const int ObjectColumns = 22; private const int ValueColumns = 16; private const int ObjectRowsPerStatement = 2000 / ObjectColumns; private const int ValueRowsPerStatement = 2000 / ValueColumns; /// /// Bulk insert objects: statements for a small set, SqlBulkCopy for a large one (). /// public async Task BulkInsertObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var objectsList = objects.ToList(); if (objectsList.Count == 0) return; if (objectsList.Count <= InsertByStatementMaxRows) { await _db.ExecuteAtomicAsync(async () => { foreach (var chunk in objectsList.Chunk(ObjectRowsPerStatement)) { cancellationToken.ThrowIfCancellationRequested(); await InsertObjectsByStatementAsync(chunk, cancellationToken); } }); return; } await _db.ExecuteAtomicAsync(async () => { var conn = (SqlConnection)await _db.GetUnderlyingConnectionAsync(); var transaction = (_db.CurrentTransaction as SqlRedbTransaction)?.SqlTransaction; using var bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.CheckConstraints, transaction) { DestinationTableName = "_objects", BatchSize = 5000 }; ApplyTimeout(bulkCopy, TimeoutSource()); MapObjectColumns(bulkCopy); var dataTable = CreateObjectsDataTable(objectsList); await bulkCopy.WriteToServerAsync(dataTable, cancellationToken); }); } /// /// Bulk insert values: statements for a small set, SqlBulkCopy for a large one (). /// The rows keep their order, array parents before their elements. /// public async Task BulkInsertValuesAsync(IEnumerable values, CancellationToken cancellationToken = default) { var valuesList = values.ToList(); if (valuesList.Count == 0) return; if (valuesList.Count <= InsertByStatementMaxRows) { await _db.ExecuteAtomicAsync(async () => { foreach (var chunk in valuesList.Chunk(ValueRowsPerStatement)) { cancellationToken.ThrowIfCancellationRequested(); await InsertValuesByStatementAsync(chunk, cancellationToken); } }); return; } await _db.ExecuteAtomicAsync(async () => { var conn = (SqlConnection)await _db.GetUnderlyingConnectionAsync(); var transaction = (_db.CurrentTransaction as SqlRedbTransaction)?.SqlTransaction; using var bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.CheckConstraints, transaction) { DestinationTableName = "_values", BatchSize = 10000 }; ApplyTimeout(bulkCopy, TimeoutSource()); MapValueColumns(bulkCopy); var dataTable = CreateValuesDataTable(valuesList); await bulkCopy.WriteToServerAsync(dataTable, cancellationToken); }); } /// /// Bulk update objects using MERGE statement. /// 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.Count == 0) return; // MSSQL parameter limit ~2100, 21 columns per object = max 100 objects per batch const int batchSize = 95; foreach (var batch in objectsList.Chunk(batchSize)) { cancellationToken.ThrowIfCancellationRequested(); await ExecuteObjectsMergeAsync(batch, cancellationToken); } } /// /// Execute MERGE for a batch of objects. /// Uses explicit CAST for varbinary columns to avoid type inference errors. /// private async Task ExecuteObjectsMergeAsync(RedbObjectRow[] batch, CancellationToken cancellationToken) { var sb = new StringBuilder(); var parameters = new List(); sb.AppendLine("MERGE INTO _objects AS target"); sb.AppendLine("USING (VALUES"); for (int i = 0; i < batch.Length; i++) { var obj = batch[i]; var offset = i * 21; // 21 columns per row - keep in sync with the source list and parameter order below if (i > 0) sb.AppendLine(","); // Cast varbinary columns explicitly to avoid type inference errors sb.Append($" (@p{offset}, @p{offset + 1}, @p{offset + 2}, @p{offset + 3}, @p{offset + 4}, "); sb.Append($"@p{offset + 5}, @p{offset + 6}, @p{offset + 7}, @p{offset + 8}, @p{offset + 9}, "); sb.Append($"@p{offset + 10}, @p{offset + 11}, @p{offset + 12}, @p{offset + 13}, @p{offset + 14}, "); sb.Append($"@p{offset + 15}, @p{offset + 16}, CAST(@p{offset + 17} AS VARBINARY(MAX)), @p{offset + 18}, @p{offset + 19}, @p{offset + 20})"); parameters.Add(obj.Id); parameters.Add((object?)obj.IdParent ?? DBNull.Value); parameters.Add(obj.IdScheme); parameters.Add((object?)obj.Name ?? DBNull.Value); parameters.Add(obj.IdOwner); parameters.Add(obj.IdWhoChange); parameters.Add(obj.DateModify); parameters.Add((object?)obj.DateBegin ?? DBNull.Value); parameters.Add((object?)obj.DateComplete ?? DBNull.Value); parameters.Add((object?)obj.Key ?? DBNull.Value); parameters.Add((object?)obj.ValueLong ?? DBNull.Value); parameters.Add((object?)obj.ValueString ?? DBNull.Value); parameters.Add((object?)obj.ValueGuid ?? DBNull.Value); parameters.Add((object?)obj.ValueBool ?? DBNull.Value); parameters.Add((object?)obj.ValueDouble ?? DBNull.Value); parameters.Add((object?)obj.ValueNumeric ?? DBNull.Value); parameters.Add((object?)obj.ValueDatetime ?? DBNull.Value); parameters.Add((object?)obj.ValueBytes ?? DBNull.Value); parameters.Add((object?)obj.Note ?? DBNull.Value); parameters.Add((object?)obj.Hash ?? DBNull.Value); parameters.Add((object?)obj.ValueUnique ?? DBNull.Value); } sb.AppendLine(); sb.AppendLine(") AS source(_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("ON target._id = source._id"); sb.AppendLine("WHEN MATCHED THEN UPDATE SET"); sb.AppendLine(" _id_parent = source._id_parent,"); sb.AppendLine(" _id_scheme = source._id_scheme,"); sb.AppendLine(" _name = source._name,"); sb.AppendLine(" _id_owner = source._id_owner,"); sb.AppendLine(" _id_who_change = source._id_who_change,"); sb.AppendLine(" _date_modify = source._date_modify,"); sb.AppendLine(" _date_begin = source._date_begin,"); sb.AppendLine(" _date_complete = source._date_complete,"); sb.AppendLine(" _key = source._key,"); sb.AppendLine(" _value_long = source._value_long,"); sb.AppendLine(" _value_string = source._value_string,"); sb.AppendLine(" _value_guid = source._value_guid,"); sb.AppendLine(" _value_bool = source._value_bool,"); sb.AppendLine(" _value_double = source._value_double,"); sb.AppendLine(" _value_numeric = source._value_numeric,"); sb.AppendLine(" _value_datetime = source._value_datetime,"); sb.AppendLine(" _value_bytes = source._value_bytes,"); sb.AppendLine(" _note = source._note,"); sb.AppendLine(" _hash = source._hash,"); sb.AppendLine(" _value_unique = source._value_unique;"); await _db.ExecuteAsync(sb.ToString(), parameters.ToArray(), cancellationToken); } /// /// Bulk update values using MERGE statement. /// 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.Count == 0) return; // MSSQL parameter limit ~2100, 14 columns per value = max 150 values per batch const int batchSize = 140; foreach (var batch in valuesList.Chunk(batchSize)) { cancellationToken.ThrowIfCancellationRequested(); await ExecuteValuesMergeAsync(batch, cancellationToken); } } /// /// Execute MERGE for a batch of values. /// Uses explicit CAST for varbinary columns to avoid type inference errors. /// private async Task ExecuteValuesMergeAsync(RedbValue[] batch, CancellationToken cancellationToken) { var sb = new StringBuilder(); var parameters = new List(); sb.AppendLine("MERGE INTO _values AS target"); sb.AppendLine("USING (VALUES"); for (int i = 0; i < batch.Length; i++) { var val = batch[i]; var offset = i * 14; // 14 columns per row - keep in sync with the source list and parameter order below if (i > 0) sb.AppendLine(","); // Cast varbinary column (_ByteArray at offset+7) explicitly sb.Append($" (@p{offset}, @p{offset + 1}, @p{offset + 2}, @p{offset + 3}, @p{offset + 4}, "); sb.Append($"@p{offset + 5}, @p{offset + 6}, CAST(@p{offset + 7} AS VARBINARY(MAX)), @p{offset + 8}, @p{offset + 9}, "); sb.Append($"@p{offset + 10}, @p{offset + 11}, @p{offset + 12}, @p{offset + 13})"); parameters.Add(val.Id); parameters.Add((object?)val.String ?? DBNull.Value); parameters.Add((object?)val.Long ?? DBNull.Value); parameters.Add((object?)val.Guid ?? DBNull.Value); parameters.Add((object?)val.Double ?? DBNull.Value); parameters.Add((object?)val.DateTimeOffset ?? DBNull.Value); parameters.Add((object?)val.Boolean ?? DBNull.Value); parameters.Add((object?)val.ByteArray ?? DBNull.Value); parameters.Add((object?)val.Numeric ?? DBNull.Value); parameters.Add((object?)val.ListItem ?? DBNull.Value); parameters.Add((object?)val.Object ?? DBNull.Value); parameters.Add((object?)val.Unique ?? DBNull.Value); parameters.Add((object?)val.ArrayParentId ?? DBNull.Value); parameters.Add((object?)val.ArrayIndex ?? DBNull.Value); } sb.AppendLine(); sb.AppendLine(") AS source(_id, _String, _Long, _Guid, _Double, _DateTimeOffset, _Boolean,"); sb.AppendLine(" _ByteArray, _Numeric, _ListItem, _Object, _unique, _array_parent_id, _array_index)"); sb.AppendLine("ON target._id = source._id"); sb.AppendLine("WHEN MATCHED THEN UPDATE SET"); sb.AppendLine(" [_String] = source._String,"); sb.AppendLine(" [_Long] = source._Long,"); sb.AppendLine(" [_Guid] = source._Guid,"); sb.AppendLine(" [_Double] = source._Double,"); sb.AppendLine(" [_DateTimeOffset] = source._DateTimeOffset,"); sb.AppendLine(" [_Boolean] = source._Boolean,"); sb.AppendLine(" [_ByteArray] = source._ByteArray,"); sb.AppendLine(" [_Numeric] = source._Numeric,"); sb.AppendLine(" [_ListItem] = source._ListItem,"); sb.AppendLine(" [_Object] = source._Object,"); sb.AppendLine(" [_unique] = source._unique,"); sb.AppendLine(" [_array_parent_id] = source._array_parent_id,"); sb.AppendLine(" [_array_index] = source._array_index;"); 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.Length == 0) return; // MSSQL uses STRING_SPLIT instead of array parameter var idList = string.Join(",", ids); await _db.ExecuteAsync( $"DELETE FROM _objects WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ','))", new object[] { idList }, cancellationToken); } /// /// Bulk delete values by IDs. /// public async Task BulkDeleteValuesAsync(IEnumerable valueIds, CancellationToken cancellationToken = default) { var ids = valueIds.ToArray(); if (ids.Length == 0) return; var idList = string.Join(",", ids); await _db.ExecuteAsync( $"DELETE FROM _values WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ','))", new object[] { idList }, cancellationToken); } /// /// Bulk delete values by object IDs. /// public async Task BulkDeleteValuesByObjectIdsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) { var ids = objectIds.ToArray(); if (ids.Length == 0) return; var idList = string.Join(",", ids); await _db.ExecuteAsync( $"DELETE FROM _values WHERE _id_object IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ','))", new object[] { idList }, cancellationToken); } /// /// Bulk delete values by ListItem IDs. /// public async Task BulkDeleteValuesByListItemIdsAsync(IEnumerable listItemIds, CancellationToken cancellationToken = default) { var ids = listItemIds.ToArray(); if (ids.Length == 0) return; // Deliberately NOT the STRING_SPLIT form the other bulk deletes use. _ListItem is // covered by a FILTERED index (IX__values__ListItem_not_null), and SQL Server does not // match a filtered index through the STRING_SPLIT semi-join - the plan degrades to a // full clustered scan of _values (tens of seconds cold on millions of rows). The // _id/_id_object deletes above sit on unfiltered indexes, where the semi-join seeks // fine. A parameterized IN list seeks the filtered index; chunked to stay well under // the 2100-parameter limit. const int chunkSize = 500; await _db.ExecuteAtomicAsync(async () => { for (var offset = 0; offset < ids.Length; offset += chunkSize) { var count = Math.Min(chunkSize, ids.Length - offset); var sb = new StringBuilder("DELETE FROM _values WHERE _ListItem IN ("); var parameters = new object[count]; for (var i = 0; i < count; i++) { if (i > 0) sb.Append(", "); sb.Append("@p").Append(i); parameters[i] = ids[offset + i]; } sb.Append(')'); await _db.ExecuteAsync(sb.ToString(), parameters, cancellationToken); } }, cancellationToken); } // === INSERT BY STATEMENT (small sets, see InsertByStatementMaxRows) === private async Task InsertObjectsByStatementAsync(RedbObjectRow[] rows, CancellationToken cancellationToken) { var sb = new StringBuilder(); var parameters = new List(rows.Length * ObjectColumns); sb.AppendLine("INSERT INTO _objects (_id, _id_parent, _id_scheme, _name, _id_owner, _id_who_change, _date_create,"); sb.AppendLine(" _date_modify, _date_begin, _date_complete, _key, _value_long, _value_string, _value_guid, _value_bool,"); sb.AppendLine(" _value_double, _value_numeric, _value_datetime, _value_bytes, _note, _hash, _value_unique)"); sb.Append("VALUES"); for (var i = 0; i < rows.Length; i++) { var obj = rows[i]; var p = i * ObjectColumns; if (i > 0) sb.Append(','); sb.Append($"\n (@p{p}, @p{p + 1}, @p{p + 2}, @p{p + 3}, @p{p + 4}, @p{p + 5}, @p{p + 6}, @p{p + 7}, @p{p + 8}, "); sb.Append($"@p{p + 9}, @p{p + 10}, @p{p + 11}, @p{p + 12}, @p{p + 13}, @p{p + 14}, @p{p + 15}, @p{p + 16}, "); sb.Append($"@p{p + 17}, @p{p + 18}, @p{p + 19}, @p{p + 20}, @p{p + 21})"); parameters.Add(Long(obj.Id)); parameters.Add(Long(obj.IdParent)); parameters.Add(Long(obj.IdScheme)); parameters.Add(Text(obj.Name)); parameters.Add(Long(obj.IdOwner)); parameters.Add(Long(obj.IdWhoChange)); parameters.Add(Moment(obj.DateCreate)); parameters.Add(Moment(obj.DateModify)); parameters.Add(Moment(obj.DateBegin)); parameters.Add(Moment(obj.DateComplete)); parameters.Add(Long(obj.Key)); parameters.Add(Long(obj.ValueLong)); parameters.Add(Text(obj.ValueString)); parameters.Add(Uuid(obj.ValueGuid)); parameters.Add(Bit(obj.ValueBool)); parameters.Add(Float(obj.ValueDouble)); parameters.Add(Numeric(obj.ValueNumeric)); parameters.Add(Moment(obj.ValueDatetime)); parameters.Add(Bytes(obj.ValueBytes)); parameters.Add(Text(obj.Note)); parameters.Add(Uuid(obj.Hash)); parameters.Add(Text(obj.ValueUnique)); } await _db.ExecuteAsync(sb.ToString(), parameters.ToArray(), cancellationToken); } private async Task InsertValuesByStatementAsync(RedbValue[] rows, CancellationToken cancellationToken) { var sb = new StringBuilder(); var parameters = new List(rows.Length * ValueColumns); sb.AppendLine("INSERT INTO _values (_id, _id_structure, _id_object, [_String], [_Long], [_Guid], [_Double],"); sb.AppendLine(" [_DateTimeOffset], [_Boolean], [_ByteArray], [_Numeric], [_ListItem], [_Object], [_unique],"); sb.AppendLine(" [_array_parent_id], [_array_index])"); sb.Append("VALUES"); for (var i = 0; i < rows.Length; i++) { var val = rows[i]; var p = i * ValueColumns; if (i > 0) sb.Append(','); sb.Append($"\n (@p{p}, @p{p + 1}, @p{p + 2}, @p{p + 3}, @p{p + 4}, @p{p + 5}, @p{p + 6}, @p{p + 7}, @p{p + 8}, "); sb.Append($"@p{p + 9}, @p{p + 10}, @p{p + 11}, @p{p + 12}, @p{p + 13}, @p{p + 14}, @p{p + 15})"); parameters.Add(Long(val.Id)); parameters.Add(Long(val.IdStructure)); parameters.Add(Long(val.IdObject)); parameters.Add(Text(val.String)); parameters.Add(Long(val.Long)); parameters.Add(Uuid(val.Guid)); parameters.Add(Float(val.Double)); parameters.Add(Moment(val.DateTimeOffset)); parameters.Add(Bit(val.Boolean)); parameters.Add(Bytes(val.ByteArray)); parameters.Add(Numeric(val.Numeric)); parameters.Add(Long(val.ListItem)); parameters.Add(Long(val.Object)); parameters.Add(Uuid(val.Unique)); parameters.Add(Long(val.ArrayParentId)); parameters.Add(Text(val.ArrayIndex)); } await _db.ExecuteAsync(sb.ToString(), parameters.ToArray(), cancellationToken); } // Declared parameters: one type and size per column whatever the value (strings and bytes as MAX, decimals as the // columns' DECIMAL(38, 18)), so a statement's parameter list depends on its row count only and its plan is reused. // Inferred from the values, every new string length or decimal scale declared a new list and compiled a new plan. // MAX keeps an over-long value an error of the column, never a silent cut at a declared size. private static SqlParameter Long(long? value) => new() { SqlDbType = SqlDbType.BigInt, Value = (object?)value ?? DBNull.Value }; private static SqlParameter Text(string? value) => new() { SqlDbType = SqlDbType.NVarChar, Size = -1, Value = (object?)value ?? DBNull.Value }; private static SqlParameter Uuid(Guid? value) => new() { SqlDbType = SqlDbType.UniqueIdentifier, Value = (object?)value ?? DBNull.Value }; private static SqlParameter Bit(bool? value) => new() { SqlDbType = SqlDbType.Bit, Value = (object?)value ?? DBNull.Value }; private static SqlParameter Float(double? value) => new() { SqlDbType = SqlDbType.Float, Value = (object?)value ?? DBNull.Value }; private static SqlParameter Numeric(decimal? value) => new() { SqlDbType = SqlDbType.Decimal, Precision = 38, Scale = 18, Value = (object?)value ?? DBNull.Value }; private static SqlParameter Moment(DateTimeOffset? value) => new() { SqlDbType = SqlDbType.DateTimeOffset, Scale = 7, Value = (object?)value ?? DBNull.Value }; private static SqlParameter Bytes(byte[]? value) => new() { SqlDbType = SqlDbType.VarBinary, Size = -1, Value = (object?)value ?? DBNull.Value }; // === COLUMN MAPPINGS === private static void MapObjectColumns(SqlBulkCopy bulkCopy) { bulkCopy.ColumnMappings.Add("_id", "_id"); bulkCopy.ColumnMappings.Add("_id_parent", "_id_parent"); bulkCopy.ColumnMappings.Add("_id_scheme", "_id_scheme"); bulkCopy.ColumnMappings.Add("_name", "_name"); bulkCopy.ColumnMappings.Add("_id_owner", "_id_owner"); bulkCopy.ColumnMappings.Add("_id_who_change", "_id_who_change"); bulkCopy.ColumnMappings.Add("_date_create", "_date_create"); bulkCopy.ColumnMappings.Add("_date_modify", "_date_modify"); bulkCopy.ColumnMappings.Add("_date_begin", "_date_begin"); bulkCopy.ColumnMappings.Add("_date_complete", "_date_complete"); bulkCopy.ColumnMappings.Add("_key", "_key"); bulkCopy.ColumnMappings.Add("_value_long", "_value_long"); bulkCopy.ColumnMappings.Add("_value_string", "_value_string"); bulkCopy.ColumnMappings.Add("_value_guid", "_value_guid"); bulkCopy.ColumnMappings.Add("_value_bool", "_value_bool"); bulkCopy.ColumnMappings.Add("_value_double", "_value_double"); bulkCopy.ColumnMappings.Add("_value_numeric", "_value_numeric"); bulkCopy.ColumnMappings.Add("_value_datetime", "_value_datetime"); bulkCopy.ColumnMappings.Add("_value_bytes", "_value_bytes"); bulkCopy.ColumnMappings.Add("_note", "_note"); bulkCopy.ColumnMappings.Add("_hash", "_hash"); bulkCopy.ColumnMappings.Add("_value_unique", "_value_unique"); } private static void MapValueColumns(SqlBulkCopy bulkCopy) { bulkCopy.ColumnMappings.Add("_id", "_id"); bulkCopy.ColumnMappings.Add("_id_structure", "_id_structure"); bulkCopy.ColumnMappings.Add("_id_object", "_id_object"); bulkCopy.ColumnMappings.Add("_String", "_String"); bulkCopy.ColumnMappings.Add("_Long", "_Long"); bulkCopy.ColumnMappings.Add("_Guid", "_Guid"); bulkCopy.ColumnMappings.Add("_Double", "_Double"); bulkCopy.ColumnMappings.Add("_DateTimeOffset", "_DateTimeOffset"); bulkCopy.ColumnMappings.Add("_Boolean", "_Boolean"); bulkCopy.ColumnMappings.Add("_ByteArray", "_ByteArray"); bulkCopy.ColumnMappings.Add("_Numeric", "_Numeric"); bulkCopy.ColumnMappings.Add("_ListItem", "_ListItem"); bulkCopy.ColumnMappings.Add("_Object", "_Object"); bulkCopy.ColumnMappings.Add("_unique", "_unique"); bulkCopy.ColumnMappings.Add("_array_parent_id", "_array_parent_id"); bulkCopy.ColumnMappings.Add("_array_index", "_array_index"); } // === DATA TABLE CREATION === private static DataTable CreateObjectsDataTable(List objects) { var dt = new DataTable("_objects"); dt.Columns.Add("_id", typeof(long)); dt.Columns.Add("_id_parent", typeof(long)); dt.Columns.Add("_id_scheme", typeof(long)); dt.Columns.Add("_name", typeof(string)); dt.Columns.Add("_id_owner", typeof(long)); dt.Columns.Add("_id_who_change", typeof(long)); dt.Columns.Add("_date_create", typeof(DateTimeOffset)); dt.Columns.Add("_date_modify", typeof(DateTimeOffset)); dt.Columns.Add("_date_begin", typeof(DateTimeOffset)); dt.Columns.Add("_date_complete", typeof(DateTimeOffset)); dt.Columns.Add("_key", typeof(long)); dt.Columns.Add("_value_long", typeof(long)); dt.Columns.Add("_value_string", typeof(string)); dt.Columns.Add("_value_guid", typeof(Guid)); dt.Columns.Add("_value_bool", typeof(bool)); dt.Columns.Add("_value_double", typeof(double)); dt.Columns.Add("_value_numeric", typeof(decimal)); dt.Columns.Add("_value_datetime", typeof(DateTimeOffset)); dt.Columns.Add("_value_bytes", typeof(byte[])); dt.Columns.Add("_note", typeof(string)); dt.Columns.Add("_hash", typeof(Guid)); dt.Columns.Add("_value_unique", typeof(string)); foreach (var obj in objects) { dt.Rows.Add( obj.Id, (object?)obj.IdParent ?? DBNull.Value, obj.IdScheme, (object?)obj.Name ?? DBNull.Value, obj.IdOwner, obj.IdWhoChange, obj.DateCreate, obj.DateModify, (object?)obj.DateBegin ?? DBNull.Value, (object?)obj.DateComplete ?? DBNull.Value, (object?)obj.Key ?? DBNull.Value, (object?)obj.ValueLong ?? DBNull.Value, (object?)obj.ValueString ?? DBNull.Value, (object?)obj.ValueGuid ?? DBNull.Value, (object?)obj.ValueBool ?? DBNull.Value, (object?)obj.ValueDouble ?? DBNull.Value, (object?)obj.ValueNumeric ?? DBNull.Value, (object?)obj.ValueDatetime ?? DBNull.Value, (object?)obj.ValueBytes ?? DBNull.Value, (object?)obj.Note ?? DBNull.Value, (object?)obj.Hash ?? DBNull.Value, (object?)obj.ValueUnique ?? DBNull.Value ); } return dt; } private static DataTable CreateValuesDataTable(List values) { var dt = new DataTable("_values"); dt.Columns.Add("_id", typeof(long)); dt.Columns.Add("_id_structure", typeof(long)); dt.Columns.Add("_id_object", typeof(long)); dt.Columns.Add("_String", typeof(string)); dt.Columns.Add("_Long", typeof(long)); dt.Columns.Add("_Guid", typeof(Guid)); dt.Columns.Add("_Double", typeof(double)); dt.Columns.Add("_DateTimeOffset", typeof(DateTimeOffset)); dt.Columns.Add("_Boolean", typeof(bool)); dt.Columns.Add("_ByteArray", typeof(byte[])); dt.Columns.Add("_Numeric", typeof(decimal)); dt.Columns.Add("_ListItem", typeof(long)); dt.Columns.Add("_Object", typeof(long)); dt.Columns.Add("_unique", typeof(Guid)); dt.Columns.Add("_array_parent_id", typeof(long)); dt.Columns.Add("_array_index", typeof(string)); foreach (var val in values) { dt.Rows.Add( val.Id, val.IdStructure, val.IdObject, (object?)val.String ?? DBNull.Value, (object?)val.Long ?? DBNull.Value, (object?)val.Guid ?? DBNull.Value, (object?)val.Double ?? DBNull.Value, (object?)val.DateTimeOffset ?? DBNull.Value, (object?)val.Boolean ?? DBNull.Value, (object?)val.ByteArray ?? DBNull.Value, (object?)val.Numeric ?? DBNull.Value, (object?)val.ListItem ?? DBNull.Value, (object?)val.Object ?? DBNull.Value, (object?)val.Unique ?? DBNull.Value, (object?)val.ArrayParentId ?? DBNull.Value, (object?)val.ArrayIndex ?? DBNull.Value ); } return dt; } } Path: redb/redb.MSSql/Data/SqlKeyGenerator.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.MSSql/Data/SqlKeyGenerator.cs ---- using Microsoft.Data.SqlClient; using redb.Core.Data; namespace redb.MSSql.Data; /// /// MS SQL Server implementation of key generator. /// Uses global_identity sequence. Caching is static in base class. /// public class SqlKeyGenerator : RedbKeyGeneratorBase { private readonly string _connectionString; // 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 MSSQL key generator from connection string. /// /// MS SQL Server connection string. /// Cache domain for key isolation (optional). /// The owning scope's connection, used for keys inside an ambient transaction. public SqlKeyGenerator(string connectionString, string? domain = null, Func? scopeConnection = null) : base(domain) { _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); _scopeConnection = scopeConnection; } // === DB-SPECIFIC IMPLEMENTATIONS === /// /// Generate batch of keys from MSSQL sequence. /// Uses sp_sequence_get_range for instant range reservation. /// protected override async Task> GenerateKeysAsync(int count) { await using var conn = new SqlConnection(_connectionString); await conn.OpenAsync(); // sp_sequence_get_range - instant range reservation (1 call for any count) var sql = $@" DECLARE @first SQL_VARIANT; EXEC sp_sequence_get_range @sequence_name = N'{SEQUENCE_NAME}', @range_size = @count, @range_first_value = @first OUTPUT; SELECT CAST(@first AS BIGINT);"; await using var cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@count", count); var firstValue = Convert.ToInt64(await cmd.ExecuteScalarAsync()); return Range(firstValue, count); } /// /// Inside a TransactionScope a refill on a connection of its own would be a second connection in the /// transaction, and SQL Server refuses the implicit distributed transaction that makes. The range is /// reserved through the scope's wrapper instead - on the transaction's connection. A sequence range 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; var sql = $@" DECLARE @first SQL_VARIANT; EXEC sp_sequence_get_range @sequence_name = N'{SEQUENCE_NAME}', @range_size = $1, @range_first_value = @first OUTPUT; SELECT CAST(@first AS BIGINT);"; var firstValue = await db.ExecuteScalarAsync(sql, new object[] { count }, CancellationToken.None); return Range(firstValue, count); } private static List Range(long firstValue, int count) { // Generate keys from range (in memory - instant) var keys = new List(count); for (int i = 0; i < count; i++) { keys.Add(firstValue + i); } return keys; } } Path: redb/redb.MSSql/Data/SqlRedbConnection.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.MSSql/Data/SqlRedbConnection.cs ---- using Microsoft.Data.SqlClient; using redb.Core.Data; using System.Data; using System.Data.Common; using System.Reflection; using System.Text; using System.Text.Json.Serialization; using System.Threading; using System.Transactions; namespace redb.MSSql.Data; /// /// MS SQL Server implementation of IRedbConnection using Microsoft.Data.SqlClient. /// Provides pure ADO.NET database access with automatic transaction management. /// public class SqlRedbConnection : IRedbConnection { private readonly string _connectionString; // V4 (LAZY Л2): session flag for the JSON builders, applied on every open of this context's connection. private readonly bool _lazyReferences; // Identity of the database in AmbientConnectionRegistry: every wrapper of one database shares the // connection an ambient transaction holds for it. private readonly string _databaseKey; // 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 readonly string _sessionSignature; private SqlConnection? _connection; private SqlRedbTransaction? _currentTransaction; // The current command's hold on the ambient transaction's connection; released with the command. private AmbientLease? _ambientLease; private bool _disposed; public bool IsDisposed => _disposed; // Commands and teardown share ONE exclusion (CommandGate, a production report 2026-09-11): // this connection holds ONE persistent SqlConnection reused for all commands and is NOT // thread-safe. Two concurrent commands fail fast; a command after teardown began is // refused with ObjectDisposedException (the lazy loader falls back to a detached scope); // DisposeAsync WAITS for the in-flight command instead of closing under it. private readonly CommandGate _gate = new(nameof(SqlRedbConnection)); 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 SqlRedbConnection _owner; private readonly CommandGate.Releaser _releaser; public CommandScope(SqlRedbConnection owner, CommandGate.Releaser releaser) { _owner = owner; _releaser = releaser; } public void Dispose() { var lease = _owner._ambientLease; _owner._ambientLease = null; try { lease?.Dispose(); } finally { _releaser.Dispose(); } } } /// /// Connection string. /// public string ConnectionString => _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) || System.Transactions.Transaction.Current != null; /// /// Create connection from connection string. /// /// MS SQL Server connection string. public SqlRedbConnection(string connectionString, bool lazyReferences = false) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString)); _connectionString = connectionString; _lazyReferences = lazyReferences; _databaseKey = DatabaseKeyOf(connectionString); _sessionSignature = redb.Core.Models.Configuration.RedbServiceConfiguration.ComputeCacheDomain(connectionString) + $"|lazy_refs={(lazyReferences ? 1 : 0)}"; } /// Server, database and login: two connection strings reaching the same data share one key. private static string DatabaseKeyOf(string connectionString) { var builder = new SqlConnectionStringBuilder(connectionString); return $"mssql|{builder.DataSource}|{builder.InitialCatalog}|{builder.UserID}|{builder.IntegratedSecurity}"; } // === CONNECTION MANAGEMENT === /// /// Get underlying connection (for bulk operations). /// This ensures all operations use the same connection and transaction. /// public async Task GetUnderlyingConnectionAsync(CancellationToken cancellationToken = default) { // Bulk 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 } && System.Transactions.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); // SqlClient refuses a command without the transaction object on a connection with a local transaction; // an enlisted connection (ambient) needs none. var transaction = _currentTransaction is { IsActive: true } explicitTransaction ? explicitTransaction.SqlTransaction : null; return new RedbConnectionLease(connection, transaction, command.Dispose); } catch { command.Dispose(); throw; } } private void ThrowIfDisposed() { // Dispose nulls _connection; without this check a call after Dispose would open a NEW // connection on a wrapper whose second Dispose is a no-op, and it would never be closed. if (_disposed) throw new ObjectDisposedException(nameof(SqlRedbConnection), "The scope that owned this connection has ended. Resolve a fresh scoped IRedbService " + "instead of reusing one from a finished scope or exchange."); } 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 make the // transaction distributed. An explicit transaction of this wrapper keeps its own connection. if (_currentTransaction is not { IsActive: true } && System.Transactions.Transaction.Current is { } ambient) { _ambientLease ??= await AmbientConnectionRegistry.AcquireAsync(ambient, _databaseKey, _sessionSignature, OpenAmbientAsync, null, cancellationToken); return (SqlConnection)_ambientLease.Entry.Connection; } var wasJustOpened = false; if (_connection == null) { _connection = new SqlConnection(_connectionString); await _connection.OpenAsync(); wasJustOpened = true; } else if (_connection.State != ConnectionState.Open) { await _connection.OpenAsync(); wasJustOpened = true; } // No speculative ROLLBACK here (plan AMBIENT_TRANSACTION, 2026-09-14): the SqlClient pool resets // the session - an open transaction included - before it hands a connection out again, and a // ROLLBACK on a connection that just enlisted in a TransactionScope would end that transaction. if (wasJustOpened) await ApplySessionSettingsAsync(_connection); return _connection; } /// Opens the connection an ambient transaction holds; opened inside the scope, SqlClient enlists it. private async Task OpenAmbientAsync(CancellationToken cancellationToken) { var connection = new SqlConnection(_connectionString); try { await connection.OpenAsync(cancellationToken); await ApplySessionSettingsAsync(connection); return connection; } catch { await connection.DisposeAsync(); throw; } } private async Task ApplySessionSettingsAsync(SqlConnection connection) { if (!_lazyReferences) return; // V4 (LAZY L2): the session flag dbo.build_field_json reads via SESSION_CONTEXT. using var lazyCmd = connection.CreateCommand(); lazyCmd.CommandText = "EXEC sp_set_session_context @key = N'redb.lazy_refs', @value = 1"; await lazyCmd.ExecuteNonQueryAsync(); } /// /// Create SqlCommand with parameter conversion from PostgreSQL $1,$2 to @p0,@p1 format. /// private SqlCommand CreateCommand(SqlConnection connection, string sql, object[] parameters) { // Convert PostgreSQL positional parameters ($1, $2) to MSSQL named parameters (@p0, @p1) var convertedSql = ConvertParameters(sql, parameters.Length); var cmd = new SqlCommand(convertedSql, connection); // Set transaction if active if (_currentTransaction != null) { cmd.Transaction = _currentTransaction.SqlTransaction; } // Add named parameters for (int i = 0; i < parameters.Length; i++) { var param = parameters[i]; if (param is SqlParameter typed) { // Declared by the caller (type and size), so the statement's parameter list - and with it its cached // plan - does not change with the values. A copy: a parameter belongs to one command only. var copy = (SqlParameter)((ICloneable)typed).Clone(); copy.ParameterName = $"@p{i}"; cmd.Parameters.Add(copy); continue; } var sqlParam = new SqlParameter($"@p{i}", param ?? DBNull.Value); if (param == null) { sqlParam.Value = DBNull.Value; } else if (param is DateTimeOffset dto) { sqlParam.Value = dto; sqlParam.SqlDbType = SqlDbType.DateTimeOffset; } else if (param is byte[] bytes) { sqlParam.Value = bytes; sqlParam.SqlDbType = SqlDbType.VarBinary; } else if (param is long[] longArray) { // MSSQL doesn't support array parameters natively // Use comma-separated string for use with STRING_SPLIT sqlParam.Value = string.Join(",", longArray); sqlParam.SqlDbType = SqlDbType.NVarChar; } else if (param is int[] intArray) { sqlParam.Value = string.Join(",", intArray); sqlParam.SqlDbType = SqlDbType.NVarChar; } else if (param is string[] stringArray) { sqlParam.Value = string.Join(",", stringArray); sqlParam.SqlDbType = SqlDbType.NVarChar; } cmd.Parameters.Add(sqlParam); } return cmd; } /// /// Convert PostgreSQL $1, $2 parameters to MSSQL @p0, @p1 format. /// private static string ConvertParameters(string sql, int paramCount) { var result = sql; // Replace in reverse order to avoid index shifting ($10 before $1) for (int i = paramCount; i >= 1; i--) { result = result.Replace($"${i}", $"@p{i - 1}"); } return result; } // ===== cancellation normalization (s3.1) ===== /// /// SqlClient does not reliably surface an attention-based cancel as /// OperationCanceledException: a token tearing down WAITFOR or a long command often /// comes back as SqlException ("A severe error occurred..." / "Operation cancelled by /// user"). The contract says cancellation has exactly one shape - normalize here. /// private static async Task NormalizeCancelAsync(Func> run, CancellationToken cancellationToken) { try { return await run(); } catch (Microsoft.Data.SqlClient.SqlException ex) when (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException("The command was canceled.", ex, cancellationToken); } } // ===== orphan transaction hygiene ===== private const string OrphanRollbackFailureKey = "redb.OrphanTransactionRollbackFailure"; /// /// A command that failed or was cancelled can leave behind a transaction its own SQL text opened: /// BEGIN TRANSACTION without SET XACT_ABORT ON survives an error outside TRY/CATCH, and a client /// cancel or command timeout bypasses CATCH altogether. This wrapper does not own that transaction, /// so nothing would ever end it: every later statement of the scope would run inside it and be /// rolled back with it when the pooled session is reset - a save reporting success, its row gone. /// 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). The original exception always propagates; a /// rollback that fails as well is attached to it instead of replacing it. /// private async Task RollbackOrphanTransactionAsync(SqlConnection conn, Exception failure) { if (_currentTransaction is { IsActive: true } || System.Transactions.Transaction.Current != null || conn.State != ConnectionState.Open) return; try { await using var cmd = conn.CreateCommand(); cmd.CommandText = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION"; // 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(SqlConnection conn, Exception failure) { if (_currentTransaction is { IsActive: true } || System.Transactions.Transaction.Current != null || conn.State != ConnectionState.Open) return; try { using var cmd = conn.CreateCommand(); cmd.CommandText = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION"; cmd.ExecuteNonQuery(); } catch (Exception rollbackFailure) { failure.Data[OrphanRollbackFailureKey] = rollbackFailure.Message; } } 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; } } /// /// One batch, read result set by result set: the first maps to , the second, when the batch /// returns one, to . For statements whose results belong together and should cost one round /// trip (a list page and the structure hash of its scheme). /// internal Task<(List First, List Second)> QueryResultSetsAsync( string sql, object[] parameters, 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, () => QueryResultSetsCoreAsync(sql, parameters, cancellationToken)) : QueryResultSetsCoreAsync(sql, parameters, cancellationToken); private async Task<(List First, List Second)> QueryResultSetsCoreAsync( string sql, object[] parameters, CancellationToken cancellationToken) where T1 : new() where T2 : new() { using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); try { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await NormalizeCancelAsync(() => cmd.ExecuteReaderAsync(cancellationToken), cancellationToken); var first = await ReadSetAsync(reader, cancellationToken); var second = await reader.NextResultAsync(cancellationToken) ? await ReadSetAsync(reader, cancellationToken) : new List(); return (first, second); } catch (Exception ex) { await RollbackOrphanTransactionAsync(conn, ex); throw; } } private static async Task> ReadSetAsync(SqlDataReader reader, CancellationToken cancellationToken) where T : new() { var results = new List(); var mapper = new SqlRowMapper(); while (await reader.ReadAsync(cancellationToken)) results.Add(mapper.MapRow(reader)); return results; } private async Task> QueryCoreAsync(SqlConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) where T : new() { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await NormalizeCancelAsync(() => cmd.ExecuteReaderAsync(cancellationToken), cancellationToken); var results = new List(); var mapper = new SqlRowMapper(); while (await reader.ReadAsync(cancellationToken)) { results.Add(mapper.MapRow(reader)); } return results; } /// /// Execute SQL query and return first result. /// MSSQL FOR JSON may split large results into multiple rows (~2033 chars each). /// This method concatenates all rows for 'result' column before mapping. /// 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(SqlConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new() { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await NormalizeCancelAsync(() => cmd.ExecuteReaderAsync(cancellationToken), cancellationToken); // Check if this is a single 'result' column (FOR JSON output OR scalar aggregate) if (reader.FieldCount == 1) { var columnName = reader.GetName(0); // FOR JSON typically returns unnamed column or starts with JSON_ if (columnName.StartsWith("JSON_") || string.IsNullOrEmpty(columnName)) { // Concatenate all rows for JSON result var jsonBuilder = new StringBuilder(); while (await reader.ReadAsync(cancellationToken)) { if (!reader.IsDBNull(0)) { jsonBuilder.Append(reader.GetString(0)); } } if (jsonBuilder.Length == 0) { return null; } // Create result object with 'result' property var resultType = typeof(T); var resultProp = resultType.GetProperty("result", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (resultProp != null && resultProp.PropertyType == typeof(string)) { var obj = new T(); resultProp.SetValue(obj, jsonBuilder.ToString()); return obj; } } // For scalar aggregation results (column named 'result' with numeric type) else if (columnName == "result") { if (await reader.ReadAsync(cancellationToken)) { if (reader.IsDBNull(0)) return null; var resultType = typeof(T); var resultProp = resultType.GetProperty("result", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (resultProp != null) { var obj = new T(); var value = reader.GetValue(0); var targetType = Nullable.GetUnderlyingType(resultProp.PropertyType) ?? resultProp.PropertyType; var convertedValue = redb.Core.Utils.RedbDecimal.ChangeType(value, targetType); resultProp.SetValue(obj, convertedValue); return obj; } } return null; } } // Standard row mapping for non-JSON results if (await reader.ReadAsync(cancellationToken)) { var mapper = new SqlRowMapper(); 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(SqlConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); var result = await NormalizeCancelAsync(() => cmd.ExecuteScalarAsync(cancellationToken), 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)redb.Core.Utils.RedbDecimal.ChangeType(result, targetType); } // === 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, session flag and pool-poisoning guard as the async // twins above. private SqlConnection GetOpenConnection() { ThrowIfDisposed(); // Same ambient-transaction rule as the async twin. if (_currentTransaction is not { IsActive: true } && System.Transactions.Transaction.Current is { } ambient) { _ambientLease ??= AmbientConnectionRegistry.Acquire(ambient, _databaseKey, _sessionSignature, OpenAmbient, null); return (SqlConnection)_ambientLease.Entry.Connection; } var wasJustOpened = false; if (_connection == null) { _connection = new SqlConnection(_connectionString); _connection.Open(); wasJustOpened = true; } else if (_connection.State != ConnectionState.Open) { _connection.Open(); wasJustOpened = true; } if (wasJustOpened) ApplySessionSettings(_connection); return _connection; } /// Synchronous . private DbConnection OpenAmbient() { var connection = new SqlConnection(_connectionString); try { connection.Open(); ApplySessionSettings(connection); return connection; } catch { connection.Dispose(); throw; } } private void ApplySessionSettings(SqlConnection connection) { if (!_lazyReferences) return; using var lazyCmd = connection.CreateCommand(); lazyCmd.CommandText = "EXEC sp_set_session_context @key = N'redb.lazy_refs', @value = 1"; lazyCmd.ExecuteNonQuery(); } /// 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(SqlConnection 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 SqlRowMapper().MapRow(reader) : null; } /// public List Query(string sql, params object[] parameters) where T : new() { using var _guard = EnterCommand(); var conn = GetOpenConnection(); try { return QueryCore(conn, sql, parameters); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private List QueryCore(SqlConnection 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 SqlRowMapper(); while (reader.Read()) results.Add(mapper.MapRow(reader)); return results; } /// public int Execute(string sql, params object[] parameters) { using var _guard = EnterCommand(); var conn = GetOpenConnection(); try { using var cmd = CreateCommand(conn, sql, parameters); return cmd.ExecuteNonQuery(); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } /// public T? ExecuteScalar(string sql, params object[] parameters) { using var _guard = EnterCommand(); var conn = GetOpenConnection(); try { return ExecuteScalarCore(conn, sql, parameters); } catch (Exception ex) { RollbackOrphanTransaction(conn, ex); throw; } } private T? ExecuteScalarCore(SqlConnection 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(SqlConnection 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(); } /// /// 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(SqlConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); return await NormalizeCancelAsync(() => cmd.ExecuteNonQueryAsync(cancellationToken), 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(SqlConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await NormalizeCancelAsync(() => cmd.ExecuteReaderAsync(cancellationToken), 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)redb.Core.Utils.RedbDecimal.ChangeType(value, targetType)); } } return results; } // === TRANSACTION METHODS === /// /// Begin new transaction. /// public async Task BeginTransactionAsync(System.Data.IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default) { if (_currentTransaction != null && _currentTransaction.IsActive) throw new InvalidOperationException("Transaction already active. Commit or rollback first."); if (System.Transactions.Transaction.Current != null) throw new InvalidOperationException( "Ambient TransactionScope detected. Cannot create explicit transaction inside TransactionScope. " + "Use ExecuteAtomicAsync() which respects ambient transactions."); using var _guard = EnterCommand(); var conn = await GetOpenConnectionAsync(cancellationToken); var sqlTx = (SqlTransaction)(isolationLevel.HasValue ? await conn.BeginTransactionAsync(isolationLevel.Value) // BR-1: the requested level : await conn.BeginTransactionAsync()); // the provider default, as always _currentTransaction = new SqlRedbTransaction(sqlTx, () => _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 (Exception failure) { await redb.Core.Data.RollbackAfterFailure.RollbackAsync(tx, failure); 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 (Exception failure) { await redb.Core.Data.RollbackAfterFailure.RollbackAsync(tx, failure); 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 (Exception failure) { await redb.Core.Data.RollbackAfterFailure.RollbackAsync(tx, failure); 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 (Exception failure) { await redb.Core.Data.RollbackAfterFailure.RollbackAsync(tx, failure); throw; } } // === JSON METHODS === /// /// Execute SQL returning JSON (for MSSQL functions returning JSON). /// 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(SqlConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await NormalizeCancelAsync(() => cmd.ExecuteReaderAsync(cancellationToken), cancellationToken); // MSSQL FOR JSON may split result across multiple rows var sb = new StringBuilder(); while (await reader.ReadAsync(cancellationToken)) { if (!reader.IsDBNull(0)) { sb.Append(reader.GetString(0)); } } var result = sb.ToString(); return string.IsNullOrEmpty(result) ? null : result; } /// /// 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(SqlConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) { await using var cmd = CreateCommand(conn, sql, parameters); await using var reader = await NormalizeCancelAsync(() => cmd.ExecuteReaderAsync(cancellationToken), 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 NormalizeCancelAsync(() => cmd.ExecuteReaderAsync(cancellationToken), 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 System.Text.Json.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). The // budget follows the connection's own Command Timeout. Unlike Npgsql/Sqlite, // SqlConnection exposes no command-timeout property on the live object - the // connection-string keyword (applied by the driver to every command) is the source. int commandTimeout; try { commandTimeout = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder(_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(); } } } /// /// Row mapper for converting SqlDataReader to objects. /// Supports multiple column name formats: /// - MSSQL table columns: _id, _name, _id_scheme /// - JSON output: id, name, id_scheme /// - PascalCase: Id, Name, IdScheme /// /// Target type. internal class SqlRowMapper 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(SqlDataReader 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 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; } // Special handling for Guid if (targetType == typeof(Guid) && value is Guid guid) { slot.Assign(obj, guid); continue; } // A value already of the target type: Convert.ChangeType would return it unchanged. var convertedValue = value.GetType() == targetType ? value : redb.Core.Utils.RedbDecimal.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.MSSql/Data/SqlRedbContext.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.MSSql/Data/SqlRedbContext.cs ---- using redb.Core.Data; namespace redb.MSSql.Data; /// /// MS SQL Server implementation of REDB context. /// Assembles all SQL Server components into single facade. /// public class SqlRedbContext : RedbContextBase { private readonly SqlRedbConnection _connection; private readonly SqlKeyGenerator _keyGenerator; private readonly SqlBulkOperations _bulkOperations; /// /// Database connection. /// public override IRedbConnection Db => _connection; /// /// Key generator with caching. /// public override IKeyGenerator Keys => _keyGenerator; /// /// Bulk operations (SqlBulkCopy). /// protected override IBulkOperations BulkOperations => _bulkOperations; /// protected override Task QueryRowsAsJsonCoreAsync(string sql, object[] parameters, System.Threading.CancellationToken cancellationToken) => _connection.QueryRowsAsJsonAsync(sql, parameters, cancellationToken); /// /// Connection string (for direct access if needed). /// public string ConnectionString { get; } /// /// Create SQL Server context from connection string. /// /// MS SQL Server connection string. public SqlRedbContext(string connectionString, bool lazyReferences = false) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString)); ConnectionString = connectionString; _connection = new SqlRedbConnection(connectionString, lazyReferences); var domain = redb.Core.Models.Configuration.RedbServiceConfiguration.ComputeCacheDomain(connectionString); _keyGenerator = new SqlKeyGenerator(connectionString, domain, scopeConnection: () => _connection); _bulkOperations = new SqlBulkOperations(_connection) { TimeoutSource = () => BulkInsertTimeout }; } /// /// Dispose context and all components. /// public override async ValueTask DisposeAsync() { await _connection.DisposeAsync(); } } Path: redb/redb.MSSql/Data/SqlRedbTransaction.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.MSSql/Data/SqlRedbTransaction.cs ---- using Microsoft.Data.SqlClient; using redb.Core.Data; namespace redb.MSSql.Data; /// /// MS SQL Server implementation of IRedbTransaction using SqlTransaction. /// Connection-scoped: parent connection automatically uses this transaction. /// public class SqlRedbTransaction : IRedbTransaction { private readonly SqlTransaction _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; /// /// 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 SqlTransaction (for command assignment). /// internal SqlTransaction SqlTransaction => _transaction; /// /// The server ended the transaction while we still hold it open: SqlClient zombies a transaction the server rolled /// back (command timeout, deadlock victim 1205, an error that dooms it, a broken connection) and its /// then reads null. Read only while /// is true; after our own Commit or Rollback the driver reads the same, and decides. /// private bool EndedByServer => _transaction.Connection is null; /// /// Create new transaction wrapper. /// /// Underlying SqlTransaction. /// Callback when transaction is disposed. public SqlRedbTransaction(SqlTransaction 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: SqlConnection._currentTransaction may still be set. // Try speculative rollback so the connection returns to the pool clean; // otherwise the next caller's BeginTransaction fails with // "SqlConnection does not support parallel transactions". // Console.WriteLine($"[Diag-TX-LIFECYCLE-MSSQL] 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-MSSQL] Speculative rollback after failed commit ALSO FAILED: {rbEx.GetType().Name}: {rbEx.Message}. Pool may receive a dirty SqlConnection (next BeginTransaction will throw 'parallel transactions')."); } 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 (Microsoft.Data.SqlClient 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); if (EndedByServer) { // The server already rolled the transaction back (timeout, deadlock victim, dooming error): the rollback // asked for has happened. Our own Commit or Rollback clears IsActive first, so a misuse still throws above. IsActive = false; _onDispose(); return; } try { await _transaction.RollbackAsync(); } catch (Exception ex) { // Console.WriteLine($"[Diag-TX-LIFECYCLE-MSSQL] RollbackAsync FAILED: {ex.GetType().Name}: {ex.Message}. Pool may receive a dirty SqlConnection (next BeginTransaction will throw 'parallel transactions')."); IsActive = false; _onDispose(); throw; } IsActive = false; _onDispose(); } /// /// Dispose transaction. /// If still active - rollback automatically. The catch CANNOT throw (Dispose contract); a /// connection that reaches the pool with its transaction still open is rolled back by the /// SqlClient pool itself, which resets the session before handing the connection out again. /// public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; Complete(committed: false); // Auto-rollback if still active; nothing to roll back when the server has ended the transaction already if (IsActive && EndedByServer) { IsActive = false; } else if (IsActive) { try { await _transaction.RollbackAsync(); } catch (Exception ex) { // Console.WriteLine($"[Diag-TX-LIFECYCLE-MSSQL] DisposeAsync auto-rollback FAILED: {ex.GetType().Name}: {ex.Message}. The SqlClient pool rolls the session back before its next hand-out."); } 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.MSSql/Extensions/MsSqlOptionsExtensions.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.MSSql/Extensions/MsSqlOptionsExtensions.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) 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.Configuration; using redb.Core.Services; using redb.MSSql.Data; using redb.MSSql.Providers; using redb.MSSql.Sql; namespace redb.MSSql.Extensions; /// /// MSSQL provider extensions for RedbOptionsBuilder. /// public static class MsSqlOptionsExtensions { /// /// Configures REDB to use Microsoft SQL Server as the database provider. /// /// The options builder. /// MSSQL connection string. If null, must be set in Configure(). /// The options builder for chaining. /// /// services.AddRedb(options => options /// .UseMsSql("Server=localhost;Database=redb;Trusted_Connection=true") /// .Configure(c => c.EnablePropsCache = true)); /// public static RedbOptionsBuilder UseMsSql( 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.MSSql.Pro package. Use AddRedbPro() from redb.MSSql.Pro.Extensions."); RegisterOpenSourceServices(services, config); }); return builder; } /// /// Registers OpenSource MSSQL services. /// Called by UseMsSql() and can be extended by Pro version. /// internal static void RegisterOpenSourceServices(IServiceCollection services, RedbServiceConfiguration config) { // Context if (!string.IsNullOrEmpty(config.ConnectionString)) { services.AddScoped(_ => new SqlRedbContext(config.ConnectionString, config.EnableLazyReferences) { BulkInsertTimeout = config.BulkInsertTimeout }); } // Security services.AddScoped(_ => AmbientSecurityContext.GetOrCreateDefault()); // SQL Dialect services.AddSingleton(); // Core providers services.AddScoped(); 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.MSSql/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.MSSql/Providers/LazyPropsLoader.cs ---- using System.Collections.Concurrent; using redb.Core.Caching; using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Exceptions; using redb.Core.Models.Configuration; using redb.Core.Providers; using redb.Core.Serialization; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// OpenSource implementation of lazy Props loading for MS SQL Server. /// Uses get_object_json SQL function for simple and efficient loading. /// 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 MsSqlDialect _sql; private readonly GlobalPropsCache _propsCache; /// public string? CacheDomain => _propsCache.Domain; /// public redb.Core.Data.IRedbContext? ScopeContext => _context; private readonly ILogger? _logger; public LazyPropsLoader( IRedbContext context, ISchemeSyncProvider schemeSync, IRedbObjectSerializer serializer, RedbServiceConfiguration config, IListProvider? listProvider = null, ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _config = config ?? throw new ArgumentNullException(nameof(config)); _propsCache = schemeSync?.PropsCache ?? throw new ArgumentNullException(nameof(schemeSync)); _sql = new MsSqlDialect(); _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. /// 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) { // For MSSQL, convert array to comma-separated string var idsString = string.Join(",", needToLoad); // Batch query via STRING_SPLIT + get_object_json var results = await _context.QueryAsync( _sql.LazyLoader_GetObjectJsonBatch(), new object[] { idsString, 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 { // Deserialization error - skip this object } } } // 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 { // For MSSQL, convert array to comma-separated string var idsString = string.Join(",", uniqueIds); var depth = DefaultBatchDepth; // Batch query var results = await _context.QueryAsync( _sql.LazyLoader_GetObjectJsonBatch(), new object[] { idsString, 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.MSSql/Providers/MssqlListProvider.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.MSSql/Providers/MssqlListProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Providers; using redb.Core.Providers.Base; using redb.MSSql.Query; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of IListProvider. /// Inherits all logic from ListProviderBase, provides MSSQL-specific SQL via MsSqlDialect. /// /// Usage: /// services.AddScoped<IListProvider, MssqlListProvider>(); /// public class MssqlListProvider : ListProviderBase { /// /// Creates MSSQL list provider with default MsSqlDialect. /// /// Database context for executing queries /// Service configuration /// Scheme sync provider (for accessing domain-bound caches) /// Optional logger for diagnostics public MssqlListProvider( IRedbContext context, RedbServiceConfiguration configuration, ISchemeSyncProvider schemeSync, ILogger? logger = null) : base(context, configuration, new MsSqlDialect(), schemeSync, logger) { } } Path: redb/redb.MSSql/Providers/MssqlMaintenanceProvider.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.MSSql/Providers/MssqlMaintenanceProvider.cs ---- using redb.Core.Data; using redb.Core.Providers; using redb.Core.Providers.Base; using redb.MSSql.Sql; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; namespace redb.MSSql.Providers; /// /// MSSQL maintenance provider. All logic lives in the base; this class wires the dialect in /// (same shape as MssqlValidationProvider) and handles the one server-level read. /// public class MssqlMaintenanceProvider : MaintenanceProviderBase { public MssqlMaintenanceProvider(IRedbContext context, int analysisLimit, ILogger? logger = null) : base(context, new MsSqlDialect(), analysisLimit, logger) { } /// /// The instance start time comes from sys.dm_os_sys_info, which needs VIEW SERVER STATE /// (VIEW SERVER PERFORMANCE STATE on SQL Server 2022). A database owner without that right /// gets a window with = null: the counters are /// still read, only their age is unknown. /// public override async Task GetStatisticsWindowAsync(CancellationToken cancellationToken = default) { try { return await base.GetStatisticsWindowAsync(cancellationToken); } catch (SqlException ex) when (IsMissingServerStateRight(ex)) { Logger?.LogDebug(ex, "REDB maintenance: no VIEW SERVER STATE right, the start of the usage counters is unknown."); return new StatisticsWindow(); } } /// 297: the user does not have permission; 300: a named permission was denied. private static bool IsMissingServerStateRight(SqlException ex) { foreach (SqlError error in ex.Errors) if (error.Number is 297 or 300) return true; return false; } } Path: redb/redb.MSSql/Providers/MssqlObjectStorageProvider.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.MSSql/Providers/MssqlObjectStorageProvider.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.MSSql.Query; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of ObjectStorageProvider. /// Inherits all business logic from ObjectStorageProviderBase, provides MSSQL-specific LazyPropsLoader. /// /// Usage: /// services.AddScoped<IObjectStorageProvider, MssqlObjectStorageProvider>(); /// public class MssqlObjectStorageProvider : ObjectStorageProviderBase { /// /// Creates a new MssqlObjectStorageProvider instance. /// public MssqlObjectStorageProvider( 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 MsSqlDialect(), listProvider, logger, saveInterceptors) { } /// /// Creates MSSQL-specific LazyPropsLoader for lazy property loading. /// protected override ILazyPropsLoader CreateLazyPropsLoader() { return new LazyPropsLoader(Context, SchemeSyncProvider, Serializer, Configuration, ListProvider, Logger); } } Path: redb/redb.MSSql/Providers/MssqlPermissionProvider.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.MSSql/Providers/MssqlPermissionProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.MSSql.Query; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of permission provider. /// Inherits all business logic from PermissionProviderBase. /// Only provides MSSQL-specific SQL dialect. /// /// Usage: /// services.AddScoped<IPermissionProvider, MssqlPermissionProvider>(); /// public class MssqlPermissionProvider : PermissionProviderBase { /// /// Creates a new MSSQL permission provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics public MssqlPermissionProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null) : base(context, securityContext, new MsSqlDialect(), logger) { } } Path: redb/redb.MSSql/Providers/MssqlQueryableProvider.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.MSSql/Providers/MssqlQueryableProvider.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.Query.Base; using redb.Core.Query.QueryExpressions; using redb.Core.Serialization; using redb.MSSql.Query; using redb.Core.Query.Parsing; using Microsoft.Extensions.Logging; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of IQueryableProvider. /// Inherits all logic from QueryableProviderBase, provides MSSQL-specific query providers. /// /// Usage: /// services.AddScoped<IQueryableProvider, MssqlQueryableProvider>(); /// public class MssqlQueryableProvider : QueryableProviderBase { public MssqlQueryableProvider( 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 MssqlQueryProvider(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 MssqlTreeQueryProvider(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 MssqlTreeQueryProvider(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 MssqlTreeQueryProvider(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 MssqlTreeQueryable(treeQueryProvider, multiRootContext, filterParser, orderingParser); } protected override IRedbQueryable CreateMultiRootTreeQueryByIds( long schemeId, long? userId, bool checkPermissions, IEnumerable rootObjectIds, int? maxDepth) { var treeQueryProvider = new MssqlTreeQueryProvider(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 MssqlTreeQueryable(treeQueryProvider, multiRootContext, filterParser, orderingParser); } } Path: redb/redb.MSSql/Providers/MssqlRoleProvider.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.MSSql/Providers/MssqlRoleProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.MSSql.Query; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of role provider. /// Inherits all business logic from RoleProviderBase. /// Only provides MSSQL-specific SQL dialect. /// /// Usage: /// services.AddScoped<IRoleProvider, MssqlRoleProvider>(); /// public class MssqlRoleProvider : RoleProviderBase { /// /// Creates a new MSSQL role provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics public MssqlRoleProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null) : base(context, securityContext, new MsSqlDialect(), logger) { } } Path: redb/redb.MSSql/Providers/MssqlSchemeSyncProvider.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.MSSql/Providers/MssqlSchemeSyncProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Configuration; using redb.Core.Providers.Base; using redb.MSSql.Query; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of scheme synchronization provider. /// Inherits all business logic from SchemeSyncProviderBase. /// Only provides MSSQL-specific SQL dialect. /// /// Usage: /// services.AddScoped<ISchemeSyncProvider, MssqlSchemeSyncProvider>(); /// public class MssqlSchemeSyncProvider : SchemeSyncProviderBase { /// /// Creates a new MSSQL scheme sync provider. /// /// Database context for executing queries /// Service configuration /// Cache domain for isolation /// Optional logger for diagnostics public MssqlSchemeSyncProvider( IRedbContext context, RedbServiceConfiguration? configuration = null, string? cacheDomain = null, ILogger? logger = null) : base(context, new MsSqlDialect(), configuration, cacheDomain, logger) { } } Path: redb/redb.MSSql/Providers/MssqlTreeProvider.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.MSSql/Providers/MssqlTreeProvider.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.MSSql.Query; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of tree provider. /// Inherits all logic from TreeProviderBase, provides MSSQL-specific SQL via MsSqlDialect. /// /// Usage: /// services.AddScoped<ITreeProvider, MssqlTreeProvider>(); /// public class MssqlTreeProvider : TreeProviderBase { /// /// Creates MSSQL tree provider with default MsSqlDialect. /// public MssqlTreeProvider( 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 MsSqlDialect(), configuration, logger, saveInterceptors) { } } Path: redb/redb.MSSql/Providers/MssqlUserProvider.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.MSSql/Providers/MssqlUserProvider.cs ---- using redb.Core.Data; using redb.Core.Models.Contracts; using redb.Core.Providers.Base; using redb.Core.Security; using redb.MSSql.Query; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of user provider. /// Inherits all business logic from UserProviderBase. /// Only provides MSSQL-specific SQL dialect and password hasher. /// /// Usage: /// services.AddScoped<IUserProvider, MssqlUserProvider>(); /// public class MssqlUserProvider : UserProviderBase { /// /// Creates a new MSSQL user provider. /// /// Database context for executing queries /// Security context for authorization /// Optional logger for diagnostics public MssqlUserProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger = null) : base(context, securityContext, new MsSqlDialect(), new BcryptPasswordHasher(), logger) { } /// protected override bool LikeBracketIsWildcard => true; /// /// Creates a new MSSQL user provider with custom password hasher. /// /// Database context for executing queries /// Security context for authorization /// Custom password hasher implementation /// Optional logger for diagnostics public MssqlUserProvider( IRedbContext context, IRedbSecurityContext securityContext, IPasswordHasher passwordHasher, ILogger? logger = null) : base(context, securityContext, new MsSqlDialect(), passwordHasher, logger) { } } Path: redb/redb.MSSql/Providers/MssqlValidationProvider.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.MSSql/Providers/MssqlValidationProvider.cs ---- using redb.Core.Data; using redb.Core.Providers.Base; using redb.MSSql.Query; using Microsoft.Extensions.Logging; using redb.MSSql.Sql; namespace redb.MSSql.Providers; /// /// MS SQL Server implementation of validation provider. /// Inherits all business logic from ValidationProviderBase. /// Only provides MSSQL-specific SQL dialect. /// /// Usage: /// services.AddScoped<IValidationProvider, MssqlValidationProvider>(); /// public class MssqlValidationProvider : ValidationProviderBase { /// /// Creates a new MSSQL validation provider. /// /// Database context for executing queries /// Optional logger for diagnostics public MssqlValidationProvider( IRedbContext context, ILogger? logger = null) : base(context, new MsSqlDialect(), logger) { } } Path: redb/redb.MSSql/Query/MssqlQueryProvider.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.MSSql/Query/MssqlQueryProvider.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.MSSql.Query; /// /// PVT-backed terminal aggregations for free MSSql. Generates the /// aggregate SQL via the server-side compiler dbo.pvt_build_aggregate_sql /// (free PVT v2 module) and executes the produced statement client-side, /// wrapping the single result row with FOR JSON PATH, WITHOUT_ARRAY_WRAPPER /// to materialize in one round-trip after the /// build step. /// /// Mirrors PostgresQueryProvider.Aggregation.cs — the goal is to keep /// every aggregation request expressible as facet/aggregations JSON that /// non-.NET clients can submit directly (e.g. a Python service composing a /// facet AST and dispatching it through the SQL dialect's UDF). /// /// Overrides the FilterExpression-typed virtual methods on the base provider. /// Legacy facet-JSON overloads are also overridden because the MSSql /// dialect's Query_AggregateField/Batch functions throw — we route /// every aggregate path through the v2-pvt compiler instead. /// public partial class MssqlQueryProvider { /// /// 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) }; } /// /// Single-aggregate path for facet-JSON callers (legacy /// /// overload). Bypasses the throwing dialect SQL and routes through the /// v2-pvt aggregate compiler. /// public override async Task ExecuteAggregateAsync( long schemeId, string fieldPath, AggregateFunction function, string? filterJson = null, CancellationToken cancellationToken = default) { var request = new AggregateRequest { FieldPath = fieldPath ?? string.Empty, Function = function, Alias = "value" }; var batch = await ExecuteAggregateBatchInternalAsync(schemeId, new[] { request }, filterJson); 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 /// dbo.pvt_build_aggregate_sql to compile the inner SQL, then executes /// it through FOR JSON PATH, WITHOUT_ARRAY_WRAPPER 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 /// () /// hit the v2-pvt module instead of the throwing legacy SQL function on the /// MSSql 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(); // Step 1: the server-side compiler builds the inner aggregate SELECT. var innerSql = await BuildAggregateSqlAsync(schemeId, list, filterJson, cancellationToken); // Step 2: wrap with FOR JSON to capture every alias in one row. // INCLUDE_NULL_VALUES preserves nulls so MIN/MAX over empty sets // round-trip as JSON null instead of being silently dropped. var wrapped = "SELECT (SELECT * FROM (" + innerSql + ") _agg_row FOR JSON PATH, WITHOUT_ARRAY_WRAPPER, INCLUDE_NULL_VALUES)"; 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 dbo.pvt_build_aggregate_sql compiles for /// the same requests and filter as the execution, which reads its one row through FOR JSON PATH. 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 dbo.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); // pvt_build_aggregate_sql expects NULL for the empty / missing filter // (a literal "{}" or "null" string would defeat the IS NULL branch in // pvt_collect_fields and produce a missing-meta marker downstream). object filterParam = string.IsNullOrEmpty(filterJson) || filterJson == "{}" || filterJson == "null" ? DBNull.Value : (object)filterJson!; // $1 → @p0 = filter, $2 → @p1 = aggregations (mirrors PG ordering). var invocation = "SELECT dbo.pvt_build_aggregate_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, N'flat')"; _logger?.LogDebug("PVT Aggregate Build (MSSql): 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( "dbo.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 /// dbo.pvt_build_aggregate_sql: /// [{"alias":"x","$sum":{"$field":"Price"}}, {"alias":"y","$count":"*"}]. /// Count with empty 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 dbo.pvt_build_aggregate_sql.") }; var entry = new Dictionary { ["alias"] = alias }; 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.MSSql/Query/MssqlQueryProvider.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.MSSql/Query/MssqlQueryProvider.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.MSSql.Query; /// /// PVT-backed GroupBy + Window Functions for free MSSql. Mirrors /// PostgresQueryProvider.GroupedWindow.cs but uses T-SQL identifier /// quoting and FOR JSON PATH, INCLUDE_NULL_VALUES for JSON /// materialization. /// /// Architecture: calls BuildGroupByInnerSqlAsync (from /// MssqlQueryProvider.Grouping.cs, same partial class) to generate /// the inner GROUP BY query, then wraps it with an outer SELECT that adds /// window-function columns via OVER (PARTITION BY ... ORDER BY ...). /// public partial class MssqlQueryProvider { /// 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 outerSql = await BuildGroupedWindowSqlAsync( schemeId, groupFields, aggregations, windowFuncs, partitionBy, orderBy, filterJson, havingJson); var jsonArray = await _context.ExecuteScalarAsync(outerSql, System.Array.Empty(), cancellationToken); if (string.IsNullOrEmpty(jsonArray)) return JsonDocument.Parse("[]"); return JsonDocument.Parse(jsonArray); } private async Task BuildGroupedWindowSqlAsync( long schemeId, IEnumerable groupFields, IEnumerable aggregations, IEnumerable windowFuncs, IEnumerable partitionBy, IEnumerable orderBy, string? filterJson, string? havingJson) { var groupList = groupFields?.ToList() ?? new List(); var aggList = aggregations?.ToList() ?? new List(); var windowList = windowFuncs?.ToList() ?? new List(); var partitionList = partitionBy?.ToList() ?? new List(); var orderList = orderBy?.ToList() ?? new List(); if (groupList.Count == 0) throw new ArgumentException( "groupFields must contain at least one entry.", nameof(groupFields)); if (windowList.Count == 0) throw new ArgumentException( "windowFuncs must contain at least one entry.", nameof(windowFuncs)); // An aggregate the window sorts, partitions or reads by need not be in the selector: computed under a private alias. var shownAggregates = aggList.ToList(); aggList = GroupedWindowSelect.WithHiddenAggregates(shownAggregates, windowList, partitionList, orderList); var innerSql = await BuildGroupByInnerSqlAsync( schemeId, groupList, aggList, filterJson, havingJson); var windowedSelect = GroupedWindowSelect.Build( innerSql, groupList, aggList, shownAggregates, windowList, partitionList, orderList, QuoteGwndIdent, rankingNeedsOrder: true); return "SELECT (SELECT * FROM (" + windowedSelect + ") _gwnd_rows FOR JSON PATH, INCLUDE_NULL_VALUES)"; } // ---------------------------------------------------------------- // Windowed SELECT builder // ---------------------------------------------------------------- /// /// T-SQL square-bracket identifier quoting (mirrors PG's double-quote quoting). /// private static string QuoteGwndIdent(string identifier) => "[" + identifier.Replace("]", "]]") + "]"; } Path: redb/redb.MSSql/Query/MssqlQueryProvider.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.MSSql/Query/MssqlQueryProvider.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.MSSql.Query; /// /// PVT-backed GROUP BY for free MSSql. Generates the projection SQL via the /// server-side compiler dbo.pvt_build_groupby_sql and wraps it with /// FOR JSON PATH to materialize a JSON array of group rows in one /// round-trip after the build step. /// /// Mirrors PostgresQueryProvider.Grouping.cs — every grouping request /// is compiled by the SQL UDF so non-.NET callers can submit the same /// filter/group-by/aggregations JSON directly. /// public partial class MssqlQueryProvider { /// 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. 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); // Wrap the inner SELECT with FOR JSON PATH to materialize a JSON array // of group rows. INCLUDE_NULL_VALUES preserves null group keys. var wrapped = "SELECT (SELECT * FROM (" + innerSql + ") _grp_rows FOR JSON PATH, INCLUDE_NULL_VALUES)"; var jsonArray = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); if (string.IsNullOrEmpty(jsonArray)) return JsonDocument.Parse("[]"); return JsonDocument.Parse(jsonArray); } /// /// Returns the inner SELECT compiled by dbo.pvt_build_groupby_sql for /// the requested grouping. Mirrors PostgreSQL's GetGroupBySqlPreviewAsync /// so ToSqlStringAsync on grouped queryables surfaces the actual SQL /// instead of a "preview not supported" placeholder. /// 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; // The HAVING used to be dropped here (NULL was passed), and GroupBy(...).Having(...) returned every group. object havingParam = string.IsNullOrEmpty(havingJson) ? DBNull.Value : (object)havingJson; // pvt_build_groupby_sql(@scheme_id, @filter, @group_by, @aggs, @having, @order, @limit, @offset, @source_mode) // $1 = filter, $2 = group_by, $3 = aggregations, $4 = having var invocation = "SELECT dbo.pvt_build_groupby_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, $3, $4, NULL, NULL, 0, N'flat')"; _logger?.LogDebug( "PVT GroupBy Build (MSSql): 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( "dbo.pvt_build_groupby_sql could not compile this grouping for scheme " + schemeId + (havingJson is null ? "." : " - the HAVING " + havingJson + " has a shape it does not support.")); return innerSql!; } /// /// Serializes group fields to the JSON shape consumed by /// dbo.pvt_build_groupby_sql: [{"field":"Department","alias":"Dept"}]. /// Base fields get the 0$: prefix so PVT resolves them to the /// underlying _objects column. /// 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); } /// /// Applies the 0$: base-field prefix when /// is and the path is not already prefixed. /// 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 SQL Server provider: dbo.pvt_build_array_groupby_sql of the module builds the /// grouping (and its HAVING); a window over the groups is written around it by . /// The module function cannot raise, so it answers what it refuses with NULL, and this refuses in turn. /// public override async Task ExecuteArrayGroupQueryAsync(ArrayGroupQuery query, CancellationToken cancellationToken = default) { var sql = await BuildArrayGroupSqlAsync(query, cancellationToken); var wrapped = "SELECT (SELECT * FROM (" + sql + ") _grp_rows FOR JSON PATH, INCLUDE_NULL_VALUES)"; var json = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); // FOR JSON gives NULL for no rows. return JsonDocument.Parse(string.IsNullOrEmpty(json) ? "[]" : 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); // dbo.pvt_build_array_groupby_sql(@scheme_id, @array_path, @filter, @group_by, @aggregations, @having, @source_mode) var invocation = "SELECT dbo.pvt_build_array_groupby_sql(" + query.SchemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, $3, $4, $5, N'flat')"; 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( "dbo.pvt_build_array_groupby_sql refused the grouping of '" + query.ArrayPath + "' for scheme " + query.SchemeId + ": a key, an aggregate, a condition or the outer filter names something the elements or the scheme do not have."); if (innerSql.StartsWith("--error:", StringComparison.Ordinal)) throw new NotSupportedException("GroupByArray (MssqlQueryProvider): " + innerSql["--error:".Length..].Trim()); return query.Window == null ? innerSql : GroupedWindowSelect.Build(innerSql, query.GroupFields, aggregations, shown, query.Window.Functions, query.Window.PartitionBy, query.Window.OrderBy, QuoteGwndIdent, rankingNeedsOrder: true); } } Path: redb/redb.MSSql/Query/MssqlQueryProvider.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.MSSql/Query/MssqlQueryProvider.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.MSSql.Query; /// /// PVT-backed window functions for free MSSql. Generates the SELECT SQL /// via the server-side compiler dbo.pvt_build_window_sql and wraps /// it with FOR JSON PATH, INCLUDE_NULL_VALUES 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. The JSON shape is identical to /// the PostgreSQL dialect so BuildPvtWindowSelectJson logic is shared. /// public partial class MssqlQueryProvider { /// 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 (SELECT * FROM (" + innerSql + ") _win_rows FOR JSON PATH, INCLUDE_NULL_VALUES)"; var jsonArray = await _context.ExecuteScalarAsync(wrapped, System.Array.Empty(), cancellationToken); if (string.IsNullOrEmpty(jsonArray)) return JsonDocument.Parse("[]"); 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; // pvt_build_window_sql(@scheme_id, @filter, @select, @order, @limit, @offset, @source_mode) // $1=filter, $2=selectJson, $3=limit, $4=offset var invocation = "SELECT dbo.pvt_build_window_sql(" + schemeId.ToString(CultureInfo.InvariantCulture) + ", $1, $2, NULL, $3, $4, N'flat')"; _logger?.LogDebug( "PVT Window Build (MSSql): 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( "dbo.pvt_build_window_sql returned an empty SQL string for scheme " + schemeId + "."); return innerSql!; } /// /// Builds the p_select JSON array: plain field projections followed /// by one $over entry per window function. partition_by / order_by / /// frame are replicated into every $over node. /// The shape is identical to the PostgreSQL dialect so the UDF on either /// side can consume the same JSON. /// 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"] = 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"] = NormalizePvtFieldName(p.FieldPath, p.IsBaseField) }) .ToList(); var orderEntries = orderBy .Select(o => new Dictionary { ["field"] = 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 WindowJsonElementConverter() } }; return JsonSerializer.Serialize(entries, options); } 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"] = NormalizePvtFieldName(f.FieldPath, f.IsBaseField) } }; } // COUNT(*) shorthand if (func == "COUNT") return new List { "*" }; return null; } /// /// Converts the legacy SerializeFrame() JSON shape /// (kind + offset) to the PVT frame shape consumed by /// dbo.pvt_compile_frame_bound. 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(); // Already PVT shape? 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() }; } /// /// Passes already-parsed values through /// serialization verbatim so the embedded frame sub-tree survives intact. /// private sealed class WindowJsonElementConverter : 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.MSSql/Query/MssqlQueryProvider.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.MSSql/Query/MssqlQueryProvider.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.MSSql.Sql; namespace redb.MSSql.Query; /// /// MS SQL Server query provider implementation. /// Inherits from QueryProviderBase and provides MSSQL-specific components. /// public partial class MssqlQueryProvider : QueryProviderBase { public MssqlQueryProvider( IRedbContext context, IRedbObjectSerializer serializer, ILazyPropsLoader? lazyPropsLoader = null, RedbServiceConfiguration? configuration = null, ILogger? logger = null, ISchemeSyncProvider? schemeSync = null, ISqlDialect? dialect = null) : base(context, serializer, dialect ?? new MsSqlDialect(), lazyPropsLoader, configuration, logger, schemeSync) { } } Path: redb/redb.MSSql/Query/MssqlTreeQueryProvider.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.MSSql/Query/MssqlTreeQueryProvider.Pvt.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Models.Entities; using redb.Core.Query.Base; using redb.Core.Query.QueryExpressions; #pragma warning disable CS0672 // Member overrides obsolete member (legacy fallback retained for HasAncestor/HasDescendant + flat search) #pragma warning disable CS0618 // Type or member is obsolete namespace redb.MSSql.Query; /// /// Routes tree-subtree LINQ queries through the MSSql v2-pvt engine. /// The free MSSql provider has no working search_tree_objects_with_facets_base /// helper, so every tree request is compiled into a dbo.pvt_build_query_sql /// invocation and materialized via FOR JSON PATH. /// Port of the PostgreSQL PostgresTreeQueryProvider PVT partials. /// public partial class MssqlTreeQueryProvider { /// /// 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 MSSql: HasAncestor / HasDescendant are routed through PVT here // because the legacy search_*_base SQL functions throw on this dialect. 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) { 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 CAST(COUNT(*) AS 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. /// See the PostgresTreeQueryProvider.ShouldRoutePvtTree routing matrix. /// 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(); 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; } 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; } /// /// MSSql tree_ids contract: NULL or a JSON array of bigints, /// e.g. '[1,2,3]'. dbo.pvt_build_query_sql parses it via OPENJSON. /// private static string FormatTreeIds(long[] ids) => ids.Length == 0 ? "NULL" : "N'[" + string.Join(",", ids.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]'"; /// /// Builds the inner SELECT _id ... SQL via dbo.pvt_build_query_sql. /// The resulting SQL binds @p0 = filter, and (when present) @p1 = order. /// /// /// SQL preview of a tree query: the statement dbo.pvt_build_query_sql compiles for it, with the values it /// binds listed above it. The base implementation asks the database for /// dbo.get_search_tree_sql_preview_base, a procedure of the retired search module that this provider no /// longer installs, so ToSqlStringAsync on a tree query failed with "Could not find stored procedure". /// public override async Task GetSqlPreviewAsync( TreeQueryContext context, CancellationToken cancellationToken = default) { if (!ShouldRoutePvtTree(context, out var route)) return await base.GetSqlPreviewAsync(context, cancellationToken); var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: false, cancellationToken); var orderByJson = context.Orderings.Count > 0 ? _facetBuilder.BuildOrderBy(context.Orderings) : null; var sb = new StringBuilder(); sb.Append("-- $1 (filter) = ") .AppendLine(string.IsNullOrEmpty(route.FilterJson) ? "{}" : route.FilterJson); if (!string.IsNullOrEmpty(orderByJson) && orderByJson != "null" && orderByJson != "[]") sb.Append("-- $2 (order) = ").AppendLine(orderByJson); sb.Append(inner); return sb.ToString(); } private async Task BuildPvtTreeInnerSqlAsync( TreeQueryContext context, PvtTreeRoute route, bool forCount, CancellationToken cancellationToken = default) where TProps : class, new() { var orderByJson = context.Orderings.Count > 0 ? _facetBuilder.BuildOrderBy(context.Orderings) : null; var hasOrder = !forCount && !string.IsNullOrEmpty(orderByJson) && orderByJson != "null" && orderByJson != "[]"; // The depth of the tree walk (TreeQuery(root, maxDepth)); none: the whole subtree. This passed MaxRecursionDepth, the // depth of nested props, so maxDepth was ignored and every subtree stopped at 10 levels. // WhereDescendantsOf(node, maxDepth) walks from that node, to its own depth when it has one. var walkDepth = context.TreeFilters?.FirstOrDefault(f => f.Operator == TreeFilterOperator.DescendantsOf)?.MaxDepth ?? context.MaxDepth; var maxDepth = walkDepth?.ToString(CultureInfo.InvariantCulture) ?? "NULL"; var limitArg = forCount || !context.Limit.HasValue ? "NULL" : context.Limit.Value.ToString(CultureInfo.InvariantCulture); var offsetArg = forCount ? "0" : (context.Offset ?? 0).ToString(CultureInfo.InvariantCulture); var treeIdsLiteral = FormatTreeIds(route.TreeIds); // dbo.pvt_build_query_sql signature (12 params, all required): // @scheme_id, @filter, @limit, @offset, @order, @max_depth, // @distinct, @source_mode, @tree_ids, @include_seed, // @polymorphic, @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" : "NULL"; var invocation = "SELECT dbo.pvt_build_query_sql(" + context.SchemeId.ToString(CultureInfo.InvariantCulture) + ", $1, " + limitArg + ", " + offsetArg + ", " + orderArg + ", " + maxDepth + ", " + (context.IsDistinct ? "1" : "0") + ", N'" + route.SourceMode + "'" + ", " + treeIdsLiteral + ", " + (route.IncludeSeed ? "1" : "0") + ", 1" // @polymorphic=1 matches Pro default + (distinctOnJson != null ? ", $3)" : ", NULL)") // @distinct_on + " 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( "dbo.pvt_build_query_sql returned an empty SQL string for tree query (scheme " + context.SchemeId + ")."); return inner; } /// /// Wraps the inner _id list with FOR JSON PATH over the 21 /// _objects columns to produce the same shape consumed by /// . /// private async Task ExecutePvtTreeAsync( TreeQueryContext context, PvtTreeRoute route, CancellationToken cancellationToken = default) where TProps : class, new() { var inner = await BuildPvtTreeInnerSqlAsync(context, route, forCount: false); // FOR JSON PATH column aliases drive the JSON keys; mirror PG's // jsonb_build_object key naming exactly so the deserializer reuses // the same property map across providers. var sql = "SELECT (SELECT " + "o.[_id] AS id," + "o.[_name] AS name," + "o.[_id_scheme] AS scheme_id," + "o.[_id_parent] AS parent_id," + "o.[_id_owner] AS owner_id," + "o.[_id_who_change] AS who_change_id," + "o.[_date_create] AS date_create," + "o.[_date_modify] AS date_modify," + "o.[_date_begin] AS date_begin," + "o.[_date_complete] AS date_complete," + "o.[_key] AS [key]," + "o.[_value_long] AS value_long," + "o.[_value_string] AS value_string," + "o.[_value_unique] AS value_unique," + "o.[_value_guid] AS value_guid," + "o.[_note] AS note," + "o.[_value_bool] AS value_bool," + "o.[_value_double] AS value_double," + "o.[_value_numeric] AS value_numeric," + "o.[_value_datetime] AS value_datetime," + "o.[_value_bytes] AS value_bytes," + "o.[_hash] AS hash" // The inner query numbers its rows in its own order ([_ord], module 0.2.45), restored after the join: the // join kept the order only while the plan happened to be a nested loop. + " FROM (" + inner + ") sub" + " JOIN dbo._objects o ON o._id = sub._id" + " ORDER BY sub._ord" + " FOR JSON PATH, INCLUDE_NULL_VALUES) AS [Value]"; 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); } } Path: redb/redb.MSSql/Query/MssqlTreeQueryProvider.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.MSSql/Query/MssqlTreeQueryProvider.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.MSSql.Query; /// /// Free MSSql: implements WhereHasAncestor / WhereHasDescendant /// via the v2-pvt orchestrator (the legacy search_*_with_facets_base /// SQL helpers throw on this dialect). Port of the PostgreSQL /// PostgresTreeQueryProvider.PvtHasFilter partial. /// public partial class MssqlTreeQueryProvider { /// /// 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; } 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>(); 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 via /// dbo.pvt_build_query_sql 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" : "N'[" + string.Join(",", scopeRootIds.Select(id => id.ToString(CultureInfo.InvariantCulture))) + "]'"; var maxDepth = searchDepth; // 12-arg call: scheme, $1=filter, NULL limit, 0 offset, NULL order, // max_depth, 0 distinct, source_mode, tree_ids, 0 include_seed, // 1 polymorphic, NULL distinct_on. var invocation = "SELECT dbo.pvt_build_query_sql(" + filter.TargetSchemeId.Value.ToString(CultureInfo.InvariantCulture) + ", $1, NULL, 0, NULL, " + maxDepth.ToString(CultureInfo.InvariantCulture) + ", 0, N'" + sourceMode + "', " + treeIdsLiteral + ", 0, 1, NULL) AS [Value]"; object filterParam = string.IsNullOrEmpty(conditionJson) || conditionJson == "null" ? (object)"{}" : (object)conditionJson; _logger?.LogDebug( "PVT HasAncestor/Descendant Build (MSSql): 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.MSSql/Query/MssqlTreeQueryProvider.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.MSSql/Query/MssqlTreeQueryProvider.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.MSSql.Sql; namespace redb.MSSql.Query; /// /// MS SQL Server tree query provider implementation. /// Inherits from TreeQueryProviderBase and provides MSSQL-specific components. /// public partial class MssqlTreeQueryProvider : TreeQueryProviderBase { public MssqlTreeQueryProvider( 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 MsSqlDialect(), cacheDomain, lazyPropsLoader, configuration, logger, schemeSync) { } /// /// Creates query provider for delegation. /// protected override IRedbQueryProvider CreateQueryProvider() { return new MssqlQueryProvider(_context, _serializer, _lazyPropsLoader, _configuration, _logger, _schemeSync); } /// /// Creates tree queryable instance. /// protected override IRedbQueryable CreateTreeQueryable(TreeQueryContext context) { return new MssqlTreeQueryable(this, context, _filterParser, _orderingParser); } } Path: redb/redb.MSSql/Query/MssqlTreeQueryable.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.MSSql/Query/MssqlTreeQueryable.cs ---- using redb.Core.Query; using redb.Core.Query.Base; using redb.Core.Query.FacetFilters; using redb.Core.Query.QueryExpressions; namespace redb.MSSql.Query; /// /// MS SQL Server tree queryable implementation. /// Inherits from TreeQueryableBase and provides MSSQL-specific components. /// public class MssqlTreeQueryable : TreeQueryableBase where TProps : class, new() { public MssqlTreeQueryable( 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 MssqlTreeQueryable(_treeProvider, context, _filterParser, _orderingParser); } } Path: redb/redb.MSSql/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.MSSql/README.md ---- # redb.MSSql SQL Server provider for **RedBase (REDB)** — Entity Database for .NET. [![NuGet](https://img.shields.io/nuget/v/redb.MSSql?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.MSSql) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../LICENSE) ## What's inside - T-SQL-optimized query generation - Tree queries with recursive CTEs - Schema initialization (`redbMSSQL.sql`) - Full LINQ-to-SQL translation - Depends on `redb.Core` and `Microsoft.Data.SqlClient` 7.0.3 ## Requirements - **SQL Server 2017 or newer.** The server-side machinery uses `OPENJSON`, `JSON_VALUE`, `JSON_QUERY`, `ISJSON` and `STRING_SPLIT` (2016), plus `STRING_AGG` and `TRIM` (2017). - **SQL Server 2022 or newer for the `$min` / `$max` expression operators**, which compile to `LEAST` / `GREATEST`. Nothing else needs 2022, and on an older server only those two operators fail, at query time rather than at startup. - Azure SQL Database tracks the latest engine, so it satisfies both. It is not part of our test run. - Developed and tested against `mcr.microsoft.com/mssql/server:2025-latest`. - **Index usage counters need `VIEW SERVER STATE`** (`VIEW SERVER PERFORMANCE STATE` on 2022 and newer). Without it, `Redb.Maintenance` still lists tables, indexes and their sizes, but `IndexStatistics.Seeks`, `Scans`, `Updates`, `LastUsed` and `StatisticsWindow.CountersSince` are null. Grant it to the application login with `GRANT VIEW SERVER STATE TO [login]`. ## Installation ```bash dotnet add package redb.MSSql ``` ## Setup ```csharp using redb.Core.Extensions; using redb.MSSql.Extensions; builder.Services.AddRedb(options => options .UseMsSql("Server=localhost;Database=mydb;User Id=sa;Password=pass;TrustServerCertificate=true")); ``` ## Limits - **A dictionary key is at most 430 characters** after serialization (`_array_index` is `NVARCHAR(430)`, within the 900-byte index key). A longer key is refused before anything is written, with `RedbDictionaryKeyTooLongException` naming the property, the length and the limit. PostgreSQL and SQLite have no such bound. - **A bulk load stops after 30 seconds by default.** `AddNewObjectsAsync` and the batch save write a large set through `SqlBulkCopy`, and the connection string's `Command Timeout` does not reach its timeout. On a busy server set `.Configure(c => c.BulkInsertTimeout = TimeSpan.FromMinutes(5))`; `TimeSpan.Zero` means no limit. ## Server settings With the SQL Server defaults (`max degree of parallelism` 0, `cost threshold for parallelism` 5) the free provider's window, GroupBy and aggregate queries go parallel on every core and run 2 to 6 times slower: on 100 000 employees an `NTILE` window took 11.5 s instead of 1.8 s. We test with `cost threshold for parallelism` 50 and `max degree of parallelism` 4, set with `sp_configure` followed by `RECONFIGURE`. Simple filters and the Pro provider are not affected. ## 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.MSSql/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.MSSql/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.Models.Contracts; using redb.Core.Models.Configuration; using redb.MSSql.Data; using redb.MSSql.Providers; using redb.MSSql.Query; using redb.MSSql.Sql; namespace redb.MSSql; /// /// MSSQL implementation of IRedbService. /// Inherits all common logic from RedbServiceBase. /// Only provides MSSQL-specific provider factories. /// public class RedbService : RedbServiceBase { private static readonly MsSqlDialect _dialect = new(); /// /// Creates a new MSSQL RedbService instance. /// public RedbService(IServiceProvider serviceProvider) : base(serviceProvider) { } // === MSSQL-SPECIFIC IMPLEMENTATIONS === protected override string DatabaseTypeName => "MSSql"; protected override ISqlDialect SqlDialect => _dialect; /// The indexes of a fresh SQL Server database of this build (MsSqlIndexCatalog, generated and pinned by a test). protected override IReadOnlyList ExpectedIndexes => MsSqlIndexCatalog.Base; // SERVERPROPERTY('EngineEdition') of the editions with ONLINE index operations: 3 Enterprise (and Developer, // Evaluation), 5 Azure SQL Database, 8 Azure SQL Managed Instance. Standard (2) and Express (4) build offline only. private static readonly int[] OnlineEditions = [3, 5, 8]; /// protected override async Task CanBuildOnlineAsync(CancellationToken cancellationToken) { var edition = await Context.ExecuteScalarAsync(_dialect.Server_EngineEdition()); return Array.IndexOf(OnlineEditions, edition) >= 0; } /// /// On an edition without ONLINE index operations an offline build blocks writes to the table while it runs, so the /// repair builds nothing there unless it was allowed to, and returns the statements instead. /// protected override async Task RefuseIndexBuildAsync(bool allowOffline, CancellationToken cancellationToken) => allowOffline || await CanBuildOnlineAsync(cancellationToken) ? null : "this SQL Server edition builds indexes offline only, which blocks writes to the table while it runs; " + "run the statements in a maintenance window, or repair again with offline building allowed."; /// WITH (ONLINE = ON) where the edition has it. protected override string IndexBuildStatement(Core.Models.RedbExpectedIndex index, bool online) => online ? index.CreateSql + " WITH (ONLINE = ON)" : index.CreateSql; /// protected override string IndexDropStatement(Core.Models.RedbExpectedIndex index) => $"DROP INDEX IF EXISTS [{index.Name}] ON [dbo].[{index.Table}]"; /// On a connection of its own: 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 SqlRedbContext sqlContext) { await Context.ExecuteAsync(sql); return; } await using var connection = new Microsoft.Data.SqlClient.SqlConnection(sqlContext.ConnectionString); await connection.OpenAsync(cancellationToken); await using var command = new Microsoft.Data.SqlClient.SqlCommand(sql, connection) { CommandTimeout = 0 }; await command.ExecuteNonQueryAsync(cancellationToken); } protected override string GetVersionSql => "SELECT @@VERSION"; protected override string GetDatabaseSizeSql => "SELECT SUM(CAST(size AS BIGINT)) * 8192 FROM sys.database_files"; // size counts 8 KB pages; dbSize is bytes protected override string ContextNotRegisteredError => "IRedbContext is not registered in DI container. Add SqlRedbContext to configuration."; // === PROVIDER FACTORIES === protected override ISchemeSyncProvider CreateSchemeSyncProvider( IRedbContext context, RedbServiceConfiguration config, string cacheDomain, ILogger? logger) => new MssqlSchemeSyncProvider(context, config, cacheDomain, logger); protected override IPermissionProvider CreatePermissionProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new MssqlPermissionProvider(context, securityContext, logger); protected override IUserProvider CreateUserProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new MssqlUserProvider(context, securityContext, ResolvePasswordHasher(), logger); protected override IRoleProvider CreateRoleProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger) => new MssqlRoleProvider(context, securityContext, logger); protected override IListProvider CreateListProvider( IRedbContext context, RedbServiceConfiguration config, ISchemeSyncProvider schemeSync, ILogger? logger) => new MssqlListProvider(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 MssqlObjectStorageProvider(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 MssqlTreeProvider(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 MssqlQueryableProvider(context, serializer, schemeSync, securityContext, lazyPropsLoader, config, cacheDomain, logger); protected override IValidationProvider CreateValidationProvider( IRedbContext context, ILogger? logger) => new MssqlValidationProvider(context, logger); protected override Core.Providers.IMaintenanceProvider CreateMaintenanceProvider( IRedbContext context, int analysisLimit, ILogger? logger) => new Providers.MssqlMaintenanceProvider(context, analysisLimit, logger); // === DATABASE SCHEMA MANAGEMENT === /// protected override async Task TableExistsAsync(string tableName) { // Params: table name, schema (null = dbo). if (Context is not SqlRedbContext context) return await Context.ExecuteScalarAsync(_dialect.Maintenance_SelectTableExists(), tableName, DBNull.Value) > 0; // On a connection of its own, returned to the pool at once: the context keeps its connection open for its // lifetime, and a node that looked for the tables and then waits for the schema lock would hold a session in // the database the whole time, which the creator's ALTER DATABASE (READ_COMMITTED_SNAPSHOT) waits out. The // pool is cleared before the lock is awaited (OpenSchemaLockAsync). await using var connection = new Microsoft.Data.SqlClient.SqlConnection(context.ConnectionString); await connection.OpenAsync(); return Convert.ToInt32(await ScalarAsync(connection, _dialect.Maintenance_SelectTableExists(), CancellationToken.None, tableName, DBNull.Value)) > 0; } /// protected override string ReadEmbeddedSql() { var assembly = typeof(RedbService).Assembly; var resourceName = "redb.MSSql.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.MSSql.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(); } /// protected override async Task ExecuteSchemaScriptAsync(string sql) { // MSSQL uses GO as a batch separator — split and execute each batch var batches = System.Text.RegularExpressions.Regex.Split(sql, @"^\s*GO\s*$", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase); try { foreach (var batch in batches) { var trimmed = batch.Trim(); if (!string.IsNullOrEmpty(trimmed)) await Context.ExecuteAsync(trimmed); } } catch (Microsoft.Data.SqlClient.SqlException) { // The guard of the script (a database that already holds the schema) sets NOEXEC ON on the session it ran // on, and the context keeps that session: every later command of this process would be compiled and not // run, a query answering nothing. SET NOEXEC OFF runs even under NOEXEC and turns it back on the same // session. Clearing the pool did not reach the connection the context holds. await Context.ExecuteAsync("SET NOEXEC OFF"); throw; } } /// protected override async Task OpenSchemaLockAsync(CancellationToken cancellationToken) { if (Context is not SqlRedbContext sql) return SchemaLockHandle.None; // Where the lock lives follows a property every node of one database reads the same, never an error: a node // that took it elsewhere after failing to reach master would not see the lock of the others. // Azure SQL Database (EngineEdition 5): in the database itself. READ_COMMITTED_SNAPSHOT is on there from the // start, the creation script does not alter the database, and a session in it keeps nobody waiting. // Any other SQL Server: in master. The creation script turns on READ_COMMITTED_SNAPSHOT, and ALTER DATABASE // waits until it is the only session in the database: a lock held there, or a waiting node logging in to // look, would keep the creator waiting. Microsoft.Data.SqlClient.SqlConnection? master = new Microsoft.Data.SqlClient.SqlConnection( new Microsoft.Data.SqlClient.SqlConnectionStringBuilder(sql.ConnectionString) { InitialCatalog = "master" }.ConnectionString); Microsoft.Data.SqlClient.SqlException? masterError = null; try { await master.OpenAsync(cancellationToken); } catch (Microsoft.Data.SqlClient.SqlException ex) { // Asked in the database instead below: on Azure SQL Database a login without a user in master is normal. masterError = ex; } try { var edition = masterError == null ? Convert.ToInt32(await ScalarAsync(master, _dialect.Server_EngineEdition(), cancellationToken)) : await Context.ExecuteScalarAsync(_dialect.Server_EngineEdition()); if (edition == AzureSqlDatabaseEdition) { var own = new Microsoft.Data.SqlClient.SqlConnection(sql.ConnectionString); try { await own.OpenAsync(cancellationToken); } catch { await own.DisposeAsync(); throw; } return new ApplicationLock(own, "redb.schema"); } // Reached only when there is schema work to do: a database already deployed starts without the lock. if (masterError != null) throw new InvalidOperationException( "The database needs schema work (creating the schema, upgrading the SQL module or synchronizing a " + "scheme), which REDB does under a schema lock held in the master database, and the login of this " + $"connection could not open master: {masterError.Message} Either give the login access to master, " + "or deploy the schema with the DBA scripts (GetSchemaScript, GetUpgradeScript) and synchronize the " + "schemes with a login that has it.", masterError); // An application lock is per database: in master the name of the database tells them apart. var database = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder(sql.ConnectionString).InitialCatalog; if (string.IsNullOrEmpty(database)) database = await Context.ExecuteScalarAsync(_dialect.Server_CurrentDatabase()); // Idle connections of this process's pool are sessions in the database too: closed before the lock is // handed out, so the creation script of this process does not wait for its own pool. await using (var pooled = new Microsoft.Data.SqlClient.SqlConnection(sql.ConnectionString)) Microsoft.Data.SqlClient.SqlConnection.ClearPool(pooled); var handle = new ApplicationLock(master, $"redb.schema:{database}"); master = null; return handle; } finally { if (master != null) await master.DisposeAsync(); } } /// /// 18456 login failed, 4060 the database of the login cannot be opened: both seen while a node creating /// the schema turns on READ_COMMITTED_SNAPSHOT. protected override bool IsDatabaseClosedForSchemaWork(Exception exception) => exception is Microsoft.Data.SqlClient.SqlException { Number: 18456 or 4060 }; // SERVERPROPERTY('EngineEdition') of Azure SQL Database (Managed Instance is 8, a server of one's own 2 to 4). private const int AzureSqlDatabaseEdition = 5; /// A dialect statement on a connection of its own; the values bind to @p0, @p1, ... as in the context. private static async Task ScalarAsync( Microsoft.Data.SqlClient.SqlConnection connection, string commandText, CancellationToken cancellationToken, params object[] parameters) { await using var command = connection.CreateCommand(); command.CommandText = commandText; for (var i = 0; i < parameters.Length; i++) command.Parameters.AddWithValue($"@p{i}", parameters[i]); return await command.ExecuteScalarAsync(cancellationToken); } /// /// The schema lock of SQL Server: an exclusive application lock owned by the session of a connection of its own. /// Every attempt asks with no wait (@LockTimeout = 0), so the wait and its log stay in the service. sp_getapplock /// is granted to public: any user of the database may take it. /// private sealed class ApplicationLock(Microsoft.Data.SqlClient.SqlConnection connection, string resource) : SchemaLockHandle { private bool _held; public override string Name => $"sp_getapplock '{resource}'"; public override async Task TryAcquireAsync(CancellationToken cancellationToken) { var result = Convert.ToInt32(await ScalarAsync(connection, _dialect.SchemaLock_TryAcquire(), cancellationToken, resource)); // 0 and 1: granted; -1: held by another session. Anything else (-2 cancelled, -3 deadlock, -999 error) is // not a wait to sit out. if (result is < -1) throw new InvalidOperationException($"sp_getapplock on '{resource}' returned {result}."); _held = result >= 0; return _held; } public override async ValueTask DisposeAsync() { try { if (_held) await ScalarAsync(connection, _dialect.SchemaLock_Release(), CancellationToken.None, resource); } finally { // Closing ends the session, and the session takes its application locks with it. await connection.DisposeAsync(); } } } } Path: redb/redb.MSSql/redb.MSSql.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.MSSql/redb.MSSql.csproj ---- net10.0;net11.0 enable enable redb.MSSql true $(NoWarn);CS1591 redb.MSSql REDB - Entity Database for .NET SQL Server provider for REDB. Includes optimized T-SQL generation, tree queries with CTEs, and full LINQ support. Requires SQL Server 2017 or newer (2022+ only for the $min / $max expression operators). https://github.com/redbase-app/redb database;orm;redb;redbase;sqlserver;mssql;linq;dotnet;typed-storage;cte;tree-query README.md redb.MSSql.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(); } if (!string.IsNullOrEmpty(Trailer)) sb.AppendLine(Trailer); System.IO.File.WriteAllText(OutputFile, sb.ToString()); ]]> Path: redb/redb.MSSql/sql/MsSqlDialect.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.MSSql/sql/MsSqlDialect.cs ---- using redb.Core.Query; using redb.Core.Utils; namespace redb.MSSql.Sql; /// /// MS SQL Server implementation of ISqlDialect. /// Uses SQL Server 2016+ features (JSON, STRING_SPLIT, sequences). /// Parameters use @p0, @p1 format (converted from $1, $2 in SqlRedbConnection). /// public class MsSqlDialect : ISqlDialect { public string ProviderName => "MSSql"; /// _values._array_index is NVARCHAR(430): 3 bigints + 860 bytes stay under the 900-byte index key. public int? DictionaryKeyMaxLength => 430; /// /// MSSQL pagination: OFFSET n ROWS FETCH NEXT m ROWS ONLY. /// Requires ORDER BY clause in the query. /// public string FormatPagination(int? limit, int? offset) { if (!limit.HasValue && !offset.HasValue) return string.Empty; var off = offset ?? 0; var lim = limit ?? int.MaxValue; return $"OFFSET {off} ROWS FETCH NEXT {lim} ROWS ONLY"; } public string WrapSubquery(string subquery, string alias) => $"({subquery}) AS {alias}"; /// /// PVT via subquery with TOP 1 (MSSQL doesn't have array_agg FILTER). /// public string FormatPvtColumn(long structureId, string dbColumn, string alias) => $"(SELECT TOP 1 {dbColumn} FROM _values v2 WHERE v2._id_object = v._id_object AND v2._id_structure = {structureId}) AS [{alias}]"; /// /// MSSQL uses IN with STRING_SPLIT for array containment. /// public string FormatArrayContains(string column, string paramName) => $"{column} IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT({paramName}, ','))"; public string GetDbTypeName(string redbType) => redbType switch { "Long" => "bigint", "String" => "nvarchar(max)", "Boolean" => "bit", "DateTime" => "datetimeoffset", "DateTimeOffset" => "datetimeoffset", "Double" => "float", "Numeric" => "decimal(38,18)", "Guid" => "uniqueidentifier", "ByteArray" => "varbinary(max)", _ => "nvarchar(max)" }; /// /// MSSQL parameter format (@p0, @p1, etc.). /// Note: SqlRedbConnection converts $1 to @p0 automatically. /// public string FormatParameter(int index) => $"@p{index - 1}"; public string QuoteIdentifier(string name) // SQL Server escapes a closing bracket by doubling it. Without this a name like // `a]b; SELECT 1--` closes the identifier and the rest becomes SQL (SQLI-PoC p.7). => "[" + name.Replace("]", "]]") + "]"; /// /// Returns the expression unchanged, and unlike SQLite this is not a gap being papered over. /// SQL Server's default collation (SQL_Latin1_General_CP1_CI_AS and its regional siblings) is /// already case-insensitive for every script, Cyrillic and Greek included, so LIKE, LOWER and /// UPPER fold correctly with no help. A database deliberately created with a case-SENSITIVE /// collation is a decision by whoever created it, and silently overriding it here would defeat /// that decision. /// public string FoldCase(string expression) => expression; public string FormatCaseInsensitiveLike(string column, string parameter) // ESCAPE '\\' is REQUIRED because UserProviderBase.EscapeLikeWildcards // escapes '_', '%', '\' with a leading backslash to make them literal. // PG defaults to '\' as the LIKE escape, SQL Server does NOT — without // this clause a search for an exact email like 'reset_53f4f0f9@…' (which // becomes the pattern 'reset\_53f4f0f9@…') is compared as the literal // string starting with 'reset\_' rather than 'reset_', and no row matches. // MSSQL case-insensitivity comes from the column collation default // (SQL_Latin1_General_CP1_CI_AS); no ILIKE / explicit COLLATE needed. => $"{column} LIKE {parameter} ESCAPE '\\'"; public string FormatDateTimeLiteral(DateTime dt) => $"'{DateTimeConverter.NormalizeForStorage(dt):yyyy-MM-ddTHH:mm:ss.ffffffZ}'"; public string FormatDateTimeOffsetLiteral(DateTimeOffset dto) => $"'{dto.UtcDateTime:yyyy-MM-ddTHH:mm:ss.ffffffZ}'"; public string FormatBooleanLiteral(bool value) => value ? "1" : "0"; // N: _String is nvarchar; a plain '...' is varchar and loses every character outside the code page. public string FormatStringLiteral(string value) => "N'" + value.Replace("'", "''") + "'"; public string FormatBinaryLiteral(byte[] value) => "0x" + Convert.ToHexString(value); // ============================================================ // === ROLES SQL === // ============================================================ public string Roles_SelectById() => "SELECT _id AS Id, _name AS Name, _id_configuration AS IdConfiguration FROM _roles WHERE _id = @p0"; public string Roles_SelectByName() => "SELECT _id AS Id, _name AS Name, _id_configuration AS IdConfiguration FROM _roles WHERE _name = @p0"; 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 (@p0, @p1)"; public string Roles_UpdateName() => "UPDATE _roles SET _name = @p0 WHERE _id = @p1"; public string Roles_Delete() => "DELETE FROM _roles WHERE _id = @p0"; public string Roles_ExistsByName() => "SELECT _id FROM _roles WHERE _name = @p0"; public string Roles_ExistsByNameExcluding() => "SELECT _id FROM _roles WHERE _name = @p0 AND _id != @p1"; public string Roles_Count() => "SELECT COUNT(*) FROM _roles"; public string Roles_UpdateConfiguration() => "UPDATE _roles SET _id_configuration = @p0 WHERE _id = @p1"; public string Roles_SelectConfigurationId() => "SELECT _id_configuration FROM _roles WHERE _id = @p0"; // ============================================================ // === USERS_ROLES SQL === // ============================================================ public string UsersRoles_Insert() => "INSERT INTO _users_roles (_id, _id_user, _id_role) VALUES (@p0, @p1, @p2)"; public string UsersRoles_Delete() => "DELETE FROM _users_roles WHERE _id_user = @p0 AND _id_role = @p1"; public string UsersRoles_DeleteByUser() => "DELETE FROM _users_roles WHERE _id_user = @p0"; public string UsersRoles_DeleteByRole() => "DELETE FROM _users_roles WHERE _id_role = @p0"; public string UsersRoles_Exists() => "SELECT _id FROM _users_roles WHERE _id_user = @p0 AND _id_role = @p1"; 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 = @p0 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 = @p0 ORDER BY u._name """; public string UsersRoles_CountByRole() => "SELECT COUNT(*) FROM _users_roles WHERE _id_role = @p0"; // ============================================================ // === USERS SQL === // ============================================================ public string Users_ExistsById() => "SELECT _id FROM _users WHERE _id = @p0"; public string Users_SelectIdByLogin() => "SELECT _id FROM _users WHERE _login = @p0"; // ============================================================ // === PERMISSIONS SQL === // ============================================================ public string Permissions_DeleteByRole() => "DELETE FROM _permissions WHERE _id_role = @p0"; /// /// Uses MSSQL function get_user_permissions_for_object() from redb_permissions.sql. /// public string Permissions_GetEffectiveForObject() => "SELECT * FROM dbo.get_user_permissions_for_object(@p0, @p1)"; public string Permissions_GetEffectiveForObjects() => """ SELECT CAST(ids.value AS BIGINT) 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 STRING_SPLIT(@p0, ',') ids CROSS APPLY dbo.get_user_permissions_for_object(CAST(ids.value AS BIGINT), @p1) p """; public string Permissions_SelectReadableObjectIds() => """ SELECT DISTINCT p.object_id FROM dbo.get_user_permissions_for_object(NULL, @p0) p WHERE p.can_select = 1 """; public string Permissions_Insert() => """ INSERT INTO _permissions (_id, _id_user, _id_role, _id_ref, _select, _insert, _update, _delete) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7) """; public string Permissions_Update() => "UPDATE _permissions SET _select = @p0, _insert = @p1, _update = @p2, _delete = @p3 WHERE _id = @p4"; public string Permissions_Delete() => "DELETE FROM _permissions WHERE _id = @p0"; 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 = @p0 """; 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 = @p0 """; 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 = @p0 """; 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 = @p0 OR _id_ref = 0 """; /// /// MSSQL equivalent of IS NOT DISTINCT FROM. /// 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 = @p0) OR (_id_user IS NULL AND @p0 IS NULL)) AND ((_id_role = @p1) OR (_id_role IS NULL AND @p1 IS NULL)) AND _id_ref = @p2 """; public string Permissions_DeleteByUserRoleObject() => """ DELETE FROM _permissions WHERE ((_id_user = @p0) OR (_id_user IS NULL AND @p0 IS NULL)) AND ((_id_role = @p1) OR (_id_role IS NULL AND @p1 IS NULL)) AND _id_ref = @p2 """; public string Permissions_DeleteByUser() => "DELETE FROM _permissions WHERE _id_user = @p0"; public string Permissions_Count() => "SELECT COUNT(*) FROM _permissions"; public string Permissions_CountByUser() => "SELECT COUNT(*) FROM _permissions WHERE _id_user = @p0"; public string Permissions_CountByRole() => "SELECT COUNT(*) FROM _permissions WHERE _id_role = @p0"; public string Permissions_SelectUserRoleIds() => "SELECT _id_role AS IdRole FROM _users_roles WHERE _id_user = @p0"; // ============================================================ // === 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 = @p0 """; public string Users_SelectByIds() => """ SELECT _id AS Id, _login AS Login, _name AS Name, _password AS Password, _phone AS Phone, _email AS Email, _enabled AS Enabled, _date_register AS DateRegister, _date_dismiss AS DateDismiss, _key AS [Key], _code_int AS CodeInt, _code_string AS CodeString, _code_guid AS CodeGuid, _note AS Note, _hash AS Hash FROM _users WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ',')) """; 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 = @p0 """; // Case-insensitive email lookup. Mirrors the PostgreSQL recipe — see PostgreSqlDialect // for the contract notes. public string Users_SelectByEmail() => """ SELECT TOP 1 _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(@p0) AND _enabled = 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 (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14) """; public string Users_Update() => """ UPDATE _users SET _login = @p0, _name = @p1, _phone = @p2, _email = @p3, _enabled = @p4, _date_dismiss = @p5, _key = @p6, _code_int = @p7, _code_string = @p8, _code_guid = @p9, _note = @p10, _hash = @p11 WHERE _id = @p12 """; // _login is immutable (Postgres trigger contract; keep MSSql parity). Tombstone via _name only. public string Users_SoftDelete() => "UPDATE _users SET _name = @p0, _enabled = @p1, _date_dismiss = @p2 WHERE _id = @p3"; public string Users_UpdatePassword() => "UPDATE _users SET _password = @p0 WHERE _id = @p1"; public string Users_UpdateStatus() => "UPDATE _users SET _enabled = @p0, _date_dismiss = @p1 WHERE _id = @p2"; public string Users_ExistsByLogin() => "SELECT _id FROM _users WHERE _login = @p0"; public string Users_ExistsByLoginExcluding() => "SELECT _id FROM _users WHERE _login = @p0 AND _id != @p1"; public string Users_ExistsByEmail() => "SELECT TOP 1 _id FROM _users WHERE _email = @p0"; public string Users_Count() => "SELECT COUNT(*) FROM _users"; public string Users_CountEnabled() => "SELECT COUNT(*) FROM _users WHERE _enabled = 1"; public string Users_SelectConfigurationId() => "SELECT _id_configuration FROM _users WHERE _id = @p0"; public string Users_UpdateConfiguration() => "UPDATE _users SET _id_configuration = @p0 WHERE _id = @p1"; public string Roles_SelectIdByName() => "SELECT _id AS Id FROM _roles WHERE _name = @p0"; public string Roles_ExistsById() => "SELECT _id FROM _roles WHERE _id = @p0"; // ============================================================ // === SCHEMES SQL === // ============================================================ public string Schemes_SelectByName() => "SELECT _id, _name, _alias, _name_space, _structure_hash, _tags, _renamed_from, _version, _type FROM _schemes WHERE _name = @p0"; public string Schemes_SelectById() => "SELECT _id, _name, _alias, _name_space, _structure_hash, _tags, _renamed_from, _version, _type FROM _schemes WHERE _id = @p0"; 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 (@p0, @p1, @p2, @p3)"; // T-SQL has no ON CONFLICT. UPDLOCK+HOLDLOCK on the probe is what makes this safe: without them // READ COMMITTED lets two sessions both see "not exists" and the loser still gets 2627. public string Schemes_InsertIfAbsent() => "INSERT INTO _schemes (_id, _name, _alias, _type, _name_space) " + "SELECT @p0, @p1, @p2, @p3, @p4 " + "WHERE NOT EXISTS (SELECT 1 FROM _schemes WITH (UPDLOCK, HOLDLOCK) WHERE _name = @p1)"; public string Schemes_UpdateHash() => "UPDATE _schemes SET _structure_hash = @p0 WHERE _id = @p1"; public string Schemes_UpdateVersion() => "UPDATE _schemes SET _version = @p0 WHERE _id = @p1 AND COALESCE(_version, 0) < @p0"; public string Schemes_Rename() => "UPDATE _schemes SET _name = @p0, _renamed_from = @p1 WHERE _id = @p2"; 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 = @p0 WHERE _id = @p1"; public string Schemes_UpdateNameSpace() => "UPDATE _schemes SET _name_space = @p0 WHERE _id = @p1"; public string Schemes_SelectHashById() => "SELECT _structure_hash FROM _schemes WHERE _id = @p0"; public string Schemes_ExistsByName() => "SELECT TOP 1 _id FROM _schemes WHERE _name = @p0"; public string Schemes_SelectObjectByName() => "SELECT _id, _name, _alias, _name_space, _structure_hash, _tags, _renamed_from, _version, _type FROM _schemes WHERE _name = @p0 AND _type = @p1"; public string Schemes_InsertObject() => "INSERT INTO _schemes (_id, _name, _type) VALUES (@p0, @p1, @p2)"; public string Schemes_InsertObjectIfAbsent() => "INSERT INTO _schemes (_id, _name, _type) " + "SELECT @p0, @p1, @p2 " + "WHERE NOT EXISTS (SELECT 1 FROM _schemes WITH (UPDLOCK, HOLDLOCK) WHERE _name = @p1)"; // ============================================================ // === 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 = @p0 """; 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 = @p0"; 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 = @p0 """; 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 (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10) """; public string Structures_UpdateType() => "UPDATE _structures SET _id_type = @p0 WHERE _id = @p1"; public string Structures_UpdateCollectionType() => "UPDATE _structures SET _collection_type = @p0 WHERE _id = @p1"; public string Structures_UpdateKeyType() => "UPDATE _structures SET _key_type = @p0 WHERE _id = @p1"; public string Structures_UpdateAlias() => "UPDATE _structures SET _alias = @p0 WHERE _id = @p1"; public string Structures_UpdateAllowNotNull() => "UPDATE _structures SET _allow_not_null = @p0 WHERE _id = @p1"; public string Structures_UpdateLazy() => "UPDATE _structures SET _lazy = @p0 WHERE _id = @p1"; public string Session_SetLazyRefs() => "EXEC sp_set_session_context @key = N'redb.lazy_refs', @value = @p0"; public string Structures_UpdateUnique() => "UPDATE _structures SET _unique = @p0, _unique_version = @p1, _unique_scope = @p2 WHERE _id = @p3"; public string Structures_UpdateTags() => "UPDATE _structures SET _tags = @p0 WHERE _id = @p1"; public string Structures_Rename() => "UPDATE _structures SET _name = @p0, _renamed_from = @p1 WHERE _id = @p2"; public string Schemes_UpdateTags() => "UPDATE _schemes SET _tags = @p0 WHERE _id = @p1"; 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 = @p0 """; // 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 INNER JOIN _objects o ON o._id = v._id_object AND o._id_scheme <> -10 WHERE v._id_structure = @p0 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 INNER JOIN _objects o ON o._id = v._id_object AND o._id_scheme <> -10 WHERE v._id_structure = @p0 AND v._array_index IS NOT NULL ORDER BY v._id """; public string Values_UpdateUnique() => "UPDATE _values SET _unique = @p0 WHERE _id = @p1"; public string Values_ClearUniqueByStructure() => "UPDATE _values SET _unique = NULL WHERE _id_structure = @p0 AND _unique IS NOT NULL"; public string Values_ExistsByStructure() => "SELECT CASE WHEN EXISTS (SELECT 1 FROM _values WHERE _id_structure = @p0) THEN 1 ELSE 0 END"; // 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 = @p0 AND _unique = @p1"; public string Values_ExistsUnhashedByStructure(string typedColumn) => $""" SELECT TOP 1 1 FROM _values v INNER JOIN _objects o ON o._id = v._id_object AND o._id_scheme <> -10 WHERE v._id_structure = @p0 AND v._unique IS NULL AND v.{typedColumn} IS NOT NULL AND v._array_index IS NULL """; 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 = @p0 """; public string Values_SetByteArrayScalar() => "UPDATE _values SET _ByteArray = CAST(@p0 AS VARBINARY(MAX)), _Guid = NULL, _Long = NULL WHERE _id = @p1"; public string Values_DeleteByteArrayElements() => "DELETE FROM _values WHERE _id_structure = @p0 AND _array_parent_id IN (SELECT _id FROM _values WHERE _id_structure = @p0)"; 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), in master // or, on Azure SQL Database, in the database itself. /// /// One attempt at the exclusive application lock of the schema, owned by the session, with no wait; returns the /// result code of sp_getapplock (0 or 1 granted, -1 held elsewhere). Params: @p0 = resource name. /// public string SchemaLock_TryAcquire() => "DECLARE @result int; " + "EXEC @result = sp_getapplock @Resource = @p0, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = 0; " + "SELECT @result;"; /// Releases the application lock of the schema. Params: @p0 = resource name. public string SchemaLock_Release() => "EXEC sp_releaseapplock @Resource = @p0, @LockOwner = 'Session'"; /// SERVERPROPERTY('EngineEdition') as int (5 = Azure SQL Database). No params. public string Server_EngineEdition() => "SELECT CAST(SERVERPROPERTY('EngineEdition') AS int)"; /// The name of the current database. No params. public string Server_CurrentDatabase() => "SELECT DB_NAME()"; // === ROOT STRUCTURE KEY === // The UNIQUE constraint IX__structures counts NULLs as equal on SQL Server: a root field cannot be written twice, // and no separate key is needed. Only the null of Structures_RootKeyExists is asked; the rest is never reached. private const string RootKeyNotApplicable = "SQL Server needs no unique key of root structures: IX__structures counts NULL parents as equal."; public string? Structures_RootKeyExists() => null; public string Structures_CreateRootKey() => throw new NotSupportedException(RootKeyNotApplicable); public string Structures_SelectRootDuplicates() => throw new NotSupportedException(RootKeyNotApplicable); public string? Structures_LockSubtree() => throw new NotSupportedException(RootKeyNotApplicable); public string Structures_SubtreeIsReferenced(bool withMigrations) => throw new NotSupportedException(RootKeyNotApplicable); public string Structures_DeleteSubtreeMetadataCache() => throw new NotSupportedException(RootKeyNotApplicable); public string Structures_DeleteById() => "DELETE FROM _structures WHERE _id = @p0"; public string Schemes_CountMetadataCache() => "SELECT CAST(COUNT(*) AS BIGINT) FROM _scheme_metadata_cache WHERE _scheme_id = @p0"; // ============================================================ // === TYPES SQL === // ============================================================ public string Types_SelectByName() => "SELECT _id, _name FROM _types WHERE _name = @p0"; public string Types_SelectAll() => "SELECT _id AS Id, _name AS Name, _db_type AS DbType, _type AS Type1 FROM _types"; // ============================================================ // === SCHEME FUNCTIONS (MSSQL stored procedures) === // ============================================================ /// /// Sync metadata cache for scheme. Uses MSSQL stored procedure. /// public string Schemes_SyncMetadataCache() => "EXEC dbo.sync_metadata_cache_for_scheme @p0"; public string Schemes_MigrateStructureType() => "EXEC dbo.migrate_structure_type @p0, @p1, @p2, @p3"; public string Schemes_GetStructureTree() => "SELECT dbo.get_scheme_structure_tree(@p0)"; // ============================================================ // === TREE SQL === // ============================================================ public string Tree_SelectChildrenJson() => """ SELECT dbo.get_object_json(o._id, 1) as json_data FROM _objects o WHERE o._id_parent = @p0 AND o._id_scheme = @p1 """; public string Tree_SelectPolymorphicChildren() => """ SELECT o._id as ObjectId, o._id_scheme as SchemeId, dbo.get_object_json(o._id, 1) as JsonData FROM _objects o WHERE o._id_parent = @p0 ORDER BY o._name, o._id """; public string Tree_SelectSchemeAndJson() => """ SELECT o._id_scheme as SchemeId, dbo.get_object_json(o._id, 1) as JsonData FROM _objects o WHERE o._id = @p0 """; 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 = @p0 AND _id_scheme = @p1 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 = @p0 ORDER BY _name, _id """; public string Tree_ObjectExists() => "SELECT TOP 1 _id FROM _objects WHERE _id = @p0"; 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 = @p0, _date_modify = @p1, _id_who_change = @p2, _hash = NULL WHERE _id = @p3"; public string Tree_DeleteValuesByObjectIds() => "DELETE FROM _values WHERE _id_object IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ','))"; // The cascade procedure locks the rows it deletes and counts only those: the INSTEAD OF trigger of a plain DELETE // reports the rows the statement qualified, one another session deleted meanwhile included. public string Tree_DeleteObjectsByIds() => "EXEC dbo.delete_objects_cascade @p0"; // MAXRECURSION 0: the depth parameter bounds the walk, which may go past the default of 100 levels. public string Tree_SelectSubtreeRows() => """ WITH sub AS ( SELECT o._id, o._id_parent, o._id_scheme, o._name, 1 AS depth FROM _objects o WHERE o._id_parent = @p0 AND (@p1 IS NULL OR o._id_scheme = @p1) 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 < @p2 AND (@p1 IS NULL OR o._id_scheme = @p1) ) SELECT _id AS Id, _id_parent AS IdParent, _id_scheme AS IdScheme, depth AS Depth FROM sub ORDER BY _name, _id OPTION (MAXRECURSION 0) """; public string Tree_SelectAncestorRows() => """ WITH up AS ( SELECT o._id, o._id_parent, o._id_scheme, 0 AS depth FROM _objects o WHERE o._id = @p0 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 < @p1 ) SELECT _id AS Id, _id_parent AS IdParent, _id_scheme AS IdScheme, depth AS Depth FROM up ORDER BY depth OPTION (MAXRECURSION 0) """; // MAXRECURSION 0: the depth parameter bounds the walk; the default of 100 levels failed on a deeper tree. public string Tree_SelectIdsWithAncestors() => """ WITH up AS ( SELECT o._id, o._id_parent, 0 AS depth FROM _objects o WHERE o._id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ',')) 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 < @p1 ) SELECT DISTINCT _id FROM up OPTION (MAXRECURSION 0) """; // ============================================================ // === 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 = @p0 """; public string ObjectStorage_SelectIdHash() => "SELECT _id as Id, _hash as Hash FROM _objects WHERE _id = @p0"; public string ObjectStorage_SelectIdBySchemeValueUnique() => "SELECT _id FROM _objects WHERE _id_scheme = @p0 AND _value_unique = @p1"; // 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 = @p0"; public string ObjectStorage_SelectObjectsByIds() => """ SELECT _id as Id, _id_scheme as IdScheme, _id_parent as IdParent, _id_owner as IdOwner, _id_who_change as IdWhoChange, _name as Name, _hash as Hash, _date_create as DateCreate, _date_modify as DateModify, _date_begin as DateBegin, _date_complete as DateComplete, _key as [Key], _note as Note, _value_long as ValueLong, _value_string as ValueString, _value_guid as ValueGuid, _value_bool as ValueBool, _value_double as ValueDouble, _value_numeric as ValueNumeric, _value_datetime as ValueDatetime, _value_bytes as ValueBytes, _value_unique as ValueUnique FROM _objects WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ',')) """; public string ObjectStorage_DeleteById() => "EXEC dbo.delete_object_cascade @p0"; public string ObjectStorage_DeleteByIds() => "EXEC dbo.delete_objects_cascade @p0"; 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 (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16, CAST(@p17 AS VARBINARY(MAX)), @p18, @p19, @p20, @p21) """; public string ObjectStorage_UpdateObject() => """ UPDATE _objects SET _name = @p0, _note = @p1, _date_modify = @p2, _id_who_change = @p3, _hash = @p4, _value_string = @p5, _value_long = @p6, _value_guid = @p7, _value_bool = @p8, _value_double = @p9, _value_numeric = @p10, _value_datetime = @p11, _value_bytes = CAST(@p12 AS VARBINARY(MAX)), _key = @p13, _date_begin = @p14, _date_complete = @p15, _value_unique = @p16 WHERE _id = @p17 """; public string ObjectStorage_DeleteValuesByObjectId() => "DELETE FROM _values WHERE _id_object = @p0"; public string ObjectStorage_GetObjectJson() => "SELECT dbo.get_object_json(@p0, @p1)"; /// /// Bulk get object JSON. Uses function call directly in SELECT. /// public string ObjectStorage_GetObjectsJsonBulk() => """ SELECT dbo.get_object_json(CAST(value AS BIGINT), @p1) as JsonData FROM STRING_SPLIT(@p0, ',') """; 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, 0) as StoreNull, COALESCE(s._unique, 0) 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 = @p0 """; public string ObjectStorage_SelectTypeById() => "SELECT _id as Id, _name as Name, _db_type as DbType, _type as Type1 FROM _types WHERE _id = @p0"; public string ObjectStorage_CheckObjectExists() => "SELECT TOP 1 _id FROM _objects WHERE _id = @p0"; public string ObjectStorage_SelectSchemeById() => "SELECT _id as Id, _name as Name FROM _schemes WHERE _id = @p0"; public string ObjectStorage_SelectValuesForObjects() => """ SELECT _id as Id, _id_structure as IdStructure, _id_object as IdObject, _string as String, _long as Long, _guid as Guid, [_Double] as [Double], _datetimeoffset as DateTimeOffset, _boolean as Boolean, _bytearray as ByteArray, _numeric as Numeric, _listitem as ListItem, _object as Object, _array_parent_id as ArrayParentId, _array_index as ArrayIndex FROM _values WHERE _id_object IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ',')) """; public string ObjectStorage_SelectSchemeIdsForObjects() => "SELECT _id as ObjectId, _id_scheme as SchemeId FROM _objects WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ','))"; 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 = @p0 """; public string ObjectStorage_SelectAllTypes() => "SELECT _id as Id, _name as Name, _db_type as DbType, _type as Type1 FROM _types"; public string ObjectStorage_SelectExistingIds() => "SELECT _id as Id FROM _objects WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ','))"; public string ObjectStorage_SelectExistingCreateDates() => "SELECT o._id as Id, o._date_create as DateCreate, s._structure_hash as SchemeHash, s._id as SchemeId FROM _objects o JOIN _schemes s ON s._id = o._id_scheme WHERE o._id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ',')) " + "UNION ALL SELECT 0, NULL, s._structure_hash, s._id FROM _schemes s WHERE s._id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p1, ','))"; public string ObjectStorage_SelectIdHashPairs() => "SELECT _id as Id, _hash as Hash FROM _objects WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ','))"; public string ObjectStorage_SelectSchemesByIds() => """ SELECT _id as Id, _name as Name, _alias as Alias, _name_space as NameSpace, _structure_hash as StructureHash, _type as Type FROM _schemes WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ',')) """; // FORCESEEK: STRING_SPLIT has a fixed row estimate, and with it the optimizer could read PK__objects as a range, // taking U locks on (and waiting for) rows of concurrent writers the save never names - a deadlock between // writers of disjoint objects. A seek per id locks exactly the named rows. public string ObjectStorage_LockObjectsForUpdate() => "SELECT _id FROM _objects WITH (UPDLOCK, ROWLOCK, FORCESEEK) WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ',')) ORDER BY _id"; public string ObjectStorage_SelectSchemeIdByObjectId() => "SELECT _id_scheme FROM _objects WHERE _id = @p0"; // ============================================================ // === LIST SQL === // ============================================================ public string Lists_SelectById() => "SELECT _id, _name FROM _lists WHERE _id = @p0"; public string Lists_SelectByName() => "SELECT _id, _name FROM _lists WHERE _name = @p0"; public string Lists_SelectAll() => "SELECT _id, _name FROM _lists ORDER BY _name"; public string Lists_Insert() => "INSERT INTO _lists (_id, _name, _alias) VALUES (@p0, @p1, @p2)"; public string Lists_Update() => "UPDATE _lists SET _name = @p0, _alias = @p1 WHERE _id = @p2"; public string Lists_Delete() => "DELETE FROM _lists WHERE _id = @p0"; public string Lists_IsUsedInStructures() => "SELECT TOP 1 _id FROM _structures WHERE _id_list = @p0"; // ============================================================ // === LIST ITEMS SQL === // ============================================================ public string ListItems_SelectById() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id = @p0"; public string ListItems_SelectByIds() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p0, ','))"; public string ListItems_SelectByListId() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id_list = @p0 ORDER BY _value"; public string ListItems_SelectByListIdAndValue() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id_list = @p0 AND _value = @p1"; public string ListItems_Insert() => "INSERT INTO _list_items (_id, _id_list, _value, _alias, _id_object) VALUES (@p0, @p1, @p2, @p3, @p4)"; public string ListItems_UpdateAliasAndObject() => "UPDATE _list_items SET _alias = @p0, _id_object = @p1 WHERE _id = @p2"; public string ListItems_Update() => "UPDATE _list_items SET _value = @p0, _alias = @p1, _id_object = @p2 WHERE _id = @p3"; public string ListItems_Delete() => "DELETE FROM _list_items WHERE _id = @p0"; public string ListItems_SelectByObjectId() => "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items WHERE _id_object = @p0"; // ============================================================ // === MAINTENANCE SQL === // ============================================================ public string Maintenance_Analyze(int analysisLimit) => "EXEC sp_updatestats"; // sys.dm_db_index_usage_stats resets on server restart and holds rows only for indexes // touched since - hence the LEFT JOIN and nullable counters. Heap rows (index_id 0) are // not indexes and are excluded. public string Maintenance_SelectIndexStats() => IndexStatsSql(withUsage: true); // The DMV needs VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE on SQL Server 2022); a // database owner without it gets this form: the same indexes and sizes, usage counters null. public string Maintenance_SelectIndexStatsNoSize() => IndexStatsSql(withUsage: false); // The index check: the named indexes of the redb tables of dbo (a heap has none). Key columns by key_ordinal, the // INCLUDE list by index_column_id. SQL Server has no invalid index. public string? Schema_SelectIndexShapes() => """ SELECT i.name AS [Name], t.name AS [Table], CAST(i.is_unique AS bit) AS [IsUnique], (SELECT STRING_AGG(c.name, ',') WITHIN GROUP (ORDER BY ic.key_ordinal) FROM sys.index_columns ic JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0 AND ic.key_ordinal > 0) AS [KeyColumnsCsv], (SELECT STRING_AGG(c.name, ',') WITHIN GROUP (ORDER BY ic.index_column_id) FROM sys.index_columns ic JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 1) AS [IncludedColumnsCsv], CAST(1 AS bit) AS [IsValid] FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id WHERE SCHEMA_NAME(t.schema_id) = 'dbo' AND t.name LIKE '[_]%' AND i.type > 0 AND i.name IS NOT NULL AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 """; private static string IndexStatsSql(bool withUsage) { var usage = withUsage ? """ CAST(MAX(u.user_seeks) AS bigint) AS [Seeks], CAST(MAX(u.user_scans) + MAX(u.user_lookups) AS bigint) AS [Scans], CAST(MAX(u.user_updates) AS bigint) AS [Updates], CASE WHEN MAX(u.last_user_seek) >= ISNULL(MAX(u.last_user_scan), '19000101') THEN MAX(u.last_user_seek) ELSE MAX(u.last_user_scan) END AS [LastUsed] """ : """ CAST(NULL AS bigint) AS [Seeks], CAST(NULL AS bigint) AS [Scans], CAST(NULL AS bigint) AS [Updates], CAST(NULL AS datetime) AS [LastUsed] """; var usageJoin = withUsage ? """ LEFT JOIN sys.dm_db_index_usage_stats u ON u.object_id = i.object_id AND u.index_id = i.index_id AND u.database_id = DB_ID() """ : ""; return $$""" SELECT SCHEMA_NAME(t.schema_id) AS [Schema], t.name AS [Table], i.name AS [Name], i.is_unique AS [IsUnique], (SELECT STRING_AGG(col.name, ',') WITHIN GROUP (ORDER BY ic.key_ordinal) FROM sys.index_columns ic JOIN sys.columns col ON col.object_id = ic.object_id AND col.column_id = ic.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0) AS [ColumnsCsv], (SELECT STRING_AGG(col.name, ',') WITHIN GROUP (ORDER BY ic.index_column_id) FROM sys.index_columns ic JOIN sys.columns col ON col.object_id = ic.object_id AND col.column_id = ic.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 1) AS [IncludedColumnsCsv], i.is_primary_key AS [IsPrimaryKey], i.is_unique_constraint AS [IsUniqueConstraint], CAST(CASE WHEN i.type = 1 THEN 1 ELSE 0 END AS bit) AS [IsClustered], CAST(CASE WHEN EXISTS ( SELECT 1 FROM sys.foreign_keys fk WHERE fk.parent_object_id = i.object_id AND NOT EXISTS ( SELECT 1 FROM sys.foreign_key_columns fkc WHERE fkc.constraint_object_id = fk.object_id AND fkc.parent_column_id NOT IN ( SELECT ic.column_id FROM sys.index_columns ic WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0)) ) THEN 1 ELSE 0 END AS bit) AS [BacksForeignKey], CAST(SUM(a.used_pages) * 8 * 1024 AS bigint) AS [SizeBytes], CAST(MAX(p.rows) AS bigint) AS [EstimatedRows], {{usage}} FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id JOIN sys.partitions p ON p.object_id = i.object_id AND p.index_id = i.index_id JOIN sys.allocation_units a ON a.container_id = p.partition_id {{usageJoin}} WHERE i.index_id > 0 AND t.is_ms_shipped = 0 GROUP BY t.schema_id, t.name, i.name, i.is_unique, i.is_primary_key, i.is_unique_constraint, i.type, i.object_id, i.index_id ORDER BY t.name, i.name """; } public string Maintenance_AnalyzeTable(string? schema, string table, int analysisLimit) => $"UPDATE STATISTICS {QuoteIdentifier(schema ?? "dbo")}.{QuoteIdentifier(table)}"; public string Maintenance_SelectTableExists() => """ SELECT COUNT(*) FROM sys.tables t WHERE t.name = @p0 AND SCHEMA_NAME(t.schema_id) = ISNULL(@p1, 'dbo') AND t.is_ms_shipped = 0 """; public string Maintenance_SelectTableStats() => """ SELECT SCHEMA_NAME(t.schema_id) AS [Schema], t.name AS [Table], CAST(SUM(CASE WHEN p.index_id IN (0, 1) THEN p.row_count ELSE 0 END) AS bigint) AS [EstimatedRows], CAST(SUM(CASE WHEN p.index_id IN (0, 1) THEN p.used_page_count ELSE 0 END) * 8 * 1024 AS bigint) AS [DataSizeBytes], CAST(SUM(CASE WHEN p.index_id NOT IN (0, 1) THEN p.used_page_count ELSE 0 END) * 8 * 1024 AS bigint) AS [IndexesSizeBytes], NULL AS [DeadRows], (SELECT MAX(COALESCE(sp.last_updated, STATS_DATE(s.object_id, s.stats_id))) FROM sys.stats s OUTER APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) sp WHERE s.object_id = t.object_id) AS [LastAnalyze], NULL AS [LastAutoAnalyze], NULL AS [LastVacuum], CAST(CASE WHEN EXISTS (SELECT 1 FROM sys.stats s WHERE s.object_id = t.object_id) THEN 1 ELSE 0 END AS bit) AS [HasStatistics] FROM sys.tables t JOIN sys.dm_db_partition_stats p ON p.object_id = t.object_id WHERE t.is_ms_shipped = 0 GROUP BY t.schema_id, t.name, t.object_id ORDER BY t.name """; public System.Collections.Generic.IReadOnlyList Maintenance_SelectTableStatsForms() => new[] { Maintenance_SelectTableStats() }; public string Maintenance_SelectStatisticsWindow() => """ SELECT CAST(sqlserver_start_time AS datetimeoffset) AS [CountersSince], CAST(NULL AS bit) AS [IsReplica] FROM sys.dm_os_sys_info """; // ============================================================ // === 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 = @p0"; 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 = @p0 """; // ============================================================ // === 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 = @p0 """; public string LazyLoader_GetObjectJson() => "SELECT dbo.get_object_json(@p0, @p1)"; /// /// Batch load Props JSON for multiple objects. Uses function call directly in SELECT. /// Deep nested objects will be loaded on demand via individual get_object_json calls. /// public string LazyLoader_GetObjectJsonBatch() => """ SELECT CAST(value AS BIGINT) as Id, dbo.get_object_json(CAST(value AS BIGINT), @p1) as JsonData FROM STRING_SPLIT(@p0, ',') """; public string LazyLoader_SelectObjectHash() => "SELECT _hash FROM _objects WHERE _id = @p0"; public string Transaction_SavepointBegin() => "SAVE TRANSACTION redb_batch_save"; public string? Transaction_SavepointRelease() => null; // MSSQL savepoints dissolve on their own public string Transaction_SavepointRollback() => "ROLLBACK TRANSACTION redb_batch_save"; // ============================================================ // === QUERY PROVIDER SQL === // ============================================================ public string Query_CheckPermissionSql() => "SELECT CASE WHEN EXISTS(SELECT 1 FROM dbo.get_user_permissions_for_object(@p0, @p1) WHERE can_select = 1) THEN 1 ELSE 0 END as has_permission"; public string Query_SqlPreviewTemplate() => "EXEC {0} @p0, @p1, @p2, @p3, @p4, @p5, @p6"; /// /// MSSQL: the descendants of the given objects down to depthLimit levels below them (WITH, without RECURSIVE). /// public string Query_GetDescendantIdsFromAncestorsSql(string idsString, int depthLimit) => $@"WITH 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"; /// /// MSSQL: WITH (without RECURSIVE) for traversing ancestors. /// public string Query_GetParentIdsFromDescendantsSql(string idsString, int depthLimit) => $@"WITH ancestors AS ( SELECT _id, _id_parent, 0 as level FROM _objects WHERE _id IN ({idsString}) UNION ALL SELECT o._id, o._id_parent, a.level + 1 FROM _objects o INNER JOIN ancestors a ON a._id_parent = o._id WHERE a.level < {depthLimit} ) SELECT DISTINCT _id FROM ancestors WHERE _id_parent IS NULL OR level > 0"; /// /// MSSQL: Load objects by IDs as JSON using get_object_json function. /// public string Query_LoadObjectsByIdsSql(string idsString, int maxDepth) => $@"SELECT dbo.get_object_json(_id, {maxDepth}) AS [Value] FROM _objects WHERE _id IN ({idsString}) ORDER BY _id"; public string Query_TreeSqlPreviewTemplate(string functionName) => $"EXEC {functionName} @p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7"; // ============================================================ // === SQL PREVIEW FUNCTION NAMES === // ============================================================ // MSSQL: Eager loading not implemented, always use _base (lazy) versions public string Query_SqlPreviewFunction() => "dbo.get_search_sql_preview_base"; public string Query_TreeSqlPreviewBaseFunction() => "dbo.get_search_tree_sql_preview_base"; // ============================================================ // === v2-pvt MODULE ENTRY-POINTS (NOT SUPPORTED, phase 1) === // MSSql free still runs the legacy search SQL functions. When the // v2-pvt SQL module gets a T-SQL port these methods will start // returning real SQL; until then they return null so the dispatcher // in QueryProviderBase routes to the legacy search path. // ============================================================ public string? Query_BuildPvtSqlFunction() => "dbo.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 inv = System.Globalization.CultureInfo.InvariantCulture; var limitArg = limit.HasValue ? limit.Value.ToString(inv) : "NULL"; var offsetArg = offset.ToString(inv); var maxDepthArg = maxDepth.ToString(inv); var distinctArg = distinct ? "1" : "0"; var modeArg = sourceMode == "tree" ? "N'tree'" : "N'flat'"; // Slice does not support tree mode; treeIds always NULL. const string treeArg = "NULL"; var distinctOnArg = hasDistinctOn ? "$3" : "NULL"; // pvt_build_query_sql(scheme_id, filter, limit, offset, order, max_depth, // distinct, source_mode, tree_ids, include_seed, polymorphic, distinct_on) return "SELECT dbo.pvt_build_query_sql(" + schemeId.ToString(inv) + ", $1, " + limitArg + ", " + offsetArg + ", $2, " + maxDepthArg + ", " + distinctArg + ", " + modeArg + ", " + treeArg + ", 0" // include_seed + ", 1" // polymorphic + ", " + distinctOnArg + ") AS [Value]"; } // The inner query numbers its rows in its own order ([_ord], module 0.2.45), restored after the join: a hash or merge // join keeps no order, and a number given outside, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), may run before the sort. 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 dbo._objects o ON o._id = sub._id ORDER BY sub._ord """; public string? Query_WrapPvtWithCount(string innerSql) => $"SELECT CAST(COUNT(*) AS BIGINT) AS [Value] FROM ({innerSql}) t"; public string? Query_WrapPvtWithExists(string innerSql) => $"SELECT CASE WHEN EXISTS ({innerSql}) THEN 1 ELSE 0 END AS [Value]"; public string? Query_WrapPvtWithIds(string innerSql) => $"SELECT t.[_id] FROM (\n{innerSql}\n) t"; public string? Query_PvtModuleVersionFunction() => "dbo.pvt_module_version"; // Bump together with the literal RETURNed by dbo.pvt_module_version() in redb.MSSql/sql/v2-pvt/99_module_version.sql. public string? Query_PvtRequiredVersion() => "0.2.50"; // Created next to dbo.pvt_module_version() in 99_module_version.sql. public string? Query_PvtModuleCompatFunction() => "dbo.pvt_module_compat"; // Native PVT projection orchestrator — not supported on MSSql (yet). // Callers gate on Query_BuildPvtProjectionSqlFunction()==null, so these // throws should never fire in practice; they exist to surface a // misconfigured caller path immediately. public string? Query_BuildPvtProjectionSqlFunction() => null; public string? Query_BuildPvtProjectionSqlInvocation( long schemeId, int? limit, int offset, int maxDepth, bool distinct, string sourceMode, long[]? treeIds, bool hasDistinctOn = false) => throw new NotSupportedException("Native PVT projection (pvt_build_projection_sql) is not supported on MSSql yet."); public string? Query_WrapPvtProjectionRowsAsJson(string innerSql, bool includeId) => throw new NotSupportedException("Native PVT projection (pvt_build_projection_sql) is not supported on MSSql yet."); // ============================================================ // === SOFT DELETE === // ============================================================ /// /// Calls sp_mark_for_deletion procedure to soft-delete objects. /// Params: @p0=objectIds (comma-separated string), @p1=userId, @p2=trashParentId (nullable) /// Returns via OUTPUT params: @trash_id, @marked_count /// public string SoftDelete_MarkForDeletion() => "DECLARE @trash_id BIGINT, @marked_count BIGINT; EXEC sp_mark_for_deletion @p0, @p1, @p2, @trash_id OUTPUT, @marked_count OUTPUT; SELECT @trash_id AS trash_id, @marked_count AS marked_count;"; /// /// Calls sp_purge_trash procedure to physically delete objects from trash. /// Params: @p0=trashId, @p1=batchSize /// Returns via OUTPUT params: @deleted_count, @remaining_count /// public string SoftDelete_PurgeTrash() => "DECLARE @deleted_count BIGINT, @remaining_count BIGINT; EXEC sp_purge_trash @p0, @p1, @deleted_count OUTPUT, @remaining_count OUTPUT; SELECT @deleted_count AS deleted_count, @remaining_count AS remaining_count;"; /// /// Objects of a trash container referenced by live objects, with the referencing objects. /// Params: @p0=trashId. Returns: referenced_id, referencing_id (at most 100 pairs). /// public string SoftDelete_SelectLiveReferrersOfTrash() => """ SELECT DISTINCT TOP (100) o.[_id] AS referenced_id, r.[_id] AS referencing_id FROM [dbo].[_objects] o INNER JOIN [dbo].[_values] v ON v.[_Object] = o.[_id] INNER JOIN [dbo].[_objects] r ON r.[_id] = v.[_id_object] WHERE o.[_id_parent] = @p0 AND r.[_id_scheme] <> -10 ORDER BY referenced_id, referencing_id """; /// /// Gets deletion progress for a specific trash container. /// Params: @p0=trashId /// 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 [dbo].[_objects] WHERE [_id] = @p0 AND [_id_scheme] = -10 """; /// /// Gets all active deletions for a user. /// Params: @p0=userId /// 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 [dbo].[_objects] WHERE [_id_owner] = @p0 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: @p0=timeoutMinutes /// 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 [dbo].[_objects] WHERE [_id_scheme] = -10 AND [_id_parent] IS NULL AND ( [_value_string] = 'pending' OR ( [_value_string] = 'running' AND [_date_modify] < DATEADD(MINUTE, -@p0, SYSDATETIMEOFFSET()) ) ) ORDER BY [_date_create] """; /// /// Atomically claim an orphaned task for processing. /// CLUSTER-SAFE: UPDATE with condition prevents race. /// Params: @p0=trashId, @p1=timeoutMinutes /// Returns: affected rows (1=success, 0=already taken) /// public string SoftDelete_ClaimOrphanedTask() => """ UPDATE [dbo].[_objects] WITH (ROWLOCK) SET [_value_string] = 'running', [_date_modify] = SYSDATETIMEOFFSET() WHERE [_id] = @p0 AND [_id_scheme] = -10 AND ( [_value_string] = 'pending' OR ( [_value_string] = 'running' AND [_date_modify] < DATEADD(MINUTE, -@p1, SYSDATETIMEOFFSET()) ) ) """; // ============================================================ // === METADATA CACHE WARMUP === // ============================================================ /// /// MSSQL uses stored procedure, returns same columns as PostgreSQL function. /// public string Warmup_AllMetadataCaches() => "EXEC warmup_all_metadata_caches"; } Path: redb/redb.MSSql/sql/deprecated/redb_aggregation.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.MSSql/sql/deprecated/redb_aggregation.sql ---- -- ===================================================== -- REDB EAV AGGREGATION FUNCTIONS (MSSQL) -- Aggregations for EAV fields (_values) -- Supports: simple fields, nested Class, arrays, dictionaries -- Ported from PostgreSQL version -- ===================================================== SET NOCOUNT ON; GO -- ===== DROP EXISTING OBJECTS ===== IF OBJECT_ID('dbo.aggregate_field', 'P') IS NOT NULL DROP PROCEDURE dbo.aggregate_field; GO IF OBJECT_ID('dbo.aggregate_batch', 'P') IS NOT NULL DROP PROCEDURE dbo.aggregate_batch; GO IF OBJECT_ID('dbo.aggregate_batch_preview', 'P') IS NOT NULL DROP PROCEDURE dbo.aggregate_batch_preview; GO -- ===================================================== -- aggregate_field: Single field aggregation -- ===================================================== -- Parameters: -- @scheme_id - Scheme ID -- @field_path - Path to field: -- "Price" - simple field -- "Customer.Name" - nested Class -- "Items[].Price" - array (ALL elements) -- "Items[2].Price" - array (SPECIFIC element) -- "PhoneBook[home]" - Dictionary (SPECIFIC key) -- @function - SUM, AVG, MIN, MAX, COUNT -- @filter_json - JSON filter or NULL -- -- Returns: numeric result -- ===================================================== CREATE PROCEDURE dbo.aggregate_field @scheme_id BIGINT, @field_path NVARCHAR(255), @function NVARCHAR(20), @filter_json NVARCHAR(MAX) = NULL AS BEGIN SET NOCOUNT ON; DECLARE @structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @dict_key NVARCHAR(255); DECLARE @array_index NVARCHAR(50); DECLARE @column_name NVARCHAR(50); DECLARE @array_condition NVARCHAR(500) = N''; DECLARE @sql NVARCHAR(MAX); DECLARE @result DECIMAL(38, 10); -- 1. Resolve field path EXEC resolve_field_path @scheme_id, @field_path, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NULL BEGIN RAISERROR('Field "%s" not found in scheme %d', 16, 1, @field_path, @scheme_id); RETURN; END -- 2. Determine column by data type SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'Int' THEN N'_Long' WHEN N'Decimal' THEN N'_Numeric' WHEN N'Money' THEN N'_Numeric' ELSE N'_Long' END; -- 3. Build array/dict condition (with SQL injection protection) IF @dict_key IS NOT NULL SET @array_condition = N' AND v._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''''; ELSE IF @array_index IS NOT NULL SET @array_condition = N' AND v._array_index = N''' + REPLACE(@array_index, '''', '''''') + N''''; ELSE IF @dict_key IS NULL AND @array_index IS NULL AND @field_path NOT LIKE N'%[]%' SET @array_condition = N' AND v._array_index IS NULL'; -- 4. Build and execute SQL IF @filter_json IS NOT NULL AND @filter_json <> N'' AND @filter_json <> N'null' BEGIN -- With filter - use temp table for object IDs CREATE TABLE #filtered_ids (_id BIGINT PRIMARY KEY); INSERT INTO #filtered_ids EXEC get_filtered_object_ids @scheme_id, @filter_json, 10; IF NOT EXISTS (SELECT 1 FROM #filtered_ids) BEGIN IF @function = N'COUNT' SELECT 0 AS result; ELSE SELECT NULL AS result; DROP TABLE #filtered_ids; RETURN; END SET @sql = N' SELECT @res = ' + UPPER(@function) + N'(CAST(v.' + @column_name + N' AS DECIMAL(38,10))) FROM _values v WHERE v._id_structure = @struct_id AND v._id_object IN (SELECT _id FROM #filtered_ids)' + @array_condition; EXEC sp_executesql @sql, N'@struct_id BIGINT, @res DECIMAL(38,10) OUTPUT', @struct_id = @structure_id, @res = @result OUTPUT; DROP TABLE #filtered_ids; END ELSE BEGIN -- Without filter - all objects in scheme SET @sql = N' SELECT @res = ' + UPPER(@function) + N'(CAST(v.' + @column_name + N' AS DECIMAL(38,10))) FROM _values v JOIN _objects o ON o._id = v._id_object WHERE v._id_structure = @struct_id AND o._id_scheme = @scheme' + @array_condition; EXEC sp_executesql @sql, N'@struct_id BIGINT, @scheme BIGINT, @res DECIMAL(38,10) OUTPUT', @struct_id = @structure_id, @scheme = @scheme_id, @res = @result OUTPUT; END SELECT @result AS result; END; GO -- ===================================================== -- aggregate_batch: Multiple aggregations in ONE query -- ===================================================== CREATE PROCEDURE dbo.aggregate_batch @scheme_id BIGINT, @aggregations NVARCHAR(MAX), @filter_json NVARCHAR(MAX) = NULL AS BEGIN SET NOCOUNT ON; DECLARE @select_parts NVARCHAR(MAX) = N''; DECLARE @has_eav_fields BIT = 0; DECLARE @sql NVARCHAR(MAX); DECLARE @field NVARCHAR(255); DECLARE @func NVARCHAR(20); DECLARE @alias NVARCHAR(255); DECLARE @structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @dict_key NVARCHAR(255); DECLARE @array_index NVARCHAR(50); DECLARE @column_name NVARCHAR(50); DECLARE @array_condition NVARCHAR(500); -- Parse aggregations JSON DECLARE @agg_cursor CURSOR; SET @agg_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field, UPPER(JSON_VALUE(value, '$.func')) AS func, JSON_VALUE(value, '$.alias') AS alias FROM OPENJSON(@aggregations); OPEN @agg_cursor; FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; WHILE @@FETCH_STATUS = 0 BEGIN -- COUNT(*) special case IF @func = N'COUNT' AND (@field IS NULL OR @field = N'*' OR @field = N'') BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + N'COUNT(DISTINCT v._id_object) AS [' + REPLACE(@alias, '''', '''''') + N']'; SET @has_eav_fields = 1; FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; CONTINUE; END -- Base field with 0$: prefix IF @field LIKE N'0$:%' BEGIN DECLARE @raw_field NVARCHAR(100) = SUBSTRING(@field, 4, 100); DECLARE @sql_column NVARCHAR(100) = dbo.normalize_base_field_name(@raw_field); IF @sql_column IS NOT NULL BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; IF @func IN (N'SUM', N'AVG') SET @select_parts = @select_parts + @func + N'(CAST(o.' + @sql_column + N' AS DECIMAL(38,10))) AS [' + REPLACE(@alias, '''', '''''') + N']'; ELSE SET @select_parts = @select_parts + @func + N'(o.' + @sql_column + N') AS [' + REPLACE(@alias, '''', '''''') + N']'; END END ELSE BEGIN -- EAV field EXEC resolve_field_path @scheme_id, @field, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @has_eav_fields = 1; SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'Int' THEN N'_Long' WHEN N'Decimal' THEN N'_Numeric' WHEN N'Money' THEN N'_Numeric' ELSE N'_Long' END; -- Build array condition (with SQL injection protection) IF @dict_key IS NOT NULL SET @array_condition = N' AND v._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''''; ELSE IF @array_index IS NOT NULL SET @array_condition = N' AND v._array_index = N''' + REPLACE(@array_index, '''', '''''') + N''''; ELSE IF @field NOT LIKE N'%[]%' SET @array_condition = N' AND v._array_index IS NULL'; ELSE SET @array_condition = N''; IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @func + N'(CASE WHEN v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + @array_condition + N' THEN CAST(v.' + @column_name + N' AS DECIMAL(38,10)) END) AS [' + REPLACE(@alias, '''', '''''') + N']'; END END FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; END CLOSE @agg_cursor; DEALLOCATE @agg_cursor; IF @select_parts = N'' BEGIN SELECT N'{}' AS result; RETURN; END -- Execute with or without filter IF @filter_json IS NOT NULL AND @filter_json <> N'' AND @filter_json <> N'null' BEGIN -- With filter CREATE TABLE #filtered_ids (_id BIGINT PRIMARY KEY); INSERT INTO #filtered_ids EXEC get_filtered_object_ids @scheme_id, @filter_json, 10; IF NOT EXISTS (SELECT 1 FROM #filtered_ids) BEGIN SELECT N'{}' AS result; DROP TABLE #filtered_ids; RETURN; END IF @has_eav_fields = 1 BEGIN SET @sql = N' SELECT ' + @select_parts + N' FROM _values v JOIN _objects o ON o._id = v._id_object WHERE v._id_object IN (SELECT _id FROM #filtered_ids) FOR JSON PATH, WITHOUT_ARRAY_WRAPPER'; END ELSE BEGIN SET @sql = N' SELECT ' + @select_parts + N' FROM _objects o WHERE o._id IN (SELECT _id FROM #filtered_ids) FOR JSON PATH, WITHOUT_ARRAY_WRAPPER'; END EXEC sp_executesql @sql; DROP TABLE #filtered_ids; END ELSE BEGIN -- Without filter IF @has_eav_fields = 1 BEGIN SET @sql = N' SELECT ' + @select_parts + N' FROM _values v JOIN _objects o ON o._id = v._id_object WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER'; END ELSE BEGIN SET @sql = N' SELECT ' + @select_parts + N' FROM _objects o WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER'; END EXEC sp_executesql @sql; END END; GO -- ===================================================== -- aggregate_batch_preview: SQL Preview for debugging -- ===================================================== CREATE PROCEDURE dbo.aggregate_batch_preview @scheme_id BIGINT, @aggregations NVARCHAR(MAX), @filter_json NVARCHAR(MAX) = NULL AS BEGIN SET NOCOUNT ON; DECLARE @select_parts NVARCHAR(MAX) = N''; DECLARE @structure_ids NVARCHAR(MAX) = N''; DECLARE @field NVARCHAR(255); DECLARE @func NVARCHAR(20); DECLARE @alias NVARCHAR(255); DECLARE @structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @dict_key NVARCHAR(255); DECLARE @array_index NVARCHAR(50); DECLARE @column_name NVARCHAR(50); DECLARE @array_condition NVARCHAR(500); DECLARE @sql NVARCHAR(MAX); -- Parse aggregations DECLARE @agg_cursor CURSOR; SET @agg_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field, UPPER(JSON_VALUE(value, '$.func')) AS func, JSON_VALUE(value, '$.alias') AS alias FROM OPENJSON(@aggregations); OPEN @agg_cursor; FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; WHILE @@FETCH_STATUS = 0 BEGIN IF @func = N'COUNT' AND (@field IS NULL OR @field = N'*' OR @field = N'') BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + N'COUNT(DISTINCT v._id_object) AS [' + REPLACE(@alias, '''', '''''') + N']'; FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; CONTINUE; END EXEC resolve_field_path @scheme_id, @field, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN IF @structure_ids <> N'' SET @structure_ids = @structure_ids + N', '; SET @structure_ids = @structure_ids + CAST(@structure_id AS NVARCHAR(20)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' ELSE N'_Long' END; IF @dict_key IS NOT NULL SET @array_condition = N' AND v._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''''; ELSE IF @array_index IS NOT NULL SET @array_condition = N' AND v._array_index = N''' + REPLACE(@array_index, '''', '''''') + N''''; ELSE IF @field NOT LIKE N'%[]%' SET @array_condition = N' AND v._array_index IS NULL'; ELSE SET @array_condition = N''; IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @func + N'(CASE WHEN v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + @array_condition + N' THEN CAST(v.' + @column_name + N' AS DECIMAL(38,10)) END) AS [' + REPLACE(@alias, '''', '''''') + N'] /* ' + REPLACE(@field, '''', '''''') + N' */'; END FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; END CLOSE @agg_cursor; DEALLOCATE @agg_cursor; IF @select_parts = N'' BEGIN SELECT N'-- No aggregations to execute' AS sql_preview; RETURN; END -- Build preview SQL IF @filter_json IS NOT NULL BEGIN SET @sql = N'-- AGGREGATE BATCH SQL PREVIEW -- Scheme: ' + CAST(@scheme_id AS NVARCHAR(20)) + N' -- Filter: ' + @filter_json + N' -- Step 1: Get object_ids via get_filtered_object_ids -- Step 2: Aggregation by object_ids SELECT ' + @select_parts + N' FROM _values v WHERE v._id_structure IN (' + @structure_ids + N') AND v._id_object IN (SELECT _id FROM #filtered_ids);'; END ELSE BEGIN SET @sql = N'-- AGGREGATE BATCH SQL PREVIEW -- Scheme: ' + CAST(@scheme_id AS NVARCHAR(20)) + N' -- Filter: NULL SELECT ' + @select_parts + N' FROM _values v JOIN _objects o ON o._id = v._id_object WHERE v._id_structure IN (' + @structure_ids + N') AND o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N';'; END SELECT @sql AS sql_preview; END; GO PRINT N'========================================='; PRINT N'Aggregation procedures created!'; PRINT N''; PRINT N'PROCEDURES:'; PRINT N' aggregate_field - Single field aggregation'; PRINT N' aggregate_batch - Multiple aggregations in one call'; PRINT N' aggregate_batch_preview - SQL preview for debugging'; PRINT N''; PRINT N'SUPPORTED FUNCTIONS:'; PRINT N' SUM, AVG, MIN, MAX, COUNT'; PRINT N''; PRINT N'FEATURES:'; PRINT N' - Base fields with 0$: prefix'; PRINT N' - EAV fields from _values'; PRINT N' - Array support: Items[].Price (all), Items[2].Price (specific)'; PRINT N' - Dictionary support: PhoneBook[home]'; PRINT N' - Filters via get_filtered_object_ids'; PRINT N'========================================='; GO Path: redb/redb.MSSql/sql/deprecated/redb_facets_search.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.MSSql/sql/deprecated/redb_facets_search.sql ---- -- ===== REDB FACETS & SEARCH MODULE FOR MSSQL ===== -- Full featured faceted search and object filtering module -- Architecture: Stored procedures with dynamic SQL (SQL injection safe) -- Supports: LINQ operators, logical operators, Class fields, Arrays, Dictionary, hierarchical search -- -- DEPENDENCIES: -- 1. redbMSSQL.sql (core tables) -- 2. redb_metadata_cache.sql (metadata cache) -- Run those scripts BEFORE this one! -- ===================================================== -- CHECK DEPENDENCIES -- ===================================================== IF OBJECT_ID('dbo._scheme_metadata_cache', 'U') IS NULL BEGIN RAISERROR('ERROR: Table _scheme_metadata_cache not found! Run redb_metadata_cache.sql first.', 16, 1); RETURN; END; IF OBJECT_ID('dbo.sync_metadata_cache_for_scheme', 'P') IS NULL BEGIN RAISERROR('ERROR: Procedure sync_metadata_cache_for_scheme not found! Run redb_metadata_cache.sql first.', 16, 1); RETURN; END; GO PRINT 'Dependencies OK. Creating facets search module...' GO -- ===================================================== -- DROP EXISTING OBJECTS -- ===================================================== IF OBJECT_ID('dbo.preview_facet_query', 'P') IS NOT NULL DROP PROCEDURE dbo.preview_facet_query; IF OBJECT_ID('dbo.search_objects_with_facets', 'P') IS NOT NULL DROP PROCEDURE dbo.search_objects_with_facets; IF OBJECT_ID('dbo.search_tree_objects_with_facets', 'P') IS NOT NULL DROP PROCEDURE dbo.search_tree_objects_with_facets; IF OBJECT_ID('dbo.get_facets', 'P') IS NOT NULL DROP PROCEDURE dbo.get_facets; IF OBJECT_ID('dbo.internal_parse_filters', 'P') IS NOT NULL DROP PROCEDURE dbo.internal_parse_filters; IF OBJECT_ID('dbo.internal_build_exists', 'P') IS NOT NULL DROP PROCEDURE dbo.internal_build_exists; IF OBJECT_ID('dbo.normalize_base_field_name', 'FN') IS NOT NULL DROP FUNCTION dbo.normalize_base_field_name; IF OBJECT_ID('dbo.get_value_column_by_type', 'FN') IS NOT NULL DROP FUNCTION dbo.get_value_column_by_type; IF OBJECT_ID('dbo.get_object_level', 'FN') IS NOT NULL DROP FUNCTION dbo.get_object_level; IF OBJECT_ID('dbo.is_ancestor_of', 'FN') IS NOT NULL DROP FUNCTION dbo.is_ancestor_of; IF OBJECT_ID('dbo.is_descendant_of', 'FN') IS NOT NULL DROP FUNCTION dbo.is_descendant_of; IF OBJECT_ID('dbo.build_facet_field_path', 'FN') IS NOT NULL DROP FUNCTION dbo.build_facet_field_path; IF OBJECT_ID('dbo.get_facets_extended', 'P') IS NOT NULL DROP PROCEDURE dbo.get_facets_extended; IF OBJECT_ID('dbo.preview_tree_facet_query', 'P') IS NOT NULL DROP PROCEDURE dbo.preview_tree_facet_query; GO -- ===================================================== -- HELPER FUNCTION: normalize_base_field_name -- Maps C# names to SQL column names on _objects table -- ===================================================== CREATE FUNCTION dbo.normalize_base_field_name(@field_name NVARCHAR(100)) RETURNS NVARCHAR(100) WITH SCHEMABINDING AS BEGIN RETURN CASE @field_name 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 'scheme_id' THEN '_id_scheme' WHEN 'SchemeId' 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' WHEN 'value_long' THEN '_value_long' WHEN 'ValueLong' THEN '_value_long' WHEN '_value_long' THEN '_value_long' WHEN 'value_string' THEN '_value_string' WHEN 'ValueString' THEN '_value_string' WHEN '_value_string' THEN '_value_string' WHEN 'value_guid' THEN '_value_guid' WHEN 'ValueGuid' THEN '_value_guid' WHEN '_value_guid' THEN '_value_guid' 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' 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' 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' ELSE NULL END; END; GO -- ===================================================== -- HELPER FUNCTION: get_value_column_by_type -- Returns _values column name based on db_type -- ===================================================== CREATE FUNCTION dbo.get_value_column_by_type(@db_type NVARCHAR(50), @type_semantic NVARCHAR(100)) RETURNS NVARCHAR(50) WITH SCHEMABINDING AS BEGIN RETURN CASE WHEN @db_type = 'String' THEN '_String' WHEN @db_type = 'Long' AND @type_semantic = '_RObject' THEN '_Long' WHEN @db_type = 'Long' THEN '_Long' WHEN @db_type = 'Double' THEN '_Double' WHEN @db_type = 'Numeric' THEN '_Numeric' WHEN @db_type = 'Boolean' THEN '_Boolean' WHEN @db_type = 'DateTimeOffset' THEN '_DateTimeOffset' WHEN @db_type = 'Guid' THEN '_Guid' WHEN @db_type = 'ListItem' THEN '_listitem' WHEN @db_type = 'ByteArray' THEN '_ByteArray' ELSE '_String' END; END; GO -- ===================================================== -- HELPER FUNCTION: get_object_level -- Returns the hierarchical level of an object (0 = root) -- ===================================================== CREATE FUNCTION dbo.get_object_level(@object_id BIGINT) RETURNS INT AS BEGIN DECLARE @level INT = 0; DECLARE @current_parent BIGINT; SELECT @current_parent = _id_parent FROM _objects WHERE _id = @object_id; WHILE @current_parent IS NOT NULL AND @level < 100 BEGIN SET @level = @level + 1; SELECT @current_parent = _id_parent FROM _objects WHERE _id = @current_parent; END; RETURN @level; END; GO -- ===================================================== -- HELPER FUNCTION: is_ancestor_of -- Returns 1 if @ancestor_id is an ancestor of @object_id -- ===================================================== CREATE FUNCTION dbo.is_ancestor_of(@object_id BIGINT, @ancestor_id BIGINT) RETURNS BIT AS BEGIN IF @object_id IS NULL OR @ancestor_id IS NULL RETURN 0; IF @object_id = @ancestor_id RETURN 0; -- not ancestor of itself DECLARE @current_parent BIGINT; DECLARE @depth INT = 0; SELECT @current_parent = _id_parent FROM _objects WHERE _id = @object_id; WHILE @current_parent IS NOT NULL AND @depth < 100 BEGIN IF @current_parent = @ancestor_id RETURN 1; SELECT @current_parent = _id_parent FROM _objects WHERE _id = @current_parent; SET @depth = @depth + 1; END; RETURN 0; END; GO -- ===================================================== -- HELPER FUNCTION: is_descendant_of -- Returns 1 if @descendant_id is a descendant of @object_id -- ===================================================== CREATE FUNCTION dbo.is_descendant_of(@object_id BIGINT, @descendant_id BIGINT) RETURNS BIT AS BEGIN -- descendant_id is descendant of object_id means object_id is ancestor of descendant_id RETURN dbo.is_ancestor_of(@descendant_id, @object_id); END; GO -- ===================================================== -- HELPER FUNCTION: build_order_by_clause -- Creates ORDER BY clause from JSON specification -- Format: [{"field": "Name", "direction": "ASC"}] -- ===================================================== IF OBJECT_ID('dbo.build_order_by_clause', 'FN') IS NOT NULL DROP FUNCTION dbo.build_order_by_clause; GO CREATE FUNCTION dbo.build_order_by_clause( @order_by NVARCHAR(MAX), @table_alias NVARCHAR(10) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @result NVARCHAR(MAX) = N''; -- If no order specified, return empty IF @order_by IS NULL OR @order_by = N'' OR @order_by = N'[]' OR @order_by = N'null' RETURN @result; -- Parse JSON array: [{"field": "Name", "direction": "ASC"}] SELECT @result = STRING_AGG(order_item, N', ') FROM ( SELECT CASE -- Base field with 0$: prefix WHEN JSON_VALUE(arr.value, '$.field') LIKE N'0$:%' THEN @table_alias + N'.' + dbo.normalize_base_field_name( SUBSTRING(JSON_VALUE(arr.value, '$.field'), 4, 100) ) + N' ' + UPPER(ISNULL(JSON_VALUE(arr.value, '$.direction'), N'ASC')) -- Regular Props field - sort via subquery to _values -- Use zero-padding for numeric types to preserve correct sort order ELSE N'(SELECT TOP 1 CASE WHEN v._String IS NOT NULL THEN v._String WHEN v._Long IS NOT NULL THEN RIGHT(''00000000000000000000'' + CAST(v._Long AS NVARCHAR(20)), 20) WHEN v.[_Double] IS NOT NULL THEN RIGHT(''0000000000000000000000000'' + REPLACE(CAST(v.[_Double] AS NVARCHAR(50)), ''.'', ''~''), 25) WHEN v._Numeric IS NOT NULL THEN RIGHT(''000000000000000000000000000000'' + REPLACE(CAST(v._Numeric AS NVARCHAR(50)), ''.'', ''~''), 30) WHEN v._DateTimeOffset IS NOT NULL THEN CONVERT(NVARCHAR(50), v._DateTimeOffset, 127) WHEN v._Boolean IS NOT NULL THEN CAST(CAST(v._Boolean AS INT) AS NVARCHAR(1)) ELSE NULL END FROM _values v JOIN _scheme_metadata_cache c ON c._structure_id = v._id_structure WHERE v._id_object = ' + @table_alias + N'._id AND c._name = N''' + JSON_VALUE(arr.value, '$.field') + N''' AND v._array_index IS NULL) ' + UPPER(ISNULL(JSON_VALUE(arr.value, '$.direction'), N'ASC')) END AS order_item FROM OPENJSON(@order_by) arr WHERE JSON_VALUE(arr.value, '$.field') IS NOT NULL ) items; IF @result IS NOT NULL AND @result <> N'' SET @result = N'ORDER BY ' + @result; RETURN @result; END; GO -- ===================================================== -- INTERNAL: Build single EXISTS condition -- Called by internal_parse_filters for each field -- ===================================================== CREATE PROCEDURE dbo.internal_build_exists @scheme_id BIGINT, @field_path NVARCHAR(500), @operator NVARCHAR(50), @value NVARCHAR(MAX), @value_type NVARCHAR(20), @table_alias NVARCHAR(10), @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; DECLARE @structure_id BIGINT; DECLARE @parent_structure_id BIGINT; DECLARE @nested_structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @type_semantic NVARCHAR(100); DECLARE @collection_type BIGINT; DECLARE @value_column NVARCHAR(50); DECLARE @root_field NVARCHAR(450); DECLARE @nested_field NVARCHAR(450); DECLARE @is_array BIT = 0; DECLARE @is_nested BIT = 0; DECLARE @dict_key NVARCHAR(500) = NULL; DECLARE @safe_value NVARCHAR(MAX); SET @safe_value = REPLACE(@value, N'''', N''''''); -- Property function: $length, $count DECLARE @property_function NVARCHAR(20) = NULL; -- Check for property function suffix: Name.$length, Tags[].$count IF @field_path LIKE '%.$length' BEGIN SET @property_function = '$length'; SET @field_path = LEFT(@field_path, LEN(@field_path) - 8); -- Remove '.$length' END ELSE IF @field_path LIKE '%.$count' BEGIN SET @property_function = '$count'; SET @field_path = LEFT(@field_path, LEN(@field_path) - 7); -- Remove '.$count' END; -- Parse field path -- Check for Dictionary: Field[key] IF @field_path LIKE '%[[]%]%' AND @field_path NOT LIKE '%[[]]%' BEGIN SET @root_field = LEFT(@field_path, CHARINDEX('[', @field_path) - 1); SET @dict_key = SUBSTRING(@field_path, CHARINDEX('[', @field_path) + 1, CHARINDEX(']', @field_path) - CHARINDEX('[', @field_path) - 1); -- Check for nested after dictionary: Field[key].Prop IF CHARINDEX('].', @field_path) > 0 BEGIN SET @nested_field = SUBSTRING(@field_path, CHARINDEX('].', @field_path) + 2, LEN(@field_path)); SET @is_nested = 1; END; END -- Check for Array: Field[] ELSE IF @field_path LIKE '%[[]]%' BEGIN SET @is_array = 1; IF CHARINDEX('.', REPLACE(@field_path, '[]', '')) > 0 BEGIN SET @root_field = LEFT(REPLACE(@field_path, '[]', ''), CHARINDEX('.', REPLACE(@field_path, '[]', '')) - 1); SET @nested_field = SUBSTRING(REPLACE(@field_path, '[]', ''), CHARINDEX('.', REPLACE(@field_path, '[]', '')) + 1, LEN(@field_path)); SET @is_nested = 1; END ELSE BEGIN SET @root_field = REPLACE(@field_path, '[]', ''); END; END -- Check for nested: Field.Prop ELSE IF CHARINDEX('.', @field_path) > 0 BEGIN SET @root_field = LEFT(@field_path, CHARINDEX('.', @field_path) - 1); SET @nested_field = SUBSTRING(@field_path, CHARINDEX('.', @field_path) + 1, LEN(@field_path)); SET @is_nested = 1; END ELSE BEGIN SET @root_field = @field_path; END; -- Find root structure SELECT @structure_id = c._structure_id, @db_type = c.db_type, @type_semantic = c.type_semantic, @collection_type = c._collection_type FROM _scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @root_field AND c._parent_structure_id IS NULL; IF @structure_id IS NULL BEGIN -- Debug: Field not found in metadata cache -- Check if cache is empty or field doesn't exist DECLARE @total_cache INT; SELECT @total_cache = COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id; IF @total_cache = 0 BEGIN -- Cache is empty - likely not synced PRINT 'WARNING: Metadata cache is EMPTY for scheme ' + CAST(@scheme_id AS NVARCHAR(20)) + '. Run sync_metadata_cache_for_scheme first!'; END ELSE BEGIN PRINT 'WARNING: Field "' + @root_field + '" not found in scheme ' + CAST(@scheme_id AS NVARCHAR(20)) + ' (cache has ' + CAST(@total_cache AS NVARCHAR(10)) + ' entries)'; END; SET @result = N'1=1'; -- Field not found, skip RETURN; END; -- Find nested structure if needed IF @is_nested = 1 AND @nested_field IS NOT NULL BEGIN -- Special handling for ListItem: Value, Alias, Id, IdList are NOT structures in cache -- They are columns in _list_items table (like PostgreSQL _get_listitem_field_type_info) IF @type_semantic = '_RListItem' AND @nested_field IN ('Value', 'Alias', 'Id', 'IdList') BEGIN -- Keep @type_semantic = '_RListItem', don't search for nested structure SET @nested_structure_id = NULL; -- Set correct db_type for ListItem field so @condition is built correctly SET @db_type = CASE @nested_field WHEN 'Value' THEN 'String' WHEN 'Alias' THEN 'String' WHEN 'Id' THEN 'Long' WHEN 'IdList' THEN 'Long' END; END ELSE BEGIN SELECT @nested_structure_id = c._structure_id, @db_type = c.db_type, @type_semantic = c.type_semantic FROM _scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @nested_field AND c._parent_structure_id = @structure_id; END; END; SET @value_column = dbo.get_value_column_by_type(@db_type, @type_semantic); -- Build EXISTS based on field type and operator DECLARE @condition NVARCHAR(MAX); -- Smart value condition based on operator and actual db_type from cache -- This handles type-aware comparisons like PostgreSQL version DECLARE @is_numeric BIT = CASE WHEN @value LIKE '[0-9]%' OR @value LIKE '-[0-9]%' THEN 1 ELSE 0 END; DECLARE @is_decimal BIT = CASE WHEN @is_numeric = 1 AND CHARINDEX('.', @value) > 0 THEN 1 ELSE 0 END; DECLARE @is_bool BIT = CASE WHEN @value IN ('true', 'false') THEN 1 ELSE 0 END; DECLARE @is_date BIT = CASE WHEN @value LIKE '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%' THEN 1 ELSE 0 END; DECLARE @is_guid BIT = CASE WHEN @value LIKE '[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]' THEN 1 ELSE 0 END; -- Build value condition based on operator with TYPE-AWARE DETECTION (using @db_type from schema) SET @condition = CASE @operator WHEN '$eq' THEN CASE WHEN @value IS NULL OR @value = 'null' THEN N'v.' + @value_column + N' IS NULL' WHEN @db_type = 'Boolean' THEN N'v._Boolean = ' + CASE WHEN @value = 'true' THEN '1' ELSE '0' END WHEN @db_type = 'DateTimeOffset' THEN N'v._DateTimeOffset = CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @db_type = 'Guid' THEN N'v._Guid = ''' + @safe_value + '''' WHEN @db_type = 'Long' THEN N'v._Long = ' + @value WHEN @db_type = 'Double' THEN N'v.[_Double] = ' + @value WHEN @db_type = 'Numeric' THEN N'v._Numeric = ' + @value WHEN @is_bool = 1 THEN N'v._Boolean = ' + CASE WHEN @value = 'true' THEN '1' ELSE '0' END WHEN @is_date = 1 THEN N'v._DateTimeOffset = CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @is_guid = 1 THEN N'v._Guid = ''' + @safe_value + '''' WHEN @is_numeric = 1 THEN N'(v._Long = ' + @value + N' OR v.[_Double] = ' + @value + N' OR v._Numeric = ' + @value + N')' ELSE N'v._String = N''' + @safe_value + N'''' END WHEN '$ne' THEN CASE WHEN @value IS NULL OR @value = 'null' THEN N'v.' + @value_column + N' IS NOT NULL' WHEN @db_type = 'Boolean' THEN N'v._Boolean <> ' + CASE WHEN @value = 'true' THEN '1' ELSE '0' END WHEN @db_type = 'DateTimeOffset' THEN N'v._DateTimeOffset <> CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @db_type = 'Guid' THEN N'v._Guid <> ''' + @safe_value + '''' WHEN @db_type = 'Long' THEN N'v._Long <> ' + @value WHEN @db_type = 'Double' THEN N'v.[_Double] <> ' + @value WHEN @db_type = 'Numeric' THEN N'v._Numeric <> ' + @value WHEN @is_bool = 1 THEN N'v._Boolean <> ' + CASE WHEN @value = 'true' THEN '1' ELSE '0' END WHEN @is_date = 1 THEN N'v._DateTimeOffset <> CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @is_guid = 1 THEN N'v._Guid <> ''' + @safe_value + '''' WHEN @is_numeric = 1 THEN N'(v._Long <> ' + @value + N' AND v.[_Double] <> ' + @value + N' AND v._Numeric <> ' + @value + N')' ELSE N'v._String <> N''' + @safe_value + N'''' END WHEN '$gt' THEN CASE WHEN @db_type = 'DateTimeOffset' THEN N'v._DateTimeOffset > CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @db_type = 'Long' THEN N'v._Long > ' + @value WHEN @db_type = 'Double' THEN N'v.[_Double] > ' + @value WHEN @db_type = 'Numeric' THEN N'v._Numeric > ' + @value WHEN @is_date = 1 THEN N'v._DateTimeOffset > CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @is_numeric = 1 THEN N'(v._Long > ' + @value + N' OR v.[_Double] > ' + @value + N' OR v._Numeric > ' + @value + N')' ELSE N'v._String > N''' + @safe_value + '''' END WHEN '$gte' THEN CASE WHEN @db_type = 'DateTimeOffset' THEN N'v._DateTimeOffset >= CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @db_type = 'Long' THEN N'v._Long >= ' + @value WHEN @db_type = 'Double' THEN N'v.[_Double] >= ' + @value WHEN @db_type = 'Numeric' THEN N'v._Numeric >= ' + @value WHEN @is_date = 1 THEN N'v._DateTimeOffset >= CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @is_numeric = 1 THEN N'(v._Long >= ' + @value + N' OR v.[_Double] >= ' + @value + N' OR v._Numeric >= ' + @value + N')' ELSE N'v._String >= N''' + @safe_value + '''' END WHEN '$lt' THEN CASE WHEN @db_type = 'DateTimeOffset' THEN N'v._DateTimeOffset < CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @db_type = 'Long' THEN N'v._Long < ' + @value WHEN @db_type = 'Double' THEN N'v.[_Double] < ' + @value WHEN @db_type = 'Numeric' THEN N'v._Numeric < ' + @value WHEN @is_date = 1 THEN N'v._DateTimeOffset < CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @is_numeric = 1 THEN N'(v._Long < ' + @value + N' OR v.[_Double] < ' + @value + N' OR v._Numeric < ' + @value + N')' ELSE N'v._String < N''' + @safe_value + '''' END WHEN '$lte' THEN CASE WHEN @db_type = 'DateTimeOffset' THEN N'v._DateTimeOffset <= CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @db_type = 'Long' THEN N'v._Long <= ' + @value WHEN @db_type = 'Double' THEN N'v.[_Double] <= ' + @value WHEN @db_type = 'Numeric' THEN N'v._Numeric <= ' + @value WHEN @is_date = 1 THEN N'v._DateTimeOffset <= CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @is_numeric = 1 THEN N'(v._Long <= ' + @value + N' OR v.[_Double] <= ' + @value + N' OR v._Numeric <= ' + @value + N')' ELSE N'v._String <= N''' + @safe_value + '''' END WHEN '$contains' THEN N'v._String LIKE N''%' + @safe_value + N'%''' WHEN '$containsIgnoreCase' THEN N'v._String LIKE N''%' + @safe_value + N'%'' COLLATE Latin1_General_CI_AS' WHEN '$startsWith' THEN N'v._String LIKE N''' + @safe_value + N'%''' WHEN '$startsWithIgnoreCase' THEN N'v._String LIKE N''' + @safe_value + N'%'' COLLATE Latin1_General_CI_AS' WHEN '$endsWith' THEN N'v._String LIKE N''%' + @safe_value + N'''' WHEN '$endsWithIgnoreCase' THEN N'v._String LIKE N''%' + @safe_value + N''' COLLATE Latin1_General_CI_AS' WHEN '$in' THEN CASE WHEN @db_type = 'ListItem' THEN N'v._listitem IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @safe_value + N'''))' WHEN @db_type = 'Long' THEN N'v._Long IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @safe_value + N'''))' WHEN @db_type = 'Double' THEN N'v.[_Double] IN (SELECT CAST([value] AS FLOAT) FROM OPENJSON(N''' + @safe_value + N'''))' WHEN @db_type = 'Numeric' THEN N'v._Numeric IN (SELECT CAST([value] AS DECIMAL(38,18)) FROM OPENJSON(N''' + @safe_value + N'''))' WHEN @is_numeric = 1 THEN N'(v._Long IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @safe_value + N''')) OR v.[_Double] IN (SELECT CAST([value] AS FLOAT) FROM OPENJSON(N''' + @safe_value + N''')))' ELSE N'v._String IN (SELECT [value] FROM OPENJSON(N''' + @safe_value + N'''))' END WHEN '$notIn' THEN CASE WHEN @db_type = 'ListItem' THEN N'v._listitem NOT IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @safe_value + N'''))' WHEN @db_type = 'Long' THEN N'v._Long NOT IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @safe_value + N'''))' WHEN @db_type = 'Double' THEN N'v.[_Double] NOT IN (SELECT CAST([value] AS FLOAT) FROM OPENJSON(N''' + @safe_value + N'''))' WHEN @db_type = 'Numeric' THEN N'v._Numeric NOT IN (SELECT CAST([value] AS DECIMAL(38,18)) FROM OPENJSON(N''' + @safe_value + N'''))' WHEN @is_numeric = 1 THEN N'v._Long NOT IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @safe_value + N''')) AND v.[_Double] NOT IN (SELECT CAST([value] AS FLOAT) FROM OPENJSON(N''' + @safe_value + N'''))' ELSE N'v._String NOT IN (SELECT [value] FROM OPENJSON(N''' + @safe_value + N'''))' END WHEN '$exists' THEN CASE WHEN @value = 'true' THEN N'1=1' ELSE N'1=0' END -- EXISTS/NOT EXISTS handles this WHEN '$between' THEN NULL -- Special handling below -- $match: Full-Text Search (requires FTS catalog) WHEN '$match' THEN N'CONTAINS(v._String, N''' + @safe_value + N''')' WHEN '$matchPrefix' THEN N'CONTAINS(v._String, N''"' + @safe_value + N'*"'')' -- $regex alternative for MSSQL: pattern matching with LIKE WHEN '$like' THEN N'v._String LIKE N''' + @safe_value + N'''' WHEN '$likeIgnoreCase' THEN N'v._String LIKE N''' + @safe_value + N''' COLLATE Latin1_General_CI_AS' -- Array operators (use @db_type for type-aware queries) WHEN '$arrayContains' THEN CASE WHEN @db_type = 'ListItem' THEN N'v._listitem = ' + @value WHEN @db_type = 'Boolean' THEN N'v._Boolean = ' + CASE WHEN @value = 'true' THEN '1' ELSE '0' END WHEN @db_type = 'Long' THEN N'v._Long = ' + @value WHEN @db_type = 'Double' THEN N'v.[_Double] = ' + @value WHEN @db_type = 'Numeric' THEN N'v._Numeric = ' + @value WHEN @is_bool = 1 THEN N'v._Boolean = ' + CASE WHEN @value = 'true' THEN '1' ELSE '0' END WHEN @is_numeric = 1 THEN N'(v._Long = ' + @value + N' OR v.[_Double] = ' + @value + N')' ELSE N'v._String = N''' + @safe_value + N'''' END WHEN '$arrayAny' THEN N'1=1' WHEN '$arrayEmpty' THEN N'1=0' -- Will be wrapped in NOT EXISTS WHEN '$arrayCount' THEN NULL -- Special handling below WHEN '$arrayCountGt' THEN NULL WHEN '$arrayCountGte' THEN NULL WHEN '$arrayCountLt' THEN NULL WHEN '$arrayCountLte' THEN NULL -- Extended array operators WHEN '$arrayFirst' THEN CASE WHEN @db_type = 'Long' THEN N'v._array_index = ''0'' AND v._Long = ' + @value WHEN @db_type = 'Double' THEN N'v._array_index = ''0'' AND v.[_Double] = ' + @value WHEN @is_numeric = 1 THEN N'v._array_index = ''0'' AND (v._Long = ' + @value + N' OR v.[_Double] = ' + @value + N')' ELSE N'v._array_index = ''0'' AND v._String = N''' + @safe_value + N'''' END WHEN '$arrayLast' THEN NULL -- Special handling below WHEN '$arrayAt' THEN N'v._array_index = N''' + @safe_value + N'''' WHEN '$arrayStartsWith' THEN N'v._String LIKE N''' + @safe_value + N'%''' WHEN '$arrayEndsWith' THEN N'v._String LIKE N''%' + @safe_value + N'''' ELSE CASE WHEN @db_type = 'ListItem' THEN N'v._listitem = ' + @value WHEN @db_type = 'Boolean' THEN N'v._Boolean = ' + CASE WHEN @value = 'true' THEN '1' ELSE '0' END WHEN @db_type = 'DateTimeOffset' THEN N'v._DateTimeOffset = CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @db_type = 'Guid' THEN N'v._Guid = ''' + @safe_value + '''' WHEN @db_type = 'Long' THEN N'v._Long = ' + @value WHEN @db_type = 'Double' THEN N'v.[_Double] = ' + @value WHEN @db_type = 'Numeric' THEN N'v._Numeric = ' + @value WHEN @is_bool = 1 THEN N'v._Boolean = ' + CASE WHEN @value = 'true' THEN '1' ELSE '0' END WHEN @is_date = 1 THEN N'v._DateTimeOffset = CONVERT(datetimeoffset, ''' + @safe_value + ''', 127)' WHEN @is_guid = 1 THEN N'v._Guid = ''' + @safe_value + '''' WHEN @is_numeric = 1 THEN N'(v._Long = ' + @value + N' OR v.[_Double] = ' + @value + N' OR v._Numeric = ' + @value + N')' ELSE N'v._String = N''' + @safe_value + N'''' END END; -- Handle array count operators specially IF @operator LIKE '$arrayCount%' BEGIN DECLARE @count_op NVARCHAR(10) = CASE @operator WHEN '$arrayCount' THEN '=' WHEN '$arrayCountGt' THEN '>' WHEN '$arrayCountGte' THEN '>=' WHEN '$arrayCountLt' THEN '<' WHEN '$arrayCountLte' THEN '<=' END; SET @result = N'(SELECT COUNT(*) FROM _values v WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL) ' + @count_op + N' ' + @value; RETURN; END; -- Handle $arrayLast - needs subquery to find max index IF @operator = '$arrayLast' BEGIN SET @result = N'EXISTS (SELECT 1 FROM _values v WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index = (SELECT MAX(v2._array_index) FROM _values v2 WHERE v2._id_object = ' + @table_alias + N'._id ' + N'AND v2._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND v2._array_index IS NOT NULL) ' + N'AND ' + CASE WHEN @is_numeric = 1 THEN N'(v._Long = ' + @value + N' OR v._Double = ' + @value + N')' ELSE N'v._String = N''' + @safe_value + N'''' END + N')'; RETURN; END; -- Handle $between - value is JSON array [min, max] IF @operator = '$between' BEGIN DECLARE @min_val NVARCHAR(500); DECLARE @max_val NVARCHAR(500); SELECT @min_val = [value] FROM OPENJSON(@value) WHERE [key] = '0'; SELECT @max_val = [value] FROM OPENJSON(@value) WHERE [key] = '1'; IF @min_val IS NOT NULL AND @max_val IS NOT NULL BEGIN SET @result = N'EXISTS (SELECT 1 FROM _values v WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NULL AND (' + CASE WHEN @min_val LIKE '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%' THEN N'v._DateTimeOffset BETWEEN CONVERT(datetimeoffset, ''' + REPLACE(@min_val, '''', '''''') + N''', 127) AND CONVERT(datetimeoffset, ''' + REPLACE(@max_val, '''', '''''') + N''', 127)' WHEN @min_val LIKE '[0-9]%' OR @min_val LIKE '-[0-9]%' THEN N'(v._Long BETWEEN ' + @min_val + N' AND ' + @max_val + N') OR (v._Double BETWEEN ' + @min_val + N' AND ' + @max_val + N')' ELSE N'v._String BETWEEN N''' + REPLACE(@min_val, '''', '''''') + N''' AND N''' + REPLACE(@max_val, '''', '''''') + N'''' END + N'))'; END ELSE SET @result = N'1=1'; RETURN; END; -- Handle array aggregation operators IF @operator IN ('$arraySum', '$arrayAvg', '$arrayMin', '$arrayMax') BEGIN DECLARE @agg_func NVARCHAR(10) = CASE @operator WHEN '$arraySum' THEN 'SUM' WHEN '$arrayAvg' THEN 'AVG' WHEN '$arrayMin' THEN 'MIN' WHEN '$arrayMax' THEN 'MAX' END; SET @result = N'(SELECT ' + @agg_func + N'(COALESCE(v._Long, v._Double, v._Numeric)) ' + N'FROM _values v WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL) = ' + @value; RETURN; END; -- Handle array aggregation comparison operators ($arraySumGt, $arraySumLt, etc.) IF @operator LIKE '$arraySum%' OR @operator LIKE '$arrayAvg%' OR @operator LIKE '$arrayMin%' OR @operator LIKE '$arrayMax%' BEGIN DECLARE @agg_base NVARCHAR(20); DECLARE @agg_cmp NVARCHAR(10); IF @operator LIKE '%Gt' SET @agg_cmp = '>'; ELSE IF @operator LIKE '%Gte' SET @agg_cmp = '>='; ELSE IF @operator LIKE '%Lt' SET @agg_cmp = '<'; ELSE IF @operator LIKE '%Lte' SET @agg_cmp = '<='; ELSE SET @agg_cmp = '='; IF @operator LIKE '$arraySum%' SET @agg_base = 'SUM'; ELSE IF @operator LIKE '$arrayAvg%' SET @agg_base = 'AVG'; ELSE IF @operator LIKE '$arrayMin%' SET @agg_base = 'MIN'; ELSE IF @operator LIKE '$arrayMax%' SET @agg_base = 'MAX'; SET @result = N'(SELECT ' + @agg_base + N'(COALESCE(v._Long, v._Double, v._Numeric)) ' + N'FROM _values v WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL) ' + @agg_cmp + N' ' + @value; RETURN; END; -- Build final EXISTS clause IF @dict_key IS NOT NULL BEGIN -- Dictionary access: Field[key] IF @is_nested = 1 AND @nested_structure_id IS NOT NULL BEGIN -- Dictionary with nested: Field[key].Prop SET @result = N'EXISTS (SELECT 1 FROM _values rv ' + N'JOIN _values v ON v._array_parent_id = rv._id AND v._id_structure = ' + CAST(@nested_structure_id AS NVARCHAR(20)) + N' ' + N'WHERE rv._id_object = ' + @table_alias + N'._id ' + N'AND rv._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND rv._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''' ' + N'AND ' + @condition + N')'; END ELSE BEGIN -- Simple dictionary: Field[key] SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''' ' + N'AND ' + @condition + N')'; END; END ELSE IF @is_array = 1 AND @is_nested = 1 AND @nested_structure_id IS NOT NULL BEGIN -- Array of Class: Field[].Prop SET @result = N'EXISTS (SELECT 1 FROM _values rv ' + N'JOIN _values v ON v._array_parent_id = rv._id AND v._id_structure = ' + CAST(@nested_structure_id AS NVARCHAR(20)) + N' ' + N'WHERE rv._id_object = ' + @table_alias + N'._id ' + N'AND rv._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND rv._array_index IS NOT NULL ' + N'AND ' + @condition + N')'; END ELSE IF @is_array = 1 AND (@type_semantic IS NULL OR @type_semantic <> '_RListItem' OR @is_nested = 0) BEGIN -- Simple array: Field[] (not ListItem array with nested field) IF @operator = '$arrayEmpty' BEGIN SET @result = N'NOT EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL)'; END ELSE BEGIN SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL ' + N'AND ' + @condition + N')'; END; END ELSE IF @is_nested = 1 AND @nested_structure_id IS NOT NULL BEGIN -- Class field: Field.Prop SET @result = N'EXISTS (SELECT 1 FROM _values rv ' + N'JOIN _values v ON v._id_object = rv._id_object AND v._id_structure = ' + CAST(@nested_structure_id AS NVARCHAR(20)) + N' ' + N'WHERE rv._id_object = ' + @table_alias + N'._id ' + N'AND rv._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND rv._array_index IS NULL ' + N'AND v._array_index IS NULL ' + N'AND ' + @condition + N')'; END -- ListItem field: Status.Value, Status.Alias, Roles[].Value ELSE IF @is_nested = 1 AND @type_semantic = '_RListItem' AND @nested_field IN ('Value', 'Alias', 'Id', 'IdList') BEGIN DECLARE @li_column NVARCHAR(20) = CASE @nested_field WHEN 'Value' THEN '_value' WHEN 'Alias' THEN '_alias' WHEN 'Id' THEN '_id' WHEN 'IdList' THEN '_id_list' END; DECLARE @li_condition NVARCHAR(MAX) = REPLACE(@condition, N'v._String', N'li.' + @li_column); SET @li_condition = REPLACE(@li_condition, N'v._Long', N'li.' + @li_column); IF @is_array = 1 BEGIN -- ListItem array: Roles[].Value SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'JOIN _list_items li ON li._id = v._listitem ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL ' + N'AND ' + @li_condition + N')'; END ELSE BEGIN -- Simple ListItem: Status.Value SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'JOIN _list_items li ON li._id = v._listitem ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NULL ' + N'AND ' + @li_condition + N')'; END; END -- ListItem direct: search by ID (Status = 123, Status $in [1,2,3]) ELSE IF @type_semantic = '_RListItem' AND @is_nested = 0 BEGIN SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NULL ' + N'AND ' + @condition + N')'; END -- Dictionary existence check: PhoneBook != null or PhoneBook.$exists -- For Dictionary, values are stored with _array_index = key (not NULL) ELSE IF @collection_type IS NOT NULL AND @dict_key IS NULL AND (@operator = '$exists' OR (@operator = '$ne' AND (@value IS NULL OR @value = 'null'))) BEGIN -- Check if any dictionary entry exists (any _array_index value) IF @operator = '$exists' AND @value = 'true' BEGIN SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL)'; END ELSE IF @operator = '$exists' AND @value = 'false' BEGIN SET @result = N'NOT EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL)'; END ELSE IF @operator = '$ne' AND (@value IS NULL OR @value = 'null') BEGIN -- PhoneBook != null means dictionary has at least one entry SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL)'; END ELSE BEGIN SET @result = N'1=1'; END; END -- Property function: $length (string length) or $count (array count) ELSE IF @property_function IS NOT NULL BEGIN DECLARE @func_compare_op NVARCHAR(10) = CASE @operator WHEN '$eq' THEN '=' WHEN '$ne' THEN '<>' WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' ELSE '=' END; IF @property_function = '$length' BEGIN -- String length: LEN(v._String) SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NULL ' + N'AND LEN(v._String) ' + @func_compare_op + N' ' + @value + N')'; END ELSE IF @property_function = '$count' BEGIN -- Array count: COUNT of array elements SET @result = N'(SELECT COUNT(*) FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NOT NULL) ' + @func_compare_op + N' ' + @value; END ELSE BEGIN SET @result = N'1=1'; -- Unknown function, skip END; END ELSE BEGIN -- Simple field IF @operator = '$exists' BEGIN -- $exists true = field exists (record in _values), $exists false = field NOT exists IF @value = 'true' SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NULL)'; ELSE SET @result = N'NOT EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NULL)'; END ELSE IF @operator = '$ne' AND @value IS NOT NULL AND @value <> 'null' BEGIN -- $ne needs NOT EXISTS for proper null handling in EAV -- Use numeric format for numeric values, string format for strings DECLARE @ne_value_expr NVARCHAR(100); IF @is_numeric = 1 SET @ne_value_expr = @value; -- Numeric: just the value ELSE SET @ne_value_expr = N'N''' + @safe_value + N''''; -- String: N'value' SET @result = N'NOT EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NULL ' + N'AND v.' + @value_column + N' = ' + @ne_value_expr + N')'; END ELSE BEGIN SET @result = N'EXISTS (SELECT 1 FROM _values v ' + N'WHERE v._id_object = ' + @table_alias + N'._id ' + N'AND v._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' ' + N'AND v._array_index IS NULL ' + N'AND ' + @condition + N')'; END; END; END; GO -- ===================================================== -- INTERNAL: Recursive filter parser -- Parses JSON filters and builds WHERE clause -- ===================================================== CREATE PROCEDURE dbo.internal_parse_filters @scheme_id BIGINT, @json NVARCHAR(MAX), @table_alias NVARCHAR(10), @logical_op NVARCHAR(10), -- 'AND' or 'OR' @negate BIT, -- For $not @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; -- Handle NULL, empty, '{}' and string 'null' from C# IF @json IS NULL OR @json = N'' OR @json = N'{}' OR @json = N'null' BEGIN SET @result = N''; RETURN; END; -- All variable declarations at the top (MSSQL requirement) DECLARE @conditions TABLE (idx INT IDENTITY(1,1), condition NVARCHAR(MAX)); DECLARE @key NVARCHAR(500); DECLARE @value NVARCHAR(MAX); DECLARE @type INT; DECLARE @exists_sql NVARCHAR(MAX); DECLARE @sub_result NVARCHAR(MAX); -- Variables for $and DECLARE @and_conditions TABLE (idx INT IDENTITY(1,1), cond NVARCHAR(MAX)); DECLARE @and_item NVARCHAR(MAX); DECLARE @and_result NVARCHAR(MAX); -- Variables for $or DECLARE @or_conditions TABLE (idx INT IDENTITY(1,1), cond NVARCHAR(MAX)); DECLARE @or_item NVARCHAR(MAX); DECLARE @or_result NVARCHAR(MAX); -- Variables for $hasAncestor DECLARE @anc_condition NVARCHAR(MAX); DECLARE @anc_scheme_id BIGINT; DECLARE @anc_max_depth INT; DECLARE @anc_temp_json NVARCHAR(MAX); DECLARE @anc_built_condition NVARCHAR(MAX); -- Variables for $hasDescendant DECLARE @desc_condition NVARCHAR(MAX); DECLARE @desc_scheme_id BIGINT; DECLARE @desc_max_depth INT; DECLARE @desc_temp_json NVARCHAR(MAX); DECLARE @desc_built_condition NVARCHAR(MAX); -- Variables for $level DECLARE @level_op NVARCHAR(50); DECLARE @level_val NVARCHAR(50); DECLARE @level_cmp NVARCHAR(10); -- Variables for base fields (0$:) DECLARE @base_field NVARCHAR(100); DECLARE @base_col NVARCHAR(100); DECLARE @base_op NVARCHAR(50); DECLARE @base_val NVARCHAR(MAX); DECLARE @base_type INT; DECLARE @base_cond NVARCHAR(MAX); DECLARE @is_datetime_col BIT; DECLARE @safe_base_val NVARCHAR(MAX); DECLARE @is_datetime_simple BIT; DECLARE @safe_value_simple NVARCHAR(MAX); -- Variables for field operators DECLARE @op_name NVARCHAR(50); DECLARE @op_value NVARCHAR(MAX); DECLARE @op_type INT; DECLARE @op_value_type NVARCHAR(20); -- Variable for STRING_AGG separator DECLARE @separator NVARCHAR(10); -- Parse JSON object DECLARE json_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@json); OPEN json_cursor; FETCH NEXT FROM json_cursor INTO @key, @value, @type; WHILE @@FETCH_STATUS = 0 BEGIN -- Handle logical operators IF @key = '$and' BEGIN -- $and: array of conditions, all must match DELETE FROM @and_conditions; DECLARE and_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@value); OPEN and_cursor; FETCH NEXT FROM and_cursor INTO @and_item; WHILE @@FETCH_STATUS = 0 BEGIN EXEC dbo.internal_parse_filters @scheme_id, @and_item, @table_alias, N'AND', 0, @and_result OUTPUT; IF @and_result IS NOT NULL AND @and_result <> N'' INSERT INTO @and_conditions (cond) VALUES (@and_result); FETCH NEXT FROM and_cursor INTO @and_item; END; CLOSE and_cursor; DEALLOCATE and_cursor; SELECT @sub_result = N'(' + STRING_AGG(cond, N' AND ') + N')' FROM @and_conditions; IF @sub_result IS NOT NULL INSERT INTO @conditions (condition) VALUES (@sub_result); DELETE FROM @and_conditions; END ELSE IF @key = '$or' BEGIN -- $or: array of conditions, any must match DELETE FROM @or_conditions; DECLARE or_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@value); OPEN or_cursor; FETCH NEXT FROM or_cursor INTO @or_item; WHILE @@FETCH_STATUS = 0 BEGIN EXEC dbo.internal_parse_filters @scheme_id, @or_item, @table_alias, N'AND', 0, @or_result OUTPUT; IF @or_result IS NOT NULL AND @or_result <> N'' INSERT INTO @or_conditions (cond) VALUES (@or_result); FETCH NEXT FROM or_cursor INTO @or_item; END; CLOSE or_cursor; DEALLOCATE or_cursor; SELECT @sub_result = N'(' + STRING_AGG(cond, N' OR ') + N')' FROM @or_conditions; IF @sub_result IS NOT NULL INSERT INTO @conditions (condition) VALUES (@sub_result); DELETE FROM @or_conditions; END ELSE IF @key = '$not' BEGIN -- $not: negate the inner condition EXEC dbo.internal_parse_filters @scheme_id, @value, @table_alias, N'AND', 1, @sub_result OUTPUT; IF @sub_result IS NOT NULL AND @sub_result <> N'' INSERT INTO @conditions (condition) VALUES (N'NOT (' + @sub_result + N')'); END -- Hierarchical operators ELSE IF @key = '$isRoot' BEGIN IF @value = 'true' INSERT INTO @conditions (condition) VALUES (@table_alias + N'._id_parent IS NULL'); ELSE INSERT INTO @conditions (condition) VALUES (@table_alias + N'._id_parent IS NOT NULL'); END ELSE IF @key = '$isLeaf' BEGIN IF @value = 'true' INSERT INTO @conditions (condition) VALUES (N'NOT EXISTS (SELECT 1 FROM _objects c WHERE c._id_parent = ' + @table_alias + N'._id)'); ELSE INSERT INTO @conditions (condition) VALUES (N'EXISTS (SELECT 1 FROM _objects c WHERE c._id_parent = ' + @table_alias + N'._id)'); END ELSE IF @key = '$childrenOf' BEGIN -- $childrenOf: direct children of specified parent INSERT INTO @conditions (condition) VALUES (@table_alias + N'._id_parent = ' + @value); END ELSE IF @key = '$hasAncestor' BEGIN -- $hasAncestor: check if object has ancestor matching condition SET @anc_condition = N''; SET @anc_scheme_id = NULL; SET @anc_max_depth = 50; IF @type = 5 -- object BEGIN SET @anc_scheme_id = JSON_VALUE(@value, '$.scheme_id'); SET @anc_max_depth = ISNULL(CAST(JSON_VALUE(@value, '$.max_depth') AS INT), 50); SET @anc_temp_json = JSON_QUERY(@value, '$.condition'); IF @anc_temp_json IS NOT NULL BEGIN EXEC dbo.internal_parse_filters @anc_scheme_id, @anc_temp_json, N'anc', N'AND', 0, @anc_condition OUTPUT; END; END; -- Build condition string separately (CASE not allowed in VALUES) SET @anc_built_condition = N'(SELECT 1 WHERE EXISTS (SELECT 1 FROM _objects anc WHERE anc._id IN (' + N'SELECT p1._id FROM _objects p1 WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION SELECT p2._id FROM _objects p2 JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION SELECT p3._id FROM _objects p3 JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION SELECT p4._id FROM _objects p4 JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION SELECT p5._id FROM _objects p5 JOIN _objects p4 ON p5._id = p4._id_parent JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N')'; IF @anc_scheme_id IS NOT NULL SET @anc_built_condition = @anc_built_condition + N' AND anc._id_scheme = ' + CAST(@anc_scheme_id AS NVARCHAR(20)); IF @anc_condition IS NOT NULL AND @anc_condition <> N'' SET @anc_built_condition = @anc_built_condition + N' AND ' + @anc_condition; SET @anc_built_condition = @anc_built_condition + N')) = 1'; INSERT INTO @conditions (condition) VALUES (@anc_built_condition); END ELSE IF @key = '$hasDescendant' BEGIN -- $hasDescendant: check if object has descendant matching condition SET @desc_condition = N''; SET @desc_scheme_id = NULL; SET @desc_max_depth = 50; IF @type = 5 -- object BEGIN SET @desc_scheme_id = JSON_VALUE(@value, '$.scheme_id'); SET @desc_max_depth = ISNULL(CAST(JSON_VALUE(@value, '$.max_depth') AS INT), 50); SET @desc_temp_json = JSON_QUERY(@value, '$.condition'); IF @desc_temp_json IS NOT NULL BEGIN EXEC dbo.internal_parse_filters @desc_scheme_id, @desc_temp_json, N'desc_obj', N'AND', 0, @desc_condition OUTPUT; END; END; -- Build condition string separately (CASE not allowed in VALUES) SET @desc_built_condition = N'EXISTS (SELECT 1 FROM _objects desc_obj WHERE desc_obj._id IN (' + N'SELECT c1._id FROM _objects c1 WHERE c1._id_parent = ' + @table_alias + N'._id ' + N'UNION SELECT c2._id FROM _objects c2 JOIN _objects c1 ON c2._id_parent = c1._id WHERE c1._id_parent = ' + @table_alias + N'._id ' + N'UNION SELECT c3._id FROM _objects c3 JOIN _objects c2 ON c3._id_parent = c2._id JOIN _objects c1 ON c2._id_parent = c1._id WHERE c1._id_parent = ' + @table_alias + N'._id ' + N'UNION SELECT c4._id FROM _objects c4 JOIN _objects c3 ON c4._id_parent = c3._id JOIN _objects c2 ON c3._id_parent = c2._id JOIN _objects c1 ON c2._id_parent = c1._id WHERE c1._id_parent = ' + @table_alias + N'._id ' + N'UNION SELECT c5._id FROM _objects c5 JOIN _objects c4 ON c5._id_parent = c4._id JOIN _objects c3 ON c4._id_parent = c3._id JOIN _objects c2 ON c3._id_parent = c2._id JOIN _objects c1 ON c2._id_parent = c1._id WHERE c1._id_parent = ' + @table_alias + N'._id' + N')'; IF @desc_scheme_id IS NOT NULL SET @desc_built_condition = @desc_built_condition + N' AND desc_obj._id_scheme = ' + CAST(@desc_scheme_id AS NVARCHAR(20)); IF @desc_condition IS NOT NULL AND @desc_condition <> N'' SET @desc_built_condition = @desc_built_condition + N' AND ' + @desc_condition; SET @desc_built_condition = @desc_built_condition + N')'; INSERT INTO @conditions (condition) VALUES (@desc_built_condition); END ELSE IF @key = '$level' BEGIN -- $level: use parent chain counting IF @type = 2 -- number (direct value like "$level": 2) BEGIN -- Simple level check via counting parent chain IF @value = '0' BEGIN INSERT INTO @conditions (condition) VALUES (@table_alias + N'._id_parent IS NULL'); END ELSE BEGIN INSERT INTO @conditions (condition) VALUES ( N'(SELECT COUNT(*) FROM (' + N'SELECT p1._id FROM _objects p1 WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p2._id FROM _objects p2 JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p3._id FROM _objects p3 JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p4._id FROM _objects p4 JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p5._id FROM _objects p5 JOIN _objects p4 ON p5._id = p4._id_parent JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N') AS parents) = ' + @value ); END; END ELSE IF @type = 5 -- object with operators like "$level": {"$gt": 2} BEGIN DECLARE level_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value] FROM OPENJSON(@value); OPEN level_cursor; FETCH NEXT FROM level_cursor INTO @level_op, @level_val; WHILE @@FETCH_STATUS = 0 BEGIN SET @level_cmp = CASE @level_op WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' WHEN '$eq' THEN '=' WHEN '$ne' THEN '<>' ELSE '=' END; -- Optimized checks for common cases IF @level_val = '0' AND @level_cmp = '=' BEGIN INSERT INTO @conditions (condition) VALUES (@table_alias + N'._id_parent IS NULL'); END ELSE IF @level_val = '0' AND @level_cmp = '>' BEGIN INSERT INTO @conditions (condition) VALUES (@table_alias + N'._id_parent IS NOT NULL'); END ELSE IF @level_val = '0' AND @level_cmp = '>=' BEGIN INSERT INTO @conditions (condition) VALUES (N'1=1'); -- all objects have level >= 0 END ELSE IF @level_val = '1' AND @level_cmp = '=' BEGIN INSERT INTO @conditions (condition) VALUES ( @table_alias + N'._id_parent IS NOT NULL AND EXISTS (SELECT 1 FROM _objects p WHERE p._id = ' + @table_alias + N'._id_parent AND p._id_parent IS NULL)' ); END ELSE BEGIN -- General case: count parent chain (supports up to 10 levels) INSERT INTO @conditions (condition) VALUES ( N'(SELECT COUNT(*) FROM (' + N'SELECT p1._id FROM _objects p1 WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p2._id FROM _objects p2 JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p3._id FROM _objects p3 JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p4._id FROM _objects p4 JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p5._id FROM _objects p5 JOIN _objects p4 ON p5._id = p4._id_parent JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p6._id FROM _objects p6 JOIN _objects p5 ON p6._id = p5._id_parent JOIN _objects p4 ON p5._id = p4._id_parent JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p7._id FROM _objects p7 JOIN _objects p6 ON p7._id = p6._id_parent JOIN _objects p5 ON p6._id = p5._id_parent JOIN _objects p4 ON p5._id = p4._id_parent JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p8._id FROM _objects p8 JOIN _objects p7 ON p8._id = p7._id_parent JOIN _objects p6 ON p7._id = p6._id_parent JOIN _objects p5 ON p6._id = p5._id_parent JOIN _objects p4 ON p5._id = p4._id_parent JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p9._id FROM _objects p9 JOIN _objects p8 ON p9._id = p8._id_parent JOIN _objects p7 ON p8._id = p7._id_parent JOIN _objects p6 ON p7._id = p6._id_parent JOIN _objects p5 ON p6._id = p5._id_parent JOIN _objects p4 ON p5._id = p4._id_parent JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N'UNION ALL SELECT p10._id FROM _objects p10 JOIN _objects p9 ON p10._id = p9._id_parent JOIN _objects p8 ON p9._id = p8._id_parent JOIN _objects p7 ON p8._id = p7._id_parent JOIN _objects p6 ON p7._id = p6._id_parent JOIN _objects p5 ON p6._id = p5._id_parent JOIN _objects p4 ON p5._id = p4._id_parent JOIN _objects p3 ON p4._id = p3._id_parent JOIN _objects p2 ON p3._id = p2._id_parent JOIN _objects p1 ON p2._id = p1._id_parent WHERE p1._id = ' + @table_alias + N'._id_parent ' + N') AS parents) ' + @level_cmp + N' ' + @level_val ); END; FETCH NEXT FROM level_cursor INTO @level_op, @level_val; END; CLOSE level_cursor; DEALLOCATE level_cursor; END; END -- Base field (0$: prefix) ELSE IF @key LIKE '0$:%' BEGIN SET @base_field = SUBSTRING(@key, 4, LEN(@key)); SET @base_col = dbo.normalize_base_field_name(@base_field); IF @base_col IS NOT NULL BEGIN IF @type = 5 -- object with operators BEGIN DECLARE base_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@value); OPEN base_cursor; FETCH NEXT FROM base_cursor INTO @base_op, @base_val, @base_type; WHILE @@FETCH_STATUS = 0 BEGIN -- Detect datetime base columns for proper CONVERT handling SET @is_datetime_col = CASE WHEN @base_col IN ('_date_create', '_date_modify', '_date_begin', '_date_complete') THEN 1 ELSE 0 END; SET @safe_base_val = REPLACE(@base_val, '''', ''''''); SET @base_cond = CASE @base_op WHEN '$eq' THEN CASE WHEN @base_type = 0 THEN @table_alias + N'.' + @base_col + N' IS NULL' WHEN @is_datetime_col = 1 THEN @table_alias + N'.' + @base_col + N' = CONVERT(datetimeoffset, ''' + @safe_base_val + N''', 127)' ELSE @table_alias + N'.' + @base_col + N' = N''' + @safe_base_val + N'''' END WHEN '$ne' THEN CASE WHEN @base_type = 0 THEN @table_alias + N'.' + @base_col + N' IS NOT NULL' WHEN @is_datetime_col = 1 THEN @table_alias + N'.' + @base_col + N' <> CONVERT(datetimeoffset, ''' + @safe_base_val + N''', 127)' ELSE @table_alias + N'.' + @base_col + N' <> N''' + @safe_base_val + N'''' END WHEN '$gt' THEN CASE WHEN @is_datetime_col = 1 THEN @table_alias + N'.' + @base_col + N' > CONVERT(datetimeoffset, ''' + @safe_base_val + N''', 127)' ELSE @table_alias + N'.' + @base_col + N' > ' + @base_val END WHEN '$gte' THEN CASE WHEN @is_datetime_col = 1 THEN @table_alias + N'.' + @base_col + N' >= CONVERT(datetimeoffset, ''' + @safe_base_val + N''', 127)' ELSE @table_alias + N'.' + @base_col + N' >= ' + @base_val END WHEN '$lt' THEN CASE WHEN @is_datetime_col = 1 THEN @table_alias + N'.' + @base_col + N' < CONVERT(datetimeoffset, ''' + @safe_base_val + N''', 127)' ELSE @table_alias + N'.' + @base_col + N' < ' + @base_val END WHEN '$lte' THEN CASE WHEN @is_datetime_col = 1 THEN @table_alias + N'.' + @base_col + N' <= CONVERT(datetimeoffset, ''' + @safe_base_val + N''', 127)' ELSE @table_alias + N'.' + @base_col + N' <= ' + @base_val END WHEN '$contains' THEN @table_alias + N'.' + @base_col + N' LIKE N''%' + @safe_base_val + N'%''' WHEN '$startsWith' THEN @table_alias + N'.' + @base_col + N' LIKE N''' + @safe_base_val + N'%''' WHEN '$endsWith' THEN @table_alias + N'.' + @base_col + N' LIKE N''%' + @safe_base_val + N'''' WHEN '$in' THEN @table_alias + N'.' + @base_col + N' IN (SELECT [value] FROM OPENJSON(N''' + @safe_base_val + N'''))' WHEN '$exists' THEN CASE WHEN @base_val = 'true' THEN @table_alias + N'.' + @base_col + N' IS NOT NULL' ELSE @table_alias + N'.' + @base_col + N' IS NULL' END ELSE CASE WHEN @is_datetime_col = 1 THEN @table_alias + N'.' + @base_col + N' = CONVERT(datetimeoffset, ''' + @safe_base_val + N''', 127)' ELSE @table_alias + N'.' + @base_col + N' = N''' + @safe_base_val + N'''' END END; IF @base_cond IS NOT NULL INSERT INTO @conditions (condition) VALUES (@base_cond); FETCH NEXT FROM base_cursor INTO @base_op, @base_val, @base_type; END; CLOSE base_cursor; DEALLOCATE base_cursor; END ELSE BEGIN -- JSON null → IS NULL (OPENJSON returns @type=0 and @value=NULL for JSON null) IF @type = 0 INSERT INTO @conditions (condition) VALUES ( @table_alias + N'.' + @base_col + N' IS NULL' ); ELSE BEGIN -- Simple value - detect datetime columns for proper CONVERT SET @is_datetime_simple = CASE WHEN @base_col IN ('_date_create', '_date_modify', '_date_begin', '_date_complete') THEN 1 ELSE 0 END; SET @safe_value_simple = REPLACE(@value, '''', ''''''); IF @is_datetime_simple = 1 INSERT INTO @conditions (condition) VALUES ( @table_alias + N'.' + @base_col + N' = CONVERT(datetimeoffset, ''' + @safe_value_simple + N''', 127)' ); ELSE INSERT INTO @conditions (condition) VALUES ( @table_alias + N'.' + @base_col + N' = N''' + @safe_value_simple + N'''' ); END; END; END; END -- Dictionary indexer: FieldName[key] (e.g.: "PhoneBook[home]": {"$eq": "+7-999..."}) -- Uses db_type from metadata cache for correct column selection ELSE IF @key LIKE '%[%]%' AND @key NOT LIKE '$%' BEGIN DECLARE @dict_idx_field_name NVARCHAR(450); DECLARE @dict_idx_key NVARCHAR(450); DECLARE @dict_idx_structure_id BIGINT; DECLARE @dict_idx_db_type NVARCHAR(50); DECLARE @dict_idx_op NVARCHAR(50); DECLARE @dict_idx_val NVARCHAR(MAX); DECLARE @dict_idx_val_type INT; DECLARE @dict_idx_condition NVARCHAR(MAX); DECLARE @dict_idx_value_cond NVARCHAR(MAX); DECLARE @dict_idx_safe_val NVARCHAR(MAX); -- Parse: "PhoneBook[home]" -> field="PhoneBook", key="home" SET @dict_idx_field_name = LEFT(@key, CHARINDEX('[', @key) - 1); SET @dict_idx_key = SUBSTRING(@key, CHARINDEX('[', @key) + 1, CHARINDEX(']', @key) - CHARINDEX('[', @key) - 1); -- Find structure and db_type for dictionary field from metadata cache SELECT @dict_idx_structure_id = c._structure_id, @dict_idx_db_type = c.db_type FROM _scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @dict_idx_field_name AND c._parent_structure_id IS NULL; IF @dict_idx_structure_id IS NOT NULL BEGIN IF @type = 5 -- object with operators like {"$eq": "value"} BEGIN DECLARE dict_idx_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@value); OPEN dict_idx_cursor; FETCH NEXT FROM dict_idx_cursor INTO @dict_idx_op, @dict_idx_val, @dict_idx_val_type; WHILE @@FETCH_STATUS = 0 BEGIN SET @dict_idx_safe_val = REPLACE(@dict_idx_val, '''', ''''''); -- Build value condition based on operator AND db_type IF @dict_idx_op IN ('$gt', '$gte', '$lt', '$lte') BEGIN -- Numeric comparisons - use db_type for correct column SET @dict_idx_value_cond = CASE @dict_idx_db_type WHEN 'Numeric' THEN N'dv._Numeric ' + CASE @dict_idx_op WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' END + N' ' + @dict_idx_val WHEN 'Double' THEN N'dv.[_Double] ' + CASE @dict_idx_op WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' END + N' ' + @dict_idx_val ELSE N'dv._Long ' + CASE @dict_idx_op WHEN '$gt' THEN '>' WHEN '$gte' THEN '>=' WHEN '$lt' THEN '<' WHEN '$lte' THEN '<=' END + N' ' + @dict_idx_val END; END ELSE IF @dict_idx_op = '$in' BEGIN -- $in operator - use db_type for correct column SET @dict_idx_value_cond = CASE @dict_idx_db_type WHEN 'Long' THEN N'dv._Long IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @dict_idx_safe_val + N'''))' WHEN 'Numeric' THEN N'dv._Numeric IN (SELECT CAST([value] AS DECIMAL(38,18)) FROM OPENJSON(N''' + @dict_idx_safe_val + N'''))' WHEN 'Double' THEN N'dv.[_Double] IN (SELECT CAST([value] AS FLOAT) FROM OPENJSON(N''' + @dict_idx_safe_val + N'''))' ELSE N'dv._String IN (SELECT [value] FROM OPENJSON(N''' + @dict_idx_safe_val + N'''))' END; END ELSE IF @dict_idx_op = '$nin' BEGIN -- $nin operator - use db_type for correct column SET @dict_idx_value_cond = CASE @dict_idx_db_type WHEN 'Long' THEN N'dv._Long NOT IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @dict_idx_safe_val + N'''))' WHEN 'Numeric' THEN N'dv._Numeric NOT IN (SELECT CAST([value] AS DECIMAL(38,18)) FROM OPENJSON(N''' + @dict_idx_safe_val + N'''))' WHEN 'Double' THEN N'dv.[_Double] NOT IN (SELECT CAST([value] AS FLOAT) FROM OPENJSON(N''' + @dict_idx_safe_val + N'''))' ELSE N'dv._String NOT IN (SELECT [value] FROM OPENJSON(N''' + @dict_idx_safe_val + N'''))' END; END ELSE BEGIN -- Other operators SET @dict_idx_value_cond = CASE @dict_idx_op -- Equality/Inequality - use db_type for correct column WHEN '$eq' THEN CASE @dict_idx_db_type WHEN 'Long' THEN N'dv._Long = ' + @dict_idx_val WHEN 'Numeric' THEN N'dv._Numeric = ' + @dict_idx_val WHEN 'Double' THEN N'dv.[_Double] = ' + @dict_idx_val ELSE N'dv._String = N''' + @dict_idx_safe_val + N'''' END WHEN '$ne' THEN CASE @dict_idx_db_type WHEN 'Long' THEN N'dv._Long <> ' + @dict_idx_val WHEN 'Numeric' THEN N'dv._Numeric <> ' + @dict_idx_val WHEN 'Double' THEN N'dv.[_Double] <> ' + @dict_idx_val ELSE N'dv._String <> N''' + @dict_idx_safe_val + N'''' END -- String operations (always use _String) WHEN '$contains' THEN N'dv._String LIKE N''%' + @dict_idx_safe_val + N'%''' WHEN '$startsWith' THEN N'dv._String LIKE N''' + @dict_idx_safe_val + N'%''' WHEN '$endsWith' THEN N'dv._String LIKE N''%' + @dict_idx_safe_val + N'''' WHEN '$containsIgnoreCase' THEN N'dv._String LIKE N''%' + @dict_idx_safe_val + N'%'' COLLATE Latin1_General_CI_AS' WHEN '$startsWithIgnoreCase' THEN N'dv._String LIKE N''' + @dict_idx_safe_val + N'%'' COLLATE Latin1_General_CI_AS' WHEN '$endsWithIgnoreCase' THEN N'dv._String LIKE N''%' + @dict_idx_safe_val + N''' COLLATE Latin1_General_CI_AS' ELSE CASE @dict_idx_db_type WHEN 'Long' THEN N'dv._Long = ' + @dict_idx_val WHEN 'Numeric' THEN N'dv._Numeric = ' + @dict_idx_val WHEN 'Double' THEN N'dv.[_Double] = ' + @dict_idx_val ELSE N'dv._String = N''' + @dict_idx_safe_val + N'''' END END; END; SET @dict_idx_condition = N'EXISTS (SELECT 1 FROM _values dv WHERE dv._id_object = ' + @table_alias + N'._id ' + N'AND dv._id_structure = ' + CAST(@dict_idx_structure_id AS NVARCHAR(20)) + N' ' + N'AND dv._array_index = N''' + REPLACE(@dict_idx_key, '''', '''''') + N''' ' + N'AND ' + @dict_idx_value_cond + N')'; INSERT INTO @conditions (condition) VALUES (@dict_idx_condition); FETCH NEXT FROM dict_idx_cursor INTO @dict_idx_op, @dict_idx_val, @dict_idx_val_type; END; CLOSE dict_idx_cursor; DEALLOCATE dict_idx_cursor; END ELSE BEGIN -- Simple value: direct equality (use db_type for correct column) SET @dict_idx_safe_val = REPLACE(@value, '''', ''''''); SET @dict_idx_condition = N'EXISTS (SELECT 1 FROM _values dv WHERE dv._id_object = ' + @table_alias + N'._id ' + N'AND dv._id_structure = ' + CAST(@dict_idx_structure_id AS NVARCHAR(20)) + N' ' + N'AND dv._array_index = N''' + REPLACE(@dict_idx_key, '''', '''''') + N''' ' + N'AND ' + CASE @dict_idx_db_type WHEN 'Long' THEN N'dv._Long = ' + @value WHEN 'Numeric' THEN N'dv._Numeric = ' + @value WHEN 'Double' THEN N'dv.[_Double] = ' + @value ELSE N'dv._String = N''' + @dict_idx_safe_val + N'''' END + N')'; INSERT INTO @conditions (condition) VALUES (@dict_idx_condition); END; END; END -- Dictionary ContainsKey: FieldName.ContainsKey (e.g.: "PhoneBook.ContainsKey": "home") ELSE IF @key LIKE '%.ContainsKey' BEGIN DECLARE @dict_field_name NVARCHAR(450) = LEFT(@key, LEN(@key) - LEN('.ContainsKey')); DECLARE @dict_key NVARCHAR(450); DECLARE @dict_structure_id BIGINT; -- Get the key value (handle both {"$eq": "key"} and "key") IF @type = 5 AND JSON_VALUE(@value, '$."$eq"') IS NOT NULL SET @dict_key = JSON_VALUE(@value, '$."$eq"'); ELSE SET @dict_key = @value; -- Remove quotes from string value SET @dict_key = REPLACE(REPLACE(@dict_key, '"', ''), '''', ''); -- Find structure for dictionary field SELECT @dict_structure_id = _id FROM _structures WHERE _id_scheme = @scheme_id AND _name = @dict_field_name AND _id_parent IS NULL; IF @dict_structure_id IS NOT NULL BEGIN -- Build EXISTS condition -- Check BOTH cases: -- 1) Dictionary: records in the structure itself (_id_structure = dict_id) -- 2) Dictionary: records in child structures (_id_parent = dict_id) INSERT INTO @conditions (condition) VALUES ( N'EXISTS (SELECT 1 FROM _values dv JOIN _structures s ON dv._id_structure = s._id ' + N'WHERE dv._id_object = ' + @table_alias + N'._id ' + N'AND (s._id = ' + CAST(@dict_structure_id AS NVARCHAR(20)) + N' OR s._id_parent = ' + CAST(@dict_structure_id AS NVARCHAR(20)) + N') ' + N'AND dv._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''')' ); END; END -- Props field ELSE IF @key NOT LIKE '$%' BEGIN IF @type = 5 -- object with operators BEGIN DECLARE op_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@value); OPEN op_cursor; FETCH NEXT FROM op_cursor INTO @op_name, @op_value, @op_type; WHILE @@FETCH_STATUS = 0 BEGIN SET @op_value_type = CASE @op_type WHEN 1 THEN 'string' WHEN 2 THEN 'number' WHEN 3 THEN 'boolean' WHEN 4 THEN 'array' ELSE 'string' END; EXEC dbo.internal_build_exists @scheme_id, @key, @op_name, @op_value, @op_value_type, @table_alias, @exists_sql OUTPUT; IF @exists_sql IS NOT NULL AND @exists_sql <> N'' AND @exists_sql <> N'1=1' INSERT INTO @conditions (condition) VALUES (@exists_sql); FETCH NEXT FROM op_cursor INTO @op_name, @op_value, @op_type; END; CLOSE op_cursor; DEALLOCATE op_cursor; END ELSE IF @type = 4 -- array - treat as $in BEGIN EXEC dbo.internal_build_exists @scheme_id, @key, '$in', @value, 'array', @table_alias, @exists_sql OUTPUT; IF @exists_sql IS NOT NULL AND @exists_sql <> N'' AND @exists_sql <> N'1=1' INSERT INTO @conditions (condition) VALUES (@exists_sql); END ELSE BEGIN -- Simple value - treat as $eq SET @op_value_type = CASE @type WHEN 1 THEN 'string' WHEN 2 THEN 'number' WHEN 3 THEN 'boolean' ELSE 'string' END; EXEC dbo.internal_build_exists @scheme_id, @key, '$eq', @value, @op_value_type, @table_alias, @exists_sql OUTPUT; IF @exists_sql IS NOT NULL AND @exists_sql <> N'' AND @exists_sql <> N'1=1' INSERT INTO @conditions (condition) VALUES (@exists_sql); END; END; FETCH NEXT FROM json_cursor INTO @key, @value, @type; END; CLOSE json_cursor; DEALLOCATE json_cursor; -- Combine all conditions (separator must be variable, not expression) SET @separator = N' ' + @logical_op + N' '; SELECT @result = STRING_AGG(condition, @separator) FROM @conditions; IF @result IS NULL SET @result = N''; END; GO -- ===================================================== -- HELPER: build_facet_field_path -- Returns full field path including parent structures -- ===================================================== CREATE FUNCTION dbo.build_facet_field_path( @structure_id BIGINT, @scheme_id BIGINT ) RETURNS NVARCHAR(500) AS BEGIN DECLARE @path NVARCHAR(500) = N''; DECLARE @current_id BIGINT = @structure_id; DECLARE @current_name NVARCHAR(450); DECLARE @parent_id BIGINT; DECLARE @collection_type BIGINT; DECLARE @depth INT = 0; WHILE @current_id IS NOT NULL AND @depth < 10 BEGIN SELECT @current_name = _name, @parent_id = _parent_structure_id, @collection_type = _collection_type FROM _scheme_metadata_cache WHERE _structure_id = @current_id AND _scheme_id = @scheme_id; IF @current_name IS NOT NULL BEGIN IF @path = N'' SET @path = @current_name + CASE WHEN @collection_type IS NOT NULL THEN N'[]' ELSE N'' END; ELSE SET @path = @current_name + CASE WHEN @collection_type IS NOT NULL THEN N'[]' ELSE N'' END + N'.' + @path; END; SET @current_id = @parent_id; SET @depth = @depth + 1; END; RETURN @path; END; GO -- ===================================================== -- get_facets: Get facet values for a scheme -- Basic version for backward compatibility -- ===================================================== CREATE PROCEDURE dbo.get_facets @scheme_id BIGINT, @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; -- Ensure metadata cache is populated IF NOT EXISTS (SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id) BEGIN EXEC dbo.sync_metadata_cache_for_scheme @scheme_id; END; DECLARE @facets TABLE (field_name NVARCHAR(450), field_values NVARCHAR(MAX)); INSERT INTO @facets (field_name, field_values) SELECT c._name, N'[' + ISNULL(STRING_AGG( CASE WHEN c.db_type = 'String' THEN N'"' + REPLACE(REPLACE(v._String, N'\', N'\\'), N'"', N'\"') + N'"' WHEN c.db_type = 'Long' AND c.type_semantic <> '_RObject' THEN CAST(v._Long AS NVARCHAR(30)) WHEN c.db_type = 'Boolean' THEN CASE WHEN v._Boolean = 1 THEN 'true' ELSE 'false' END WHEN c.db_type = 'Double' THEN FORMAT(v._Double, 'G', 'en-US') ELSE N'"' + REPLACE(REPLACE(ISNULL(v._String, ''), N'\', N'\\'), N'"', N'\"') + N'"' END , N','), N'') + N']' FROM _scheme_metadata_cache c LEFT JOIN ( SELECT DISTINCT v._id_structure, v._String, v._Long, v._Boolean, v._Double FROM _values v JOIN _objects o ON o._id = v._id_object WHERE o._id_scheme = @scheme_id AND v._array_index IS NULL ) v ON v._id_structure = c._structure_id WHERE c._scheme_id = @scheme_id AND c._parent_structure_id IS NULL AND c.db_type NOT IN ('Guid', 'ByteArray') GROUP BY c._name HAVING COUNT(DISTINCT ISNULL(v._String, CAST(v._Long AS NVARCHAR(30)))) <= 100; SELECT @result = N'{' + ISNULL(STRING_AGG(N'"' + field_name + N'":' + field_values, N','), N'') + N'}' FROM @facets; IF @result IS NULL SET @result = N'{}'; END; GO -- ===================================================== -- get_facets_extended: Get facet values with options -- Supports: filtering, limiting, specific fields, nested fields -- ===================================================== IF OBJECT_ID('dbo.get_facets_extended', 'P') IS NOT NULL DROP PROCEDURE dbo.get_facets_extended; GO CREATE PROCEDURE dbo.get_facets_extended @scheme_id BIGINT, @fields NVARCHAR(MAX) = NULL, -- JSON array of field names to include, NULL = all @max_values_per_field INT = 100, -- Max unique values per facet @include_counts BIT = 0, -- Include count of objects per value @include_nested BIT = 0, -- Include nested Class fields @filter_prefix NVARCHAR(100) = NULL, -- Filter fields by prefix @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; -- Ensure metadata cache is populated IF NOT EXISTS (SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id) BEGIN EXEC dbo.sync_metadata_cache_for_scheme @scheme_id; END; DECLARE @facets TABLE ( field_path NVARCHAR(500), field_values NVARCHAR(MAX), total_count INT ); -- Build field list DECLARE @field_filter TABLE (field_name NVARCHAR(450)); IF @fields IS NOT NULL AND @fields <> N'' AND @fields <> N'[]' BEGIN INSERT INTO @field_filter (field_name) SELECT [value] FROM OPENJSON(@fields); END; -- Get facets for root fields INSERT INTO @facets (field_path, field_values, total_count) SELECT c._name + CASE WHEN c._collection_type IS NOT NULL THEN N'[]' ELSE N'' END, N'[' + ISNULL(STRING_AGG( CASE WHEN c.db_type = 'String' THEN N'"' + REPLACE(REPLACE(v._String, N'\', N'\\'), N'"', N'\"') + N'"' WHEN c.db_type = 'Long' AND c.type_semantic <> '_RObject' THEN CAST(v._Long AS NVARCHAR(30)) WHEN c.db_type = 'Boolean' THEN CASE WHEN v._Boolean = 1 THEN 'true' ELSE 'false' END WHEN c.db_type = 'Double' THEN FORMAT(v._Double, 'G', 'en-US') WHEN c.db_type = 'ListItem' THEN N'"' + REPLACE(REPLACE(ISNULL(li._value, ''), N'\', N'\\'), N'"', N'\"') + N'"' ELSE N'"' + REPLACE(REPLACE(ISNULL(v._String, ''), N'\', N'\\'), N'"', N'\"') + N'"' END , N','), N'') + N']', COUNT(DISTINCT v._id_object) FROM _scheme_metadata_cache c LEFT JOIN ( SELECT DISTINCT v._id_structure, v._id_object, v._String, v._Long, v._Boolean, v._Double, v._listitem FROM _values v JOIN _objects o ON o._id = v._id_object WHERE o._id_scheme = @scheme_id ) v ON v._id_structure = c._structure_id LEFT JOIN _list_items li ON c.type_semantic = '_RListItem' AND li._id = v._listitem WHERE c._scheme_id = @scheme_id AND (@include_nested = 1 OR c._parent_structure_id IS NULL) AND c.db_type NOT IN ('Guid', 'ByteArray') AND (@filter_prefix IS NULL OR c._name LIKE @filter_prefix + N'%') AND (NOT EXISTS (SELECT 1 FROM @field_filter) OR c._name IN (SELECT field_name FROM @field_filter)) GROUP BY c._name, c._collection_type, c.db_type, c.type_semantic HAVING COUNT(DISTINCT COALESCE(v._String, CAST(v._Long AS NVARCHAR(30)), li._value)) <= @max_values_per_field; -- Build result JSON IF @include_counts = 1 BEGIN SELECT @result = N'{' + ISNULL(STRING_AGG( N'"' + field_path + N'":{"values":' + field_values + N',"count":' + CAST(total_count AS NVARCHAR(20)) + N'}' , N','), N'') + N'}' FROM @facets; END ELSE BEGIN SELECT @result = N'{' + ISNULL(STRING_AGG(N'"' + field_path + N'":' + field_values, N','), N'') + N'}' FROM @facets; END; IF @result IS NULL SET @result = N'{}'; END; GO -- ===================================================== -- MAIN: search_objects_with_facets -- Full featured search with all operators -- ===================================================== CREATE PROCEDURE dbo.search_objects_with_facets @scheme_id BIGINT, @facet_filters NVARCHAR(MAX) = NULL, @limit_count INT = NULL, @offset_count INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_recursion_depth INT = 10, @include_facets BIT = 0, @distinct_hash BIT = 0 AS BEGIN SET NOCOUNT ON; -- Ensure metadata cache is populated IF NOT EXISTS (SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id) BEGIN EXEC dbo.sync_metadata_cache_for_scheme @scheme_id; END; -- Parse filters DECLARE @where_clause NVARCHAR(MAX) = N''; IF @facet_filters IS NOT NULL AND @facet_filters <> N'' AND @facet_filters <> N'{}' AND @facet_filters <> N'null' BEGIN EXEC dbo.internal_parse_filters @scheme_id, @facet_filters, N'o', N'AND', 0, @where_clause OUTPUT; END; -- Build ORDER BY clause using unified function -- Format: [{"field": "Name", "direction": "ASC"}] - extended format from C# DECLARE @order_clause NVARCHAR(MAX) = N'ORDER BY o._id'; IF @order_by IS NOT NULL AND @order_by <> N'' AND @order_by <> N'[]' AND @order_by <> N'null' BEGIN SET @order_clause = dbo.build_order_by_clause(@order_by, N'o'); IF @order_clause IS NULL OR @order_clause = N'' SET @order_clause = N'ORDER BY o._id'; END; -- Build and execute query DECLARE @sql NVARCHAR(MAX); DECLARE @count_sql NVARCHAR(MAX); DECLARE @total_count INT; SET @sql = N'INSERT INTO #temp_ids (_id) SELECT ' + CASE WHEN @distinct_hash = 1 THEN 'DISTINCT' ELSE '' END + N' o._id FROM _objects o WHERE o._id_scheme = @p_scheme_id ' + CASE WHEN @where_clause <> N'' THEN N' AND ' + @where_clause ELSE N'' END + N' ' + @order_clause; IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; -- Allow ORDER BY without FETCH for count queries SET @sql = @sql + N'; SELECT @p_count = @@ROWCOUNT;'; -- Count query SET @count_sql = N'SELECT @p_total = COUNT(' + CASE WHEN @distinct_hash = 1 THEN 'DISTINCT o._hash' ELSE '*' END + N') FROM _objects o WHERE o._id_scheme = @p_scheme_id ' + CASE WHEN @where_clause <> N'' THEN N' AND ' + @where_clause ELSE N'' END; -- Execute (use _sort_order to preserve ORDER BY) CREATE TABLE #temp_ids (_sort_order INT IDENTITY(1,1), _id BIGINT); DECLARE @row_count INT; -- OPTIMIZATION: For CountAsync (limit = 0), only execute count query, skip temp table creation IF @limit_count IS NULL OR @limit_count > 0 BEGIN EXEC sp_executesql @sql, N'@p_scheme_id BIGINT, @p_count INT OUTPUT', @p_scheme_id = @scheme_id, @p_count = @row_count OUTPUT; END; EXEC sp_executesql @count_sql, N'@p_scheme_id BIGINT, @p_total INT OUTPUT', @p_scheme_id = @scheme_id, @p_total = @total_count OUTPUT; -- Build result JSON using function (no cursor - much faster!) DECLARE @objects_json NVARCHAR(MAX) = N'[]'; DECLARE @facets_json NVARCHAR(MAX) = N'{}'; -- OPTIMIZATION: Skip loading objects if limit = 0 (CountAsync case) IF @limit_count IS NULL OR @limit_count > 0 BEGIN -- STRING_AGG with WITHIN GROUP to preserve ORDER BY from INSERT SELECT @objects_json = N'[' + ISNULL(STRING_AGG( dbo.get_object_json(t._id, @max_recursion_depth), N',' ) WITHIN GROUP (ORDER BY t._sort_order), N'') + N']' FROM #temp_ids t; END; IF @include_facets = 1 EXEC dbo.get_facets @scheme_id, @facets_json OUTPUT; -- Return result with NULL protection SELECT N'{"objects":' + ISNULL(@objects_json, N'[]') + N',"total_count":' + CAST(ISNULL(@total_count, 0) AS NVARCHAR(20)) + N',"limit":' + ISNULL(CAST(@limit_count AS NVARCHAR(20)), N'null') + N',"offset":' + CAST(ISNULL(@offset_count, 0) AS NVARCHAR(20)) + N',"facets":' + ISNULL(@facets_json, N'[]') + N'}' AS result; DROP TABLE #temp_ids; END; GO -- ===================================================== -- search_tree_objects_with_facets -- Search children/descendants with filters -- Supports MULTIPLE parent_ids (comma-separated string) -- ===================================================== CREATE PROCEDURE dbo.search_tree_objects_with_facets @scheme_id BIGINT, @parent_ids NVARCHAR(MAX), -- Comma-separated list of parent IDs (e.g. '123,456,789') or NULL/empty for global search @facet_filters NVARCHAR(MAX) = NULL, @limit_count INT = NULL, @offset_count INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_depth INT = 10, @max_recursion_depth INT = 10, @include_facets BIT = 0 AS BEGIN SET NOCOUNT ON; IF NOT EXISTS (SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id) EXEC dbo.sync_metadata_cache_for_scheme @scheme_id; DECLARE @where_clause NVARCHAR(MAX) = N''; IF @facet_filters IS NOT NULL AND @facet_filters <> N'' AND @facet_filters <> N'{}' AND @facet_filters <> N'null' EXEC dbo.internal_parse_filters @scheme_id, @facet_filters, N'd', N'AND', 0, @where_clause OUTPUT; -- Build ORDER BY clause from @order_by parameter (use 'd' alias) DECLARE @order_clause NVARCHAR(MAX) = N'ORDER BY d._id'; IF @order_by IS NOT NULL AND @order_by <> N'' AND @order_by <> N'[]' AND @order_by <> N'null' BEGIN SET @order_clause = dbo.build_order_by_clause(@order_by, N'd'); IF @order_clause IS NULL OR @order_clause = N'' SET @order_clause = N'ORDER BY d._id'; END; DECLARE @sql NVARCHAR(MAX); DECLARE @total_count INT; DECLARE @objects_json NVARCHAR(MAX); DECLARE @facets_json NVARCHAR(MAX) = N'{}'; -- Use temp table with sort_order to preserve ORDER BY CREATE TABLE #tree_ids (_sort_order INT IDENTITY(1,1), _id BIGINT); -- Check if parent_ids is empty or NULL - global search mode DECLARE @has_parents BIT = CASE WHEN @parent_ids IS NULL OR LTRIM(RTRIM(@parent_ids)) = N'' THEN 0 ELSE 1 END; -- CASE 1: Global search (no parent_ids) - search entire scheme with hierarchical filters IF @has_parents = 0 BEGIN SET @sql = N'INSERT INTO #tree_ids (_id) SELECT d._id FROM _objects d WHERE d._id_scheme = @p_scheme ' + CASE WHEN @where_clause <> N'' THEN N' AND ' + @where_clause ELSE N'' END + N' ' + @order_clause; IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; END -- CASE 2: Direct children only (max_depth = 1) ELSE IF @max_depth = 1 BEGIN SET @sql = N'INSERT INTO #tree_ids (_id) SELECT d._id FROM _objects d WHERE d._id_scheme = @p_scheme AND d._id_parent IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@p_parents, N'','') WHERE LTRIM(RTRIM(value)) <> N'''') ' + CASE WHEN @where_clause <> N'' THEN N' AND ' + @where_clause ELSE N'' END + N' ' + @order_clause; IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; END -- CASE 3: Recursive descendants from multiple parents ELSE BEGIN SET @sql = N';WITH descendants AS ( SELECT CAST(value AS BIGINT) AS _id, 0 AS depth FROM STRING_SPLIT(@p_parents, N'','') WHERE LTRIM(RTRIM(value)) <> N'''' UNION ALL SELECT o._id, d.depth + 1 FROM _objects o JOIN descendants d ON o._id_parent = d._id WHERE d.depth < ' + CAST(@max_depth AS NVARCHAR(10)) + N' ) INSERT INTO #tree_ids (_id) SELECT d._id FROM descendants dt JOIN _objects d ON dt._id = d._id WHERE dt.depth > 0 AND d._id_scheme = @p_scheme ' + CASE WHEN @where_clause <> N'' THEN N' AND ' + @where_clause ELSE N'' END + N' ' + @order_clause; IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; END; -- Execute the query EXEC sp_executesql @sql, N'@p_scheme BIGINT, @p_parents NVARCHAR(MAX)', @p_scheme = @scheme_id, @p_parents = @parent_ids; SELECT @total_count = COUNT(*) FROM #tree_ids; -- Build JSON using function with ORDER BY to preserve sort order! SET @objects_json = N'[]'; -- OPTIMIZATION: Skip loading objects if limit = 0 (CountAsync case) IF @limit_count IS NULL OR @limit_count > 0 BEGIN -- STRING_AGG with WITHIN GROUP to preserve order from INSERT SELECT @objects_json = N'[' + ISNULL(STRING_AGG( dbo.get_object_json(t._id, @max_recursion_depth), N',' ) WITHIN GROUP (ORDER BY t._sort_order), N'') + N']' FROM #tree_ids t; END; IF @include_facets = 1 EXEC dbo.get_facets @scheme_id, @facets_json OUTPUT; -- Return result with NULL protection SELECT N'{"objects":' + ISNULL(@objects_json, N'[]') + N',"total_count":' + CAST(ISNULL(@total_count, 0) AS NVARCHAR(20)) + N',"limit":' + ISNULL(CAST(@limit_count AS NVARCHAR(20)), N'null') + N',"offset":' + CAST(ISNULL(@offset_count, 0) AS NVARCHAR(20)) + N',"parent_ids":"' + ISNULL(@parent_ids, N'') + N'"' + N',"max_depth":' + CAST(ISNULL(@max_depth, 10) AS NVARCHAR(10)) + N',"facets":' + ISNULL(@facets_json, N'[]') + N'}' AS result; DROP TABLE #tree_ids; END; GO PRINT '=============================================================' PRINT 'FULL Facets Search Module Created!' PRINT '' PRINT 'MAIN PROCEDURES:' PRINT ' search_objects_with_facets - Search with JSON filters' PRINT ' search_tree_objects_with_facets - Search in hierarchy' PRINT ' get_facets - Get facet values for scheme' PRINT '' PRINT 'HELPER FUNCTIONS:' PRINT ' get_object_level(object_id) - Get hierarchy level' PRINT ' is_ancestor_of(object_id, anc_id) - Check ancestor' PRINT ' is_descendant_of(object_id, desc_id) - Check descendant' PRINT ' normalize_base_field_name(name) - Map field names' PRINT ' get_value_column_by_type(type,sem) - Get value column' PRINT '' PRINT 'OPERATORS SUPPORTED:' PRINT ' Comparison: $eq, $ne, $gt, $gte, $lt, $lte' PRINT ' String: $contains, $startsWith, $endsWith (+ IgnoreCase)' PRINT ' List: $in, $exists' PRINT ' Logical: $and, $or, $not' PRINT ' Array: $arrayContains, $arrayAny, $arrayEmpty, $arrayCount*' PRINT ' Hierarchy: $isRoot, $isLeaf, $hasAncestor, $hasDescendant, $level' PRINT '' PRINT 'FIELD TYPES SUPPORTED:' PRINT ' Base fields: 0$:name, 0$:date_create, etc.' PRINT ' Simple fields: Status, Name' PRINT ' Class fields: Contact.Name, Address.City' PRINT ' Arrays: Tags[], Contacts[].Email' PRINT ' Dictionary: PhoneBook[home], Settings[theme]' PRINT '' PRINT 'USAGE EXAMPLE:' PRINT ' EXEC search_objects_with_facets ' PRINT ' @scheme_id = 1,' PRINT ' @facet_filters = N''{"Status":{"$eq":"Active"},"$and":[{"Age":{"$gte":18}}]}''' PRINT ' preview_facet_query - Show generated SQL (debug)' PRINT '=============================================================' GO -- ===================================================== -- DEBUG: preview_facet_query -- Shows generated SQL without execution (for debugging) -- ===================================================== CREATE PROCEDURE dbo.preview_facet_query @scheme_id BIGINT, @facet_filters NVARCHAR(MAX) = NULL AS BEGIN SET NOCOUNT ON; -- Diagnostics DECLARE @cache_count INT; DECLARE @scheme_exists BIT = 0; DECLARE @cache_populated BIT = 0; -- Check if scheme exists IF EXISTS (SELECT 1 FROM _schemes WHERE _id = @scheme_id) SET @scheme_exists = 1; -- Check cache before sync SELECT @cache_count = COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id; -- Ensure metadata cache is populated IF @cache_count = 0 BEGIN EXEC dbo.sync_metadata_cache_for_scheme @scheme_id; SELECT @cache_count = COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id; IF @cache_count > 0 SET @cache_populated = 1; END ELSE SET @cache_populated = 1; -- Parse filters DECLARE @where_clause NVARCHAR(MAX) = N''; IF @facet_filters IS NOT NULL AND @facet_filters <> N'' AND @facet_filters <> N'{}' AND @facet_filters <> N'null' BEGIN EXEC dbo.internal_parse_filters @scheme_id, @facet_filters, N'o', N'AND', 0, @where_clause OUTPUT; END; -- Build preview SQL DECLARE @preview_sql NVARCHAR(MAX); SET @preview_sql = N'SELECT o._id, o._name, o._id_scheme FROM _objects o WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' '; IF @where_clause IS NOT NULL AND @where_clause <> N'' SET @preview_sql = @preview_sql + N' AND ' + @where_clause; SET @preview_sql = @preview_sql + N' ORDER BY o._id'; -- Return preview with diagnostics SELECT @scheme_id AS scheme_id, @scheme_exists AS scheme_exists, @cache_count AS metadata_cache_entries, @cache_populated AS cache_ok, @facet_filters AS input_filters, @where_clause AS generated_where_clause, @preview_sql AS full_sql_preview; -- Also return available fields in cache for debugging SELECT _name AS field_name, db_type, type_semantic, CASE WHEN _collection_type IS NOT NULL THEN 'Array/Dict' ELSE 'Simple' END AS field_type, CASE WHEN _parent_structure_id IS NULL THEN 'Root' ELSE 'Nested' END AS level FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id ORDER BY CASE WHEN _parent_structure_id IS NULL THEN 0 ELSE 1 END, _name; END; GO PRINT 'preview_facet_query procedure created!' GO -- ===================================================== -- DEBUG: preview_tree_facet_query -- Shows generated SQL for tree search (for debugging) -- ===================================================== IF OBJECT_ID('dbo.preview_tree_facet_query', 'P') IS NOT NULL DROP PROCEDURE dbo.preview_tree_facet_query; GO CREATE PROCEDURE dbo.preview_tree_facet_query @scheme_id BIGINT, @parent_id BIGINT, @facet_filters NVARCHAR(MAX) = NULL, @max_depth INT = 10 AS BEGIN SET NOCOUNT ON; -- Diagnostics DECLARE @cache_count INT; DECLARE @scheme_exists BIT = 0; DECLARE @parent_exists BIT = 0; DECLARE @cache_populated BIT = 0; -- Check if scheme exists IF EXISTS (SELECT 1 FROM _schemes WHERE _id = @scheme_id) SET @scheme_exists = 1; -- Check if parent object exists (NULL = global search, always valid) IF @parent_id IS NULL SET @parent_exists = 1; ELSE IF EXISTS (SELECT 1 FROM _objects WHERE _id = @parent_id) SET @parent_exists = 1; -- Check cache SELECT @cache_count = COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id; IF @cache_count = 0 BEGIN EXEC dbo.sync_metadata_cache_for_scheme @scheme_id; SELECT @cache_count = COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id; IF @cache_count > 0 SET @cache_populated = 1; END ELSE SET @cache_populated = 1; -- Parse filters DECLARE @where_clause NVARCHAR(MAX) = N''; IF @facet_filters IS NOT NULL AND @facet_filters <> N'' AND @facet_filters <> N'{}' AND @facet_filters <> N'null' BEGIN EXEC dbo.internal_parse_filters @scheme_id, @facet_filters, N'd', N'AND', 0, @where_clause OUTPUT; END; -- Build preview SQL DECLARE @preview_sql NVARCHAR(MAX); -- CASE 1: Global search (no parent_id) IF @parent_id IS NULL BEGIN SET @preview_sql = N'-- Global search (no parent_id) SELECT d._id, d._name, d._id_parent FROM _objects d WHERE d._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' '; END -- CASE 2: Direct children only ELSE IF @max_depth = 1 BEGIN SET @preview_sql = N'SELECT d._id, d._name, d._id_parent FROM _objects d WHERE d._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' AND d._id_parent = ' + CAST(@parent_id AS NVARCHAR(20)) + N' '; END -- CASE 3: Recursive descendants with CTE ELSE BEGIN SET @preview_sql = N';WITH descendants AS ( SELECT ' + CAST(@parent_id AS NVARCHAR(20)) + N' AS _id, 0 AS depth UNION ALL SELECT o._id, d.depth + 1 FROM _objects o JOIN descendants d ON o._id_parent = d._id WHERE d.depth < ' + CAST(@max_depth AS NVARCHAR(10)) + N' ) SELECT d._id, d._name, d._id_parent, dt.depth FROM descendants dt JOIN _objects d ON dt._id = d._id WHERE dt.depth > 0 AND d._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' '; END; IF @where_clause IS NOT NULL AND @where_clause <> N'' SET @preview_sql = @preview_sql + N' AND ' + @where_clause; SET @preview_sql = @preview_sql + N' ORDER BY d._id'; -- Return preview with diagnostics SELECT @scheme_id AS scheme_id, @parent_id AS parent_id, @max_depth AS max_depth, @scheme_exists AS scheme_exists, @parent_exists AS parent_exists, @cache_count AS metadata_cache_entries, @cache_populated AS cache_ok, @facet_filters AS input_filters, @where_clause AS generated_where_clause, @preview_sql AS full_sql_preview; -- Return fields in cache SELECT _name AS field_name, db_type, type_semantic, CASE WHEN _collection_type IS NOT NULL THEN 'Array/Dict' ELSE 'Simple' END AS field_type, CASE WHEN _parent_structure_id IS NULL THEN 'Root' ELSE 'Nested' END AS level FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id ORDER BY CASE WHEN _parent_structure_id IS NULL THEN 0 ELSE 1 END, _name; END; GO PRINT 'preview_tree_facet_query procedure created!' GO -- ===================================================== -- SUMMARY AND USAGE EXAMPLES -- ===================================================== PRINT '=============================================================' PRINT 'REDB FACETS SEARCH MODULE FOR MSSQL - COMPLETE!' PRINT '' PRINT 'MAIN PROCEDURES:' PRINT ' search_objects_with_facets - Full featured search with JSON filters' PRINT ' search_tree_objects_with_facets - Search children/descendants' PRINT ' get_facets - Get unique values for UI filters' PRINT ' get_facets_extended - Extended facets with options' PRINT ' preview_facet_query - Debug: show generated SQL' PRINT ' preview_tree_facet_query - Debug: show tree search SQL' PRINT '' PRINT 'HELPER FUNCTIONS:' PRINT ' normalize_base_field_name - Map C# names to SQL columns' PRINT ' get_value_column_by_type - Get _values column for db_type' PRINT ' get_object_level - Get hierarchy level (0=root)' PRINT ' is_ancestor_of - Check if object is ancestor' PRINT ' is_descendant_of - Check if object is descendant' PRINT ' build_facet_field_path - Build full field path for facets' PRINT '' PRINT 'SUPPORTED OPERATORS:' PRINT ' Comparison: $eq, $ne, $gt, $gte, $lt, $lte' PRINT ' Lists: $in, $notIn, $between' PRINT ' String: $contains, $startsWith, $endsWith (+IgnoreCase)' PRINT ' Pattern: $like, $likeIgnoreCase (MSSQL alternative to $regex)' PRINT ' Full-Text: $match, $matchPrefix (requires FTS catalog)' PRINT ' Logical: $and, $or, $not' PRINT ' Array: $arrayContains, $arrayAny, $arrayEmpty, $arrayCount*' PRINT ' Array Ext: $arrayFirst, $arrayLast, $arrayAt, $arrayStartsWith, $arrayEndsWith' PRINT ' Array Agg: $arraySum, $arrayAvg, $arrayMin, $arrayMax (+Gt/Gte/Lt/Lte)' PRINT ' Hierarchy: $isRoot, $isLeaf, $hasAncestor, $hasDescendant, $level' PRINT ' Existence: $exists' PRINT '' PRINT 'FIELD TYPES:' PRINT ' Base fields (0$:): 0$:name, 0$:date_create, 0$:id_parent, etc.' PRINT ' Simple fields: Status, Name, Age' PRINT ' Class fields: Contact.Name, Address.City' PRINT ' Arrays: Tags[], Contacts[].Email' PRINT ' Dictionary: PhoneBook[home], Settings[theme]' PRINT ' ListItem: Status.Value, Roles[].Alias' PRINT '' PRINT 'SMART TYPE DETECTION:' PRINT ' Numbers -> checks Long, Double, Numeric columns' PRINT ' Booleans (true/false) -> checks _Boolean column' PRINT ' Dates (YYYY-MM-DD...) -> checks _DateTimeOffset column' PRINT ' GUIDs -> checks _Guid column' PRINT ' Strings -> checks _String column' PRINT '' PRINT 'ORDER BY OPTIONS:' PRINT ' Simple: [{"field": "asc"}, {"0$:date_create": "desc"}]' PRINT ' With nulls: [{"field": {"dir": "asc", "nulls": "first"}}]' PRINT '=============================================================' GO /* ===== USAGE EXAMPLES ===== -- 1. Basic search with filters: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"Status": {"$eq": "Active"}, "Age": {"$gte": 18}}'; -- 2. Complex AND/OR logic: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{ "$and": [ {"Status": {"$eq": "Active"}}, {"$or": [ {"City": {"$eq": "Moscow"}}, {"City": {"$eq": "SPb"}} ]} ] }'; -- 3. Array operators: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{ "Tags[]": {"$arrayContains": "vip"}, "Scores[]": {"$arrayCountGt": 3} }'; -- 4. Class fields (nested): EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{ "Contact.Name": {"$contains": "John"}, "Address.City": {"$in": ["Moscow", "SPb"]} }'; -- 5. Hierarchical search: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"$isRoot": true, "$hasDescendant": {"scheme_id": 2}}'; -- 6. Base fields (RedbObject columns): EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{ "0$:name": {"$startsWith": "Test"}, "0$:date_create": {"$gte": "2024-01-01"} }'; -- 7. Dictionary access: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"PhoneBook[home]": {"$eq": "+7-999-123-45-67"}}'; -- 8. With sorting and pagination: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"Status": {"$eq": "Active"}}', @limit_count = 10, @offset_count = 0, @order_by = N'[{"0$:date_create": "desc"}]'; -- 9. Debug preview (shows generated SQL): EXEC preview_facet_query @scheme_id = 1, @facet_filters = N'{"Status": {"$eq": "Active"}}'; -- 10. Tree search (children of parent): EXEC search_tree_objects_with_facets @scheme_id = 1, @parent_id = 100, @max_depth = 1; -- direct children only -- 10a. Global tree search (all objects with hierarchical filters): EXEC search_tree_objects_with_facets @scheme_id = 1, @parent_id = NULL, -- NULL = search entire scheme @facet_filters = N'{"$isRoot": true}'; -- find all root objects -- 10b. Find all leaf objects (no children): EXEC search_tree_objects_with_facets @scheme_id = 1, @parent_id = NULL, @facet_filters = N'{"$isLeaf": true}'; -- 11. Between operator (date range): EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"0$:date_create": {"$between": ["2024-01-01", "2024-12-31"]}}'; -- 12. Not In operator: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"Status": {"$notIn": ["Deleted", "Archived"]}}'; -- 13. Full-Text Search (requires FTS catalog): EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"Description": {"$match": "important AND urgent"}}'; -- 14. LIKE patterns (alternative to regex): EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"Email": {"$like": "%@company.com"}}'; -- 15. Sorting with NULLS handling: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{}', @order_by = N'[{"Priority": {"dir": "asc", "nulls": "last"}}, {"0$:date_create": "desc"}]'; -- 16. Extended facets with options: DECLARE @facets NVARCHAR(MAX); EXEC get_facets_extended @scheme_id = 1, @fields = N'["Status", "City", "Tags"]', @max_values_per_field = 50, @include_counts = 1, @result = @facets OUTPUT; SELECT @facets; -- 17. Tree search preview (debugging): EXEC preview_tree_facet_query @scheme_id = 1, @parent_id = 100, @max_depth = 3, @facet_filters = N'{"Status": {"$eq": "Active"}}'; -- 18. ListItem field search: EXEC search_objects_with_facets @scheme_id = 1, @facet_filters = N'{"Status.Value": {"$eq": "Active"}, "Roles[].Alias": {"$arrayContains": "Admin"}}'; */ Path: redb/redb.MSSql/sql/deprecated/redb_grouping.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.MSSql/sql/deprecated/redb_grouping.sql ---- -- ===================================================== -- REDB EAV GROUPING FUNCTIONS (MSSQL) -- GroupBy aggregations for EAV model -- Ported from PostgreSQL version -- ===================================================== SET NOCOUNT ON; GO -- ===== DROP EXISTING OBJECTS ===== IF OBJECT_ID('dbo.aggregate_grouped', 'P') IS NOT NULL DROP PROCEDURE dbo.aggregate_grouped; GO IF OBJECT_ID('dbo.aggregate_grouped_preview', 'P') IS NOT NULL DROP PROCEDURE dbo.aggregate_grouped_preview; GO IF OBJECT_ID('dbo.aggregate_array_grouped', 'P') IS NOT NULL DROP PROCEDURE dbo.aggregate_array_grouped; GO -- ===================================================== -- aggregate_grouped: GroupBy with aggregations -- ===================================================== -- Parameters: -- @scheme_id - Scheme ID -- @group_fields - JSON array of grouping fields: -- [{"field":"Category","alias":"Category"}] -- @aggregations - JSON array of aggregations: -- [{"field":"Stock","func":"SUM","alias":"TotalStock"}] -- @filter_json - JSON filter (optional) -- -- Returns: JSON array of groups -- ===================================================== CREATE PROCEDURE dbo.aggregate_grouped @scheme_id BIGINT, @group_fields NVARCHAR(MAX), @aggregations NVARCHAR(MAX), @filter_json NVARCHAR(MAX) = NULL AS BEGIN SET NOCOUNT ON; DECLARE @select_parts NVARCHAR(MAX) = N''; DECLARE @join_parts NVARCHAR(MAX) = N''; DECLARE @group_parts NVARCHAR(MAX) = N''; DECLARE @where_clause NVARCHAR(MAX) = N''; DECLARE @join_idx INT = 0; DECLARE @join_alias NVARCHAR(10); DECLARE @column_name NVARCHAR(50); DECLARE @field NVARCHAR(255); DECLARE @alias NVARCHAR(255); DECLARE @func NVARCHAR(20); DECLARE @structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @dict_key NVARCHAR(255); DECLARE @array_index NVARCHAR(50); DECLARE @array_condition NVARCHAR(500); DECLARE @sql NVARCHAR(MAX); -- ========================================= -- 1. Process grouping fields -- ========================================= DECLARE @group_cursor CURSOR; SET @group_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field, ISNULL(JSON_VALUE(value, '$.alias'), JSON_VALUE(value, '$.field')) AS alias FROM OPENJSON(@group_fields); OPEN @group_cursor; FETCH NEXT FROM @group_cursor INTO @field, @alias; WHILE @@FETCH_STATUS = 0 BEGIN IF @field IS NOT NULL BEGIN -- Check for base field (0$: prefix) IF @field LIKE N'0$:%' BEGIN DECLARE @raw_field NVARCHAR(100) = SUBSTRING(@field, 4, 100); DECLARE @sql_column NVARCHAR(100) = dbo.normalize_base_field_name(@raw_field); IF @sql_column IS NOT NULL BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + N'o.' + @sql_column + N' AS [' + REPLACE(@alias, '''', '''''') + N']'; IF @group_parts <> N'' SET @group_parts = @group_parts + N', '; SET @group_parts = @group_parts + N'o.' + @sql_column; END END ELSE BEGIN -- EAV field EXEC resolve_field_path @scheme_id, @field, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'g' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'String' THEN N'_String' WHEN N'Bool' THEN N'_Boolean' WHEN N'ListItem' THEN N'_ListItem' ELSE N'_String' END; IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @join_alias + N'.' + @column_name + N' AS [' + REPLACE(@alias, '''', '''''') + N']'; -- Build JOIN (with SQL injection protection) IF @dict_key IS NOT NULL SET @join_parts = @join_parts + N' JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''''; ELSE IF @array_index IS NOT NULL SET @join_parts = @join_parts + N' JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + REPLACE(@array_index, '''', '''''') + N''''; ELSE SET @join_parts = @join_parts + N' JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index IS NULL'; IF @group_parts <> N'' SET @group_parts = @group_parts + N', '; SET @group_parts = @group_parts + @join_alias + N'.' + @column_name; END END END FETCH NEXT FROM @group_cursor INTO @field, @alias; END CLOSE @group_cursor; DEALLOCATE @group_cursor; -- ========================================= -- 2. Process aggregations -- ========================================= DECLARE @agg_cursor CURSOR; SET @agg_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field, UPPER(JSON_VALUE(value, '$.func')) AS func, ISNULL(JSON_VALUE(value, '$.alias'), UPPER(JSON_VALUE(value, '$.func'))) AS alias FROM OPENJSON(@aggregations); OPEN @agg_cursor; FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; WHILE @@FETCH_STATUS = 0 BEGIN -- COUNT(*) special case IF @func = N'COUNT' AND (@field IS NULL OR @field = N'*' OR @field = N'') BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + N'COUNT(DISTINCT o._id) AS [' + REPLACE(@alias, '''', '''''') + N']'; FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; CONTINUE; END IF @field IS NOT NULL BEGIN -- Check for base field (0$: prefix) IF @field LIKE N'0$:%' BEGIN SET @raw_field = SUBSTRING(@field, 4, 100); SET @sql_column = dbo.normalize_base_field_name(@raw_field); IF @sql_column IS NOT NULL BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; IF @func IN (N'SUM', N'AVG') SET @select_parts = @select_parts + @func + N'(CAST(o.' + @sql_column + N' AS DECIMAL(38,10))) AS [' + REPLACE(@alias, '''', '''''') + N']'; ELSE SET @select_parts = @select_parts + @func + N'(o.' + @sql_column + N') AS [' + REPLACE(@alias, '''', '''''') + N']'; END END ELSE BEGIN -- EAV field EXEC resolve_field_path @scheme_id, @field, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'a' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' ELSE N'_Long' END; -- Build array condition IF @dict_key IS NOT NULL SET @array_condition = N' AND ' + @join_alias + N'._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''''; ELSE IF @array_index IS NOT NULL SET @array_condition = N' AND ' + @join_alias + N'._array_index = N''' + REPLACE(@array_index, '''', '''''') + N''''; ELSE IF @field NOT LIKE N'%[]%' SET @array_condition = N' AND ' + @join_alias + N'._array_index IS NULL'; ELSE SET @array_condition = N''; SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + @array_condition; IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @func + N'(CAST(' + @join_alias + N'.' + @column_name + N' AS DECIMAL(38,10))) AS [' + REPLACE(@alias, '''', '''''') + N']'; END END END FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; END CLOSE @agg_cursor; DEALLOCATE @agg_cursor; -- ========================================= -- 3. Process filter -- ========================================= IF @filter_json IS NOT NULL AND @filter_json <> N'' AND @filter_json <> N'null' BEGIN CREATE TABLE #filtered_ids (_id BIGINT PRIMARY KEY); INSERT INTO #filtered_ids EXEC get_filtered_object_ids @scheme_id, @filter_json, 10; IF NOT EXISTS (SELECT 1 FROM #filtered_ids) BEGIN SELECT N'[]' AS result; DROP TABLE #filtered_ids; RETURN; END SET @where_clause = N' AND o._id IN (SELECT _id FROM #filtered_ids)'; END -- ========================================= -- 4. Build and execute SQL -- ========================================= DECLARE @result NVARCHAR(MAX); IF @group_parts = N'' OR @group_parts IS NULL BEGIN -- No grouping (simple aggregation) - still return array for consistency SET @sql = N' SELECT @result = ( SELECT ' + @select_parts + N' FROM _objects o' + @join_parts + N' WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + @where_clause + N' FOR JSON PATH )'; END ELSE BEGIN -- With grouping SET @sql = N' SELECT @result = ( SELECT ' + @select_parts + N' FROM _objects o' + @join_parts + N' WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + @where_clause + N' GROUP BY ' + @group_parts + N' ORDER BY ' + @group_parts + N' FOR JSON PATH )'; END EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result = @result OUTPUT; -- Return with 'result' column name for C# mapping SELECT @result AS result; IF OBJECT_ID('tempdb..#filtered_ids') IS NOT NULL DROP TABLE #filtered_ids; END; GO -- ===================================================== -- aggregate_grouped_preview: SQL preview for debugging -- ===================================================== CREATE PROCEDURE dbo.aggregate_grouped_preview @scheme_id BIGINT, @group_fields NVARCHAR(MAX), @aggregations NVARCHAR(MAX), @filter_json NVARCHAR(MAX) = NULL AS BEGIN SET NOCOUNT ON; DECLARE @select_parts NVARCHAR(MAX) = N''; DECLARE @join_parts NVARCHAR(MAX) = N''; DECLARE @group_parts NVARCHAR(MAX) = N''; DECLARE @join_idx INT = 0; DECLARE @join_alias NVARCHAR(10); DECLARE @column_name NVARCHAR(50); DECLARE @field NVARCHAR(255); DECLARE @alias NVARCHAR(255); DECLARE @func NVARCHAR(20); DECLARE @structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @dict_key NVARCHAR(255); DECLARE @array_index NVARCHAR(50); DECLARE @sql NVARCHAR(MAX); -- Process grouping fields DECLARE @group_cursor CURSOR; SET @group_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field, ISNULL(JSON_VALUE(value, '$.alias'), JSON_VALUE(value, '$.field')) AS alias FROM OPENJSON(@group_fields); OPEN @group_cursor; FETCH NEXT FROM @group_cursor INTO @field, @alias; WHILE @@FETCH_STATUS = 0 BEGIN EXEC resolve_field_path @scheme_id, @field, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'g' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'String' THEN N'_String' WHEN N'ListItem' THEN N'_ListItem' ELSE N'_String' END; IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @join_alias + N'.' + @column_name + N' AS [' + REPLACE(@alias, '''', '''''') + N']'; IF @dict_key IS NOT NULL SET @join_parts = @join_parts + N' JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + REPLACE(@dict_key, '''', '''''') + N''''; ELSE IF @array_index IS NOT NULL SET @join_parts = @join_parts + N' JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + REPLACE(@array_index, '''', '''''') + N''''; ELSE SET @join_parts = @join_parts + N' JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index IS NULL'; IF @group_parts <> N'' SET @group_parts = @group_parts + N', '; SET @group_parts = @group_parts + @join_alias + N'.' + @column_name; END FETCH NEXT FROM @group_cursor INTO @field, @alias; END CLOSE @group_cursor; DEALLOCATE @group_cursor; -- Process aggregations DECLARE @agg_cursor CURSOR; SET @agg_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field, UPPER(JSON_VALUE(value, '$.func')) AS func, ISNULL(JSON_VALUE(value, '$.alias'), UPPER(JSON_VALUE(value, '$.func'))) AS alias FROM OPENJSON(@aggregations); OPEN @agg_cursor; FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; WHILE @@FETCH_STATUS = 0 BEGIN IF @func = N'COUNT' AND (@field IS NULL OR @field = N'*') BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + N'COUNT(DISTINCT o._id) AS [' + REPLACE(@alias, '''', '''''') + N']'; END ELSE IF @field IS NOT NULL BEGIN EXEC resolve_field_path @scheme_id, @field, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'a' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' ELSE N'_Numeric' END; SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index IS NULL'; IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @func + N'(' + @join_alias + N'.' + @column_name + N') AS [' + REPLACE(@alias, '''', '''''') + N']'; END END FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; END CLOSE @agg_cursor; DEALLOCATE @agg_cursor; SET @sql = N'SELECT ' + @select_parts + N' FROM _objects o' + @join_parts + N' WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' GROUP BY ' + @group_parts; SELECT @sql AS sql_preview; END; GO -- ===================================================== -- aggregate_array_grouped: GroupBy by array elements -- ===================================================== CREATE PROCEDURE dbo.aggregate_array_grouped @scheme_id BIGINT, @array_path NVARCHAR(255), @group_fields NVARCHAR(MAX), @aggregations NVARCHAR(MAX), @filter_json NVARCHAR(MAX) = NULL AS BEGIN SET NOCOUNT ON; DECLARE @array_struct_id BIGINT; DECLARE @structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @dict_key NVARCHAR(255); DECLARE @array_index NVARCHAR(50); DECLARE @select_parts NVARCHAR(MAX) = N''; DECLARE @group_parts NVARCHAR(MAX) = N''; DECLARE @join_parts NVARCHAR(MAX) = N''; DECLARE @join_idx INT = 0; DECLARE @join_alias NVARCHAR(10); DECLARE @column_name NVARCHAR(50); DECLARE @field NVARCHAR(255); DECLARE @alias NVARCHAR(255); DECLARE @func NVARCHAR(20); DECLARE @full_path NVARCHAR(500); DECLARE @sql NVARCHAR(MAX); -- 1. Get array structure_id EXEC resolve_field_path @scheme_id, @array_path, @array_struct_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @array_struct_id IS NULL BEGIN RAISERROR('Array "%s" not found in scheme %d', 16, 1, @array_path, @scheme_id); RETURN; END -- 2. Process grouping fields DECLARE @group_cursor CURSOR; SET @group_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field, ISNULL(JSON_VALUE(value, '$.alias'), JSON_VALUE(value, '$.field')) AS alias FROM OPENJSON(@group_fields); OPEN @group_cursor; FETCH NEXT FROM @group_cursor INTO @field, @alias; WHILE @@FETCH_STATUS = 0 BEGIN SET @full_path = @array_path + N'[].' + @field; EXEC resolve_field_path @scheme_id, @full_path, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'g' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'String' THEN N'_String' WHEN N'ListItem' THEN N'_ListItem' ELSE N'_String' END; SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = arr._id_object AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_parent_id = arr._id'; IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @join_alias + N'.' + @column_name + N' AS [' + REPLACE(@alias, '''', '''''') + N']'; IF @group_parts <> N'' SET @group_parts = @group_parts + N', '; SET @group_parts = @group_parts + @join_alias + N'.' + @column_name; END FETCH NEXT FROM @group_cursor INTO @field, @alias; END CLOSE @group_cursor; DEALLOCATE @group_cursor; -- 3. Process aggregations DECLARE @agg_cursor CURSOR; SET @agg_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field, UPPER(JSON_VALUE(value, '$.func')) AS func, ISNULL(JSON_VALUE(value, '$.alias'), UPPER(JSON_VALUE(value, '$.func'))) AS alias FROM OPENJSON(@aggregations); OPEN @agg_cursor; FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; WHILE @@FETCH_STATUS = 0 BEGIN IF @func = N'COUNT' AND (@field IS NULL OR @field = N'*') BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + N'COUNT(*) AS [' + REPLACE(@alias, '''', '''''') + N']'; END ELSE IF @field IS NOT NULL BEGIN SET @full_path = @array_path + N'[].' + @field; EXEC resolve_field_path @scheme_id, @full_path, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'a' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' ELSE N'_Long' END; SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = arr._id_object AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_parent_id = arr._id'; IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @func + N'(' + @join_alias + N'.' + @column_name + N') AS [' + REPLACE(@alias, '''', '''''') + N']'; END END FETCH NEXT FROM @agg_cursor INTO @field, @func, @alias; END CLOSE @agg_cursor; DEALLOCATE @agg_cursor; -- 4. Build and execute SQL DECLARE @result NVARCHAR(MAX); SET @sql = N' SELECT @result = ( SELECT ' + @select_parts + N' FROM _values arr JOIN _objects o ON o._id = arr._id_object' + @join_parts + N' WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' AND arr._id_structure = ' + CAST(@array_struct_id AS NVARCHAR(20)) + N' AND arr._array_index IS NOT NULL GROUP BY ' + @group_parts + N' FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result = @result OUTPUT; -- Return with 'result' column name for C# mapping SELECT @result AS result; END; GO PRINT N'========================================='; PRINT N'Grouping procedures created!'; PRINT N''; PRINT N'PROCEDURES:'; PRINT N' aggregate_grouped - GroupBy with aggregations'; PRINT N' aggregate_grouped_preview - SQL preview for debugging'; PRINT N' aggregate_array_grouped - GroupBy by array elements'; PRINT N''; PRINT N'FEATURES:'; PRINT N' - Base fields with 0$: prefix'; PRINT N' - EAV fields from _values'; PRINT N' - Nested paths: Address.City'; PRINT N' - Array support: Items[].Price, Items[2].Price'; PRINT N' - Dictionary support: PhoneBook[home]'; PRINT N' - Multiple grouping keys'; PRINT N' - Filters via get_filtered_object_ids'; PRINT N'========================================='; GO Path: redb/redb.MSSql/sql/deprecated/redb_lazy_loading_search.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.MSSql/sql/deprecated/redb_lazy_loading_search.sql ---- -- ===== LAZY LOADING SUPPORT FOR FACET SEARCH (MSSQL) ===== -- Functions for returning base objects WITHOUT Props -- Ported from PostgreSQL version -- Original functions (search_objects_with_facets, search_tree_objects_with_facets) remain unchanged SET NOCOUNT ON; GO -- ===== DROP EXISTING OBJECTS ===== IF OBJECT_ID('dbo.get_object_base_fields', 'FN') IS NOT NULL DROP FUNCTION dbo.get_object_base_fields; GO IF OBJECT_ID('dbo.execute_objects_query_base', 'P') IS NOT NULL DROP PROCEDURE dbo.execute_objects_query_base; GO IF OBJECT_ID('dbo.search_objects_with_facets_base', 'P') IS NOT NULL DROP PROCEDURE dbo.search_objects_with_facets_base; GO IF OBJECT_ID('dbo.get_filtered_object_ids', 'P') IS NOT NULL DROP PROCEDURE dbo.get_filtered_object_ids; GO IF OBJECT_ID('dbo.search_tree_objects_with_facets_base', 'P') IS NOT NULL DROP PROCEDURE dbo.search_tree_objects_with_facets_base; GO IF OBJECT_ID('dbo.get_search_sql_preview_base', 'P') IS NOT NULL DROP PROCEDURE dbo.get_search_sql_preview_base; GO IF OBJECT_ID('dbo.get_search_tree_sql_preview_base', 'P') IS NOT NULL DROP PROCEDURE dbo.get_search_tree_sql_preview_base; GO -- ========== FUNCTION 1: Return base fields WITHOUT Props ========== -- Returns JSON object with base fields only (no properties from _values) CREATE FUNCTION dbo.get_object_base_fields(@object_id BIGINT) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @result NVARCHAR(MAX); SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._id_who_change AS [who_change_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._date_begin AS [date_begin], o._date_complete AS [date_complete], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._note AS [note], o._value_bool AS [value_bool], o._value_double AS [value_double], o._value_numeric AS [value_numeric], o._value_datetime AS [value_datetime], o._value_bytes AS [value_bytes], o._hash AS [hash] FROM _objects o WHERE o._id = @object_id FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ); RETURN @result; END; GO -- ========== PROCEDURE 2: Execute query with base fields ========== -- Returns search results with base objects (no Props) CREATE PROCEDURE dbo.execute_objects_query_base @scheme_id BIGINT, @base_conditions NVARCHAR(MAX), @hierarchical_conditions NVARCHAR(MAX), @order_conditions NVARCHAR(MAX), @limit_count INT = NULL, @offset_count INT = 0, @distinct_hash BIT = 0 AS BEGIN SET NOCOUNT ON; DECLARE @sql NVARCHAR(MAX); DECLARE @count_sql NVARCHAR(MAX); DECLARE @final_where NVARCHAR(MAX); DECLARE @objects_json NVARCHAR(MAX); DECLARE @total_count INT; DECLARE @order_clause NVARCHAR(MAX); -- Build WHERE clause SET @final_where = N'WHERE obj._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)); IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @final_where = @final_where + N' AND ' + @base_conditions; IF @hierarchical_conditions IS NOT NULL AND @hierarchical_conditions <> N'' SET @final_where = @final_where + N' AND ' + @hierarchical_conditions; -- Build ORDER clause IF @order_conditions IS NOT NULL AND @order_conditions <> N'' SET @order_clause = @order_conditions; ELSE SET @order_clause = N'ORDER BY obj._id'; -- Handle DISTINCT by hash using ROW_NUMBER IF @distinct_hash = 1 BEGIN -- DISTINCT ON equivalent: use ROW_NUMBER to get first row per hash SET @sql = N' SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._id_who_change AS [who_change_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._date_begin AS [date_begin], o._date_complete AS [date_complete], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._note AS [note], o._value_bool AS [value_bool], o._value_double AS [value_double], o._value_numeric AS [value_numeric], o._value_datetime AS [value_datetime], o._value_bytes AS [value_bytes], o._hash AS [hash] FROM ( SELECT obj._id, obj._hash, ROW_NUMBER() OVER (PARTITION BY obj._hash ORDER BY obj._id) AS rn FROM _objects obj ' + @final_where + N' ) ranked JOIN _objects o ON o._id = ranked._id WHERE ranked.rn = 1'; -- Add ORDER BY for outer query (must use 'o' alias, not 'obj') IF @order_conditions IS NOT NULL AND @order_conditions <> N'' SET @sql = @sql + N' ' + REPLACE(REPLACE(@order_conditions, N'obj.', N'o.'), N'obj._', N'o._'); ELSE SET @sql = @sql + N' ORDER BY o._id'; -- Add pagination IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; -- Allow ORDER BY without FETCH for count queries SET @sql = @sql + N' FOR JSON PATH)'; -- Count query for distinct SET @count_sql = N'SELECT @cnt = COUNT(DISTINCT obj._hash) FROM _objects obj ' + @final_where; END ELSE BEGIN -- Standard query without distinct SET @sql = N' SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._id_who_change AS [who_change_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._date_begin AS [date_begin], o._date_complete AS [date_complete], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._note AS [note], o._value_bool AS [value_bool], o._value_double AS [value_double], o._value_numeric AS [value_numeric], o._value_datetime AS [value_datetime], o._value_bytes AS [value_bytes], o._hash AS [hash] FROM _objects o JOIN ( SELECT obj._id, ROW_NUMBER() OVER (' + @order_clause + N') AS _sort_order FROM _objects obj ' + @final_where + N' ' + @order_clause; -- Add pagination IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; -- Allow ORDER BY without FETCH for count queries SET @sql = @sql + N' ) sub ON sub._id = o._id ORDER BY sub._sort_order FOR JSON PATH)'; -- Count query SET @count_sql = N'SELECT @cnt = COUNT(*) FROM _objects obj ' + @final_where; END -- Execute count query first EXEC sp_executesql @count_sql, N'@cnt INT OUTPUT', @cnt = @total_count OUTPUT; -- OPTIMIZATION: For CountAsync (limit = 0), skip objects loading IF @limit_count IS NULL OR @limit_count > 0 BEGIN EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result = @objects_json OUTPUT; END; -- Return result as JSON with 'result' column for C# mapping -- Use JSON_QUERY to embed JSON arrays properly (not as escaped strings) SELECT ISNULL(( SELECT JSON_QUERY(ISNULL(@objects_json, N'[]')) AS objects, ISNULL(@total_count, 0) AS total_count, ISNULL(@limit_count, 2147483647) AS [limit], ISNULL(@offset_count, 0) AS [offset], JSON_QUERY(N'[]') AS facets FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ), N'{"objects":[],"total_count":0,"limit":2147483647,"offset":0,"facets":[]}') AS result; END; GO -- ========== PROCEDURE 3: Search with facets (base objects) ========== -- Faceted search returning base objects WITHOUT Props (7 parameters - for lazy loading) CREATE PROCEDURE dbo.search_objects_with_facets_base @scheme_id BIGINT, @facet_filters NVARCHAR(MAX) = NULL, @limit_count INT = NULL, @offset_count INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_recursion_depth INT = 10, @distinct_hash BIT = 0 AS BEGIN SET NOCOUNT ON; DECLARE @base_conditions NVARCHAR(MAX); DECLARE @hierarchical_conditions NVARCHAR(MAX); DECLARE @order_conditions NVARCHAR(MAX); -- Build conditions using existing procedures from redb_facets_search.sql EXEC dbo.internal_parse_filters @scheme_id, @facet_filters, N'obj', N'AND', 0, @base_conditions OUTPUT; -- Build order conditions SET @order_conditions = dbo.build_order_by_clause(@order_by, N'obj'); -- Execute base query EXEC execute_objects_query_base @scheme_id, @base_conditions, NULL, -- hierarchical_conditions not implemented yet @order_conditions, @limit_count, @offset_count, @distinct_hash; END; GO -- NOTE: search_objects_with_facets (8 params) already exists in redb_facets_search.sql -- We only define search_objects_with_facets_base (7 params) here for lazy loading -- ========== PROCEDURE 4: Get filtered object IDs only ========== -- Optimized for aggregations - returns only IDs without JSON overhead CREATE PROCEDURE dbo.get_filtered_object_ids @scheme_id BIGINT, @filter_json NVARCHAR(MAX) = NULL, @max_recursion_depth INT = 10 AS BEGIN SET NOCOUNT ON; DECLARE @base_conditions NVARCHAR(MAX); DECLARE @sql NVARCHAR(MAX); DECLARE @final_where NVARCHAR(MAX); -- Build conditions EXEC dbo.internal_parse_filters @scheme_id, @filter_json, N'obj', N'AND', 0, @base_conditions OUTPUT; -- Build WHERE clause SET @final_where = N'WHERE obj._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)); IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @final_where = @final_where + N' AND ' + @base_conditions; -- Return only IDs SET @sql = N'SELECT obj._id FROM _objects obj ' + @final_where; EXEC sp_executesql @sql; END; GO -- ========== PROCEDURE 5: Tree search (base objects) ========== -- Tree search returning base objects WITHOUT Props CREATE PROCEDURE dbo.search_tree_objects_with_facets_base @scheme_id BIGINT, @parent_ids NVARCHAR(MAX), -- Comma-separated list of parent IDs @facet_filters NVARCHAR(MAX) = NULL, @limit_count INT = NULL, @offset_count INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_depth INT = 10, @max_recursion_depth INT = 10 AS BEGIN SET NOCOUNT ON; DECLARE @sql NVARCHAR(MAX); DECLARE @count_sql NVARCHAR(MAX); DECLARE @base_conditions NVARCHAR(MAX); DECLARE @order_conditions NVARCHAR(MAX); DECLARE @objects_json NVARCHAR(MAX); DECLARE @total_count INT; -- Ensure metadata cache is populated IF NOT EXISTS (SELECT 1 FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id) BEGIN EXEC sync_metadata_cache_for_scheme @scheme_id; END -- Build conditions (use 'o' alias - all conditions on outer _objects table) EXEC dbo.internal_parse_filters @scheme_id, @facet_filters, N'o', N'AND', 0, @base_conditions OUTPUT; -- Build order conditions (use 'o' alias - ORDER BY is on outer level) SET @order_conditions = dbo.build_order_by_clause(@order_by, N'o'); IF @order_conditions IS NULL OR @order_conditions = N'' SET @order_conditions = N'ORDER BY o._id'; -- Direct children only (max_depth = 1) IF @max_depth = 1 BEGIN SET @sql = N' SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._id_who_change AS [who_change_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._date_begin AS [date_begin], o._date_complete AS [date_complete], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._note AS [note], o._value_bool AS [value_bool], o._value_double AS [value_double], o._value_numeric AS [value_numeric], o._value_datetime AS [value_datetime], o._value_bytes AS [value_bytes], o._hash AS [hash] FROM _objects o WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' AND o._id_parent IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@parents, '',''))'; IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @sql = @sql + N' AND ' + @base_conditions; -- ORDER BY on clean SELECT SET @sql = @sql + N' ' + @order_conditions; IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; -- Allow ORDER BY without FETCH for count queries SET @sql = @sql + N' FOR JSON PATH)'; -- Count query (use alias 'o' to match base_conditions) SET @count_sql = N' SELECT @cnt = COUNT(*) FROM _objects o WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' AND o._id_parent IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@parents, '',''))'; IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @count_sql = @count_sql + N' AND ' + @base_conditions; END ELSE BEGIN -- Recursive search for descendants -- Use WHERE ... IN instead of JOIN with DISTINCT to avoid MSSQL ORDER BY issue SET @sql = N' ;WITH descendants AS ( SELECT CAST(value AS BIGINT) AS _id, 0 AS depth FROM STRING_SPLIT(@parents, '','') UNION ALL SELECT obj._id, d.depth + 1 FROM _objects obj JOIN descendants d ON obj._id_parent = d._id WHERE d.depth < ' + CAST(@max_depth AS NVARCHAR(10)) + N' ) SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._id_who_change AS [who_change_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._date_begin AS [date_begin], o._date_complete AS [date_complete], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._note AS [note], o._value_bool AS [value_bool], o._value_double AS [value_double], o._value_numeric AS [value_numeric], o._value_datetime AS [value_datetime], o._value_bytes AS [value_bytes], o._hash AS [hash] FROM _objects o WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' AND EXISTS ( SELECT 1 FROM descendants dt WHERE dt._id = o._id AND dt.depth > 0 )'; IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @sql = @sql + N' AND ' + @base_conditions; -- ORDER BY on clean SELECT (no JOIN with DISTINCT) SET @sql = @sql + N' ' + @order_conditions; IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; -- Allow ORDER BY without FETCH for count queries SET @sql = @sql + N' FOR JSON PATH)'; -- Count query (use alias 'o' and WHERE IN to match main query) SET @count_sql = N' ;WITH descendants AS ( SELECT CAST(value AS BIGINT) AS _id, 0 AS depth FROM STRING_SPLIT(@parents, '','') UNION ALL SELECT obj._id, d.depth + 1 FROM _objects obj JOIN descendants d ON obj._id_parent = d._id WHERE d.depth < ' + CAST(@max_depth AS NVARCHAR(10)) + N' ) SELECT @cnt = COUNT(*) FROM _objects o WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' AND EXISTS ( SELECT 1 FROM descendants dt WHERE dt._id = o._id AND dt.depth > 0 )'; IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @count_sql = @count_sql + N' AND ' + @base_conditions; END -- Execute queries EXEC sp_executesql @sql, N'@parents NVARCHAR(MAX), @result NVARCHAR(MAX) OUTPUT', @parents = @parent_ids, @result = @objects_json OUTPUT; EXEC sp_executesql @count_sql, N'@parents NVARCHAR(MAX), @cnt INT OUTPUT', @parents = @parent_ids, @cnt = @total_count OUTPUT; -- Return result as JSON with 'result' column for C# mapping -- Use JSON_QUERY to embed JSON arrays properly (not as escaped strings) SELECT ISNULL(( SELECT JSON_QUERY(ISNULL(@objects_json, N'[]')) AS objects, ISNULL(@total_count, 0) AS total_count, ISNULL(@limit_count, 2147483647) AS [limit], ISNULL(@offset_count, 0) AS [offset], N'[' + ISNULL(@parent_ids, N'') + N']' AS parent_ids, ISNULL(@max_depth, 10) AS max_depth, JSON_QUERY(N'[]') AS facets FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ), N'{"objects":[],"total_count":0,"limit":2147483647,"offset":0,"parent_ids":[],"max_depth":10,"facets":[]}') AS result; END; GO -- ========== PROCEDURE 6: SQL Preview for base search ========== -- Returns generated SQL for debugging CREATE PROCEDURE dbo.get_search_sql_preview_base @scheme_id BIGINT, @facet_filters NVARCHAR(MAX) = NULL, @limit_count INT = NULL, @offset_count INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_recursion_depth INT = 10, @distinct_hash BIT = 0 AS BEGIN SET NOCOUNT ON; DECLARE @base_conditions NVARCHAR(MAX); DECLARE @order_conditions NVARCHAR(MAX); DECLARE @sql NVARCHAR(MAX); DECLARE @final_where NVARCHAR(MAX); -- Build conditions EXEC dbo.internal_parse_filters @scheme_id, @facet_filters, N'obj', N'AND', 0, @base_conditions OUTPUT; -- Build order conditions SET @order_conditions = dbo.build_order_by_clause(@order_by, N'obj'); IF @order_conditions IS NULL OR @order_conditions = N'' SET @order_conditions = N'ORDER BY obj._id'; -- Build WHERE clause SET @final_where = N'WHERE obj._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)); IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @final_where = @final_where + N' AND ' + @base_conditions; -- Build preview SQL IF @distinct_hash = 1 BEGIN SET @sql = N' SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._hash AS [hash], ... FROM ( SELECT obj._id, obj._hash, ROW_NUMBER() OVER (PARTITION BY obj._hash ORDER BY obj._id) AS rn FROM _objects obj ' + @final_where + N' ) ranked JOIN _objects o ON o._id = ranked._id WHERE ranked.rn = 1 ' + CASE WHEN @order_conditions IS NOT NULL AND @order_conditions <> N'' THEN REPLACE(REPLACE(@order_conditions, N'obj.', N'o.'), N'obj._', N'o._') ELSE N'ORDER BY o._id' END; END ELSE BEGIN SET @sql = N' SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._hash AS [hash], ... FROM _objects o JOIN ( SELECT obj._id FROM _objects obj ' + @final_where + N' ' + @order_conditions; END IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; -- Allow ORDER BY without FETCH for count queries IF @distinct_hash = 0 SET @sql = @sql + N' ) sub ON sub._id = o._id'; SET @sql = @sql + N' FOR JSON PATH'; SELECT @sql AS sql_preview; END; GO -- ========== PROCEDURE 7: SQL Preview for tree search ========== -- Returns generated SQL for tree search debugging CREATE PROCEDURE dbo.get_search_tree_sql_preview_base @scheme_id BIGINT, @parent_ids NVARCHAR(MAX), @facet_filters NVARCHAR(MAX) = NULL, @limit_count INT = NULL, @offset_count INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_depth INT = 10, @max_recursion_depth INT = 10 AS BEGIN SET NOCOUNT ON; DECLARE @base_conditions NVARCHAR(MAX); DECLARE @order_conditions NVARCHAR(MAX); DECLARE @sql NVARCHAR(MAX); -- Build conditions (use 'o' alias - all conditions on outer _objects table) EXEC dbo.internal_parse_filters @scheme_id, @facet_filters, N'o', N'AND', 0, @base_conditions OUTPUT; -- Build order conditions (use 'o' alias) SET @order_conditions = dbo.build_order_by_clause(@order_by, N'o'); IF @order_conditions IS NULL OR @order_conditions = N'' SET @order_conditions = N'ORDER BY o._id'; IF @max_depth = 1 BEGIN SET @sql = N' -- Direct children only (WHERE ... IN structure) SELECT o._id, o._name, o._hash, ... FROM _objects o WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' AND o._id_parent IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(''' + @parent_ids + N''', '',''))'; IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @sql = @sql + N' AND ' + @base_conditions; -- ORDER BY on clean SELECT SET @sql = @sql + N' ' + @order_conditions; END ELSE BEGIN SET @sql = N' -- Recursive descendants search (WHERE ... IN structure) ;WITH descendants AS ( SELECT CAST(value AS BIGINT) AS _id, 0 AS depth FROM STRING_SPLIT(''' + @parent_ids + N''', '','') UNION ALL SELECT obj._id, d.depth + 1 FROM _objects obj JOIN descendants d ON obj._id_parent = d._id WHERE d.depth < ' + CAST(@max_depth AS NVARCHAR(10)) + N' ) SELECT o._id, o._name, o._hash, ... FROM _objects o WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)) + N' AND EXISTS ( SELECT 1 FROM descendants dt WHERE dt._id = o._id AND dt.depth > 0 )'; IF @base_conditions IS NOT NULL AND @base_conditions <> N'' SET @sql = @sql + N' AND ' + @base_conditions; -- ORDER BY on clean SELECT SET @sql = @sql + N' ' + @order_conditions; END IF @limit_count IS NOT NULL AND @limit_count > 0 SET @sql = @sql + N' OFFSET ' + CAST(@offset_count AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit_count AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @sql = @sql + N' OFFSET 0 ROWS'; -- Allow ORDER BY without FETCH for count queries SET @sql = @sql + N' FOR JSON PATH'; SELECT @sql AS sql_preview; END; GO -- ========== HELPER: Build ORDER BY clause ========== -- Creates ORDER BY clause from JSON specification IF OBJECT_ID('dbo.build_order_by_clause', 'FN') IS NOT NULL DROP FUNCTION dbo.build_order_by_clause; GO CREATE FUNCTION dbo.build_order_by_clause( @order_by NVARCHAR(MAX), @table_alias NVARCHAR(10) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @result NVARCHAR(MAX) = N''; -- If no order specified, return empty (including string 'null' from C#) IF @order_by IS NULL OR @order_by = N'' OR @order_by = N'[]' OR @order_by = N'null' RETURN @result; -- Parse JSON array of order items -- Expected format: [{"field": "Name", "direction": "ASC"}] SELECT @result = STRING_AGG(order_item, N', ') FROM ( SELECT CASE -- Base field with 0$: prefix WHEN JSON_VALUE(arr.value, '$.field') LIKE N'0$:%' THEN @table_alias + N'.' + dbo.normalize_base_field_name( SUBSTRING(JSON_VALUE(arr.value, '$.field'), 4, 100) ) + N' ' + UPPER(ISNULL(JSON_VALUE(arr.value, '$.direction'), N'ASC')) -- Regular field - sort via subquery to _values -- Use zero-padding for numeric types to preserve correct sort order ELSE N'(SELECT TOP 1 CASE WHEN v._String IS NOT NULL THEN v._String WHEN v._Long IS NOT NULL THEN RIGHT(''00000000000000000000'' + CAST(v._Long AS NVARCHAR(20)), 20) WHEN v.[_Double] IS NOT NULL THEN RIGHT(''0000000000000000000000000'' + REPLACE(CAST(v.[_Double] AS NVARCHAR(50)), ''.'', ''~''), 25) WHEN v._Numeric IS NOT NULL THEN RIGHT(''000000000000000000000000000000'' + REPLACE(CAST(v._Numeric AS NVARCHAR(50)), ''.'', ''~''), 30) WHEN v._DateTimeOffset IS NOT NULL THEN CONVERT(NVARCHAR(50), v._DateTimeOffset, 127) WHEN v._Boolean IS NOT NULL THEN CAST(CAST(v._Boolean AS INT) AS NVARCHAR(1)) ELSE NULL END FROM _values v JOIN _scheme_metadata_cache c ON c._structure_id = v._id_structure WHERE v._id_object = ' + @table_alias + N'._id AND c._name = N''' + JSON_VALUE(arr.value, '$.field') + N''' AND v._array_index IS NULL) ' + UPPER(ISNULL(JSON_VALUE(arr.value, '$.direction'), N'ASC')) END AS order_item FROM OPENJSON(@order_by) arr WHERE JSON_VALUE(arr.value, '$.field') IS NOT NULL ) items; IF @result IS NOT NULL AND @result <> N'' SET @result = N'ORDER BY ' + @result; RETURN @result; END; GO PRINT N'========================================='; PRINT N'Lazy Loading Search procedures created!'; PRINT N''; PRINT N'PROCEDURES:'; PRINT N' search_objects_with_facets_base - Search without Props'; PRINT N' search_tree_objects_with_facets_base - Tree search without Props'; PRINT N' get_filtered_object_ids - Get only IDs for aggregations'; PRINT N' execute_objects_query_base - Execute query with base fields'; PRINT N' get_search_sql_preview_base - SQL preview for debugging'; PRINT N' get_search_tree_sql_preview_base - Tree SQL preview'; PRINT N''; PRINT N'FUNCTIONS:'; PRINT N' get_object_base_fields - Get single object base fields'; PRINT N' build_order_by_clause - Build ORDER BY from JSON'; PRINT N'========================================='; GO Path: redb/redb.MSSql/sql/deprecated/redb_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.MSSql/sql/deprecated/redb_projection.sql ---- -- ============================================================ -- PROJECTION FUNCTIONS (MSSQL): Optimized loading of specific fields -- ============================================================ -- Result format: -- - Class fields -> flat with paths: "Contact.Name": "John" -- - Arrays -> flat with indexes: "Items[0].Price": 100 -- - _RObject -> NESTED object: "Author": { "Name": "Pushkin", ... } -- OPTIMIZED: Set-based approach without cursors (like PostgreSQL) -- ============================================================ SET NOCOUNT ON; GO -- ===== DROP EXISTING OBJECTS ===== IF OBJECT_ID('dbo.build_flat_projection', 'P') IS NOT NULL DROP PROCEDURE dbo.build_flat_projection; GO IF OBJECT_ID('dbo.search_objects_with_projection', 'P') IS NOT NULL DROP PROCEDURE dbo.search_objects_with_projection; GO IF OBJECT_ID('dbo.get_object_with_projection', 'P') IS NOT NULL DROP PROCEDURE dbo.get_object_with_projection; GO IF OBJECT_ID('dbo.search_objects_with_projection_by_paths', 'P') IS NOT NULL DROP PROCEDURE dbo.search_objects_with_projection_by_paths; GO IF OBJECT_ID('dbo.search_objects_with_projection_by_ids', 'P') IS NOT NULL DROP PROCEDURE dbo.search_objects_with_projection_by_ids; GO IF OBJECT_ID('dbo._build_field_path', 'FN') IS NOT NULL DROP FUNCTION dbo._build_field_path; GO -- ============================================================ -- Helper: _build_field_path - Build field path from structure_id -- ============================================================ CREATE FUNCTION dbo._build_field_path( @structure_id BIGINT, @scheme_id BIGINT ) RETURNS NVARCHAR(500) AS BEGIN DECLARE @path NVARCHAR(500) = N''; DECLARE @current_id BIGINT = @structure_id; DECLARE @name NVARCHAR(255); DECLARE @parent_id BIGINT; DECLARE @depth INT = 0; WHILE @depth < 20 BEGIN SELECT @name = _name, @parent_id = _parent_structure_id FROM _scheme_metadata_cache WHERE _scheme_id = @scheme_id AND _structure_id = @current_id; IF @name IS NULL BREAK; IF @path = N'' SET @path = @name; ELSE SET @path = @name + N'.' + @path; IF @parent_id IS NULL BREAK; SET @current_id = @parent_id; SET @depth = @depth + 1; END RETURN @path; END; GO -- ============================================================ -- get_object_with_projection: Get single object with projection -- OPTIMIZED: Single query approach -- ============================================================ CREATE PROCEDURE dbo.get_object_with_projection @object_id BIGINT, @projection_paths NVARCHAR(MAX), @max_depth INT = 10 AS BEGIN SET NOCOUNT ON; DECLARE @scheme_id BIGINT; DECLARE @sql NVARCHAR(MAX); -- Get scheme_id SELECT @scheme_id = _id_scheme FROM _objects WHERE _id = @object_id; IF @scheme_id IS NULL BEGIN SELECT NULL AS result; RETURN; END -- Parse projection paths into table (no cursor!) DECLARE @projections TABLE ( path NVARCHAR(255), structure_id BIGINT, db_type NVARCHAR(50), column_name NVARCHAR(50) ); INSERT INTO @projections (path, structure_id) SELECT JSON_VALUE(value, '$.path'), CAST(JSON_VALUE(value, '$.structure_id') AS BIGINT) FROM OPENJSON(@projection_paths) WHERE JSON_VALUE(value, '$.structure_id') IS NOT NULL; -- Get db_type for each structure (single query) UPDATE p SET p.db_type = c.db_type, p.column_name = CASE c.db_type WHEN N'String' THEN N'_String' WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'Boolean' THEN N'_Boolean' WHEN N'Guid' THEN N'_Guid' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' ELSE N'_String' END FROM @projections p JOIN _scheme_metadata_cache c ON c._scheme_id = @scheme_id AND c._structure_id = p.structure_id; -- Remove Object (Class) type fields without nested paths (like PostgreSQL) DELETE FROM @projections WHERE EXISTS ( SELECT 1 FROM _scheme_metadata_cache c WHERE c._structure_id = [@projections].structure_id AND c._scheme_id = @scheme_id AND c.type_semantic = N'Object' ); -- Build dynamic PVT query DECLARE @pvt_columns NVARCHAR(MAX) = N''; DECLARE @select_columns NVARCHAR(MAX) = N''; SELECT @pvt_columns = @pvt_columns + N',' + QUOTENAME(structure_id), @select_columns = @select_columns + N', JSON_VALUE(pvt.' + QUOTENAME(structure_id) + N', ''$.' + column_name + N''') AS [properties.' + REPLACE(REPLACE(path, N'[', N'.'), N']', N'') + N']' FROM @projections; IF @pvt_columns = N'' BEGIN -- No projection fields - return basic object SELECT ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._hash AS [hash], o._date_modify AS [date_modify] FROM _objects o WHERE o._id = @object_id FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ) AS result; RETURN; END SET @pvt_columns = STUFF(@pvt_columns, 1, 1, N''); SET @sql = N' WITH values_json AS ( SELECT v._id_object, v._id_structure, (SELECT v._String AS _String, v._Long AS _Long, v._Double AS _Double, v._Numeric AS _Numeric, v._Boolean AS _Boolean, v._Guid AS _Guid, v._DateTimeOffset AS _DateTimeOffset FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS val_json FROM _values v WHERE v._id_object = @obj_id AND v._id_structure IN (SELECT structure_id FROM @proj) AND v._array_index IS NULL ), pvted AS ( SELECT _id_object, ' + @pvt_columns + N' FROM values_json PVT (MAX(val_json) FOR _id_structure IN (' + @pvt_columns + N')) AS pvt ) SELECT ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._hash AS [hash], o._date_modify AS [date_modify]' + @select_columns + N' FROM _objects o LEFT JOIN pvted pvt ON pvt._id_object = o._id WHERE o._id = @obj_id FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ) AS result'; EXEC sp_executesql @sql, N'@obj_id BIGINT, @proj AS dbo.BigIntTable READONLY', @obj_id = @object_id; END; GO -- ============================================================ -- search_objects_with_projection_by_ids: Search with projection by structure IDs -- OPTIMIZED: No cursors, single PVT query -- ============================================================ CREATE PROCEDURE dbo.search_objects_with_projection_by_ids @scheme_id BIGINT, @filter_json NVARCHAR(MAX) = NULL, @structure_ids NVARCHAR(MAX), -- Comma-separated structure IDs @limit INT = NULL, @offset INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_depth INT = 10 AS BEGIN SET NOCOUNT ON; DECLARE @sql NVARCHAR(MAX); DECLARE @where_clause NVARCHAR(MAX) = N''; DECLARE @order_clause NVARCHAR(MAX); DECLARE @objects_json NVARCHAR(MAX); DECLARE @total_count INT; -- Parse structure_ids into table (no cursor!) CREATE TABLE #struct_ids (structure_id BIGINT PRIMARY KEY); INSERT INTO #struct_ids (structure_id) SELECT DISTINCT CAST(value AS BIGINT) FROM STRING_SPLIT(@structure_ids, N',') WHERE value IS NOT NULL AND value <> N''; -- Get field info for all structures at once CREATE TABLE #projections ( structure_id BIGINT PRIMARY KEY, field_name NVARCHAR(255), db_type NVARCHAR(50), column_name NVARCHAR(50) ); INSERT INTO #projections (structure_id, field_name, db_type, column_name) SELECT c._structure_id, c._name, c.db_type, CASE c.db_type WHEN N'String' THEN N'_String' WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'Boolean' THEN N'_Boolean' WHEN N'Guid' THEN N'_Guid' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' ELSE N'_String' END FROM _scheme_metadata_cache c JOIN #struct_ids s ON s.structure_id = c._structure_id WHERE c._scheme_id = @scheme_id; -- Remove Object (Class) type fields without nested paths (like PostgreSQL) DELETE p FROM #projections p JOIN _scheme_metadata_cache c ON c._structure_id = p.structure_id AND c._scheme_id = @scheme_id WHERE c.type_semantic = N'Object'; -- Build PVT columns dynamically DECLARE @pvt_columns NVARCHAR(MAX) = N''; DECLARE @select_columns NVARCHAR(MAX) = N''; SELECT @pvt_columns = @pvt_columns + N',' + QUOTENAME(structure_id), @select_columns = @select_columns + N', pvt.[' + CAST(structure_id AS NVARCHAR(20)) + N'_val] AS [properties.' + REPLACE(REPLACE(field_name, N'[', N'.'), N']', N'') + N']' FROM #projections ORDER BY structure_id; -- Build filter conditions IF @filter_json IS NOT NULL AND @filter_json <> N'' AND @filter_json <> N'null' BEGIN EXEC dbo.internal_parse_filters @scheme_id, @filter_json, N'o', N'AND', 0, @where_clause OUTPUT; END IF @where_clause IS NOT NULL AND @where_clause <> N'' SET @where_clause = N' AND ' + @where_clause; -- Build order clause SET @order_clause = dbo.build_order_by_clause(@order_by, N'o'); IF @order_clause IS NULL OR @order_clause = N'' SET @order_clause = N'ORDER BY o._id'; -- Count query SET @sql = N' SELECT @cnt = COUNT(*) FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause; EXEC sp_executesql @sql, N'@cnt INT OUTPUT, @sch_id BIGINT', @cnt = @total_count OUTPUT, @sch_id = @scheme_id; -- Build main query with PVT approach IF @pvt_columns = N'' BEGIN -- No projection fields - return basic objects SET @sql = N' SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._hash AS [hash] FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause + N' ' + @order_clause; IF @limit IS NOT NULL SET @sql = @sql + N' OFFSET @off ROWS FETCH NEXT @lim ROWS ONLY'; SET @sql = @sql + N' FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT, @sch_id BIGINT, @off INT, @lim INT', @result = @objects_json OUTPUT, @sch_id = @scheme_id, @off = @offset, @lim = @limit; END ELSE BEGIN SET @pvt_columns = STUFF(@pvt_columns, 1, 1, N''); -- Build value extraction for each column DECLARE @value_extracts NVARCHAR(MAX) = N''; SELECT @value_extracts = @value_extracts + N', CASE WHEN v._id_structure = ' + CAST(structure_id AS NVARCHAR(20)) + N' THEN v.' + column_name + N' END AS [' + CAST(structure_id AS NVARCHAR(20)) + N'_val]' FROM #projections; SET @value_extracts = STUFF(@value_extracts, 1, 1, N''); -- Aggregate columns DECLARE @agg_columns NVARCHAR(MAX) = N''; SELECT @agg_columns = @agg_columns + N', MAX([' + CAST(structure_id AS NVARCHAR(20)) + N'_val]) AS [' + CAST(structure_id AS NVARCHAR(20)) + N'_val]' FROM #projections; SET @agg_columns = STUFF(@agg_columns, 1, 1, N''); -- Use temp table instead of CTE to materialize filtered IDs (avoids re-computation) CREATE TABLE #filtered_ids (_id BIGINT PRIMARY KEY); SET @sql = N' INSERT INTO #filtered_ids (_id) SELECT o._id FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause + N' ' + @order_clause; IF @limit IS NOT NULL SET @sql = @sql + N' OFFSET @off ROWS FETCH NEXT @lim ROWS ONLY'; EXEC sp_executesql @sql, N'@sch_id BIGINT, @off INT, @lim INT', @sch_id = @scheme_id, @off = @offset, @lim = @limit; SET @sql = N' ;WITH val_expanded AS ( SELECT v._id_object, ' + @value_extracts + N' FROM #filtered_ids f JOIN _values v ON v._id_object = f._id WHERE v._id_structure IN (SELECT structure_id FROM #projections) AND v._array_index IS NULL ), pvt AS ( SELECT _id_object, ' + @agg_columns + N' FROM val_expanded GROUP BY _id_object ) SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._hash AS [hash]' + @select_columns + N' FROM #filtered_ids f JOIN _objects o ON o._id = f._id LEFT JOIN pvt ON pvt._id_object = o._id ORDER BY o._id FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result = @objects_json OUTPUT; DROP TABLE #filtered_ids; END -- Return result SELECT ( SELECT JSON_QUERY(ISNULL(@objects_json, N'[]')) AS objects, @total_count AS total_count, @limit AS [limit], @offset AS [offset], JSON_QUERY(N'[]') AS facets FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ) AS result; DROP TABLE #struct_ids; DROP TABLE #projections; END; GO -- ============================================================ -- search_objects_with_projection_by_paths: Search with projection by text paths -- OPTIMIZED: No cursors, batch processing -- ============================================================ CREATE PROCEDURE dbo.search_objects_with_projection_by_paths @scheme_id BIGINT, @filter_json NVARCHAR(MAX) = NULL, @field_paths NVARCHAR(MAX), -- JSON array of paths: ["Name", "Address.City"] @limit INT = NULL, @offset INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_depth INT = 10 AS BEGIN SET NOCOUNT ON; DECLARE @sql NVARCHAR(MAX); DECLARE @where_clause NVARCHAR(MAX) = N''; DECLARE @order_clause NVARCHAR(MAX); DECLARE @objects_json NVARCHAR(MAX); DECLARE @total_count INT; -- Parse field paths into table CREATE TABLE #paths ( idx INT IDENTITY(1,1) PRIMARY KEY, path NVARCHAR(255), structure_id BIGINT, db_type NVARCHAR(50), dict_key NVARCHAR(255), array_index NVARCHAR(50), column_name NVARCHAR(50), parent_structure_id BIGINT, -- Parent structure for nested dict paths (AddressBook for AddressBook[home].City) is_nested_dict BIT DEFAULT 0 -- Flag for nested dictionary paths ); -- Insert paths from JSON array or comma-separated IF LEFT(@field_paths, 1) = N'[' INSERT INTO #paths (path) SELECT REPLACE(value, N'"', N'') FROM OPENJSON(@field_paths); ELSE INSERT INTO #paths (path) SELECT value FROM STRING_SPLIT(@field_paths, N','); -- Resolve all paths at once using resolve_field_path DECLARE @path NVARCHAR(255); DECLARE @structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @dict_key NVARCHAR(255); DECLARE @array_index NVARCHAR(50); DECLARE @idx INT; DECLARE @parent_path NVARCHAR(255); DECLARE @parent_structure_id BIGINT; DECLARE @parent_db_type NVARCHAR(50); DECLARE @parent_dict_key NVARCHAR(255); DECLARE @parent_array_index NVARCHAR(50); DECLARE @is_nested_dict BIT; DECLARE @bracket_pos INT; DECLARE @dot_after_bracket INT; DECLARE path_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT idx, path FROM #paths WHERE path IS NOT NULL AND path <> N''; OPEN path_cursor; FETCH NEXT FROM path_cursor INTO @idx, @path; WHILE @@FETCH_STATUS = 0 BEGIN SET @is_nested_dict = 0; SET @parent_structure_id = NULL; -- Check if this is a nested dictionary path: AddressBook[home].City SET @bracket_pos = CHARINDEX(N'[', @path); IF @bracket_pos > 0 BEGIN SET @dot_after_bracket = CHARINDEX(N'].', @path); IF @dot_after_bracket > 0 BEGIN -- This is a nested dictionary path SET @is_nested_dict = 1; -- Get parent path: AddressBook[home] SET @parent_path = LEFT(@path, @dot_after_bracket); -- Resolve parent structure (AddressBook with dict_key) EXEC resolve_field_path @scheme_id, @parent_path, @parent_structure_id OUTPUT, @parent_db_type OUTPUT, @parent_dict_key OUTPUT, @parent_array_index OUTPUT; END END -- Resolve the field path EXEC resolve_field_path @scheme_id, @path, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; UPDATE #paths SET structure_id = @structure_id, db_type = @db_type, dict_key = @dict_key, array_index = @array_index, column_name = CASE @db_type WHEN N'String' THEN N'_String' WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'Boolean' THEN N'_Boolean' WHEN N'Guid' THEN N'_Guid' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' ELSE N'_String' END, parent_structure_id = @parent_structure_id, is_nested_dict = @is_nested_dict WHERE idx = @idx; FETCH NEXT FROM path_cursor INTO @idx, @path; END CLOSE path_cursor; DEALLOCATE path_cursor; -- Remove unresolved paths DELETE FROM #paths WHERE structure_id IS NULL; -- Remove Object (Class) type fields without nested paths (like PostgreSQL) -- When user requests Address1 without specifying Address1.City, Address1.Street, etc. -- we should skip it (Object fields need nested field specification) DELETE p FROM #paths p JOIN _scheme_metadata_cache c ON c._structure_id = p.structure_id AND c._scheme_id = @scheme_id WHERE c.type_semantic = N'Object'; -- Build filter conditions IF @filter_json IS NOT NULL AND @filter_json <> N'' AND @filter_json <> N'null' BEGIN EXEC dbo.internal_parse_filters @scheme_id, @filter_json, N'o', N'AND', 0, @where_clause OUTPUT; END IF @where_clause IS NOT NULL AND @where_clause <> N'' SET @where_clause = N' AND ' + @where_clause; -- Build order clause SET @order_clause = dbo.build_order_by_clause(@order_by, N'o'); IF @order_clause IS NULL OR @order_clause = N'' SET @order_clause = N'ORDER BY o._id'; -- Count query SET @sql = N' SELECT @cnt = COUNT(*) FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause; EXEC sp_executesql @sql, N'@cnt INT OUTPUT, @sch_id BIGINT', @cnt = @total_count OUTPUT, @sch_id = @scheme_id; -- Build value extraction columns DECLARE @value_extracts NVARCHAR(MAX) = N''; DECLARE @agg_columns NVARCHAR(MAX) = N''; DECLARE @select_columns NVARCHAR(MAX) = N''; DECLARE @nested_dict_joins NVARCHAR(MAX) = N''; DECLARE @nested_dict_selects NVARCHAR(MAX) = N''; -- Process non-nested-dict paths (simple fields, simple dict keys like PhoneBook[home]) SELECT @value_extracts = @value_extracts + N', CASE WHEN v._id_structure = ' + CAST(structure_id AS NVARCHAR(20)) + CASE WHEN dict_key IS NOT NULL AND is_nested_dict = 0 THEN N' AND v._array_index = N''' + dict_key + N'''' WHEN array_index IS NOT NULL THEN N' AND v._array_index = N''' + array_index + N'''' ELSE N' AND v._array_index IS NULL' END + N' THEN v.' + column_name + N' END AS [col_' + CAST(idx AS NVARCHAR(10)) + N']', @agg_columns = @agg_columns + N', MAX([col_' + CAST(idx AS NVARCHAR(10)) + N']) AS [col_' + CAST(idx AS NVARCHAR(10)) + N']', @select_columns = @select_columns + N', pvt.[col_' + CAST(idx AS NVARCHAR(10)) + N'] AS [properties.' + -- FOR JSON PATH uses dots for hierarchy: PhoneBook[home] → properties.PhoneBook.home REPLACE(REPLACE(path, N'[', N'.'), N']', N'') + N']' FROM #paths WHERE is_nested_dict = 0 ORDER BY idx; -- Process nested dictionary paths (AddressBook[home].City) - need JOIN through _array_parent_id -- FOR JSON PATH uses dots for hierarchy: AddressBook[home].City → properties.AddressBook.home.City SELECT @nested_dict_joins = @nested_dict_joins + N' LEFT JOIN ( SELECT v_child._id_object, v_child.' + column_name + N' AS val FROM _values v_parent JOIN _values v_child ON v_child._array_parent_id = v_parent._id WHERE v_parent._id_structure = ' + CAST(parent_structure_id AS NVARCHAR(20)) + N' AND v_parent._array_index = N''' + dict_key + N''' AND v_child._id_structure = ' + CAST(structure_id AS NVARCHAR(20)) + N' ) nd_' + CAST(idx AS NVARCHAR(10)) + N' ON nd_' + CAST(idx AS NVARCHAR(10)) + N'._id_object = o._id', @nested_dict_selects = @nested_dict_selects + N', nd_' + CAST(idx AS NVARCHAR(10)) + N'.val AS [properties.' + -- FOR JSON PATH uses dots for hierarchy: AddressBook[home].City → properties.AddressBook.home.City REPLACE(REPLACE(path, N'[', N'.'), N']', N'') + N']' FROM #paths WHERE is_nested_dict = 1 ORDER BY idx; -- Create temp table for filtered IDs once (used in projection branches) CREATE TABLE #filtered_ids (_id BIGINT PRIMARY KEY); -- Check if we have any projections at all IF @value_extracts = N'' AND @nested_dict_joins = N'' BEGIN -- No projection fields - return basic objects SET @sql = N' SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._hash AS [hash] FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause + N' ' + @order_clause; IF @limit IS NOT NULL SET @sql = @sql + N' OFFSET @off ROWS FETCH NEXT @lim ROWS ONLY'; SET @sql = @sql + N' FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT, @sch_id BIGINT, @off INT, @lim INT', @result = @objects_json OUTPUT, @sch_id = @scheme_id, @off = @offset, @lim = @limit; END ELSE IF @value_extracts = N'' BEGIN -- Only nested dict fields (no simple projections) SET @sql = N' INSERT INTO #filtered_ids (_id) SELECT o._id FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause + N' ' + @order_clause; IF @limit IS NOT NULL SET @sql = @sql + N' OFFSET @off ROWS FETCH NEXT @lim ROWS ONLY'; EXEC sp_executesql @sql, N'@sch_id BIGINT, @off INT, @lim INT', @sch_id = @scheme_id, @off = @offset, @lim = @limit; SET @sql = N' SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._hash AS [hash]' + @nested_dict_selects + N' FROM #filtered_ids f JOIN _objects o ON o._id = f._id' + @nested_dict_joins + N' ORDER BY o._id FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result = @objects_json OUTPUT; END ELSE BEGIN SET @value_extracts = STUFF(@value_extracts, 1, 1, N''); SET @agg_columns = STUFF(@agg_columns, 1, 1, N''); -- Get distinct structure_ids for filter (only non-nested-dict) DECLARE @struct_ids NVARCHAR(MAX); SELECT @struct_ids = STRING_AGG(CAST(structure_id AS NVARCHAR(20)), N',') FROM #paths WHERE is_nested_dict = 0; SET @sql = N' INSERT INTO #filtered_ids (_id) SELECT o._id FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause + N' ' + @order_clause; IF @limit IS NOT NULL SET @sql = @sql + N' OFFSET @off ROWS FETCH NEXT @lim ROWS ONLY'; EXEC sp_executesql @sql, N'@sch_id BIGINT, @off INT, @lim INT', @sch_id = @scheme_id, @off = @offset, @lim = @limit; -- Now query with materialized IDs - JOIN instead of IN for better performance SET @sql = N' ;WITH val_expanded AS ( SELECT v._id_object, ' + @value_extracts + N' FROM #filtered_ids f JOIN _values v ON v._id_object = f._id WHERE v._id_structure IN (' + @struct_ids + N') ), pvt AS ( SELECT _id_object, ' + @agg_columns + N' FROM val_expanded GROUP BY _id_object ) SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._id_owner AS [owner_id], o._date_create AS [date_create], o._date_modify AS [date_modify], o._key AS [key], o._value_long AS [value_long], o._value_string AS [value_string], o._value_guid AS [value_guid], o._hash AS [hash]' + @select_columns + @nested_dict_selects + N' FROM #filtered_ids f JOIN _objects o ON o._id = f._id LEFT JOIN pvt ON pvt._id_object = o._id' + @nested_dict_joins + N' ORDER BY o._id FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result = @objects_json OUTPUT; END -- Return result SELECT ( SELECT JSON_QUERY(ISNULL(@objects_json, N'[]')) AS objects, @total_count AS total_count, @limit AS [limit], @offset AS [offset], JSON_QUERY(N'[]') AS facets FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ) AS result; DROP TABLE #filtered_ids; DROP TABLE #paths; END; GO -- ============================================================ -- search_objects_with_projection: Search with projection (JSONB paths) -- OPTIMIZED: Set-based approach -- ============================================================ CREATE PROCEDURE dbo.search_objects_with_projection @scheme_id BIGINT, @filter_json NVARCHAR(MAX) = NULL, @projection_paths NVARCHAR(MAX) = N'[]', @limit INT = NULL, @offset INT = 0, @order_by NVARCHAR(MAX) = NULL, @max_depth INT = 10 AS BEGIN SET NOCOUNT ON; DECLARE @sql NVARCHAR(MAX); DECLARE @where_clause NVARCHAR(MAX) = N''; DECLARE @order_clause NVARCHAR(MAX); DECLARE @objects_json NVARCHAR(MAX); DECLARE @total_count INT; -- Parse projection paths into table CREATE TABLE #projections ( idx INT IDENTITY(1,1) PRIMARY KEY, path NVARCHAR(255), structure_id BIGINT, db_type NVARCHAR(50), column_name NVARCHAR(50) ); INSERT INTO #projections (path, structure_id) SELECT JSON_VALUE(value, '$.path'), CAST(JSON_VALUE(value, '$.structure_id') AS BIGINT) FROM OPENJSON(@projection_paths) WHERE JSON_VALUE(value, '$.structure_id') IS NOT NULL; -- Get db_type for each structure (single query) UPDATE p SET p.db_type = c.db_type, p.column_name = CASE c.db_type WHEN N'String' THEN N'_String' WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'Boolean' THEN N'_Boolean' WHEN N'Guid' THEN N'_Guid' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' ELSE N'_String' END FROM #projections p JOIN _scheme_metadata_cache c ON c._scheme_id = @scheme_id AND c._structure_id = p.structure_id; -- Remove rows with no match DELETE FROM #projections WHERE db_type IS NULL; -- Remove Object (Class) type fields without nested paths (like PostgreSQL) DELETE p FROM #projections p JOIN _scheme_metadata_cache c ON c._structure_id = p.structure_id AND c._scheme_id = @scheme_id WHERE c.type_semantic = N'Object'; -- Build filter conditions IF @filter_json IS NOT NULL AND @filter_json <> N'' AND @filter_json <> N'null' BEGIN EXEC dbo.internal_parse_filters @scheme_id, @filter_json, N'o', N'AND', 0, @where_clause OUTPUT; END IF @where_clause IS NOT NULL AND @where_clause <> N'' SET @where_clause = N' AND ' + @where_clause; -- Build order clause SET @order_clause = dbo.build_order_by_clause(@order_by, N'o'); IF @order_clause IS NULL OR @order_clause = N'' SET @order_clause = N'ORDER BY o._id'; -- Count query SET @sql = N' SELECT @cnt = COUNT(*) FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause; EXEC sp_executesql @sql, N'@cnt INT OUTPUT, @sch_id BIGINT', @cnt = @total_count OUTPUT, @sch_id = @scheme_id; -- Build value extraction columns DECLARE @value_extracts NVARCHAR(MAX) = N''; DECLARE @agg_columns NVARCHAR(MAX) = N''; DECLARE @select_columns NVARCHAR(MAX) = N''; SELECT @value_extracts = @value_extracts + N', CASE WHEN v._id_structure = ' + CAST(structure_id AS NVARCHAR(20)) + N' AND v._array_index IS NULL THEN v.' + column_name + N' END AS [col_' + CAST(idx AS NVARCHAR(10)) + N']', @agg_columns = @agg_columns + N', MAX([col_' + CAST(idx AS NVARCHAR(10)) + N']) AS [col_' + CAST(idx AS NVARCHAR(10)) + N']', @select_columns = @select_columns + N', pvt.[col_' + CAST(idx AS NVARCHAR(10)) + N'] AS [properties.' + REPLACE(REPLACE(path, N'[', N'.'), N']', N'') + N']' FROM #projections ORDER BY idx; IF @value_extracts = N'' BEGIN -- No projection fields - return basic objects SET @sql = N' SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._hash AS [hash] FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause + N' ' + @order_clause; IF @limit IS NOT NULL SET @sql = @sql + N' OFFSET @off ROWS FETCH NEXT @lim ROWS ONLY'; SET @sql = @sql + N' FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT, @sch_id BIGINT, @off INT, @lim INT', @result = @objects_json OUTPUT, @sch_id = @scheme_id, @off = @offset, @lim = @limit; END ELSE BEGIN SET @value_extracts = STUFF(@value_extracts, 1, 1, N''); SET @agg_columns = STUFF(@agg_columns, 1, 1, N''); -- Get distinct structure_ids for filter DECLARE @struct_ids NVARCHAR(MAX); SELECT @struct_ids = STRING_AGG(CAST(structure_id AS NVARCHAR(20)), N',') FROM #projections; -- Use temp table instead of CTE to materialize filtered IDs (avoids re-computation) CREATE TABLE #filtered_ids (_id BIGINT PRIMARY KEY); SET @sql = N' INSERT INTO #filtered_ids (_id) SELECT o._id FROM _objects o WHERE o._id_scheme = @sch_id' + @where_clause + N' ' + @order_clause; IF @limit IS NOT NULL SET @sql = @sql + N' OFFSET @off ROWS FETCH NEXT @lim ROWS ONLY'; EXEC sp_executesql @sql, N'@sch_id BIGINT, @off INT, @lim INT', @sch_id = @scheme_id, @off = @offset, @lim = @limit; SET @sql = N' ;WITH val_expanded AS ( SELECT v._id_object, ' + @value_extracts + N' FROM #filtered_ids f JOIN _values v ON v._id_object = f._id WHERE v._id_structure IN (' + @struct_ids + N') ), pvt AS ( SELECT _id_object, ' + @agg_columns + N' FROM val_expanded GROUP BY _id_object ) SELECT @result = ( SELECT o._id AS [id], o._name AS [name], o._id_scheme AS [scheme_id], o._id_parent AS [parent_id], o._hash AS [hash]' + @select_columns + N' FROM #filtered_ids f2 JOIN _objects o ON o._id = f2._id LEFT JOIN pvt ON pvt._id_object = o._id ORDER BY o._id FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result = @objects_json OUTPUT; DROP TABLE #filtered_ids; END -- Return result SELECT ( SELECT JSON_QUERY(ISNULL(@objects_json, N'[]')) AS objects, @total_count AS total_count, @limit AS [limit], @offset AS [offset] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ) AS result; DROP TABLE #projections; END; GO PRINT N'========================================='; PRINT N'OPTIMIZED Projection procedures created!'; PRINT N''; PRINT N'KEY OPTIMIZATIONS:'; PRINT N' - Replaced cursors with table variables'; PRINT N' - Temp table #filtered_ids instead of CTE filtered'; PRINT N' - Materialized IDs avoid CTE re-computation in subqueries'; PRINT N' - CASE expressions instead of N LEFT JOINs'; PRINT N' - GROUP BY aggregation instead of PVT'; PRINT N''; PRINT N'PROCEDURES:'; PRINT N' get_object_with_projection'; PRINT N' search_objects_with_projection'; PRINT N' search_objects_with_projection_by_paths'; PRINT N' search_objects_with_projection_by_ids'; PRINT N''; PRINT N'Expected speedup: 5-50x for multi-field projections'; PRINT N'========================================='; GO Path: redb/redb.MSSql/sql/deprecated/redb_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.MSSql/sql/deprecated/redb_window.sql ---- -- ===================================================== -- REDB EAV WINDOW FUNCTIONS (MSSQL) -- Window functions for EAV model -- ROW_NUMBER, RANK, SUM OVER, etc. -- Ported from PostgreSQL version -- ===================================================== SET NOCOUNT ON; GO -- ===== DROP EXISTING OBJECTS ===== IF OBJECT_ID('dbo.query_with_window', 'P') IS NOT NULL DROP PROCEDURE dbo.query_with_window; GO IF OBJECT_ID('dbo.resolve_field_path', 'P') IS NOT NULL DROP PROCEDURE dbo.resolve_field_path; GO -- ===================================================== -- Helper: resolve_field_path -- Resolves field path to structure info -- Supports: simple fields, nested paths (Address1.City), -- dictionaries (PhoneBook[home]), nested dict (AddressBook[home].City) -- ===================================================== CREATE PROCEDURE dbo.resolve_field_path @scheme_id BIGINT, @field_path NVARCHAR(255), @structure_id BIGINT OUTPUT, @db_type NVARCHAR(50) OUTPUT, @dict_key NVARCHAR(255) OUTPUT, @array_index NVARCHAR(50) OUTPUT AS BEGIN SET NOCOUNT ON; SET @structure_id = NULL; SET @db_type = NULL; SET @dict_key = NULL; SET @array_index = NULL; DECLARE @remaining_path NVARCHAR(255) = @field_path; DECLARE @current_segment NVARCHAR(255); DECLARE @parent_structure_id BIGINT = NULL; DECLARE @dot_pos INT; DECLARE @bracket_pos INT; DECLARE @key_end INT; DECLARE @segment_name NVARCHAR(255); DECLARE @key_value NVARCHAR(255); -- Process path segments (split by dots, respecting brackets) WHILE @remaining_path IS NOT NULL AND LEN(@remaining_path) > 0 BEGIN -- Find next segment: either up to dot or end of string -- But dots inside [] should be ignored SET @bracket_pos = CHARINDEX(N'[', @remaining_path); SET @dot_pos = CHARINDEX(N'.', @remaining_path); -- If bracket comes before dot, find dot after bracket end IF @bracket_pos > 0 AND (@dot_pos = 0 OR @bracket_pos < @dot_pos) BEGIN SET @key_end = CHARINDEX(N']', @remaining_path); -- Find dot after bracket end IF @key_end > 0 SET @dot_pos = CHARINDEX(N'.', @remaining_path, @key_end); END IF @dot_pos > 0 BEGIN SET @current_segment = LEFT(@remaining_path, @dot_pos - 1); SET @remaining_path = SUBSTRING(@remaining_path, @dot_pos + 1, LEN(@remaining_path)); END ELSE BEGIN SET @current_segment = @remaining_path; SET @remaining_path = NULL; END -- Parse current segment for bracket notation SET @bracket_pos = CHARINDEX(N'[', @current_segment); IF @bracket_pos > 0 BEGIN SET @key_end = CHARINDEX(N']', @current_segment); SET @segment_name = LEFT(@current_segment, @bracket_pos - 1); SET @key_value = SUBSTRING(@current_segment, @bracket_pos + 1, @key_end - @bracket_pos - 1); -- Save key when we find bracket notation (for dict/array access) -- This applies even for intermediate segments like AddressBook[home].City IF @key_value <> N'' AND @key_value NOT LIKE N'%[^0-9]%' SET @array_index = @key_value; ELSE IF @key_value <> N'' SET @dict_key = @key_value; END ELSE BEGIN SET @segment_name = @current_segment; END -- Find structure for this segment IF @parent_structure_id IS NULL BEGIN -- Top-level field SELECT TOP 1 @structure_id = c._structure_id, @db_type = c.db_type FROM _scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @segment_name AND c._parent_structure_id IS NULL; END ELSE BEGIN -- Nested field SELECT TOP 1 @structure_id = c._structure_id, @db_type = c.db_type FROM _scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @segment_name AND c._parent_structure_id = @parent_structure_id; END -- If not found, try to find by full path (for backward compatibility) IF @structure_id IS NULL AND @parent_structure_id IS NULL BEGIN SELECT TOP 1 @structure_id = c._structure_id, @db_type = c.db_type FROM _scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @field_path AND c._parent_structure_id IS NULL; IF @structure_id IS NOT NULL RETURN; -- Found by full path, exit END IF @structure_id IS NULL RETURN; -- Segment not found -- Move to next level SET @parent_structure_id = @structure_id; END END; GO -- ===================================================== -- query_with_window: Query with window functions -- ===================================================== -- Parameters: -- @scheme_id - Scheme ID -- @select_fields - JSON array of SELECT fields: -- [{"field":"Name","alias":"Name"}] -- @window_funcs - JSON array of window functions: -- [{"func":"ROW_NUMBER","alias":"Rank"}] -- @partition_by - JSON array for PARTITION BY: -- [{"field":"Category"}] -- @order_by - JSON array for ORDER BY inside window: -- [{"field":"Stock","dir":"DESC"}] -- @filter_json - JSON filter (optional) -- @limit - Record limit -- @frame_json - Frame specification (optional) -- -- Returns: JSON array of objects with window functions -- ===================================================== CREATE PROCEDURE dbo.query_with_window @scheme_id BIGINT, @select_fields NVARCHAR(MAX), @window_funcs NVARCHAR(MAX), @partition_by NVARCHAR(MAX) = N'[]', @order_by NVARCHAR(MAX) = N'[]', @filter_json NVARCHAR(MAX) = NULL, @limit INT = 1000, @frame_json NVARCHAR(MAX) = NULL AS BEGIN SET NOCOUNT ON; DECLARE @select_parts NVARCHAR(MAX) = N''; DECLARE @join_parts NVARCHAR(MAX) = N''; DECLARE @partition_parts NVARCHAR(MAX) = N''; DECLARE @order_parts NVARCHAR(MAX) = N''; DECLARE @over_clause NVARCHAR(MAX); DECLARE @frame_clause NVARCHAR(500) = N''; DECLARE @where_clause NVARCHAR(MAX) = N''; DECLARE @join_idx INT = 0; DECLARE @join_alias NVARCHAR(10); DECLARE @column_name NVARCHAR(50); DECLARE @field_path NVARCHAR(255); DECLARE @alias NVARCHAR(255); DECLARE @func_name NVARCHAR(50); DECLARE @dir NVARCHAR(10); DECLARE @buckets INT; DECLARE @structure_id BIGINT; DECLARE @db_type NVARCHAR(50); DECLARE @dict_key NVARCHAR(255); DECLARE @array_index NVARCHAR(50); DECLARE @sql NVARCHAR(MAX); DECLARE @result NVARCHAR(MAX); -- ========================================= -- 1. Base SELECT fields -- ========================================= SET @select_parts = N'o._id AS [id], o._name AS [name]'; -- Process select fields from JSON DECLARE @field_cursor CURSOR; SET @field_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field_path, ISNULL(JSON_VALUE(value, '$.alias'), JSON_VALUE(value, '$.field')) AS alias FROM OPENJSON(@select_fields); OPEN @field_cursor; FETCH NEXT FROM @field_cursor INTO @field_path, @alias; WHILE @@FETCH_STATUS = 0 BEGIN IF @field_path IS NOT NULL BEGIN -- Check for base field (0$: prefix) IF @field_path LIKE N'0$:%' BEGIN DECLARE @raw_field NVARCHAR(100) = SUBSTRING(@field_path, 4, 100); DECLARE @sql_column NVARCHAR(100) = dbo.normalize_base_field_name(@raw_field); IF @sql_column IS NOT NULL SET @select_parts = @select_parts + N', o.' + @sql_column + N' AS [' + @alias + N']'; END ELSE BEGIN -- EAV field from _values EXEC resolve_field_path @scheme_id, @field_path, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N's' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'String' THEN N'_String' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' WHEN N'Boolean' THEN N'_Boolean' ELSE N'_String' END; SET @select_parts = @select_parts + N', ' + @join_alias + N'.' + @column_name + N' AS [' + @alias + N']'; -- Build JOIN IF @dict_key IS NOT NULL SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + @dict_key + N''''; ELSE IF @array_index IS NOT NULL SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + @array_index + N''''; ELSE SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index IS NULL'; END END END FETCH NEXT FROM @field_cursor INTO @field_path, @alias; END CLOSE @field_cursor; DEALLOCATE @field_cursor; -- ========================================= -- 2. PARTITION BY -- ========================================= SET @field_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field_path FROM OPENJSON(@partition_by); OPEN @field_cursor; FETCH NEXT FROM @field_cursor INTO @field_path; WHILE @@FETCH_STATUS = 0 BEGIN IF @field_path IS NOT NULL BEGIN IF @field_path LIKE N'0$:%' BEGIN SET @raw_field = SUBSTRING(@field_path, 4, 100); SET @sql_column = dbo.normalize_base_field_name(@raw_field); IF @sql_column IS NOT NULL BEGIN IF @partition_parts <> N'' SET @partition_parts = @partition_parts + N', '; SET @partition_parts = @partition_parts + N'o.' + @sql_column; END END ELSE BEGIN EXEC resolve_field_path @scheme_id, @field_path, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'p' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'String' THEN N'_String' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' WHEN N'Boolean' THEN N'_Boolean' ELSE N'_String' END; IF @partition_parts <> N'' SET @partition_parts = @partition_parts + N', '; SET @partition_parts = @partition_parts + @join_alias + N'.' + @column_name; -- Build JOIN IF @dict_key IS NOT NULL SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + @dict_key + N''''; ELSE IF @array_index IS NOT NULL SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + @array_index + N''''; ELSE SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index IS NULL'; END END END FETCH NEXT FROM @field_cursor INTO @field_path; END CLOSE @field_cursor; DEALLOCATE @field_cursor; -- ========================================= -- 3. ORDER BY inside window -- ========================================= SET @field_cursor = CURSOR FOR SELECT JSON_VALUE(value, '$.field') AS field_path, ISNULL(UPPER(JSON_VALUE(value, '$.dir')), N'ASC') AS dir FROM OPENJSON(@order_by); OPEN @field_cursor; FETCH NEXT FROM @field_cursor INTO @field_path, @dir; WHILE @@FETCH_STATUS = 0 BEGIN IF @field_path IS NOT NULL BEGIN IF @field_path LIKE N'0$:%' BEGIN SET @raw_field = SUBSTRING(@field_path, 4, 100); SET @sql_column = dbo.normalize_base_field_name(@raw_field); IF @sql_column IS NOT NULL BEGIN IF @order_parts <> N'' SET @order_parts = @order_parts + N', '; SET @order_parts = @order_parts + N'o.' + @sql_column + N' ' + @dir; END END ELSE BEGIN EXEC resolve_field_path @scheme_id, @field_path, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'w' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' WHEN N'Boolean' THEN N'_Boolean' ELSE N'_String' END; IF @order_parts <> N'' SET @order_parts = @order_parts + N', '; SET @order_parts = @order_parts + @join_alias + N'.' + @column_name + N' ' + @dir; -- Build JOIN IF @dict_key IS NOT NULL SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + @dict_key + N''''; ELSE IF @array_index IS NOT NULL SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + @array_index + N''''; ELSE SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index IS NULL'; END END END FETCH NEXT FROM @field_cursor INTO @field_path, @dir; END CLOSE @field_cursor; DEALLOCATE @field_cursor; -- ========================================= -- 4. Build OVER clause (with ROWS BETWEEN support) -- ========================================= IF @frame_json IS NOT NULL AND @frame_json <> N'' AND @frame_json <> N'null' BEGIN DECLARE @frame_type NVARCHAR(10) = ISNULL(UPPER(JSON_VALUE(@frame_json, '$.type')), N'ROWS'); DECLARE @start_kind NVARCHAR(50) = UPPER(JSON_VALUE(@frame_json, '$.start.kind')); DECLARE @start_offset INT = ISNULL(CAST(JSON_VALUE(@frame_json, '$.start.offset') AS INT), 0); DECLARE @end_kind NVARCHAR(50) = UPPER(JSON_VALUE(@frame_json, '$.end.kind')); DECLARE @end_offset INT = ISNULL(CAST(JSON_VALUE(@frame_json, '$.end.offset') AS INT), 0); SET @frame_clause = @frame_type + N' BETWEEN '; -- Start bound SET @frame_clause = @frame_clause + CASE @start_kind WHEN N'UNBOUNDEDPRECEDING' THEN N'UNBOUNDED PRECEDING' WHEN N'CURRENTROW' THEN N'CURRENT ROW' WHEN N'PRECEDING' THEN CAST(@start_offset AS NVARCHAR(10)) + N' PRECEDING' WHEN N'FOLLOWING' THEN CAST(@start_offset AS NVARCHAR(10)) + N' FOLLOWING' ELSE N'UNBOUNDED PRECEDING' END; SET @frame_clause = @frame_clause + N' AND '; -- End bound SET @frame_clause = @frame_clause + CASE @end_kind WHEN N'UNBOUNDEDFOLLOWING' THEN N'UNBOUNDED FOLLOWING' WHEN N'CURRENTROW' THEN N'CURRENT ROW' WHEN N'PRECEDING' THEN CAST(@end_offset AS NVARCHAR(10)) + N' PRECEDING' WHEN N'FOLLOWING' THEN CAST(@end_offset AS NVARCHAR(10)) + N' FOLLOWING' ELSE N'CURRENT ROW' END; END -- Build OVER clause SET @over_clause = N'OVER ('; IF @partition_parts <> N'' SET @over_clause = @over_clause + N'PARTITION BY ' + @partition_parts; IF @order_parts <> N'' BEGIN IF @partition_parts <> N'' SET @over_clause = @over_clause + N' '; SET @over_clause = @over_clause + N'ORDER BY ' + @order_parts; END IF @frame_clause <> N'' BEGIN IF @partition_parts <> N'' OR @order_parts <> N'' SET @over_clause = @over_clause + N' '; SET @over_clause = @over_clause + @frame_clause; END SET @over_clause = @over_clause + N')'; -- ========================================= -- 5. Window functions -- ========================================= SET @field_cursor = CURSOR FOR SELECT UPPER(JSON_VALUE(value, '$.func')) AS func_name, ISNULL(JSON_VALUE(value, '$.alias'), UPPER(JSON_VALUE(value, '$.func'))) AS alias, JSON_VALUE(value, '$.field') AS field_path, ISNULL(CAST(JSON_VALUE(value, '$.buckets') AS INT), 4) AS buckets FROM OPENJSON(@window_funcs); OPEN @field_cursor; FETCH NEXT FROM @field_cursor INTO @func_name, @alias, @field_path, @buckets; WHILE @@FETCH_STATUS = 0 BEGIN IF @func_name IN (N'ROW_NUMBER', N'RANK', N'DENSE_RANK', N'COUNT') BEGIN -- Ranking functions (no field) IF @func_name = N'COUNT' SET @select_parts = @select_parts + N', COUNT(*) ' + @over_clause + N' AS [' + @alias + N']'; ELSE SET @select_parts = @select_parts + N', ' + @func_name + N'() ' + @over_clause + N' AS [' + @alias + N']'; END ELSE IF @func_name = N'NTILE' BEGIN SET @select_parts = @select_parts + N', NTILE(' + CAST(@buckets AS NVARCHAR(10)) + N') ' + @over_clause + N' AS [' + @alias + N']'; END ELSE IF @func_name IN (N'SUM', N'AVG', N'MIN', N'MAX', N'LAG', N'LEAD', N'FIRST_VALUE', N'LAST_VALUE') BEGIN IF @field_path IS NOT NULL AND @field_path <> N'' BEGIN EXEC resolve_field_path @scheme_id, @field_path, @structure_id OUTPUT, @db_type OUTPUT, @dict_key OUTPUT, @array_index OUTPUT; IF @structure_id IS NOT NULL BEGIN SET @join_idx = @join_idx + 1; SET @join_alias = N'f' + CAST(@join_idx AS NVARCHAR(10)); SET @column_name = CASE @db_type WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'String' THEN N'_String' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' WHEN N'Boolean' THEN N'_Boolean' ELSE N'_Long' END; -- Build JOIN IF @dict_key IS NOT NULL SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + @dict_key + N''''; ELSE IF @array_index IS NOT NULL SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index = N''' + @array_index + N''''; ELSE SET @join_parts = @join_parts + N' LEFT JOIN _values ' + @join_alias + N' ON ' + @join_alias + N'._id_object = o._id AND ' + @join_alias + N'._id_structure = ' + CAST(@structure_id AS NVARCHAR(20)) + N' AND ' + @join_alias + N'._array_index IS NULL'; SET @select_parts = @select_parts + N', ' + @func_name + N'(' + @join_alias + N'.' + @column_name + N') ' + @over_clause + N' AS [' + @alias + N']'; END END END FETCH NEXT FROM @field_cursor INTO @func_name, @alias, @field_path, @buckets; END CLOSE @field_cursor; DEALLOCATE @field_cursor; -- ========================================= -- 6. Filter -- ========================================= IF @filter_json IS NOT NULL AND @filter_json <> N'' AND @filter_json <> N'null' BEGIN -- Use internal_parse_filters to get WHERE clause DECLARE @filter_result NVARCHAR(MAX); EXEC internal_parse_filters @scheme_id, @filter_json, N'o', N'AND', 0, @filter_result OUTPUT; IF @filter_result IS NOT NULL AND @filter_result <> N'' SET @where_clause = N' AND ' + @filter_result; END -- ========================================= -- 7. Build and execute SQL -- ========================================= SET @sql = N' SELECT @result = ( SELECT ' + @select_parts + N' FROM _objects o' + @join_parts + N' WHERE o._id_scheme = ' + CAST(@scheme_id AS NVARCHAR(20)); IF @where_clause IS NOT NULL AND @where_clause <> N'' SET @sql = @sql + @where_clause; SET @sql = @sql + N' ORDER BY o._id OFFSET 0 ROWS FETCH NEXT ' + CAST(@limit AS NVARCHAR(20)) + N' ROWS ONLY FOR JSON PATH )'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result = @result OUTPUT; SELECT ISNULL(@result, N'[]') AS result; END; GO PRINT N'========================================='; PRINT N'Window Functions procedures created!'; PRINT N''; PRINT N'PROCEDURES:'; PRINT N' query_with_window - Query with window functions'; PRINT N' resolve_field_path - Helper to resolve field paths'; PRINT N''; PRINT N'SUPPORTED FUNCTIONS:'; PRINT N' Ranking: ROW_NUMBER, RANK, DENSE_RANK, NTILE'; PRINT N' Aggregate: SUM, AVG, MIN, MAX, COUNT'; PRINT N' Offset: LAG, LEAD, FIRST_VALUE, LAST_VALUE'; PRINT N''; PRINT N'FEATURES:'; PRINT N' - Base fields with 0$: prefix'; PRINT N' - EAV fields from _values'; PRINT N' - Dictionary support: PhoneBook[home]'; PRINT N' - Array index support: Items[2]'; PRINT N' - ROWS BETWEEN frame support'; PRINT N'========================================='; GO Path: redb/redb.MSSql/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.MSSql/sql/maintenance/free_value_indexes.sql ---- -- ===================================================================== -- REDB (SQL Server): value indexes for the FREE provider -- ===================================================================== -- The PVT module 0.2.30 replaced eleven object-leading value indexes (_id_structure, _id_object, ) -- with value-leading ones (_id_structure, , _id_object). The new ones serve a filter on a field; -- the old ones served reading the value of a known object. -- -- This file brings them back under names of their own (IX__values__free_*). 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. -- -- Eight indexes, one per value column, and one over the children of a collection element (below). Left out -- on purpose: -- IX__values__{Long,DateTimeOffset,Numeric}_not_null - the same definition as the *_filter index of -- the same column, so each was a duplicate; -- the string - NVARCHAR(MAX) cannot be an index key; -- the seven indexes the module 0.2.29 dropped as duplicates: the leading columns of each are the -- leading columns of an index or UNIQUE constraint of the same table that stays. -- IX__values__structure_object_lookup was never dropped on SQL Server and stays in the schema. -- -- What was measured: on the examples database (100 613 objects, 8.46 million values) the eight -- *_by_object indexes gave no gain. Free queries there read IX__values__object_structure_lookup, which -- covers every value column, and over a whole run of the examples one of the eight was read 16 times and -- the others never. They are kept because they restore the indexes the free provider had before the -- module retired them, for databases whose queries differ from the examples. Only -- IX__values__free_parent_children has a measured gain (below). -- -- Price: every index here is updated on each save of a value of its column. Run the file only if free -- queries got slower, and keep an index only if its usage counters show reads. -- -- Nothing runs this file automatically. Run it yourself, once per database: -- sqlcmd -S -d -i free_value_indexes.sql -- Without ONLINE = ON writes to _values wait while an index is built. ONLINE = ON is available on -- Enterprise and Developer editions and on Azure SQL: add WITH (ONLINE = ON) to each CREATE there. -- Running it again is safe: an existing index is kept. -- -- To remove them: -- DROP INDEX IF EXISTS [IX__values__free_long_by_object] ON [dbo].[_values]; (and so on for each name below) -- ===================================================================== -- Filtered indexes need these; sqlcmd starts with QUOTED_IDENTIFIER OFF. SET QUOTED_IDENTIFIER ON; SET ANSI_NULLS ON; SET NOCOUNT ON; GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_long_by_object') CREATE INDEX [IX__values__free_long_by_object] ON [dbo].[_values]([_id_structure], [_id_object], [_Long]) WHERE [_Long] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_guid_by_object') CREATE INDEX [IX__values__free_guid_by_object] ON [dbo].[_values]([_id_structure], [_id_object], [_Guid]) WHERE [_Guid] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_double_by_object') CREATE INDEX [IX__values__free_double_by_object] ON [dbo].[_values]([_id_structure], [_id_object], [_Double]) WHERE [_Double] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_datetimeoffset_by_object') CREATE INDEX [IX__values__free_datetimeoffset_by_object] ON [dbo].[_values]([_id_structure], [_id_object], [_DateTimeOffset]) WHERE [_DateTimeOffset] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_boolean_by_object') CREATE INDEX [IX__values__free_boolean_by_object] ON [dbo].[_values]([_id_structure], [_id_object], [_Boolean]) WHERE [_Boolean] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_numeric_by_object') CREATE INDEX [IX__values__free_numeric_by_object] ON [dbo].[_values]([_id_structure], [_id_object], [_Numeric]) WHERE [_Numeric] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_listitem_by_object') CREATE INDEX [IX__values__free_listitem_by_object] ON [dbo].[_values]([_id_structure], [_id_object], [_ListItem]) WHERE [_ListItem] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_object_by_object') CREATE INDEX [IX__values__free_object_by_object] ON [dbo].[_values]([_id_structure], [_id_object], [_Object]) WHERE [_Object] IS NOT NULL; GO -- Children of a collection element with their field and string value. A field of a class inside a dictionary -- or an array (Dict[key].Field) is joined to its element by _array_parent_id alone, and the field is picked -- afterwards; no other index carries _id_structure, _array_index and _String by parent, so SQL Server read the -- whole _values instead. Example E062 (Dictionary, nested class property), 100 613 objects, 8.46 million -- values: 13.4 s -> 1.9 s. Holds every child value of every collection element, the string included, so it -- is large where collections of classes carry long strings. IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__free_parent_children') CREATE INDEX [IX__values__free_parent_children] ON [dbo].[_values]([_array_parent_id]) INCLUDE ([_id_structure], [_array_index], [_String]) WHERE [_array_parent_id] IS NOT NULL; GO UPDATE STATISTICS [dbo].[_values]; GO Path: redb/redb.MSSql/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.MSSql/sql/maintenance/rebuild_objects_indexes_without_date_modify.sql ---- -- ===================================================================== -- REDB (SQL Server): bring three _objects indexes of an EXISTING database to the current schema -- ===================================================================== -- redbMSSQL.sql no longer puts _date_modify into INCLUDE of these indexes. That file runs only on a -- new database, so an existing one keeps the old definitions until this file is run. -- -- Why it matters: _date_modify changes on every save, so an index that carries it is rewritten for -- every saved object. On PostgreSQL, with frequent saves, these three had grown to 700-1400 bytes per -- entry and shrank 10-20 times when rebuilt without the column. -- -- Nothing runs this file automatically. Run it yourself, once per database: -- sqlcmd -S -d -i rebuild_objects_indexes_without_date_modify.sql -- -- Each index is rebuilt in place under its own name (DROP_EXISTING = ON); an index that is missing is -- created. Without ONLINE = ON writes to _objects wait while an index is rebuilt. ONLINE = ON is -- available on Enterprise and Developer editions and on Azure SQL: add it to the WITH clauses there. -- Running the file again only pays for one more rebuild. -- ===================================================================== -- Filtered indexes need these; sqlcmd starts with QUOTED_IDENTIFIER OFF. SET QUOTED_IDENTIFIER ON; SET ANSI_NULLS ON; SET NOCOUNT ON; GO -- 1. Descendants of an object IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._objects') AND name = N'IX__objects__parent_id_descendant_lookup') CREATE INDEX [IX__objects__parent_id_descendant_lookup] ON [dbo].[_objects]([_id_parent], [_id_scheme]) INCLUDE ([_id], [_id_owner], [_date_create]) WHERE [_id_parent] IS NOT NULL WITH (DROP_EXISTING = ON); ELSE CREATE INDEX [IX__objects__parent_id_descendant_lookup] ON [dbo].[_objects]([_id_parent], [_id_scheme]) INCLUDE ([_id], [_id_owner], [_date_create]) WHERE [_id_parent] IS NOT NULL; GO -- 2. Tree queries sorted by creation date IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._objects') AND name = N'IX__objects__scheme_parent_date_create') CREATE INDEX [IX__objects__scheme_parent_date_create] ON [dbo].[_objects]([_id_scheme], [_id_parent], [_date_create] DESC) INCLUDE ([_id], [_id_owner]) WITH (DROP_EXISTING = ON); ELSE CREATE INDEX [IX__objects__scheme_parent_date_create] ON [dbo].[_objects]([_id_scheme], [_id_parent], [_date_create] DESC) INCLUDE ([_id], [_id_owner]); GO -- 3. Tree queries filtered by owner or name IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._objects') AND name = N'IX__objects__scheme_parent_owner') CREATE INDEX [IX__objects__scheme_parent_owner] ON [dbo].[_objects]([_id_scheme], [_id_parent]) INCLUDE ([_id], [_id_owner], [_date_create], [_name]) WHERE [_id_parent] IS NOT NULL WITH (DROP_EXISTING = ON); ELSE CREATE INDEX [IX__objects__scheme_parent_owner] ON [dbo].[_objects]([_id_scheme], [_id_parent]) INCLUDE ([_id], [_id_owner], [_date_create], [_name]) WHERE [_id_parent] IS NOT NULL; GO UPDATE STATISTICS [dbo].[_objects]; GO Path: redb/redb.MSSql/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.MSSql/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 -- IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'TR__objects__deleted_objects') -- DROP TRIGGER [dbo].[TR__objects__deleted_objects] -- GO -- 2. Drop the archive table IF OBJECT_ID('[dbo].[_deleted_objects]', 'U') IS NOT NULL DROP TABLE [dbo].[_deleted_objects] GO -- 3. Add the @@__deleted scheme if not exists IF NOT EXISTS (SELECT 1 FROM [dbo].[_schemes] WHERE [_id] = -10) INSERT INTO [dbo].[_schemes] ([_id], [_name], [_alias], [_type]) VALUES (-10, '@@__deleted', 'Deleted Objects', -9223372036854775703) GO -- ===================================================== -- VERIFICATION -- ===================================================== -- After running this script, verify: -- SELECT * FROM [dbo].[_schemes] WHERE [_id] = -10 -- Expected: @@__deleted scheme exists -- -- SELECT * FROM sys.triggers WHERE name = 'TR__objects__deleted_objects' -- Expected: No rows (trigger removed) -- ===================================================== Path: redb/redb.MSSql/sql/redbMSSQL.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.MSSql/sql/redbMSSQL.sql ---- -- ===================================================== -- REDB MS SQL Server Schema -- Version: 2.0 (with Array/Dictionary/JsonDocument support) -- Compatible with SQL Server 2016+ -- Creates the schema in an EMPTY database. A database that already holds it is left as it is: the guard below stops -- the script before any statement. An existing schema is upgraded by the service at start or with -- `redb schema --upgrade --provider mssql` (GetUpgradeScript), never by running this script again. -- ===================================================== -- Guard: the schema is already here. RAISERROR reports it; SET NOEXEC ON makes sqlcmd and SSMS compile the remaining -- batches without running them (SET NOEXEC OFF at the end of the script turns it back). This script used to drop every -- foreign key and the identity sequence first, so a second run left a live database without both. IF OBJECT_ID(N'[dbo].[_types]', N'U') IS NOT NULL BEGIN RAISERROR(N'redb: this database already holds the redb schema (dbo._types exists). The creation script runs on an empty database only and has changed nothing. Upgrade an existing schema with `redb schema --upgrade --provider mssql` or by starting the service; to start over, drop and create the database first.', 16, 1); SET NOEXEC ON; END GO -- Enable row-versioning for READ COMMITTED to eliminate reader/writer deadlocks DECLARE @dbname NVARCHAR(256) = DB_NAME(); DECLARE @rcsi NVARCHAR(500) = N'ALTER DATABASE ' + QUOTENAME(@dbname) + N' SET READ_COMMITTED_SNAPSHOT ON;'; -- Only when it is off: ALTER DATABASE waits until it is the only session in the database, and a script run again on -- a database in use (an upgrade, a second node) would wait for every other connection. IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = @dbname AND is_read_committed_snapshot_on = 1) EXEC sp_executesql @rcsi; GO -- ===================================================== -- CREATE TABLES -- ===================================================== -- Types table (base types for structures) CREATE TABLE [dbo].[_types]( [_id] BIGINT NOT NULL, [_name] NVARCHAR(450) NOT NULL, -- max for UNIQUE index (900 bytes) [_db_type] NVARCHAR(450) NULL, [_type] NVARCHAR(450) NULL, CONSTRAINT [PK__types] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [IX__types_name] UNIQUE ([_name]) ) GO -- Links table (many-to-many relations) CREATE TABLE [dbo].[_links]( [_id] BIGINT NOT NULL, [_id_1] BIGINT NOT NULL, [_id_2] BIGINT NOT NULL, CONSTRAINT [PK__links] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [IX__links] UNIQUE ([_id_1], [_id_2]), CONSTRAINT [CK__links] CHECK ([_id_1] <> [_id_2]) ) GO -- Lists table (reference lists/dictionaries) CREATE TABLE [dbo].[_lists]( [_id] BIGINT NOT NULL, [_name] NVARCHAR(450) NOT NULL, -- max for UNIQUE index [_alias] NVARCHAR(450) NULL, CONSTRAINT [PK__lists] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [IX__lists_name] UNIQUE ([_name]) ) GO -- Roles table CREATE TABLE [dbo].[_roles]( [_id] BIGINT NOT NULL, [_name] NVARCHAR(450) NOT NULL, -- max for UNIQUE index [_id_configuration] BIGINT NULL, CONSTRAINT [PK__roles] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [IX__roles] UNIQUE ([_name]) ) GO -- Users table CREATE TABLE [dbo].[_users]( [_id] BIGINT NOT NULL, [_login] NVARCHAR(450) NOT NULL, [_password] NVARCHAR(MAX) NOT NULL, [_name] NVARCHAR(450) NOT NULL, [_phone] NVARCHAR(450) NULL, [_email] NVARCHAR(450) NULL, [_date_register] DATETIMEOFFSET NOT NULL DEFAULT SYSDATETIMEOFFSET(), [_date_dismiss] DATETIMEOFFSET NULL, [_enabled] BIT NOT NULL DEFAULT 1, [_key] BIGINT NULL, [_code_int] BIGINT NULL, [_code_string] NVARCHAR(MAX) NULL, [_code_guid] UNIQUEIDENTIFIER NULL, [_note] NVARCHAR(MAX) NULL, [_hash] UNIQUEIDENTIFIER NULL, [_id_configuration] BIGINT NULL, CONSTRAINT [PK__users] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [IX__users_login] UNIQUE ([_login]) ) GO -- Users-Roles junction table CREATE TABLE [dbo].[_users_roles]( [_id] BIGINT NOT NULL, [_id_role] BIGINT NOT NULL, [_id_user] BIGINT NOT NULL, CONSTRAINT [PK__users_roles] PRIMARY KEY CLUSTERED ([_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 NO ACTION ) GO -- Schemes table (class definitions) CREATE TABLE [dbo].[_schemes]( [_id] BIGINT NOT NULL, [_id_parent] BIGINT NULL, [_name] NVARCHAR(450) NOT NULL, -- max for UNIQUE index [_alias] NVARCHAR(450) NULL, [_name_space] NVARCHAR(MAX) NULL, [_structure_hash] UNIQUEIDENTIFIER NULL, [_tags] NVARCHAR(450) NULL, -- V4: free-form marker for future / custom extensions (sync never wipes it) [_renamed_from] NVARCHAR(MAX) NULL, -- previous names, oldest first, as a JSON array (RedbRename / RedbScheme.RenamedFrom); NULL = never renamed [_version] INT NULL, -- version of the Props class last synchronised (RedbScheme.Version); NULL = 0; never lowered [_type] BIGINT NOT NULL DEFAULT -9223372036854775675, -- Class by default CONSTRAINT [PK__schemes] PRIMARY KEY CLUSTERED ([_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]) ) GO -- Scheme name validation. Mirrors the PostgreSQL validate_scheme_name() trigger rule for rule so -- that a name accepted by one provider is accepted by all three. -- -- This is a BACKSTOP against writes that bypass the library. The library validates explicit names -- in C# first (redb.Core/Attributes/SchemeNameValidator.cs), which is what reports the offending -- type instead of a bare error number, and which also covers databases created before this trigger -- existed -- EnsureDatabaseAsync skips initialisation entirely when _schemes is already present, so -- older databases never receive it. CREATE TRIGGER [dbo].[tr_validate_scheme_name] ON [dbo].[_schemes] AFTER INSERT, UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @name NVARCHAR(450), @reason NVARCHAR(400); ;WITH changed AS ( -- Only rows whose _name was actually written; an UPDATE of the hash or alias must not pay -- for validation, and must not fail on a legacy name that predates these rules. SELECT i.[_name] FROM inserted i LEFT JOIN deleted d ON d.[_id] = i.[_id] WHERE (d.[_id] IS NULL OR d.[_name] <> i.[_name]) AND i.[_name] NOT LIKE '@@%' -- system schemes (e.g. @@__deleted) bypass validation ), parts AS ( SELECT c.[_name], s.value AS part FROM changed c CROSS APPLY STRING_SPLIT(REPLACE(c.[_name], '+', '.'), '.') s ), violations AS ( SELECT 1 AS rule_no, [_name], N'it cannot start with a digit' AS reason FROM changed WHERE [_name] LIKE '[0-9]%' UNION ALL SELECT 2, [_name], N'it contains characters outside [a-zA-Z0-9_.+] or does not start with a letter/underscore' FROM changed WHERE [_name] LIKE '%[^a-zA-Z0-9_.+]%' OR [_name] LIKE '[^a-zA-Z_]%' UNION ALL SELECT 3, [_name], N'it cannot end with a dot' FROM changed WHERE [_name] LIKE '%.' UNION ALL SELECT 4, [_name], N'it cannot contain two consecutive dots' FROM changed WHERE [_name] LIKE '%..%' UNION ALL SELECT 5, [_name], N'it cannot be empty' FROM changed WHERE LEN(LTRIM(RTRIM([_name]))) = 0 UNION ALL SELECT 6, [_name], N'it is longer than 128 characters' FROM changed WHERE LEN([_name]) > 128 UNION ALL SELECT 7, [_name], N'one of its parts is a C# reserved word' FROM parts WHERE LOWER(part) IN ( N'abstract', N'as', N'bool', N'break', N'byte', N'case', N'catch', N'char', N'checked', N'class', N'const', N'continue', N'decimal', N'default', N'delegate', N'do', N'double', N'else', N'enum', N'event', N'explicit', N'extern', N'false', N'finally', N'fixed', N'float', N'for', N'foreach', N'goto', N'if', N'implicit', N'in', N'int', N'interface', N'internal', N'is', N'lock', N'long', N'namespace', N'new', N'null', N'object', N'operator', N'out', N'override', N'params', N'private', N'protected', N'public', N'readonly', N'ref', N'return', N'sbyte', N'sealed', N'short', N'sizeof', N'stackalloc', N'static', N'string', N'struct', N'switch', N'this', N'throw', N'true', N'try', N'typeof', N'uint', N'ulong', N'unchecked', N'unsafe', N'ushort', N'using', N'virtual', N'void', N'volatile', N'while') UNION ALL SELECT 8, [_name], N'one of its parts is not a valid identifier' FROM parts WHERE LEN(LTRIM(RTRIM(part))) = 0 OR part LIKE '[0-9]%' OR part LIKE '%[^a-zA-Z0-9_]%' OR part LIKE '[^a-zA-Z_]%' ) -- Report the lowest-numbered broken rule, matching the order PostgreSQL checks them in. SELECT TOP 1 @name = [_name], @reason = reason FROM violations ORDER BY rule_no; IF @reason IS NOT NULL BEGIN DECLARE @msg NVARCHAR(700) = N'Scheme name "' + ISNULL(@name, N'') + N'" is invalid: ' + @reason + N'. Scheme names follow C# identifier rules; use _alias for human-readable titles.'; THROW 50000, @msg, 1; END END GO -- Structures table (field definitions) CREATE TABLE [dbo].[_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] NVARCHAR(440) NOT NULL, -- max for composite UNIQUE (8+8+880 = 896 < 900 bytes) [_alias] NVARCHAR(450) NULL, [_order] BIGINT NULL, [_readonly] BIT NULL, [_allow_not_null] BIT 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] BIT NULL, [_store_null] BIT NULL, [_unique] BIT 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] BIT NULL, -- V4 (LAZY Л2): lazy reference marker (virtual) [_tags] NVARCHAR(450) NULL, -- V4: free-form marker for future / custom extensions (sync never wipes it) [_renamed_from] NVARCHAR(MAX) NULL, -- previous names, oldest first, as a JSON array (RedbRename / RedbScheme.RenamedFrom); NULL = never renamed [_default_value] VARBINARY(MAX) NULL, [_default_editor] NVARCHAR(MAX) NULL, CONSTRAINT [PK__structures] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [IX__structures] UNIQUE ([_id_scheme], [_name], [_id_parent]), CONSTRAINT [FK__structures__structures] FOREIGN KEY ([_id_parent]) REFERENCES [_structures]([_id]) ON DELETE NO ACTION, 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]) ) GO -- Dependencies table (scheme dependencies) CREATE TABLE [dbo].[_dependencies]( [_id] BIGINT NOT NULL, [_id_scheme_1] BIGINT NULL, [_id_scheme_2] BIGINT NOT NULL, CONSTRAINT [PK__dependencies] PRIMARY KEY CLUSTERED ([_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 ) GO -- Objects table (data instances) CREATE TABLE [dbo].[_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] DATETIMEOFFSET NOT NULL DEFAULT SYSDATETIMEOFFSET(), [_date_modify] DATETIMEOFFSET NOT NULL DEFAULT SYSDATETIMEOFFSET(), [_date_begin] DATETIMEOFFSET NULL, [_date_complete] DATETIMEOFFSET NULL, [_key] BIGINT NULL, [_name] NVARCHAR(450) NULL, -- limited for index on IX__objects__name [_note] NVARCHAR(MAX) NULL, [_hash] UNIQUEIDENTIFIER NULL, -- Value columns for RedbPrimitive (Props = primitive value stored directly) [_value_long] BIGINT NULL, [_value_string] NVARCHAR(450) NULL, -- identifiers/external keys (owner decision 2026-09-02): 450*2=900 keeps the index key legal, same width as _name; long text belongs in _note [_value_guid] UNIQUEIDENTIFIER NULL, [_value_bool] BIT NULL, [_value_double] FLOAT NULL, [_value_numeric] DECIMAL(38, 18) NULL, [_value_datetime] DATETIMEOFFSET NULL, [_value_bytes] VARBINARY(MAX) NULL, [_value_unique] NVARCHAR(440) NULL, -- V4: unique key within the scheme (8+880 = 888 < 900); index below CONSTRAINT [PK__objects] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [FK__objects__objects] FOREIGN KEY ([_id_parent]) REFERENCES [_objects]([_id]) ON DELETE NO ACTION, CONSTRAINT [FK__objects__schemes] FOREIGN KEY ([_id_scheme]) REFERENCES [_schemes]([_id]) ON DELETE NO ACTION, CONSTRAINT [FK__objects__users1] FOREIGN KEY ([_id_owner]) REFERENCES [_users]([_id]), CONSTRAINT [FK__objects__users2] FOREIGN KEY ([_id_who_change]) REFERENCES [_users]([_id]) ) GO -- List items table CREATE TABLE [dbo].[_list_items]( [_id] BIGINT NOT NULL, [_id_list] BIGINT NOT NULL, [_value] NVARCHAR(440) NULL, -- max for composite UNIQUE (8+880 = 888 < 900 bytes) [_alias] NVARCHAR(450) NULL, [_id_object] BIGINT NULL, CONSTRAINT [PK__list_items] PRIMARY KEY CLUSTERED ([_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 ) GO -- Unique index for list items (list + value must be unique) CREATE UNIQUE INDEX [IX__list_items_unique] ON [dbo].[_list_items]([_id_list], [_value]) GO -- Values table (EAV data storage) CREATE TABLE [dbo].[_values]( [_id] BIGINT NOT NULL, [_id_structure] BIGINT NOT NULL, [_id_object] BIGINT NOT NULL, [_String] NVARCHAR(MAX) NULL, [_Long] BIGINT NULL, [_Guid] UNIQUEIDENTIFIER NULL, [_Double] FLOAT NULL, [_DateTimeOffset] DATETIMEOFFSET NULL, [_Boolean] BIT NULL, [_ByteArray] VARBINARY(MAX) NULL, [_Numeric] DECIMAL(38, 18) NULL, [_ListItem] BIGINT NULL, [_Object] BIGINT NULL, -- V4: unique-key hash of the typed value (UniqueKeyEncoder) for [RedbUnique] root scalars [_unique] UNIQUEIDENTIFIER NULL, -- Fields for relational collections (arrays, dictionaries, JSON/XML documents) [_array_parent_id] BIGINT NULL, [_array_index] NVARCHAR(430) NULL, -- Text key for Dictionary (limited: 3*BIGINT + 860 bytes = 884 < 900) CONSTRAINT [PK__values] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [FK__values__objects] FOREIGN KEY ([_id_object]) REFERENCES [_objects]([_id]) ON DELETE NO ACTION, -- DESIGN: NO ACTION here is required because MSSQL forbids multiple -- cascade paths into [_values] (conflict with FK__values__objects / -- FK__values__array_parent). The cascade behavior is provided instead -- by the INSTEAD OF DELETE trigger TR__structures__cascade_values -- (defined below at ~L717), which makes the runtime effect equivalent -- to PostgreSQL's ON DELETE CASCADE on _values._id_structure -- (redb.Postgres/sql/redbPostgre.sql ~L215). Destructive structure -- deletion 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 NO ACTION, CONSTRAINT [FK__values__array_parent] FOREIGN KEY ([_array_parent_id]) REFERENCES [_values]([_id]) ON DELETE NO ACTION, CONSTRAINT [FK__values__list_items] FOREIGN KEY ([_ListItem]) REFERENCES [_list_items]([_id]), CONSTRAINT [FK__values__objects_ref] FOREIGN KEY ([_Object]) REFERENCES [_objects]([_id]) ) -- NOTE: CASCADE delete handled by TR__objects__deleted_objects and TR__values__cascade_array_parent triggers GO -- Permissions table CREATE TABLE [dbo].[_permissions]( [_id] BIGINT NOT NULL, [_id_role] BIGINT NULL, [_id_user] BIGINT NULL, [_id_ref] BIGINT NOT NULL, [_select] BIT NULL, [_insert] BIT NULL, [_update] BIT NULL, [_delete] BIT NULL, CONSTRAINT [PK__permissions] PRIMARY KEY CLUSTERED ([_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 NO ACTION ) GO -- Functions table (stored procedures/expressions) CREATE TABLE [dbo].[_functions]( [_id] BIGINT NOT NULL, [_id_scheme] BIGINT NOT NULL, [_language] NVARCHAR(50) NOT NULL, [_name] NVARCHAR(440) NOT NULL, -- max for composite UNIQUE (8 bytes for _id_scheme + 880 bytes = 888 < 900) [_body] NVARCHAR(MAX) NOT NULL, CONSTRAINT [PK__functions] PRIMARY KEY CLUSTERED ([_id]), CONSTRAINT [IX__functions_scheme_name] UNIQUE ([_id_scheme], [_name]), CONSTRAINT [FK__functions__schemes] FOREIGN KEY ([_id_scheme]) REFERENCES [_schemes]([_id]) ) GO -- ===================================================== -- CREATE INDEXES -- ===================================================== -- Users/Roles indexes -- REMOVED (2026-10-14): [IX__users_roles__roles] (_id_role) is the leading column of the UNIQUE -- constraint IX__users_roles (_id_role, _id_user). CREATE INDEX [IX__users_roles__users] ON [dbo].[_users_roles]([_id_user]) CREATE INDEX [IX__users__id_configuration] ON [dbo].[_users]([_id_configuration]) WHERE [_id_configuration] IS NOT NULL CREATE INDEX [IX__users__name] ON [dbo].[_users]([_name]) CREATE INDEX [IX__roles__id_configuration] ON [dbo].[_roles]([_id_configuration]) WHERE [_id_configuration] IS NOT NULL GO -- Schemes indexes CREATE INDEX [IX__schemes__schemes] ON [dbo].[_schemes]([_id_parent]) CREATE INDEX [IX__schemes__structure_hash] ON [dbo].[_schemes]([_structure_hash]) CREATE INDEX [IX__schemes__type] ON [dbo].[_schemes]([_type]) GO -- Structures indexes CREATE INDEX [IX__structures__structures] ON [dbo].[_structures]([_id_parent]) CREATE INDEX [IX__structures__schemes] ON [dbo].[_structures]([_id_scheme]) -- V4: lookup by the free-form _tags marker; filtered - most structures carry no tags. CREATE INDEX [IX__structures__tags] ON [dbo].[_structures]([_tags]) WHERE [_tags] IS NOT NULL CREATE INDEX [IX__structures__types] ON [dbo].[_structures]([_id_type]) CREATE INDEX [IX__structures__lists] ON [dbo].[_structures]([_id_list]) -- Covering index for ORDER BY queries by structure name CREATE INDEX [IX__structures__name] ON [dbo].[_structures]([_name]) INCLUDE ([_id], [_id_type], [_collection_type], [_id_scheme]) -- Covering index for structure lookup by ID (critical for InitPlan/EXISTS) CREATE INDEX [IX__structures__id_lookup] ON [dbo].[_structures]([_id]) INCLUDE ([_id_type], [_name], [_collection_type], [_id_scheme]) -- REMOVED (2026-10-14): [IX__structures__not_collection] (_id, _name, _id_scheme) WHERE _collection_type IS NULL -- is a prefix of IX__structures__not_collection_enhanced below, same predicate. -- Enhanced partial index for non-collection structures with type CREATE INDEX [IX__structures__not_collection_enhanced] ON [dbo].[_structures]([_id], [_name], [_id_scheme], [_id_type]) WHERE [_collection_type] IS NULL -- Index for collection fields (Array/Dictionary) CREATE INDEX [IX__structures__collection] ON [dbo].[_structures]([_id], [_id_scheme], [_collection_type]) WHERE [_collection_type] IS NOT NULL CREATE INDEX [IX__structures__collection_type] ON [dbo].[_structures]([_collection_type]) WHERE [_collection_type] IS NOT NULL CREATE INDEX [IX__structures__key_type] ON [dbo].[_structures]([_key_type]) WHERE [_key_type] IS NOT NULL GO -- Dependencies indexes -- REMOVED (2026-10-14): [IX__dependencies__schemes_1] (_id_scheme_1) is the leading column of the UNIQUE -- constraint IX__dependencies (_id_scheme_1, _id_scheme_2). The index on _id_scheme_2 below stays. CREATE INDEX [IX__dependencies__schemes_2] ON [dbo].[_dependencies]([_id_scheme_2]) GO -- Objects indexes CREATE INDEX [IX__objects__objects] ON [dbo].[_objects]([_id_parent]) CREATE INDEX [IX__objects__schemes] ON [dbo].[_objects]([_id_scheme]) CREATE INDEX [IX__objects__users1] ON [dbo].[_objects]([_id_owner]) CREATE INDEX [IX__objects__users2] ON [dbo].[_objects]([_id_who_change]) CREATE INDEX [IX__objects__date_create] ON [dbo].[_objects]([_date_create]) CREATE INDEX [IX__objects__date_modify] ON [dbo].[_objects]([_date_modify]) CREATE INDEX [IX__objects__name] ON [dbo].[_objects]([_name]) CREATE INDEX [IX__objects__hash] ON [dbo].[_objects]([_hash]) -- V4: application-defined object key, unique per scheme; INCLUDE makes the lookup index-only (P6). CREATE UNIQUE INDEX [UIX__objects__scheme_unique] ON [dbo].[_objects]([_id_scheme], [_value_unique]) INCLUDE ([_id]) WHERE [_value_unique] IS NOT NULL GO -- RedbPrimitive value indexes (filtered) CREATE INDEX [IX__objects__value_long] ON [dbo].[_objects]([_value_long]) WHERE [_value_long] IS NOT NULL CREATE INDEX [IX__objects__value_string] ON [dbo].[_objects]([_value_string]) WHERE [_value_string] IS NOT NULL CREATE INDEX [IX__objects__value_guid] ON [dbo].[_objects]([_value_guid]) WHERE [_value_guid] IS NOT NULL CREATE INDEX [IX__objects__value_datetime] ON [dbo].[_objects]([_value_datetime]) WHERE [_value_datetime] IS NOT NULL CREATE INDEX [IX__objects__value_numeric] ON [dbo].[_objects]([_value_numeric]) WHERE [_value_numeric] IS NOT NULL -- Tree query indexes CREATE INDEX [IX__objects__scheme_parent] ON [dbo].[_objects]([_id_scheme], [_id_parent], [_id]) CREATE INDEX [IX__objects__root_objects] ON [dbo].[_objects]([_id_scheme], [_id]) WHERE [_id_parent] IS NULL CREATE INDEX [IX__objects__parent_scheme_id] ON [dbo].[_objects]([_id_parent], [_id_scheme], [_id]) WHERE [_id_parent] IS NOT NULL CREATE INDEX [IX__objects__scheme_date_create] ON [dbo].[_objects]([_id_scheme], [_date_create] DESC, [_id]) CREATE INDEX [IX__objects__scheme_date_modify] ON [dbo].[_objects]([_id_scheme], [_date_modify] DESC, [_id]) CREATE INDEX [IX__objects__scheme_name] ON [dbo].[_objects]([_id_scheme], [_name], [_id]) -- _date_modify is deliberately NOT in INCLUDE of the three covering _objects indexes below (as in PostgreSQL, -- 2026-10-12). It changes on every save, so an index that carries it is rewritten for every saved object and -- grows on a database with frequent saves. Queries that go through them read the object row anyway. An existing -- database keeps the old definitions: sql/maintenance/rebuild_objects_indexes_without_date_modify.sql. -- Covering index for descendant lookup (WhereHasAncestor optimization) CREATE INDEX [IX__objects__parent_id_descendant_lookup] ON [dbo].[_objects]( [_id_parent], [_id_scheme] ) INCLUDE ([_id], [_id_owner], [_date_create]) WHERE [_id_parent] IS NOT NULL -- Covering index for tree queries with date sorting CREATE INDEX [IX__objects__scheme_parent_date_create] ON [dbo].[_objects]( [_id_scheme], [_id_parent], [_date_create] DESC ) INCLUDE ([_id], [_id_owner]) -- Composite index for reverse ancestor lookup (child -> parent) CREATE INDEX [IX__objects__id_parent_scheme] ON [dbo].[_objects]([_id], [_id_parent], [_id_scheme]) WHERE [_id_parent] IS NOT NULL -- Covering index for tree queries with filtering CREATE INDEX [IX__objects__scheme_parent_owner] ON [dbo].[_objects]( [_id_scheme], [_id_parent] ) INCLUDE ([_id], [_id_owner], [_date_create], [_name]) WHERE [_id_parent] IS NOT NULL GO -- List items indexes CREATE INDEX [IX__list_items__id_list] ON [dbo].[_list_items]([_id_list]) CREATE INDEX [IX__list_items__objects] ON [dbo].[_list_items]([_id_object]) GO -- Values indexes CREATE INDEX [IX__values__objects] ON [dbo].[_values]([_id_object]) CREATE INDEX [IX__values__structures] ON [dbo].[_values]([_id_structure]) -- FK-column indexes: _Object/_ListItem carry foreign keys, and without a leading index every -- DELETE of a referenced object or list item scans the whole table for the FK check. Filtered: -- reference fields are a small fraction of rows, so the indexes stay nearly empty. CREATE INDEX [IX__values__ListItem_not_null] ON [dbo].[_values]([_ListItem]) WHERE [_ListItem] IS NOT NULL CREATE INDEX [IX__values__Object_not_null] ON [dbo].[_values]([_Object]) WHERE [_Object] IS NOT NULL -- REMOVED (module 0.2.50): [IX__values__array_parent_id] ([_array_parent_id]), the leading column of -- IX__values__array_parent_index below, which serves its lookups, the key check and the cascade trigger. CREATE INDEX [IX__values__array_parent_index] ON [dbo].[_values]([_array_parent_id], [_array_index]) CREATE INDEX [IX__values__array_key] ON [dbo].[_values]([_id_structure], [_array_index]) WHERE [_array_index] IS NOT NULL -- Index for nested Dictionary/Array field lookups via _array_parent_id (PRO PVT CTE) CREATE INDEX [IX__values__parent_structure] ON [dbo].[_values]([_array_parent_id], [_id_structure]) WHERE [_array_parent_id] IS NOT NULL -- V4: uniqueness of [RedbUnique] fields. Covers keyed rows at ANY position (root and S2 nested -- scalars; element keys join in S3); INCLUDE makes the key lookup index-only (P6). CREATE UNIQUE INDEX [UIX__values__structure_unique] ON [dbo].[_values]([_id_structure], [_unique]) INCLUDE ([_id_object]) WHERE [_unique] IS NOT NULL -- Covering index for object-structure lookups with array_index CREATE INDEX [IX__values__object_structure_lookup] ON [dbo].[_values]( [_id_object], [_id_structure], [_array_index] ) INCLUDE ( [_String], [_Long], [_DateTimeOffset], [_Boolean], [_Double], [_Guid], [_Numeric], [_ListItem], [_Object] ) -- Covering index for non-array values (Index Only Scan for EXISTS/JOIN) CREATE INDEX [IX__values__object_array_null] ON [dbo].[_values]( [_id_object], [_id_structure] ) INCLUDE ( [_String], [_Long], [_DateTimeOffset], [_Boolean], [_Double], [_Guid], [_Numeric], [_ListItem], [_Object] ) WHERE [_array_index] IS NULL -- Critical: Covering index for facet queries (structure -> object) CREATE INDEX [IX__values__structure_object_lookup] ON [dbo].[_values]( [_id_structure], [_id_object] ) INCLUDE ( [_String], [_Long], [_DateTimeOffset], [_Boolean], [_Double], [_Guid], [_Numeric], [_ListItem], [_Object] ) -- Partial indexes for NOT NULL values (EXISTS with value conditions) CREATE INDEX [IX__values__String_not_null] ON [dbo].[_values]([_id_structure], [_id_object]) WHERE [_String] IS NOT NULL -- Values found by value: (_id_structure, , _id_object), one per value column but the string, which as -- NVARCHAR(MAX) cannot be an index key (PVT module 0.2.30). A filter on a field reads one range of its index and -- gets the objects that pass. _array_index in INCLUDE: a query on a scalar field checks it as IS NULL in the index. -- REMOVED (2026-10-16): the object-leading forms these replace, (_id_structure, _id_object, ), eleven of them, -- three of which (*_not_null) were exact duplicates of three others (*_filter): -- CREATE INDEX [IX__values__Long_not_null] ON [dbo].[_values]([_id_structure], [_id_object], [_Long]) WHERE [_Long] IS NOT NULL; -- CREATE INDEX [IX__values__DateTimeOffset_not_null] ON [dbo].[_values]([_id_structure], [_id_object], [_DateTimeOffset]) WHERE [_DateTimeOffset] IS NOT NULL; -- CREATE INDEX [IX__values__Numeric_not_null] ON [dbo].[_values]([_id_structure], [_id_object], [_Numeric]) WHERE [_Numeric] IS NOT NULL; -- CREATE INDEX [IX__values__Long_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Long]) WHERE [_Long] IS NOT NULL; -- CREATE INDEX [IX__values__Guid_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Guid]) WHERE [_Guid] IS NOT NULL; -- CREATE INDEX [IX__values__Double_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Double]) WHERE [_Double] IS NOT NULL; -- CREATE INDEX [IX__values__DateTimeOffset_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_DateTimeOffset]) WHERE [_DateTimeOffset] IS NOT NULL; -- CREATE INDEX [IX__values__Boolean_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Boolean]) WHERE [_Boolean] IS NOT NULL; -- CREATE INDEX [IX__values__Numeric_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Numeric]) WHERE [_Numeric] IS NOT NULL; -- CREATE INDEX [IX__values__ListItem_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_ListItem]) WHERE [_ListItem] IS NOT NULL; -- CREATE INDEX [IX__values__Object_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Object]) WHERE [_Object] IS NOT NULL; CREATE INDEX [IX__values__structure_long_object] ON [dbo].[_values]([_id_structure], [_Long], [_id_object]) INCLUDE ([_array_index]) WHERE [_Long] IS NOT NULL CREATE INDEX [IX__values__structure_numeric_object] ON [dbo].[_values]([_id_structure], [_Numeric], [_id_object]) INCLUDE ([_array_index]) WHERE [_Numeric] IS NOT NULL CREATE INDEX [IX__values__structure_double_object] ON [dbo].[_values]([_id_structure], [_Double], [_id_object]) INCLUDE ([_array_index]) WHERE [_Double] IS NOT NULL CREATE INDEX [IX__values__structure_datetimeoffset_object] ON [dbo].[_values]([_id_structure], [_DateTimeOffset], [_id_object]) INCLUDE ([_array_index]) WHERE [_DateTimeOffset] IS NOT NULL CREATE INDEX [IX__values__structure_boolean_object] ON [dbo].[_values]([_id_structure], [_Boolean], [_id_object]) INCLUDE ([_array_index]) WHERE [_Boolean] IS NOT NULL CREATE INDEX [IX__values__structure_guid_object] ON [dbo].[_values]([_id_structure], [_Guid], [_id_object]) INCLUDE ([_array_index]) WHERE [_Guid] IS NOT NULL CREATE INDEX [IX__values__structure_listitem_object] ON [dbo].[_values]([_id_structure], [_ListItem], [_id_object]) INCLUDE ([_array_index]) WHERE [_ListItem] IS NOT NULL CREATE INDEX [IX__values__structure_object_object] ON [dbo].[_values]([_id_structure], [_Object], [_id_object]) INCLUDE ([_array_index]) WHERE [_Object] IS NOT NULL -- Индекс для быстрого LEFT JOIN nested Dictionary полей (AddressBook[home].City) -- Ускоряет Nested Loop → Index Only Scan для вложенных полей CREATE NONCLUSTERED INDEX IX__values__structure_parent_batch ON _values (_id_structure, _array_parent_id) INCLUDE (_String, _Long, _Double, _Boolean, _Guid) WHERE _array_parent_id IS NOT NULL; CREATE NONCLUSTERED INDEX IX__values__array_null_structure ON _values (_array_index, _id_structure) INCLUDE (_id_object, _Long); CREATE NONCLUSTERED INDEX IX__values__pvt_dict_lookup ON [dbo].[_values] ([_id_structure], [_array_index], [_id_object]) INCLUDE ([_string], [_Long], [_Double], [_DateTimeOffset]) CREATE NONCLUSTERED INDEX IX__objects__id_parent ON [dbo].[_objects] ([_id_parent]) INCLUDE ([_id], [_hash], [_id_scheme]) WHERE [_id_parent] IS NOT NULL; -- REMOVED (2026-10-14): ix__objects_parent_scheme (_id_parent, _id_scheme) WHERE _id_parent IS NOT NULL -- has the key and the predicate of IX__objects__parent_id_descendant_lookup. GO -- ===================================================== -- NO FULL-TEXT INDEX ON _values._String (owner decision 2026-09-02) -- ===================================================== -- A full-text index accelerates only CONTAINS()/FREETEXT(), which redb never generates: every -- string predicate translates to LIKE, and LIKE does not use full-text. The index existed with -- CHANGE_TRACKING AUTO - a background reindex on EVERY _values write - and not a single reader. -- The upgrade block drops it from existing databases. If a word-search operator ($match) ever -- lands, recreate it deliberately with that feature. GO -- REMOVED (2026-10-14): [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. -- Unique indexes for data integrity CREATE UNIQUE INDEX [UIX__values__structure_object] ON [dbo].[_values]([_id_structure], [_id_object]) WHERE [_array_index] IS NULL AND [_array_parent_id] IS NULL CREATE UNIQUE INDEX [UIX__values__structure_object_parent] ON [dbo].[_values]([_id_structure], [_id_object], [_array_parent_id]) WHERE [_array_index] IS NULL AND [_array_parent_id] IS NOT NULL CREATE UNIQUE INDEX [UIX__values__structure_object_array_index] ON [dbo].[_values]([_id_structure], [_id_object], [_array_parent_id], [_array_index]) WHERE [_array_index] IS NOT NULL GO -- Permissions indexes -- REMOVED (2026-10-14): [IX__permissions__roles] (_id_role) is the leading column of the UNIQUE constraint -- IX__permissions (_id_role, _id_user, ...). CREATE INDEX [IX__permissions__users] ON [dbo].[_permissions]([_id_user]) CREATE INDEX [IX__permissions__ref] ON [dbo].[_permissions]([_id_ref]) GO -- REMOVED (2026-10-14): [IX__functions__schemes] (_id_scheme) is the leading column of the UNIQUE constraint -- IX__functions_scheme_name (_id_scheme, _name); the constraint's index serves the same lookups. -- ===================================================== -- CREATE SEQUENCE -- ===================================================== CREATE SEQUENCE [dbo].[global_identity] AS BIGINT START WITH 1000000 INCREMENT BY 1 MINVALUE 1000000 MAXVALUE 9223372036854775807 NO CACHE GO -- ===================================================== -- INSERT BASE TYPES -- ===================================================== -- Core types INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775709, 'Boolean', 'Boolean', 'boolean') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775708, 'DateTime', 'DateTimeOffset', 'DateTime') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775707, 'Double', 'Double', 'double') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775706, 'ListItem', 'ListItem', '_RListItem') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775705, 'Guid', 'Guid', 'Guid') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775704, 'Long', 'Long', 'long') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775703, 'Object', 'Object', '_RObject') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775701, 'ByteArray', 'ByteArray', 'byte[]') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775700, 'String', 'String', 'string') -- Extended types INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775699, 'Int', 'Long', 'int') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775698, 'Short', 'Long', 'short') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775697, 'Byte', 'Long', 'byte') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775696, 'Float', 'Double', 'float') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775695, 'Decimal', 'Numeric', 'decimal') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775694, 'Char', 'String', 'char') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775693, 'Url', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775692, 'Email', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775691, 'Phone', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775690, 'Json', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775689, 'Xml', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775688, 'Base64', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775687, 'Color', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775686, 'DateOnly', 'DateTimeOffset', 'DateOnly') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775685, 'TimeOnly', 'Long', 'TimeOnly') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775684, 'TimeSpan', 'Long', 'TimeSpan') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775683, 'Enum', 'String', 'Enum') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775682, 'EnumInt', 'Long', 'Enum') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775681, 'Latitude', 'Double', 'double') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775680, 'Longitude', 'Double', 'double') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775679, 'GeoPoint', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775678, 'FilePath', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775677, 'FileName', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775676, 'MimeType', 'String', 'string') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775675, 'Class', 'Guid', 'Object') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775674, 'Numeric', 'Numeric', 'decimal') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775673, 'DateTimeOffset', 'DateTimeOffset', 'DateTimeOffset') -- Collection and document types INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775668, 'Array', 'Guid', 'Array') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775667, 'Dictionary', 'Guid', 'Dictionary') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775666, 'JsonDocument', 'Guid', 'JsonDocument') INSERT INTO [dbo].[_types] ([_id], [_name], [_db_type], [_type]) VALUES (-9223372036854775665, 'XDocument', 'Guid', 'XDocument') GO -- ===================================================== -- INSERT DEFAULT USERS -- ===================================================== INSERT INTO [dbo].[_users] ([_id], [_login], [_password], [_name], [_phone], [_email], [_date_register], [_date_dismiss], [_enabled]) VALUES (-1, 'default', '', 'default', NULL, NULL, '2023-12-26T01:14:34.410+00:00', NULL, 1) INSERT INTO [dbo].[_users] ([_id], [_login], [_password], [_name], [_phone], [_email], [_date_register], [_date_dismiss], [_enabled]) VALUES (0, 'sys', '', 'sys', NULL, NULL, '2023-12-26T01:14:34.410+00:00', NULL, 1) INSERT INTO [dbo].[_users] ([_id], [_login], [_password], [_name], [_phone], [_email], [_date_register], [_date_dismiss], [_enabled]) VALUES (1, 'admin', '', 'admin', NULL, NULL, '2023-12-26T01:14:34.410+00:00', NULL, 1) GO -- ===================================================== -- 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 IF NOT EXISTS (SELECT 1 FROM [dbo].[_schemes] WHERE [_id] = -10) INSERT INTO [dbo].[_schemes] ([_id], [_name], [_alias], [_type]) VALUES (-10, '@@__deleted', 'Deleted Objects', -9223372036854775703) GO -- ===================================================== -- ADD FOREIGN KEY FOR CONFIGURATION (after _objects exists) -- ===================================================== ALTER TABLE [dbo].[_users] ADD CONSTRAINT [FK__users__configuration] FOREIGN KEY ([_id_configuration]) REFERENCES [_objects]([_id]) ON DELETE NO ACTION GO ALTER TABLE [dbo].[_roles] ADD CONSTRAINT [FK__roles__configuration] FOREIGN KEY ([_id_configuration]) REFERENCES [_objects]([_id]) ON DELETE NO ACTION GO -- ===================================================== -- TRIGGER: Protect system users from deletion and modification -- Prohibits deletion of users with ID -1, 0, 1 -- IDs 0 (sys), -1 (default): fully immutable (no changes allowed) -- Login (_login) is immutable for ALL users -- ===================================================== IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'TR__users__protect_system') DROP TRIGGER [dbo].[TR__users__protect_system] GO CREATE TRIGGER [dbo].[TR__users__protect_system] ON [dbo].[_users] INSTEAD OF DELETE, UPDATE AS BEGIN SET NOCOUNT ON; IF EXISTS (SELECT 1 FROM deleted) AND NOT EXISTS (SELECT 1 FROM inserted) BEGIN -- DELETE operation: prohibit for system users IF EXISTS (SELECT 1 FROM deleted WHERE [_id] IN (0, 1, -1)) BEGIN RAISERROR('Cannot delete system user', 16, 1); RETURN; END -- Manual cascade (replaces ON DELETE CASCADE removed from FK constraints -- to allow INSTEAD OF trigger on _users table — MSSQL restriction) DELETE ur FROM [dbo].[_users_roles] ur INNER JOIN deleted d ON ur.[_id_user] = d.[_id]; DELETE p FROM [dbo].[_permissions] p INNER JOIN deleted d ON p.[_id_user] = d.[_id]; DELETE u FROM [dbo].[_users] u INNER JOIN deleted d ON u.[_id] = d.[_id]; RETURN; END -- UPDATE operation IF EXISTS (SELECT 1 FROM inserted) BEGIN -- Prohibit changing ID IF EXISTS (SELECT 1 FROM deleted d INNER JOIN inserted i ON d.[_id] != i.[_id]) BEGIN RAISERROR('Cannot change user ID', 16, 1); RETURN; END -- IDs 0 (sys) and -1 (default): fully immutable, no changes allowed IF EXISTS ( SELECT 1 FROM deleted d INNER JOIN inserted i ON d.[_id] = i.[_id] WHERE d.[_id] IN (0, -1) AND ( d.[_login] != i.[_login] OR d.[_password] != i.[_password] OR d.[_name] != i.[_name] OR ISNULL(d.[_phone], '') != ISNULL(i.[_phone], '') OR ISNULL(d.[_email], '') != ISNULL(i.[_email], '') OR d.[_enabled] != i.[_enabled] OR ISNULL(d.[_note], '') != ISNULL(i.[_note], '') ) ) BEGIN RAISERROR('Cannot modify system user with ID 0 or -1', 16, 1); RETURN; END -- Login is immutable for ALL users IF EXISTS ( SELECT 1 FROM deleted d INNER JOIN inserted i ON d.[_id] = i.[_id] WHERE d.[_login] != i.[_login] ) BEGIN RAISERROR('Cannot change user login', 16, 1); RETURN; END -- Apply the update UPDATE u SET u.[_login] = i.[_login], u.[_password] = i.[_password], u.[_name] = i.[_name], u.[_phone] = i.[_phone], u.[_email] = i.[_email], u.[_date_register] = i.[_date_register], u.[_date_dismiss] = i.[_date_dismiss], u.[_enabled] = i.[_enabled], u.[_key] = i.[_key], u.[_code_int] = i.[_code_int], u.[_code_string] = i.[_code_string], u.[_code_guid] = i.[_code_guid], u.[_note] = i.[_note], u.[_hash] = i.[_hash], u.[_id_configuration] = i.[_id_configuration] FROM [dbo].[_users] u INNER JOIN inserted i ON u.[_id] = i.[_id]; END END GO -- ===================================================== -- TRIGGER: Cascade delete _values before _structures -- (MSSQL workaround - no ON DELETE CASCADE for _values._id_structure) -- ===================================================== IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'TR__structures__cascade_values') DROP TRIGGER [dbo].[TR__structures__cascade_values] GO CREATE TRIGGER [dbo].[TR__structures__cascade_values] ON [dbo].[_structures] INSTEAD OF DELETE AS BEGIN SET NOCOUNT ON; -- Delete values first (cascade) DELETE v FROM [dbo].[_values] v INNER JOIN deleted d ON v.[_id_structure] = d.[_id]; -- Delete the structures DELETE s FROM [dbo].[_structures] s INNER JOIN deleted d ON s.[_id] = d.[_id]; END GO -- ===================================================== -- TRIGGER: Cascade delete _values before _objects -- (MSSQL workaround - no ON DELETE CASCADE for _values._id_object) -- ===================================================== IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'TR__objects__cascade_values') DROP TRIGGER [dbo].[TR__objects__cascade_values] GO CREATE TRIGGER [dbo].[TR__objects__cascade_values] ON [dbo].[_objects] INSTEAD OF DELETE AS BEGIN SET NOCOUNT ON; -- Clear configuration references (replaces ON DELETE SET NULL removed from FK constraints -- to allow INSTEAD OF trigger on _users table — MSSQL restriction) UPDATE u SET u.[_id_configuration] = NULL FROM [dbo].[_users] u INNER JOIN deleted d ON u.[_id_configuration] = d.[_id]; UPDATE r SET r.[_id_configuration] = NULL FROM [dbo].[_roles] r INNER JOIN deleted d ON r.[_id_configuration] = d.[_id]; -- Delete values first (cascade) DELETE v FROM [dbo].[_values] v INNER JOIN deleted d ON v.[_id_object] = d.[_id]; -- Delete the objects DELETE o FROM [dbo].[_objects] o INNER JOIN deleted d ON o.[_id] = d.[_id]; END GO -- ===================================================== -- TRIGGER: Cascade delete for _values._array_parent_id -- (MSSQL workaround for multiple cascade paths restriction) -- ===================================================== IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'TR__values__cascade_array_parent') DROP TRIGGER [dbo].[TR__values__cascade_array_parent] GO CREATE TRIGGER [dbo].[TR__values__cascade_array_parent] ON [dbo].[_values] INSTEAD OF DELETE AS BEGIN SET NOCOUNT ON; -- Recursively delete children first (depth-first) ;WITH cte AS ( SELECT [_id] FROM deleted UNION ALL SELECT v.[_id] FROM [dbo].[_values] v INNER JOIN cte ON v.[_array_parent_id] = cte.[_id] ) DELETE FROM [dbo].[_values] WHERE [_id] IN (SELECT [_id] FROM cte); END GO -- delete_object_cascade and delete_objects_cascade: v2-pvt/32_delete_cascade.sql (the versioned module), so an -- existing database gets a change of them on its next start. -- ===================================================== -- VIEW: v_user_permissions -- Hierarchical permission inheritance (PostgreSQL compatible) -- ===================================================== IF OBJECT_ID('dbo.v_user_permissions', 'V') IS NOT NULL DROP VIEW dbo.v_user_permissions; GO CREATE VIEW dbo.v_user_permissions AS WITH 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, CASE WHEN EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = o._id) THEN 1 ELSE 0 END 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, CASE WHEN EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = o._id) THEN 1 ELSE 0 END AS has_permission FROM _objects o JOIN permission_search ps ON o._id = ps._id_parent WHERE ps.level < 50 AND ps.has_permission = 0 -- continue only if NO permission ), -- Get first found permission for each object (using ROW_NUMBER instead of DISTINCT ON) object_permissions AS ( SELECT ps.object_id, p._id AS permission_id, p._id_user, p._id_role, p._select, p._insert, p._update, p._delete, ps.level, ROW_NUMBER() OVER (PARTITION BY ps.object_id ORDER BY ps.level) AS rn FROM permission_search ps JOIN _permissions p ON p._id_ref = ps.current_search_id WHERE ps.has_permission = 1 ), object_permissions_first AS ( SELECT * FROM object_permissions WHERE rn = 1 ), -- Global permissions as virtual records with object_id = 0 global_permissions AS ( SELECT CAST(0 AS BIGINT) 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, 1 AS rn FROM _permissions p WHERE p._id_ref = 0 ), -- Combine specific and global permissions all_permissions AS ( SELECT object_id, permission_id, _id_user, _id_role, _select, _insert, _update, _delete, level FROM object_permissions_first UNION ALL SELECT object_id, permission_id, _id_user, _id_role, _select, _insert, _update, _delete, level FROM global_permissions ), -- Get first by priority (specific > global) final_permissions AS ( SELECT object_id, permission_id, _id_user, _id_role, _select, _insert, _update, _delete, level, ROW_NUMBER() OVER (PARTITION BY object_id ORDER BY level) AS rn FROM all_permissions ), final_permissions_first AS ( SELECT * FROM final_permissions WHERE rn = 1 ) -- Result: for user permissions - direct, for role - through users_roles SELECT fp.object_id, CASE WHEN fp._id_user IS NOT NULL THEN fp._id_user ELSE ur._id_user END AS user_id, fp.permission_id, CASE WHEN fp._id_user IS NOT NULL THEN N'user' ELSE N'role' 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_first fp LEFT JOIN _users_roles ur ON ur._id_role = fp._id_role WHERE fp._id_user IS NOT NULL OR ur._id_user IS NOT NULL; GO PRINT '=========================================' PRINT 'REDB MS SQL Server Schema v2.0 created!' PRINT 'Includes: Array, Dictionary, JsonDocument, XDocument support' PRINT '=========================================' GO Path: redb/redb.MSSql/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.MSSql/sql/redb_metadata_cache.sql ---- -- ============================================================ -- METADATA CACHE: Solution for repeated JOINs -- MS SQL Server version -- ============================================================ -- Goal: Avoid repeated JOIN _structures <- _types in every query -- Approach: Regular table + automatic sync via triggers on _structure_hash -- Benefits: -- No recursion issues (indexes created once) -- Works with connection pooling (global table) -- Automatic invalidation (triggers on _schemes._structure_hash) -- No C# code changes required -- Minimal cache rebuilds (only on real schema changes) -- ============================================================ -- ===================================================== -- DROP EXISTING OBJECTS -- ===================================================== IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'TR__schemes__sync_metadata_cache') DROP TRIGGER [dbo].[TR__schemes__sync_metadata_cache] GO IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'TR__schemes__cleanup_metadata_cache') DROP TRIGGER [dbo].[TR__schemes__cleanup_metadata_cache] GO IF EXISTS (SELECT * FROM sys.triggers WHERE name = 'TR__types__invalidate_metadata_cache') DROP TRIGGER [dbo].[TR__types__invalidate_metadata_cache] GO IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'check_metadata_cache_consistency') DROP PROCEDURE [dbo].[check_metadata_cache_consistency] GO IF OBJECT_ID('[dbo].[_scheme_metadata_cache]', 'U') IS NOT NULL DROP TABLE [dbo].[_scheme_metadata_cache] GO -- ===================================================== -- 1. CREATE METADATA CACHE TABLE -- ===================================================== CREATE TABLE [dbo].[_scheme_metadata_cache] ( -- Identifiers [_scheme_id] BIGINT NOT NULL, [_structure_id] BIGINT NOT NULL, [_parent_structure_id] BIGINT NULL, [_id_override] BIGINT NULL, -- Names and aliases [_name] NVARCHAR(450) NOT NULL, [_alias] NVARCHAR(450) NULL, -- Structure type info [_type_id] BIGINT NOT NULL, [_list_id] BIGINT NULL, [type_name] NVARCHAR(450) NOT NULL, [db_type] NVARCHAR(450) NOT NULL, [type_semantic] NVARCHAR(450) NOT NULL, -- Scheme type info (Class/Array/Dictionary/JsonDocument/XDocument) [_scheme_type] BIGINT NULL, [scheme_type_name] NVARCHAR(450) NULL, -- Structure attributes [_order] BIGINT NULL, [_collection_type] BIGINT NULL, -- NULL = not collection, Array/Dictionary type ID [collection_type_name] NVARCHAR(450) NULL, -- Collection type name [_key_type] BIGINT NULL, -- Key type for Dictionary [key_type_name] NVARCHAR(450) NULL, -- Key type name [_readonly] BIT NULL, [_allow_not_null] BIT NULL, [_is_compress] BIT NULL, [_store_null] BIT NULL, [_unique] BIT NULL, -- V4: unique key flag ([RedbUnique]) [_unique_scope] BIGINT NULL, -- S3: element-key scope of a collection key [_tags] NVARCHAR(450) NULL, -- V4: free-form marker mirrored from _structures [_unique_version] BIGINT NULL, -- V4: encoder version of the stored keys [_lazy] BIT NULL, -- V4 (LAZY Л2): lazy reference marker -- Default values [_default_value] VARBINARY(MAX) NULL, [_default_editor] NVARCHAR(MAX) NULL ) GO -- ===================================================== -- 2. CREATE INDEXES -- ===================================================== CREATE INDEX [idx_metadata_cache_lookup] ON [dbo].[_scheme_metadata_cache]([_scheme_id], [_parent_structure_id], [_order]) GO CREATE INDEX [idx_metadata_cache_structure] ON [dbo].[_scheme_metadata_cache]([_structure_id]) GO CREATE INDEX [idx_metadata_cache_scheme] ON [dbo].[_scheme_metadata_cache]([_scheme_id]) GO CREATE INDEX [idx_metadata_cache_name] ON [dbo].[_scheme_metadata_cache]([_scheme_id], [_name]) GO CREATE INDEX [idx_metadata_cache_collection] ON [dbo].[_scheme_metadata_cache]([_scheme_id], [_collection_type]) WHERE [_collection_type] IS NOT NULL GO CREATE INDEX [idx_metadata_cache_scheme_type] ON [dbo].[_scheme_metadata_cache]([_scheme_id], [_scheme_type]) GO CREATE INDEX [idx_metadata_cache_key_type] ON [dbo].[_scheme_metadata_cache]([_scheme_id], [_key_type]) WHERE [_key_type] IS NOT NULL GO -- ===================================================== -- 3. SYNC PROCEDURE — MODULE-OWNED since V4 -- ===================================================== -- sync_metadata_cache_for_scheme 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 EXEC -- it by name at run time. -- ===================================================== -- 4. TRIGGER: Sync cache on _structure_hash change -- ===================================================== CREATE TRIGGER [dbo].[TR__schemes__sync_metadata_cache] ON [dbo].[_schemes] AFTER INSERT, UPDATE AS BEGIN SET NOCOUNT ON; -- Handle UPDATE: rebuild cache if _structure_hash changed IF EXISTS (SELECT 1 FROM deleted) BEGIN DECLARE @scheme_id BIGINT; DECLARE cur CURSOR LOCAL FAST_FORWARD FOR SELECT i.[_id] FROM inserted i INNER JOIN deleted d ON i.[_id] = d.[_id] WHERE i.[_structure_hash] IS NOT NULL AND (d.[_structure_hash] IS NULL OR i.[_structure_hash] <> d.[_structure_hash]); OPEN cur; FETCH NEXT FROM cur INTO @scheme_id; WHILE @@FETCH_STATUS = 0 BEGIN EXEC [dbo].[sync_metadata_cache_for_scheme] @scheme_id; PRINT 'Metadata cache rebuilt for scheme_id=' + CAST(@scheme_id AS NVARCHAR(20)); FETCH NEXT FROM cur INTO @scheme_id; END CLOSE cur; DEALLOCATE cur; END ELSE BEGIN -- Handle INSERT: create cache for new schemes with hash DECLARE cur_insert CURSOR LOCAL FAST_FORWARD FOR SELECT [_id] FROM inserted WHERE [_structure_hash] IS NOT NULL; OPEN cur_insert; FETCH NEXT FROM cur_insert INTO @scheme_id; WHILE @@FETCH_STATUS = 0 BEGIN EXEC [dbo].[sync_metadata_cache_for_scheme] @scheme_id; PRINT 'Metadata cache created for new scheme_id=' + CAST(@scheme_id AS NVARCHAR(20)); FETCH NEXT FROM cur_insert INTO @scheme_id; END CLOSE cur_insert; DEALLOCATE cur_insert; END END GO -- ===================================================== -- 5. TRIGGER: Cleanup cache on scheme delete -- ===================================================== CREATE TRIGGER [dbo].[TR__schemes__cleanup_metadata_cache] ON [dbo].[_schemes] AFTER DELETE AS BEGIN SET NOCOUNT ON; DELETE c FROM [dbo].[_scheme_metadata_cache] c INNER JOIN deleted d ON c.[_scheme_id] = d.[_id]; IF @@ROWCOUNT > 0 PRINT 'Metadata cache cleared for deleted schemes'; END GO -- ===================================================== -- 6. TRIGGER: Invalidate all caches on _types change -- ===================================================== CREATE TRIGGER [dbo].[TR__types__invalidate_metadata_cache] ON [dbo].[_types] AFTER UPDATE, DELETE AS BEGIN SET NOCOUNT ON; TRUNCATE TABLE [dbo].[_scheme_metadata_cache]; PRINT 'All metadata caches invalidated due to _types change'; END GO -- ===================================================== -- 7. WARMUP PROCEDURE — MODULE-OWNED since V4 -- ===================================================== -- See v2-pvt/29_metadata_cache_sync.sql (same reason as the sync procedure). -- ===================================================== -- 8. CONSISTENCY CHECK PROCEDURE -- ===================================================== CREATE PROCEDURE [dbo].[check_metadata_cache_consistency] AS BEGIN SET NOCOUNT ON; SELECT s.[_id] AS scheme_id, s.[_name] AS scheme_name, ISNULL(cache_stats.cached_count, 0) AS cached_count, ISNULL(actual_stats.actual_count, 0) AS actual_count, CASE WHEN ISNULL(cache_stats.cached_count, 0) = ISNULL(actual_stats.actual_count, 0) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS is_consistent FROM [dbo].[_schemes] s LEFT JOIN ( SELECT [_scheme_id], COUNT(*) AS cached_count FROM [dbo].[_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 [dbo].[_structures] GROUP BY [_id_scheme] ) actual_stats ON actual_stats.[_id_scheme] = s.[_id] ORDER BY s.[_id]; END GO -- ===================================================== -- DONE! Usage: -- -- 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 -- -- WARMUP: -- EXEC warmup_all_metadata_caches -- -- CONSISTENCY CHECK: -- EXEC check_metadata_cache_consistency -- ===================================================== PRINT '=========================================' PRINT 'Metadata cache for MS SQL Server created!' PRINT 'Run: EXEC warmup_all_metadata_caches' PRINT '=========================================' GO Path: redb/redb.MSSql/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.MSSql/sql/redb_migrations.sql ---- -- ===================================================== -- REDB Pro: Таблица истории миграций (SQL Server) -- ===================================================== IF NOT EXISTS (SELECT 1 FROM sys.tables WHERE name = '_migrations') BEGIN CREATE TABLE _migrations ( -- No IDENTITY: like every other redb table, the id is supplied by the application -- (NextObjectIdAsync) and MigrationExecutor passes it explicitly. IDENTITY made that -- INSERT fail with "Cannot insert explicit value for identity column ... IDENTITY_INSERT -- is OFF", so migration history could never be written on MSSql. _id BIGINT NOT NULL PRIMARY KEY, _migration_id NVARCHAR(500) NOT NULL, -- уникальный ID миграции "OrderProps_TotalPrice_v1" _scheme_id BIGINT NOT NULL REFERENCES _schemes(_id) ON DELETE CASCADE, _structure_id BIGINT REFERENCES _structures(_id), -- NULL = вся схема (ON DELETE SET NULL not supported with CASCADE on same table) _property_name NVARCHAR(500), -- имя свойства (для логов) _expression_hash NVARCHAR(500), -- MD5 от Expression для детекции изменений _migration_type NVARCHAR(200) NOT NULL, -- ComputedFrom, TypeChange, DefaultValue, Transform _applied_at DATETIMEOFFSET NOT NULL DEFAULT SYSDATETIMEOFFSET(), _applied_by NVARCHAR(500), -- кто применил (user/system) _sql_executed NVARCHAR(MAX), -- SQL который был выполнен (для аудита) _affected_rows INT, -- сколько записей затронуто _duration_ms INT, -- время выполнения _dry_run BIT NOT NULL DEFAULT 0, -- это был dry-run? CONSTRAINT uq_migration_scheme UNIQUE(_scheme_id, _migration_id) ); END; -- Индексы для быстрого поиска IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'idx_migrations_scheme') CREATE INDEX idx_migrations_scheme ON _migrations(_scheme_id); IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'idx_migrations_applied') CREATE INDEX idx_migrations_applied ON _migrations(_applied_at DESC); GO Path: redb/redb.MSSql/sql/redb_permissions.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.MSSql/sql/redb_permissions.sql ---- -- ============================================================================= -- REDB Permissions Functions for MS SQL Server -- Compatible with SQL Server 2016+ (uses JSON functions, window functions, CTEs) -- ============================================================================= -- Drop existing function if exists IF OBJECT_ID('dbo.get_user_permissions_for_object', 'TF') IS NOT NULL DROP FUNCTION dbo.get_user_permissions_for_object; GO -- ============================================================================= -- Function: get_user_permissions_for_object -- Purpose: Returns effective permissions for a specific object considering -- hierarchical inheritance and priorities (user > role). -- If @user_id = NULL, returns the first found permission without -- filtering by user (for use in triggers). -- -- Parameters: -- @object_id BIGINT - Target object ID -- @user_id BIGINT = NULL - User ID (optional for trigger usage) -- -- Returns: Table with permission details -- -- Usage: -- SELECT * FROM dbo.get_user_permissions_for_object(12345, 100); -- SELECT * FROM dbo.get_user_permissions_for_object(12345, NULL); -- for triggers -- ============================================================================= CREATE FUNCTION dbo.get_user_permissions_for_object ( @object_id BIGINT, @user_id BIGINT = NULL ) RETURNS @result TABLE ( object_id BIGINT, user_id BIGINT, permission_source_id BIGINT, permission_type NVARCHAR(50), _id_role BIGINT, _id_user BIGINT, can_select BIT, can_insert BIT, can_update BIT, can_delete BIT ) AS BEGIN -- System user (id=0) has full permissions on everything IF @user_id = 0 BEGIN INSERT INTO @result SELECT @object_id AS object_id, 0 AS user_id, 0 AS permission_source_id, N'system' AS permission_type, NULL AS _id_role, 0 AS _id_user, 1 AS can_select, 1 AS can_insert, 1 AS can_update, 1 AS can_delete; RETURN; END; -- Use CTE to find permissions with hierarchical search ;WITH permission_search AS ( -- Step 1: Start from target object SELECT @object_id AS object_id, @object_id AS current_search_id, o._id_parent, 0 AS level, CASE WHEN EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = @object_id) THEN 1 ELSE 0 END AS has_permission FROM _objects o WHERE o._id = @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, CASE WHEN EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = o._id) THEN 1 ELSE 0 END AS has_permission FROM _objects o INNER JOIN permission_search ps ON o._id = ps._id_parent WHERE ps.level < 50 AND ps.has_permission = 0 -- continue only if NO permission ), -- Get first found permission for object using ROW_NUMBER instead of DISTINCT ON object_permission_ranked AS ( SELECT ps.object_id, p._id AS permission_id, p._id_user, p._id_role, p._select, p._insert, p._update, p._delete, ps.level, ps.current_search_id AS permission_source_id, ROW_NUMBER() OVER (PARTITION BY ps.object_id ORDER BY ps.level) AS rn FROM permission_search ps INNER JOIN _permissions p ON p._id_ref = ps.current_search_id WHERE ps.has_permission = 1 ), object_permission AS ( SELECT object_id, permission_id, _id_user, _id_role, _select, _insert, _update, _delete, level, permission_source_id FROM object_permission_ranked WHERE rn = 1 ), -- Add global permissions as fallback (_id_ref = 0) global_permission AS ( SELECT @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 CAST(0 AS BIGINT) AS permission_source_id FROM _permissions p WHERE p._id_ref = 0 ), -- Combine specific and global permissions all_permissions AS ( SELECT * FROM object_permission UNION ALL SELECT * FROM global_permission ), -- Get first by priority (specific > global) using ROW_NUMBER final_permission_ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY object_id ORDER BY level) AS rn FROM all_permissions ), final_permission AS ( SELECT object_id, permission_id, _id_user, _id_role, _select, _insert, _update, _delete, level, permission_source_id FROM final_permission_ranked WHERE rn = 1 ) -- Result: for user permissions - direct, for role - through users_roles INSERT INTO @result SELECT fp.object_id, CASE WHEN @user_id IS NULL THEN NULL -- if user_id not passed for trigger WHEN fp._id_user IS NOT NULL THEN fp._id_user -- direct user permission ELSE ur._id_user -- through role END AS user_id, fp.permission_source_id, CASE WHEN fp._id_user IS NOT NULL THEN N'user' ELSE N'role' END AS permission_type, fp._id_role, fp._id_user, fp._select AS can_select, fp._insert AS can_insert, fp._update AS can_update, fp._delete AS can_delete FROM final_permission fp LEFT JOIN _users_roles ur ON ur._id_role = fp._id_role -- only for role permissions WHERE @user_id IS NULL OR (fp._id_user = @user_id OR ur._id_user = @user_id); -- if user_id NULL - all permissions, else filter RETURN; END; GO -- ============================================================================= -- Trigger: auto_create_node_permissions -- Purpose: Automatically creates permissions when creating node objects. -- If parent has no direct permission, finds inherited permission -- and creates copy for the new object. -- -- Note: This trigger is for reference. Adjust based on your actual requirements. -- ============================================================================= -- Drop existing trigger if exists IF OBJECT_ID('dbo.tr_auto_create_node_permissions', 'TR') IS NOT NULL DROP TRIGGER dbo.tr_auto_create_node_permissions; GO CREATE TRIGGER dbo.tr_auto_create_node_permissions ON _objects AFTER INSERT AS BEGIN SET NOCOUNT ON; DECLARE @new_id BIGINT; DECLARE @parent_id BIGINT; DECLARE @source_permission_id BIGINT; DECLARE @source_user_id BIGINT; DECLARE @source_role_id BIGINT; DECLARE @source_select BIT; DECLARE @source_insert BIT; DECLARE @source_update BIT; DECLARE @source_delete BIT; DECLARE @next_id BIGINT; -- Process each inserted object with parent DECLARE insert_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT i._id, i._id_parent FROM inserted i WHERE i._id_parent IS NOT NULL; OPEN insert_cursor; FETCH NEXT FROM insert_cursor INTO @new_id, @parent_id; WHILE @@FETCH_STATUS = 0 BEGIN -- Check if parent already has direct permission IF NOT EXISTS(SELECT 1 FROM _permissions WHERE _id_ref = @parent_id) BEGIN -- Use function without user_id to find source permission SELECT TOP 1 @source_permission_id = permission_source_id, @source_user_id = _id_user, @source_role_id = _id_role, @source_select = can_select, @source_insert = can_insert, @source_update = can_update, @source_delete = can_delete FROM dbo.get_user_permissions_for_object(@parent_id, NULL); -- If source permission found, create copy for parent IF @source_permission_id IS NOT NULL BEGIN -- Get next ID from sequence SELECT @next_id = NEXT VALUE FOR global_identity; INSERT INTO _permissions ( _id, _id_ref, _id_user, _id_role, _select, _insert, _update, _delete ) VALUES ( @next_id, @parent_id, @source_user_id, @source_role_id, @source_select, @source_insert, @source_update, @source_delete ); END; END; FETCH NEXT FROM insert_cursor INTO @new_id, @parent_id; END; CLOSE insert_cursor; DEALLOCATE insert_cursor; END; GO -- Disabled, as on PostgreSQL: the save path does not rely on it, and the bulk copy fires triggers (module 0.2.41). ALTER TABLE [dbo].[_objects] DISABLE TRIGGER [tr_auto_create_node_permissions]; GO -- ============================================================================= -- Function: check_user_permission -- Purpose: Quick check if user has specific permission on object. -- Returns 1 if has permission, 0 otherwise. -- -- Parameters: -- @object_id BIGINT - Target object ID -- @user_id BIGINT - User ID -- @permission_type NVARCHAR(10) - 'select', 'insert', 'update', 'delete' -- -- Usage: -- IF dbo.check_user_permission(12345, 100, 'update') = 1 -- PRINT 'User can update'; -- ============================================================================= IF OBJECT_ID('dbo.check_user_permission', 'FN') IS NOT NULL DROP FUNCTION dbo.check_user_permission; GO CREATE FUNCTION dbo.check_user_permission ( @object_id BIGINT, @user_id BIGINT, @permission_type NVARCHAR(10) ) RETURNS BIT AS BEGIN DECLARE @result BIT = 0; -- System user always has permission IF @user_id = 0 RETURN 1; SELECT @result = CASE @permission_type WHEN N'select' THEN can_select WHEN N'insert' THEN can_insert WHEN N'update' THEN can_update WHEN N'delete' THEN can_delete ELSE 0 END FROM dbo.get_user_permissions_for_object(@object_id, @user_id); RETURN ISNULL(@result, 0); END; GO -- ============================================================================= -- Function: get_user_accessible_objects -- Purpose: Returns list of object IDs that user can access with given permission. -- Uses hierarchical permission inheritance. -- -- Parameters: -- @user_id BIGINT - User ID -- @permission_type NVARCHAR(10) - 'select', 'insert', 'update', 'delete' -- @scheme_id BIGINT = NULL - Optional filter by scheme -- -- Usage: -- SELECT * FROM dbo.get_user_accessible_objects(100, 'select', NULL); -- ============================================================================= IF OBJECT_ID('dbo.get_user_accessible_objects', 'TF') IS NOT NULL DROP FUNCTION dbo.get_user_accessible_objects; GO CREATE FUNCTION dbo.get_user_accessible_objects ( @user_id BIGINT, @permission_type NVARCHAR(10), @scheme_id BIGINT = NULL ) RETURNS @result TABLE ( object_id BIGINT PRIMARY KEY ) AS BEGIN -- System user sees everything IF @user_id = 0 BEGIN INSERT INTO @result SELECT _id FROM _objects WHERE @scheme_id IS NULL OR _id_scheme = @scheme_id; RETURN; END; -- Get user's roles DECLARE @user_roles TABLE (role_id BIGINT PRIMARY KEY); INSERT INTO @user_roles SELECT _id_role FROM _users_roles WHERE _id_user = @user_id; -- Find all permissions applicable to user (direct or via role) ;WITH applicable_permissions AS ( SELECT p._id_ref AS object_id, CASE @permission_type WHEN N'select' THEN p._select WHEN N'insert' THEN p._insert WHEN N'update' THEN p._update WHEN N'delete' THEN p._delete ELSE 0 END AS has_permission FROM _permissions p WHERE p._id_user = @user_id OR p._id_role IN (SELECT role_id FROM @user_roles) ), -- Objects with direct permissions permitted_roots AS ( SELECT object_id FROM applicable_permissions WHERE has_permission = 1 ), -- Recursively find all descendants of permitted objects all_accessible AS ( SELECT o._id AS object_id FROM _objects o WHERE o._id IN (SELECT object_id FROM permitted_roots) UNION ALL SELECT o._id FROM _objects o INNER JOIN all_accessible a ON o._id_parent = a.object_id ) INSERT INTO @result SELECT DISTINCT aa.object_id FROM all_accessible aa INNER JOIN _objects o ON o._id = aa.object_id WHERE @scheme_id IS NULL OR o._id_scheme = @scheme_id; RETURN; END; GO -- ============================================================================= -- Inline Function: fn_can_user_edit_object -- Purpose: Optimized scalar check for edit (update) permission. -- Returns 1 if user can edit, 0 otherwise. -- Inline version for better query plan optimization. -- ============================================================================= IF OBJECT_ID('dbo.fn_can_user_edit_object', 'IF') IS NOT NULL DROP FUNCTION dbo.fn_can_user_edit_object; GO CREATE FUNCTION dbo.fn_can_user_edit_object ( @object_id BIGINT, @user_id BIGINT ) RETURNS TABLE AS RETURN ( SELECT CASE WHEN @user_id = 0 THEN 1 -- system user WHEN EXISTS( SELECT 1 FROM dbo.get_user_permissions_for_object(@object_id, @user_id) WHERE can_update = 1 ) THEN 1 ELSE 0 END AS can_edit ); GO -- ============================================================================= -- Inline Function: fn_can_user_select_object -- Purpose: Optimized scalar check for select permission. -- ============================================================================= IF OBJECT_ID('dbo.fn_can_user_select_object', 'IF') IS NOT NULL DROP FUNCTION dbo.fn_can_user_select_object; GO CREATE FUNCTION dbo.fn_can_user_select_object ( @object_id BIGINT, @user_id BIGINT ) RETURNS TABLE AS RETURN ( SELECT CASE WHEN @user_id = 0 THEN 1 -- system user WHEN EXISTS( SELECT 1 FROM dbo.get_user_permissions_for_object(@object_id, @user_id) WHERE can_select = 1 ) THEN 1 ELSE 0 END AS can_select ); GO -- ============================================================================= -- Inline Function: fn_can_user_delete_object -- Purpose: Optimized scalar check for delete permission. -- ============================================================================= IF OBJECT_ID('dbo.fn_can_user_delete_object', 'IF') IS NOT NULL DROP FUNCTION dbo.fn_can_user_delete_object; GO CREATE FUNCTION dbo.fn_can_user_delete_object ( @object_id BIGINT, @user_id BIGINT ) RETURNS TABLE AS RETURN ( SELECT CASE WHEN @user_id = 0 THEN 1 -- system user WHEN EXISTS( SELECT 1 FROM dbo.get_user_permissions_for_object(@object_id, @user_id) WHERE can_delete = 1 ) THEN 1 ELSE 0 END AS can_delete ); GO -- ============================================================================= -- Inline Function: fn_can_user_insert_scheme -- Purpose: Check if user can insert objects of specific scheme. -- Looks for global permission (on _id_ref = 0 or scheme itself). -- ============================================================================= IF OBJECT_ID('dbo.fn_can_user_insert_scheme', 'IF') IS NOT NULL DROP FUNCTION dbo.fn_can_user_insert_scheme; GO CREATE FUNCTION dbo.fn_can_user_insert_scheme ( @scheme_id BIGINT, @user_id BIGINT ) RETURNS TABLE AS RETURN ( WITH user_roles AS ( SELECT _id_role AS role_id FROM _users_roles WHERE _id_user = @user_id ) SELECT CASE WHEN @user_id = 0 THEN 1 -- system user WHEN EXISTS( SELECT 1 FROM _permissions p WHERE (p._id_ref = 0 OR p._id_ref = @scheme_id) AND p._insert = 1 AND (p._id_user = @user_id OR p._id_role IN (SELECT role_id FROM user_roles)) ) THEN 1 ELSE 0 END AS can_insert ); GO PRINT 'REDB Permissions functions created successfully'; GO Path: redb/redb.MSSql/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.MSSql/sql/redb_save_json_objects.sql ---- -- ============================================================ -- SAVE OBJECT FROM JSON (MS SQL Server) -- 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 stored procedures (mirroring read architecture): -- sp_save_object_json(@json NVARCHAR(MAX), @result_id BIGINT OUTPUT) [mirror of get_object_json] -- sp_save_hierarchical_properties(...) [mirror of build_field_json/build_properties] -- -- Supported field types (all branches from build_field_json): -- 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 procedures IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'sp_save_object_json') DROP PROCEDURE [dbo].[sp_save_object_json] GO IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'sp_save_hierarchical_properties') DROP PROCEDURE [dbo].[sp_save_hierarchical_properties] GO -- ============================================================ -- 1. RECURSIVE PROPERTY WRITER -- Mirror of build_field_json / build_properties (reader) -- Walks _scheme_metadata_cache, extracts values from JSON, -- INSERTs into _values with correct column routing -- ============================================================ CREATE PROCEDURE [dbo].[sp_save_hierarchical_properties] @object_id BIGINT, -- owning object _id @parent_structure_id BIGINT, -- NULL for root level, structure _id for nested Class @scheme_id BIGINT, -- scheme _id (for metadata cache lookup) @properties_json NVARCHAR(MAX), -- JSON object: {"Name":"Alice","Tags":[...],"Address":{...}} @parent_value_id BIGINT = NULL -- NULL for root, parent _values._id for nested AS BEGIN SET NOCOUNT ON; -- Ensure metadata cache is populated (mirrors read function) IF NOT EXISTS(SELECT 1 FROM [dbo].[_scheme_metadata_cache] WHERE [_scheme_id] = @scheme_id) BEGIN EXEC [dbo].[sync_metadata_cache_for_scheme] @scheme_id; END -- Variables for cursor DECLARE @structure_id BIGINT; DECLARE @field_name NVARCHAR(450); DECLARE @field_order BIGINT; DECLARE @collection_type BIGINT; DECLARE @is_array BIT; DECLARE @is_dictionary BIT; DECLARE @type_name NVARCHAR(450); DECLARE @db_type NVARCHAR(450); DECLARE @type_semantic NVARCHAR(450); -- Variables for JSON extraction DECLARE @field_json NVARCHAR(MAX); DECLARE @field_type NVARCHAR(50); DECLARE @v_value_id BIGINT; DECLARE @v_head_id BIGINT; DECLARE @v_element_id BIGINT; DECLARE @v_nested_id BIGINT; -- Variables for array/dictionary iteration DECLARE @arr_len INT; DECLARE @arr_idx INT; DECLARE @element_json NVARCHAR(MAX); DECLARE @element_type NVARCHAR(50); -- Variables for OPENJSON dictionary iteration DECLARE @dict_key NVARCHAR(430); DECLARE @dict_value NVARCHAR(MAX); DECLARE @dict_type INT; -- Walk structures for this level (same query & ordering as build_properties) DECLARE structure_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT c.[_structure_id], c.[_name], c.[_order], c.[_collection_type], CASE WHEN c.[_collection_type] = -9223372036854775668 THEN 1 ELSE 0 END, CASE WHEN c.[_collection_type] = -9223372036854775667 THEN 1 ELSE 0 END, c.[type_name], c.[db_type], c.[type_semantic] FROM [dbo].[_scheme_metadata_cache] c WHERE c.[_scheme_id] = @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]; OPEN structure_cursor; FETCH NEXT FROM structure_cursor INTO @structure_id, @field_name, @field_order, @collection_type, @is_array, @is_dictionary, @type_name, @db_type, @type_semantic; WHILE @@FETCH_STATUS = 0 BEGIN -- Extract field value using OPENJSON (NVARCHAR(MAX), no 4000-char JSON_VALUE limit) SET @field_json = NULL; SELECT @field_json = [value] FROM OPENJSON(@properties_json) WHERE [key] = @field_name; -- Skip if field not present or JSON null IF @field_json IS NULL OR @field_json = N'null' BEGIN FETCH NEXT FROM structure_cursor INTO @structure_id, @field_name, @field_order, @collection_type, @is_array, @is_dictionary, @type_name, @db_type, @type_semantic; CONTINUE; END -- ================================================================ -- DISPATCH BY TYPE -- Mirrors the CASE tree in build_field_json -- ================================================================ IF @is_array = 1 BEGIN -- ======================================================== -- ARRAY FIELDS (branches 1-3) -- ======================================================== -- Insert head record: marker "this array property exists" SET @v_head_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_values] ([_id], [_id_structure], [_id_object], [_array_index], [_array_parent_id]) VALUES (@v_head_id, @structure_id, @object_id, NULL, @parent_value_id); -- Empty array [] -> head record alone (read returns []) SET @arr_len = (SELECT COUNT(*) FROM OPENJSON(@field_json)); IF @arr_len = 0 BEGIN FETCH NEXT FROM structure_cursor INTO @structure_id, @field_name, @field_order, @collection_type, @is_array, @is_dictionary, @type_name, @db_type, @type_semantic; CONTINUE; END -- ----- Branch 1: Array of Class fields ----- IF @type_semantic = 'Object' BEGIN DECLARE class_arr_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT CAST([key] AS INT), [value], [type] FROM OPENJSON(@field_json) ORDER BY CAST([key] AS INT); OPEN class_arr_cursor; DECLARE @ca_idx INT, @ca_val NVARCHAR(MAX), @ca_type INT; FETCH NEXT FROM class_arr_cursor INTO @ca_idx, @ca_val, @ca_type; WHILE @@FETCH_STATUS = 0 BEGIN IF @ca_val IS NOT NULL AND @ca_val != N'null' BEGIN -- Insert element record SET @v_element_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_values] ([_id], [_id_structure], [_id_object], [_array_index], [_array_parent_id]) VALUES (@v_element_id, @structure_id, @object_id, CAST(@ca_idx AS NVARCHAR(30)), @v_head_id); -- Recurse into child properties of this array element IF @ca_type = 5 -- JSON object BEGIN EXEC [dbo].[sp_save_hierarchical_properties] @object_id, @structure_id, @scheme_id, @ca_val, @v_element_id; END END FETCH NEXT FROM class_arr_cursor INTO @ca_idx, @ca_val, @ca_type; END CLOSE class_arr_cursor; DEALLOCATE class_arr_cursor; END -- ----- Branch 2: Array of Object references (_RObject) ----- ELSE IF @type_semantic = '_RObject' BEGIN DECLARE robj_arr_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT CAST([key] AS INT), [value], [type] FROM OPENJSON(@field_json) ORDER BY CAST([key] AS INT); OPEN robj_arr_cursor; DECLARE @ra_idx INT, @ra_val NVARCHAR(MAX), @ra_type INT; FETCH NEXT FROM robj_arr_cursor INTO @ra_idx, @ra_val, @ra_type; WHILE @@FETCH_STATUS = 0 BEGIN SET @v_nested_id = NULL; IF @ra_type = 5 -- JSON object -> recursive save BEGIN EXEC [dbo].[sp_save_object_json] @ra_val, @v_nested_id OUTPUT; END ELSE IF @ra_val IS NOT NULL AND @ra_val != N'null' BEGIN SET @v_nested_id = CAST(@ra_val AS BIGINT); END SET @v_element_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_values] ( [_id], [_id_structure], [_id_object], [_Object], [_array_index], [_array_parent_id] ) VALUES ( @v_element_id, @structure_id, @object_id, @v_nested_id, CAST(@ra_idx AS NVARCHAR(30)), @v_head_id ); FETCH NEXT FROM robj_arr_cursor INTO @ra_idx, @ra_val, @ra_type; END CLOSE robj_arr_cursor; DEALLOCATE robj_arr_cursor; END -- ----- Branch 3: Array of primitive types ----- ELSE BEGIN DECLARE prim_arr_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT CAST([key] AS INT), [value], [type] FROM OPENJSON(@field_json) ORDER BY CAST([key] AS INT); OPEN prim_arr_cursor; DECLARE @pa_idx INT, @pa_val NVARCHAR(MAX), @pa_type INT; FETCH NEXT FROM prim_arr_cursor INTO @pa_idx, @pa_val, @pa_type; WHILE @@FETCH_STATUS = 0 BEGIN SET @v_element_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_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_id, @object_id, CAST(@pa_idx AS NVARCHAR(30)), @v_head_id, -- Route value to correct column based on db_type CASE WHEN @db_type = 'String' THEN @pa_val END, CASE WHEN @db_type = 'Long' AND @pa_type != 5 THEN CAST(@pa_val AS BIGINT) END, CASE WHEN @db_type = 'Guid' THEN CAST(@pa_val AS UNIQUEIDENTIFIER) END, CASE WHEN @db_type = 'Double' THEN CAST(@pa_val AS FLOAT) END, CASE WHEN @db_type = 'Numeric' THEN CAST(@pa_val AS DECIMAL(38,18)) END, CASE WHEN @db_type IN ('DateTimeOffset', 'DateTime') THEN CAST(@pa_val AS DATETIMEOFFSET) END, CASE WHEN @db_type = 'Boolean' THEN CASE WHEN @pa_val = 'true' THEN 1 WHEN @pa_val = 'false' THEN 0 ELSE CAST(@pa_val AS BIT) END END, CASE WHEN @db_type = 'ByteArray' THEN CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@pa_val"))', 'VARBINARY(MAX)') END, -- _ListItem: ListItem type OR Long backward-compat (Long field with ListItem JSON) CASE WHEN @db_type = 'ListItem' THEN CASE WHEN @pa_type = 5 THEN CAST(JSON_VALUE(@pa_val, '$.id') AS BIGINT) ELSE CAST(@pa_val AS BIGINT) END WHEN @db_type = 'Long' AND @pa_type = 5 THEN CAST(JSON_VALUE(@pa_val, '$.id') AS BIGINT) END ); FETCH NEXT FROM prim_arr_cursor INTO @pa_idx, @pa_val, @pa_type; END CLOSE prim_arr_cursor; DEALLOCATE prim_arr_cursor; END END ELSE IF @is_dictionary = 1 BEGIN -- ======================================================== -- DICTIONARY FIELDS (branches 4-6) -- ======================================================== -- Insert head record (marker: "this dictionary property exists") SET @v_head_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_values] ([_id], [_id_structure], [_id_object], [_array_index], [_array_parent_id]) VALUES (@v_head_id, @structure_id, @object_id, NULL, @parent_value_id); -- Empty dict {} -> head record alone (read returns {}); OPENJSON yields zero rows -- ----- Branch 4: Dictionary of Class fields ----- IF @type_semantic = 'Object' BEGIN DECLARE class_dict_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@field_json); OPEN class_dict_cursor; DECLARE @cd_key NVARCHAR(430), @cd_val NVARCHAR(MAX), @cd_type INT; FETCH NEXT FROM class_dict_cursor INTO @cd_key, @cd_val, @cd_type; WHILE @@FETCH_STATUS = 0 BEGIN SET @v_element_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_values] ([_id], [_id_structure], [_id_object], [_array_index], [_array_parent_id]) VALUES (@v_element_id, @structure_id, @object_id, @cd_key, @v_head_id); IF @cd_type = 5 -- JSON object BEGIN EXEC [dbo].[sp_save_hierarchical_properties] @object_id, @structure_id, @scheme_id, @cd_val, @v_element_id; END FETCH NEXT FROM class_dict_cursor INTO @cd_key, @cd_val, @cd_type; END CLOSE class_dict_cursor; DEALLOCATE class_dict_cursor; END -- ----- Branch 5: Dictionary of Object references (_RObject) ----- ELSE IF @type_semantic = '_RObject' BEGIN DECLARE robj_dict_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@field_json); OPEN robj_dict_cursor; DECLARE @rd_key NVARCHAR(430), @rd_val NVARCHAR(MAX), @rd_type INT; FETCH NEXT FROM robj_dict_cursor INTO @rd_key, @rd_val, @rd_type; WHILE @@FETCH_STATUS = 0 BEGIN SET @v_nested_id = NULL; IF @rd_type = 5 -- JSON object -> recursive save BEGIN EXEC [dbo].[sp_save_object_json] @rd_val, @v_nested_id OUTPUT; END ELSE IF @rd_val IS NOT NULL AND @rd_val != N'null' BEGIN SET @v_nested_id = CAST(@rd_val AS BIGINT); END SET @v_element_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_values] ( [_id], [_id_structure], [_id_object], [_Object], [_array_index], [_array_parent_id] ) VALUES ( @v_element_id, @structure_id, @object_id, @v_nested_id, @rd_key, @v_head_id ); FETCH NEXT FROM robj_dict_cursor INTO @rd_key, @rd_val, @rd_type; END CLOSE robj_dict_cursor; DEALLOCATE robj_dict_cursor; END -- ----- Branch 6: Dictionary of primitive types ----- ELSE BEGIN DECLARE prim_dict_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@field_json); OPEN prim_dict_cursor; DECLARE @pd_key NVARCHAR(430), @pd_val NVARCHAR(MAX), @pd_type INT; FETCH NEXT FROM prim_dict_cursor INTO @pd_key, @pd_val, @pd_type; WHILE @@FETCH_STATUS = 0 BEGIN SET @v_element_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_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_id, @object_id, @pd_key, @v_head_id, CASE WHEN @db_type = 'String' THEN @pd_val END, CASE WHEN @db_type = 'Long' THEN CAST(@pd_val AS BIGINT) END, CASE WHEN @db_type = 'Guid' THEN CAST(@pd_val AS UNIQUEIDENTIFIER) END, CASE WHEN @db_type = 'Double' THEN CAST(@pd_val AS FLOAT) END, CASE WHEN @db_type = 'Numeric' THEN CAST(@pd_val AS DECIMAL(38,18)) END, CASE WHEN @db_type IN ('DateTimeOffset', 'DateTime') THEN CAST(@pd_val AS DATETIMEOFFSET) END, CASE WHEN @db_type = 'Boolean' THEN CASE WHEN @pd_val = 'true' THEN 1 WHEN @pd_val = 'false' THEN 0 ELSE CAST(@pd_val AS BIT) END END, CASE WHEN @db_type = 'ByteArray' THEN CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@pd_val"))', 'VARBINARY(MAX)') END, CASE WHEN @db_type = 'ListItem' THEN CASE WHEN @pd_type = 5 THEN CAST(JSON_VALUE(@pd_val, '$.id') AS BIGINT) ELSE CAST(@pd_val AS BIGINT) END END ); FETCH NEXT FROM prim_dict_cursor INTO @pd_key, @pd_val, @pd_type; END CLOSE prim_dict_cursor; DEALLOCATE prim_dict_cursor; END END ELSE IF @type_name = 'Object' AND @type_semantic = '_RObject' BEGIN -- ======================================================== -- Branch 7: SINGLE OBJECT REFERENCE -- Mirror: get_object_json(current_Object, max_depth - 1) -- ======================================================== SET @v_nested_id = NULL; SET @field_type = (SELECT CASE WHEN ISJSON(@field_json) = 1 AND LEFT(LTRIM(@field_json), 1) = '{' THEN 'object' ELSE 'scalar' END); IF @field_type = 'object' BEGIN -- Full nested object JSON -> save recursively, get ID EXEC [dbo].[sp_save_object_json] @field_json, @v_nested_id OUTPUT; END ELSE BEGIN -- Numeric ID reference SET @v_nested_id = CAST(@field_json AS BIGINT); END SET @v_value_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_values] ([_id], [_id_structure], [_id_object], [_Object], [_array_parent_id]) VALUES (@v_value_id, @structure_id, @object_id, @v_nested_id, @parent_value_id); END ELSE IF @type_semantic = 'Object' BEGIN -- ======================================================== -- Branch 8: CLASS FIELD (nested class with child properties) -- Mirror: WHEN _Guid IS NULL THEN NULL ELSE build_properties(...) -- ======================================================== -- Insert marker record with _Guid (read checks: _Guid IS NULL -> class is null) SET @v_value_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_values] ([_id], [_id_structure], [_id_object], [_Guid], [_array_parent_id]) VALUES (@v_value_id, @structure_id, @object_id, NEWID(), @parent_value_id); -- Recurse: save child properties under this class structure EXEC [dbo].[sp_save_hierarchical_properties] @object_id, @structure_id, @scheme_id, @field_json, @v_value_id; END ELSE BEGIN -- ======================================================== -- Branches 9-10: PRIMITIVE SCALAR FIELDS + LISTITEM -- ======================================================== SET @v_value_id = NEXT VALUE FOR [dbo].[global_identity]; SET @field_type = (SELECT CASE WHEN ISJSON(@field_json) = 1 AND LEFT(LTRIM(@field_json), 1) = '{' THEN 'object' ELSE 'scalar' END); -- Branch 9: ListItem (db_type='ListItem', or Long backward-compat with ListItem JSON) IF @db_type = 'ListItem' OR (@db_type = 'Long' AND @field_type = 'object') BEGIN INSERT INTO [dbo].[_values] ([_id], [_id_structure], [_id_object], [_ListItem], [_array_parent_id]) VALUES (@v_value_id, @structure_id, @object_id, CAST(JSON_VALUE(@field_json, '$.id') AS BIGINT), @parent_value_id); END -- Branch 10: Standard primitive types ELSE BEGIN INSERT INTO [dbo].[_values] ( [_id], [_id_structure], [_id_object], [_array_parent_id], [_String], [_Long], [_Guid], [_Double], [_Numeric], [_DateTimeOffset], [_Boolean], [_ByteArray] ) VALUES ( @v_value_id, @structure_id, @object_id, @parent_value_id, CASE WHEN @db_type = 'String' THEN @field_json END, CASE WHEN @db_type = 'Long' THEN CAST(@field_json AS BIGINT) END, CASE WHEN @db_type = 'Guid' THEN CAST(@field_json AS UNIQUEIDENTIFIER) END, CASE WHEN @db_type = 'Double' THEN CAST(@field_json AS FLOAT) END, CASE WHEN @db_type = 'Numeric' THEN CAST(@field_json AS DECIMAL(38,18)) END, CASE WHEN @db_type IN ('DateTimeOffset', 'DateTime') THEN CAST(@field_json AS DATETIMEOFFSET) END, CASE WHEN @db_type = 'Boolean' THEN CASE WHEN @field_json = 'true' THEN 1 WHEN @field_json = 'false' THEN 0 ELSE CAST(@field_json AS BIT) END END, CASE WHEN @db_type = 'ByteArray' THEN CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@field_json"))', 'VARBINARY(MAX)') END ); END END FETCH NEXT FROM structure_cursor INTO @structure_id, @field_name, @field_order, @collection_type, @is_array, @is_dictionary, @type_name, @db_type, @type_semantic; END CLOSE structure_cursor; DEALLOCATE structure_cursor; END GO -- ============================================================ -- 2. MAIN ENTRY POINT -- Mirror of get_object_json (reader) -- JSON -> UPSERT _objects -> DELETE _values -> save properties -- ============================================================ CREATE PROCEDURE [dbo].[sp_save_object_json] @json_data NVARCHAR(MAX), @result_id BIGINT = NULL OUTPUT AS BEGIN SET NOCOUNT ON; DECLARE @object_id BIGINT; DECLARE @scheme_id BIGINT; DECLARE @properties_json NVARCHAR(MAX); DECLARE @exists BIT; DECLARE @v_bytes_b64 NVARCHAR(MAX); DECLARE @v_note NVARCHAR(MAX); DECLARE @v_value_string NVARCHAR(MAX); -- Extract required fields SET @object_id = CAST(JSON_VALUE(@json_data, '$.id') AS BIGINT); SET @scheme_id = CAST(JSON_VALUE(@json_data, '$.scheme_id') AS BIGINT); -- Extract NVARCHAR(MAX) fields via OPENJSON (no 4000-char JSON_VALUE limit) SELECT @v_note = note, @v_value_string = value_string, @v_bytes_b64 = value_bytes FROM OPENJSON(@json_data) WITH ( note NVARCHAR(MAX) '$.note', value_string NVARCHAR(MAX) '$.value_string', value_bytes NVARCHAR(MAX) '$.value_bytes' ); IF @scheme_id IS NULL BEGIN RAISERROR('sp_save_object_json: scheme_id is required', 16, 1); RETURN; END -- Verify scheme exists IF NOT EXISTS(SELECT 1 FROM [dbo].[_schemes] WHERE [_id] = @scheme_id) BEGIN RAISERROR('sp_save_object_json: scheme_id not found', 16, 1); RETURN; END -- Generate new ID for new objects (id = 0 or absent) IF @object_id IS NULL OR @object_id = 0 SET @object_id = NEXT VALUE FOR [dbo].[global_identity]; -- Check if object already exists SET @exists = CASE WHEN EXISTS(SELECT 1 FROM [dbo].[_objects] WHERE [_id] = @object_id) THEN 1 ELSE 0 END; IF @exists = 1 BEGIN -- ===== UPDATE existing object ===== -- _date_create is preserved (not updated) UPDATE [dbo].[_objects] SET [_id_scheme] = @scheme_id, [_id_parent] = CAST(JSON_VALUE(@json_data, '$.parent_id') AS BIGINT), [_id_owner] = COALESCE(CAST(JSON_VALUE(@json_data, '$.owner_id') AS BIGINT), [_id_owner]), [_id_who_change] = COALESCE(CAST(JSON_VALUE(@json_data, '$.who_change_id') AS BIGINT), [_id_who_change]), [_name] = JSON_VALUE(@json_data, '$.name'), [_note] = @v_note, [_key] = CAST(JSON_VALUE(@json_data, '$.key') AS BIGINT), [_hash] = CAST(JSON_VALUE(@json_data, '$.hash') AS UNIQUEIDENTIFIER), [_date_modify] = SYSDATETIMEOFFSET(), [_date_begin] = CAST(JSON_VALUE(@json_data, '$.date_begin') AS DATETIMEOFFSET), [_date_complete] = CAST(JSON_VALUE(@json_data, '$.date_complete') AS DATETIMEOFFSET), [_value_long] = CAST(JSON_VALUE(@json_data, '$.value_long') AS BIGINT), [_value_string] = @v_value_string, [_value_guid] = CAST(JSON_VALUE(@json_data, '$.value_guid') AS UNIQUEIDENTIFIER), [_value_bool] = CASE WHEN JSON_VALUE(@json_data, '$.value_bool') = 'true' THEN 1 WHEN JSON_VALUE(@json_data, '$.value_bool') = 'false' THEN 0 ELSE NULL END, [_value_double] = CAST(JSON_VALUE(@json_data, '$.value_double') AS FLOAT), [_value_numeric] = CAST(JSON_VALUE(@json_data, '$.value_numeric') AS DECIMAL(38,18)), [_value_datetime] = CAST(JSON_VALUE(@json_data, '$.value_datetime') AS DATETIMEOFFSET), [_value_bytes] = CASE WHEN @v_bytes_b64 IS NOT NULL THEN CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@v_bytes_b64"))', 'VARBINARY(MAX)') ELSE NULL END WHERE [_id] = @object_id; -- DeleteInsert strategy: remove all old values before inserting new DELETE FROM [dbo].[_values] WHERE [_id_object] = @object_id; END ELSE BEGIN -- ===== INSERT new object ===== INSERT INTO [dbo].[_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 ( @object_id, @scheme_id, CAST(JSON_VALUE(@json_data, '$.parent_id') AS BIGINT), COALESCE(CAST(JSON_VALUE(@json_data, '$.owner_id') AS BIGINT), 1), COALESCE(CAST(JSON_VALUE(@json_data, '$.who_change_id') AS BIGINT), 1), JSON_VALUE(@json_data, '$.name'), @v_note, CAST(JSON_VALUE(@json_data, '$.key') AS BIGINT), CAST(JSON_VALUE(@json_data, '$.hash') AS UNIQUEIDENTIFIER), COALESCE(CAST(JSON_VALUE(@json_data, '$.date_create') AS DATETIMEOFFSET), SYSDATETIMEOFFSET()), SYSDATETIMEOFFSET(), CAST(JSON_VALUE(@json_data, '$.date_begin') AS DATETIMEOFFSET), CAST(JSON_VALUE(@json_data, '$.date_complete') AS DATETIMEOFFSET), CAST(JSON_VALUE(@json_data, '$.value_long') AS BIGINT), @v_value_string, CAST(JSON_VALUE(@json_data, '$.value_guid') AS UNIQUEIDENTIFIER), CASE WHEN JSON_VALUE(@json_data, '$.value_bool') = 'true' THEN 1 WHEN JSON_VALUE(@json_data, '$.value_bool') = 'false' THEN 0 ELSE NULL END, CAST(JSON_VALUE(@json_data, '$.value_double') AS FLOAT), CAST(JSON_VALUE(@json_data, '$.value_numeric') AS DECIMAL(38,18)), CAST(JSON_VALUE(@json_data, '$.value_datetime') AS DATETIMEOFFSET), CASE WHEN @v_bytes_b64 IS NOT NULL THEN CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@v_bytes_b64"))', 'VARBINARY(MAX)') ELSE NULL END ); END -- Save properties if present SET @properties_json = JSON_QUERY(@json_data, '$.properties'); IF @properties_json IS NOT NULL BEGIN EXEC [dbo].[sp_save_hierarchical_properties] @object_id, NULL, -- root level (no parent structure) @scheme_id, @properties_json, NULL; -- root level (no parent value) END SET @result_id = @object_id; END GO -- ============================================================ -- USAGE EXAMPLES -- ============================================================ -- -- Save/update object from JSON: -- DECLARE @id BIGINT; -- EXEC sp_save_object_json @json_data = N'{"id":123,"scheme_id":1,...,"properties":{...}}', @result_id = @id OUTPUT; -- SELECT @id; -- -- Insert new object (id=0 or absent -> auto-generate): -- DECLARE @id BIGINT; -- EXEC sp_save_object_json @json_data = N'{"id":0,"scheme_id":1,...}', @result_id = @id OUTPUT; -- SELECT @id; -- ============================================================ PRINT '=========================================' PRINT 'Save JSON object procedures created!' Path: redb/redb.MSSql/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.MSSql/sql/redb_structure_tree.sql ---- -- ==================================================================================================== -- FUNCTIONS FOR SCHEME STRUCTURE TREE -- MS SQL Server version -- ==================================================================================================== -- Supports hierarchical navigation: parent -> children -> descendants -- Solves flat structure search issues in SaveAsync -- ==================================================================================================== -- ===================================================== -- DROP EXISTING OBJECTS -- ===================================================== IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'get_scheme_structure_tree') DROP PROCEDURE [dbo].[get_scheme_structure_tree] GO IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'get_structure_children') DROP PROCEDURE [dbo].[get_structure_children] GO IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'validate_structure_tree') DROP PROCEDURE [dbo].[validate_structure_tree] GO IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'get_structure_descendants') DROP PROCEDURE [dbo].[get_structure_descendants] GO -- ===================================================== -- 1. MAIN PROCEDURE: Build scheme structure tree -- ===================================================== CREATE PROCEDURE [dbo].[get_scheme_structure_tree] @scheme_id BIGINT, @parent_id BIGINT = NULL, @max_depth INT = 10, @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; DECLARE @structure_id BIGINT; DECLARE @name NVARCHAR(450); DECLARE @order BIGINT; DECLARE @is_array BIT; DECLARE @collection_type BIGINT; DECLARE @store_null BIT; DECLARE @allow_not_null BIT; DECLARE @type_name NVARCHAR(450); DECLARE @db_type NVARCHAR(450); DECLARE @type_semantic NVARCHAR(450); DECLARE @children_json NVARCHAR(MAX); DECLARE @item_json NVARCHAR(MAX); DECLARE @next_depth INT; SET @result = N'[]'; -- Protection from infinite recursion IF @max_depth <= 0 BEGIN SET @result = N'[{"error":"Max recursion depth reached"}]'; RETURN; END -- Check if scheme exists IF NOT EXISTS(SELECT 1 FROM [dbo].[_schemes] WHERE [_id] = @scheme_id) BEGIN SET @result = N'[{"error":"Scheme not found"}]'; RETURN; END -- Auto-fill cache if empty IF NOT EXISTS(SELECT 1 FROM [dbo].[_scheme_metadata_cache] WHERE [_scheme_id] = @scheme_id) BEGIN EXEC [dbo].[sync_metadata_cache_for_scheme] @scheme_id; END -- Create temp table for results DECLARE @items TABLE ( [structure_id] BIGINT, [name] NVARCHAR(450), [order] BIGINT, [is_array] BIT, [collection_type] BIGINT, [store_null] BIT, [allow_not_null] BIT, [type_name] NVARCHAR(450), [db_type] NVARCHAR(450), [type_semantic] NVARCHAR(450), [children] NVARCHAR(MAX) ); -- Get structures for current level from cache DECLARE cur CURSOR LOCAL FAST_FORWARD FOR SELECT c.[_structure_id], c.[_name], c.[_order], CASE WHEN c.[_collection_type] IS NOT NULL THEN 1 ELSE 0 END, c.[_collection_type], c.[_store_null], c.[_allow_not_null], c.[type_name], c.[db_type], c.[type_semantic] FROM [dbo].[_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]; OPEN cur; FETCH NEXT FROM cur INTO @structure_id, @name, @order, @is_array, @collection_type, @store_null, @allow_not_null, @type_name, @db_type, @type_semantic; WHILE @@FETCH_STATUS = 0 BEGIN -- Check if has children IF EXISTS(SELECT 1 FROM [dbo].[_structures] WHERE [_id_scheme] = @scheme_id AND [_id_parent] = @structure_id) BEGIN -- Recursively get children SET @next_depth = @max_depth - 1; EXEC [dbo].[get_scheme_structure_tree] @scheme_id, @structure_id, @next_depth, @children_json OUTPUT; END ELSE BEGIN SET @children_json = N'[]'; END -- Insert into temp table INSERT INTO @items VALUES ( @structure_id, @name, @order, @is_array, @collection_type, @store_null, @allow_not_null, @type_name, @db_type, @type_semantic, @children_json ); FETCH NEXT FROM cur INTO @structure_id, @name, @order, @is_array, @collection_type, @store_null, @allow_not_null, @type_name, @db_type, @type_semantic; END CLOSE cur; DEALLOCATE cur; -- Build JSON result SELECT @result = N'[' + ISNULL(STRING_AGG( N'{"structure_id":' + CAST([structure_id] AS NVARCHAR(20)) + N',"name":' + QUOTENAME([name], '"') + N',"order":' + ISNULL(CAST([order] AS NVARCHAR(20)), 'null') + N',"is_array":' + CASE WHEN [is_array] = 1 THEN 'true' ELSE 'false' END + N',"collection_type":' + ISNULL(CAST([collection_type] AS NVARCHAR(20)), 'null') + N',"store_null":' + CASE WHEN [store_null] = 1 THEN 'true' WHEN [store_null] = 0 THEN 'false' ELSE 'null' END + N',"allow_not_null":' + CASE WHEN [allow_not_null] = 1 THEN 'true' WHEN [allow_not_null] = 0 THEN 'false' ELSE 'null' END + N',"type_name":' + QUOTENAME([type_name], '"') + N',"db_type":' + QUOTENAME([db_type], '"') + N',"type_semantic":' + QUOTENAME([type_semantic], '"') + N',"children":' + [children] + N'}' , ','), '') + N']' FROM @items; END GO -- ===================================================== -- 2. HELPER: Get direct children only -- ===================================================== CREATE PROCEDURE [dbo].[get_structure_children] @scheme_id BIGINT, @parent_id BIGINT, @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; -- Auto-fill cache if empty IF NOT EXISTS(SELECT 1 FROM [dbo].[_scheme_metadata_cache] WHERE [_scheme_id] = @scheme_id) BEGIN EXEC [dbo].[sync_metadata_cache_for_scheme] @scheme_id; END SELECT @result = N'[' + ISNULL(STRING_AGG(json_item, ',') WITHIN GROUP (ORDER BY [_order], [_structure_id]), '') + N']' FROM ( SELECT c.[_structure_id], c.[_order], N'{"structure_id":' + CAST(c.[_structure_id] AS NVARCHAR(20)) + N',"name":' + QUOTENAME(c.[_name], '"') + N',"order":' + ISNULL(CAST(c.[_order] AS NVARCHAR(20)), 'null') + N',"is_array":' + CASE WHEN c.[_collection_type] IS NOT NULL THEN 'true' ELSE 'false' END + N',"collection_type":' + ISNULL(CAST(c.[_collection_type] AS NVARCHAR(20)), 'null') + N',"type_name":' + QUOTENAME(c.[type_name], '"') + N',"db_type":' + QUOTENAME(c.[db_type], '"') + N',"type_semantic":' + QUOTENAME(c.[type_semantic], '"') + N'}' AS json_item FROM [dbo].[_scheme_metadata_cache] c WHERE c.[_scheme_id] = @scheme_id AND c.[_parent_structure_id] = @parent_id ) sub; END GO -- ===================================================== -- 3. DIAGNOSTIC: Validate structure tree -- ===================================================== CREATE PROCEDURE [dbo].[validate_structure_tree] @scheme_id BIGINT, @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; DECLARE @excessive_json NVARCHAR(MAX); DECLARE @orphaned_json NVARCHAR(MAX); DECLARE @circular_json NVARCHAR(MAX); DECLARE @total_count INT; DECLARE @is_valid BIT; -- 1. Find excessive structures (no values linked) SELECT @excessive_json = N'[' + ISNULL(STRING_AGG( N'{"structure_id":' + CAST(s.[_id] AS NVARCHAR(20)) + N',"name":' + QUOTENAME(s.[_name], '"') + N',"parent_name":' + ISNULL(QUOTENAME(parent_s.[_name], '"'), 'null') + N',"issue":"No values found - possibly excessive structure"}' , ','), '') + N']' FROM [dbo].[_structures] s LEFT JOIN [dbo].[_structures] parent_s ON parent_s.[_id] = s.[_id_parent] LEFT JOIN [dbo].[_values] v ON v.[_id_structure] = s.[_id] WHERE s.[_id_scheme] = @scheme_id AND v.[_id] IS NULL AND s.[_id_parent] IS NOT NULL; -- 2. Find orphaned structures (parent does not exist) SELECT @orphaned_json = N'[' + ISNULL(STRING_AGG( N'{"structure_id":' + CAST(s.[_id] AS NVARCHAR(20)) + N',"name":' + QUOTENAME(s.[_name], '"') + N',"parent_id":' + CAST(s.[_id_parent] AS NVARCHAR(20)) + N',"issue":"Parent structure does not exist"}' , ','), '') + N']' FROM [dbo].[_structures] s WHERE s.[_id_scheme] = @scheme_id AND s.[_id_parent] IS NOT NULL AND NOT EXISTS(SELECT 1 FROM [dbo].[_structures] parent_s WHERE parent_s.[_id] = s.[_id_parent]); -- 3. Check for circular references (using path string) ;WITH cycle_check AS ( SELECT [_id], [_id_parent], CAST([_id] AS NVARCHAR(MAX)) AS [path], 0 AS has_cycle FROM [dbo].[_structures] WHERE [_id_scheme] = @scheme_id AND [_id_parent] IS NOT NULL UNION ALL SELECT s.[_id], s.[_id_parent], cc.[path] + ',' + CAST(s.[_id] AS NVARCHAR(20)), CASE WHEN CHARINDEX(',' + CAST(s.[_id] AS NVARCHAR(20)) + ',', ',' + cc.[path] + ',') > 0 THEN 1 ELSE 0 END FROM [dbo].[_structures] s INNER JOIN cycle_check cc ON cc.[_id_parent] = s.[_id] WHERE cc.has_cycle = 0 AND LEN(cc.[path]) < 1000 ) SELECT @circular_json = N'[' + ISNULL(STRING_AGG( N'{"structure_id":' + CAST([_id] AS NVARCHAR(20)) + N',"path":"' + [path] + N'","issue":"Circular reference detected"}' , ','), '') + N']' FROM cycle_check WHERE has_cycle = 1; -- Get total count SELECT @total_count = COUNT(*) FROM [dbo].[_structures] WHERE [_id_scheme] = @scheme_id; -- Determine if valid SET @is_valid = CASE WHEN @excessive_json = N'[]' AND @orphaned_json = N'[]' AND @circular_json = N'[]' THEN 1 ELSE 0 END; -- Build result SET @result = N'{' + N'"scheme_id":' + CAST(@scheme_id AS NVARCHAR(20)) + N',"validation_date":"' + CONVERT(NVARCHAR(30), GETDATE(), 127) + '"' + N',"excessive_structures":' + ISNULL(@excessive_json, N'[]') + N',"orphaned_structures":' + ISNULL(@orphaned_json, N'[]') + N',"circular_references":' + ISNULL(@circular_json, N'[]') + N',"total_structures":' + CAST(@total_count AS NVARCHAR(10)) + N',"is_valid":' + CASE WHEN @is_valid = 1 THEN 'true' ELSE 'false' END + N'}'; END GO -- ===================================================== -- 4. HELPER: Get all descendants (flat list) -- ===================================================== CREATE PROCEDURE [dbo].[get_structure_descendants] @scheme_id BIGINT, @parent_id BIGINT, @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; ;WITH descendants AS ( -- Direct children SELECT [_id], [_name], [_id_parent], 0 AS [level] FROM [dbo].[_structures] WHERE [_id_scheme] = @scheme_id AND [_id_parent] = @parent_id UNION ALL -- Recursive descendants SELECT s.[_id], s.[_name], s.[_id_parent], d.[level] + 1 FROM [dbo].[_structures] s INNER JOIN descendants d ON d.[_id] = s.[_id_parent] WHERE s.[_id_scheme] = @scheme_id AND d.[level] < 10 ) SELECT @result = N'[' + ISNULL(STRING_AGG(json_item, ',') WITHIN GROUP (ORDER BY [level], [_id]), '') + N']' FROM ( SELECT [_id], [level], N'{"structure_id":' + CAST([_id] AS NVARCHAR(20)) + N',"name":' + QUOTENAME([_name], '"') + N',"parent_id":' + ISNULL(CAST([_id_parent] AS NVARCHAR(20)), 'null') + N',"level":' + CAST([level] AS NVARCHAR(10)) + N'}' AS json_item FROM descendants ) sub; END GO -- ===================================================== -- USAGE EXAMPLES -- ===================================================== -- -- Get full structure tree: -- DECLARE @json NVARCHAR(MAX); -- EXEC get_scheme_structure_tree @scheme_id = 123, @result = @json OUTPUT; -- SELECT @json; -- -- Get direct children: -- DECLARE @json NVARCHAR(MAX); -- EXEC get_structure_children @scheme_id = 123, @parent_id = 456, @result = @json OUTPUT; -- SELECT @json; -- -- Validate tree: -- DECLARE @json NVARCHAR(MAX); -- EXEC validate_structure_tree @scheme_id = 123, @result = @json OUTPUT; -- SELECT @json; -- -- Get all descendants: -- DECLARE @json NVARCHAR(MAX); -- EXEC get_structure_descendants @scheme_id = 123, @parent_id = 456, @result = @json OUTPUT; -- SELECT @json; -- ===================================================== PRINT '=========================================' PRINT 'Structure tree procedures created!' PRINT '=========================================' GO Path: redb/redb.MSSql/sql/sp_redb_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.MSSql/sql/sp_redb_json_objects.sql ---- -- ==================================================================================================== -- JSON OBJECT FUNCTIONS -- MS SQL Server version -- ==================================================================================================== -- Builds JSON representation of objects from EAV model -- Supports: hierarchical Class fields, arrays, dictionaries, Object references -- ==================================================================================================== -- ===================================================== -- DROP EXISTING OBJECTS -- ===================================================== IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'sp_get_object_json') DROP PROCEDURE [dbo].[sp_get_object_json] GO IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'sp_get_object_json_internal') DROP PROCEDURE [dbo].[sp_get_object_json_internal] GO IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'sp_build_hierarchical_properties') DROP PROCEDURE [dbo].[sp_build_hierarchical_properties] GO -- Drop temp table type if exists IF EXISTS (SELECT * FROM sys.types WHERE name = 'ValuesTableType') DROP TYPE [dbo].[ValuesTableType] GO -- ===================================================== -- CREATE TABLE TYPE FOR VALUES (used in temp table) -- ===================================================== -- Note: We use #all_values temp table instead of TVP for recursion support -- ===================================================== -- HELPER: Build hierarchical properties from #all_values -- ===================================================== -- IMPORTANT: Requires #all_values temp table to exist in session! -- Called recursively by get_object_json CREATE PROCEDURE [dbo].[sp_build_hierarchical_properties] @object_id BIGINT, @parent_structure_id BIGINT = NULL, @object_scheme_id BIGINT, @max_depth INT = 10, @array_index NVARCHAR(430) = NULL, @parent_value_id BIGINT = NULL, @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; DECLARE @field_results TABLE ( [field_name] NVARCHAR(450), [field_order] BIGINT, [field_value] NVARCHAR(MAX) ); -- Variables for cursor DECLARE @structure_id BIGINT; DECLARE @field_name NVARCHAR(450); DECLARE @field_order BIGINT; DECLARE @collection_type BIGINT; DECLARE @is_array BIT; DECLARE @is_dictionary BIT; DECLARE @type_name NVARCHAR(450); DECLARE @db_type NVARCHAR(450); DECLARE @type_semantic NVARCHAR(450); -- Variables for current value DECLARE @current_value_id BIGINT; DECLARE @current_String NVARCHAR(MAX); DECLARE @current_Long BIGINT; DECLARE @current_Guid UNIQUEIDENTIFIER; DECLARE @current_Double FLOAT; DECLARE @current_Numeric DECIMAL(38,18); DECLARE @current_DateTimeOffset DATETIMEOFFSET; DECLARE @current_Boolean BIT; DECLARE @current_ByteArray VARBINARY(MAX); DECLARE @current_ListItem BIGINT; DECLARE @current_Object BIGINT; DECLARE @field_value NVARCHAR(MAX); DECLARE @base_array_value_id BIGINT; DECLARE @children_json NVARCHAR(MAX); DECLARE @temp_json NVARCHAR(MAX); DECLARE @next_depth INT; -- Variables for array/dictionary handling (must be declared at procedure level) DECLARE @elem_array_index NVARCHAR(430); DECLARE @elem_value_id BIGINT; DECLARE @ref_object_id BIGINT; DECLARE @dict_key NVARCHAR(430); DECLARE @dict_value_id BIGINT; DECLARE @dict_obj_key NVARCHAR(430); DECLARE @dict_obj_id BIGINT; -- Table variables for collecting results (must be declared at procedure level) DECLARE @array_elements TABLE ([idx] INT IDENTITY, [element_json] NVARCHAR(MAX)); DECLARE @obj_array TABLE ([idx] INT IDENTITY, [obj_json] NVARCHAR(MAX)); DECLARE @dict_elements TABLE ([key] NVARCHAR(430), [element_json] NVARCHAR(MAX)); DECLARE @dict_obj TABLE ([key] NVARCHAR(430), [obj_json] NVARCHAR(MAX)); -- Protection against infinite recursion IF @max_depth < -100 BEGIN SET @result = N'{"error":"Max recursion depth reached"}'; RETURN; END -- Auto-fill cache if empty IF NOT EXISTS(SELECT 1 FROM [dbo].[_scheme_metadata_cache] WHERE [_scheme_id] = @object_scheme_id) BEGIN EXEC [dbo].[sync_metadata_cache_for_scheme] @object_scheme_id; END -- Iterate through structures for current level DECLARE structure_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT c.[_structure_id], c.[_name], c.[_order], c.[_collection_type], CASE WHEN c.[_collection_type] = -9223372036854775668 THEN 1 ELSE 0 END, -- Array type ID CASE WHEN c.[_collection_type] = -9223372036854775667 THEN 1 ELSE 0 END, -- Dictionary type ID c.[type_name], c.[db_type], c.[type_semantic] FROM [dbo].[_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]; OPEN structure_cursor; FETCH NEXT FROM structure_cursor INTO @structure_id, @field_name, @field_order, @collection_type, @is_array, @is_dictionary, @type_name, @db_type, @type_semantic; WHILE @@FETCH_STATUS = 0 BEGIN SET @field_value = NULL; SET @current_value_id = NULL; SET @base_array_value_id = NULL; -- Find current value from #all_values IF @parent_value_id IS NOT NULL BEGIN -- For nested fields inside array/dictionary elements SELECT TOP 1 @current_value_id = [_id], @current_String = [_String], @current_Long = [_Long], @current_Guid = [_Guid], @current_Double = [_Double], @current_Numeric = [_Numeric], @current_DateTimeOffset = [_DateTimeOffset], @current_Boolean = [_Boolean], @current_ByteArray = [_ByteArray], @current_ListItem = [_ListItem], @current_Object = [_Object] FROM #all_values WHERE [_id_object] = @object_id AND [_id_structure] = @structure_id AND [_array_parent_id] = @parent_value_id; END ELSE IF @array_index IS NOT NULL BEGIN -- For array/dictionary elements SELECT TOP 1 @current_value_id = [_id], @current_String = [_String], @current_Long = [_Long], @current_Guid = [_Guid], @current_Double = [_Double], @current_Numeric = [_Numeric], @current_DateTimeOffset = [_DateTimeOffset], @current_Boolean = [_Boolean], @current_ByteArray = [_ByteArray], @current_ListItem = [_ListItem], @current_Object = [_Object] FROM #all_values WHERE [_id_object] = @object_id AND [_id_structure] = @structure_id AND [_array_index] = @array_index; END ELSE BEGIN -- For regular fields SELECT TOP 1 @current_value_id = [_id], @current_String = [_String], @current_Long = [_Long], @current_Guid = [_Guid], @current_Double = [_Double], @current_Numeric = [_Numeric], @current_DateTimeOffset = [_DateTimeOffset], @current_Boolean = [_Boolean], @current_ByteArray = [_ByteArray], @current_ListItem = [_ListItem], @current_Object = [_Object] FROM #all_values WHERE [_id_object] = @object_id AND [_id_structure] = @structure_id AND [_array_index] IS NULL; END -- Get base array/dictionary record ID for collections IF @is_array = 1 OR @is_dictionary = 1 BEGIN IF @parent_value_id IS NULL BEGIN SELECT TOP 1 @base_array_value_id = [_id] FROM #all_values WHERE [_id_object] = @object_id AND [_id_structure] = @structure_id AND [_array_index] IS NULL AND [_array_parent_id] IS NULL; END ELSE BEGIN SELECT TOP 1 @base_array_value_id = [_id] FROM #all_values WHERE [_id_object] = @object_id AND [_id_structure] = @structure_id AND [_array_index] IS NULL AND [_array_parent_id] = @parent_value_id; END -- No head record = array/dictionary property is null (not empty []/{}) -- Without this, @base_array_value_id IS NULL fallback matches wrong records IF @base_array_value_id IS NULL BEGIN FETCH NEXT FROM structure_cursor INTO @structure_id, @field_name, @field_order, @collection_type, @is_array, @is_dictionary, @type_name, @db_type, @type_semantic; CONTINUE; END END -- ===================================================== -- ARRAYS -- ===================================================== IF @is_array = 1 BEGIN IF @type_semantic = 'Object' -- Array of Class fields BEGIN -- Build array of Class objects recursively DELETE FROM @array_elements; DECLARE elem_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [_array_index], [_id] FROM #all_values WHERE [_id_object] = @object_id AND [_id_structure] = @structure_id AND [_array_index] IS NOT NULL AND (@base_array_value_id IS NULL OR [_array_parent_id] = @base_array_value_id) ORDER BY CASE WHEN [_array_index] LIKE '[0-9]%' AND ISNUMERIC([_array_index]) = 1 THEN CAST([_array_index] AS INT) ELSE 0 END, [_array_index]; OPEN elem_cursor; FETCH NEXT FROM elem_cursor INTO @elem_array_index, @elem_value_id; WHILE @@FETCH_STATUS = 0 BEGIN EXEC [dbo].[sp_build_hierarchical_properties] @object_id, @structure_id, @object_scheme_id, @max_depth, @elem_array_index, @elem_value_id, @temp_json OUTPUT; INSERT INTO @array_elements ([element_json]) VALUES (@temp_json); FETCH NEXT FROM elem_cursor INTO @elem_array_index, @elem_value_id; END CLOSE elem_cursor; DEALLOCATE elem_cursor; -- Build JSON array SELECT @field_value = N'[' + ISNULL(STRING_AGG([element_json], N',') WITHIN GROUP (ORDER BY [idx]), N'') + N']' FROM @array_elements; END ELSE -- Array of primitives or _RObject references BEGIN -- Handle _RObject arrays with recursion (cannot use subquery in STRING_AGG) IF @type_semantic = '_RObject' BEGIN DELETE FROM @obj_array; DECLARE obj_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT v.[_Object] FROM #all_values v WHERE v.[_id_object] = @object_id AND v.[_id_structure] = @structure_id AND v.[_array_index] IS NOT NULL AND v.[_Object] IS NOT NULL AND (@base_array_value_id IS NULL OR v.[_array_parent_id] = @base_array_value_id) ORDER BY CASE WHEN v.[_array_index] LIKE '[0-9]%' AND ISNUMERIC(v.[_array_index]) = 1 THEN CAST(v.[_array_index] AS INT) ELSE 0 END, v.[_array_index]; OPEN obj_cursor; FETCH NEXT FROM obj_cursor INTO @ref_object_id; WHILE @@FETCH_STATUS = 0 BEGIN SET @next_depth = @max_depth - 1; EXEC [dbo].[sp_get_object_json_internal] @ref_object_id, @next_depth, @temp_json OUTPUT; INSERT INTO @obj_array ([obj_json]) VALUES (@temp_json); FETCH NEXT FROM obj_cursor INTO @ref_object_id; END CLOSE obj_cursor; DEALLOCATE obj_cursor; SELECT @field_value = N'[' + ISNULL(STRING_AGG([obj_json], N',') WITHIN GROUP (ORDER BY [idx]), N'') + N']' FROM @obj_array; END ELSE BEGIN -- Array of primitives (String, Long, Guid, Double, ListItem, etc.) SELECT @field_value = N'[' + ISNULL(STRING_AGG( CASE WHEN @db_type = 'String' THEN CASE WHEN v.[_String] IS NULL THEN N'null' ELSE N'"' + REPLACE(REPLACE(v.[_String], N'\', N'\\'), N'"', N'\"') + N'"' END WHEN @db_type = 'Long' THEN CASE WHEN v.[_Long] IS NULL THEN N'null' ELSE CAST(v.[_Long] AS NVARCHAR(30)) END WHEN @db_type = 'Guid' THEN CASE WHEN v.[_Guid] IS NULL THEN N'null' ELSE N'"' + CAST(v.[_Guid] AS NVARCHAR(50)) + N'"' END WHEN @db_type = 'Double' THEN CASE WHEN v.[_Double] IS NULL THEN N'null' ELSE FORMAT(v.[_Double], 'G', 'en-US') END WHEN @db_type = 'Numeric' THEN CASE WHEN v.[_Numeric] IS NULL THEN N'null' ELSE REPLACE(CAST(v.[_Numeric] AS NVARCHAR(50)), N',', N'.') END WHEN @db_type = 'DateTimeOffset' THEN CASE WHEN v.[_DateTimeOffset] IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), v.[_DateTimeOffset], 127) + N'"' END WHEN @db_type = 'Boolean' THEN CASE WHEN v.[_Boolean] IS NULL THEN N'null' WHEN v.[_Boolean] = 1 THEN N'true' ELSE N'false' END WHEN @db_type = 'ListItem' THEN CASE WHEN v.[_ListItem] IS NULL THEN N'null' ELSE dbo.build_listitem_json(v.[_ListItem]) END ELSE N'null' END , N',') WITHIN GROUP (ORDER BY CASE WHEN v.[_array_index] LIKE '[0-9]%' AND ISNUMERIC(v.[_array_index]) = 1 THEN CAST(v.[_array_index] AS INT) ELSE 0 END, v.[_array_index] ), N'') + N']' FROM #all_values v WHERE v.[_id_object] = @object_id AND v.[_id_structure] = @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 END END -- ===================================================== -- DICTIONARIES -- ===================================================== ELSE IF @is_dictionary = 1 BEGIN IF @type_semantic = 'Object' -- Dictionary of Class fields BEGIN DELETE FROM @dict_elements; DECLARE dict_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [_array_index], [_id] FROM #all_values WHERE [_id_object] = @object_id AND [_id_structure] = @structure_id AND [_array_index] IS NOT NULL AND (@base_array_value_id IS NULL OR [_array_parent_id] = @base_array_value_id); OPEN dict_cursor; FETCH NEXT FROM dict_cursor INTO @dict_key, @dict_value_id; WHILE @@FETCH_STATUS = 0 BEGIN EXEC [dbo].[sp_build_hierarchical_properties] @object_id, @structure_id, @object_scheme_id, @max_depth, NULL, @dict_value_id, @temp_json OUTPUT; INSERT INTO @dict_elements ([key], [element_json]) VALUES (@dict_key, @temp_json); FETCH NEXT FROM dict_cursor INTO @dict_key, @dict_value_id; END CLOSE dict_cursor; DEALLOCATE dict_cursor; -- Build JSON object SELECT @field_value = N'{' + ISNULL(STRING_AGG( N'"' + REPLACE(REPLACE([key], N'\', N'\\'), N'"', N'\"') + N'":' + [element_json] , N','), N'') + N'}' FROM @dict_elements; END ELSE IF @type_semantic = '_RObject' -- Dictionary of Object references BEGIN DELETE FROM @dict_obj; DECLARE dict_obj_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT v.[_array_index], v.[_Object] FROM #all_values v WHERE v.[_id_object] = @object_id AND v.[_id_structure] = @structure_id AND v.[_array_index] IS NOT NULL AND v.[_Object] IS NOT NULL AND (@base_array_value_id IS NULL OR v.[_array_parent_id] = @base_array_value_id); OPEN dict_obj_cursor; FETCH NEXT FROM dict_obj_cursor INTO @dict_obj_key, @dict_obj_id; WHILE @@FETCH_STATUS = 0 BEGIN SET @next_depth = @max_depth - 1; EXEC [dbo].[sp_get_object_json_internal] @dict_obj_id, @next_depth, @temp_json OUTPUT; INSERT INTO @dict_obj ([key], [obj_json]) VALUES (@dict_obj_key, @temp_json); FETCH NEXT FROM dict_obj_cursor INTO @dict_obj_key, @dict_obj_id; END CLOSE dict_obj_cursor; DEALLOCATE dict_obj_cursor; SELECT @field_value = N'{' + ISNULL(STRING_AGG( N'"' + REPLACE(REPLACE([key], N'\', N'\\'), N'"', N'\"') + N'":' + [obj_json] , N','), N'') + N'}' FROM @dict_obj; END ELSE -- Dictionary of primitives BEGIN SELECT @field_value = N'{' + ISNULL(STRING_AGG( N'"' + REPLACE(REPLACE(v.[_array_index], N'\', N'\\'), N'"', N'\"') + N'":' + CASE WHEN @db_type = 'String' THEN CASE WHEN v.[_String] IS NULL THEN N'null' ELSE N'"' + REPLACE(REPLACE(v.[_String], N'\', N'\\'), N'"', N'\"') + N'"' END WHEN @db_type = 'Long' THEN CASE WHEN v.[_Long] IS NULL THEN N'null' ELSE CAST(v.[_Long] AS NVARCHAR(30)) END WHEN @db_type = 'Guid' THEN CASE WHEN v.[_Guid] IS NULL THEN N'null' ELSE N'"' + CAST(v.[_Guid] AS NVARCHAR(50)) + N'"' END WHEN @db_type = 'Double' THEN CASE WHEN v.[_Double] IS NULL THEN N'null' ELSE FORMAT(v.[_Double], 'G', 'en-US') END WHEN @db_type = 'Numeric' THEN CASE WHEN v.[_Numeric] IS NULL THEN N'null' ELSE REPLACE(CAST(v.[_Numeric] AS NVARCHAR(50)), N',', N'.') END WHEN @db_type = 'DateTimeOffset' THEN CASE WHEN v.[_DateTimeOffset] IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), v.[_DateTimeOffset], 127) + N'"' END WHEN @db_type = 'Boolean' THEN CASE WHEN v.[_Boolean] IS NULL THEN N'null' WHEN v.[_Boolean] = 1 THEN N'true' ELSE N'false' END ELSE N'null' END , N','), N'') + N'}' FROM #all_values v WHERE v.[_id_object] = @object_id AND v.[_id_structure] = @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 END -- ===================================================== -- OBJECT REFERENCE (_RObject) -- ===================================================== ELSE IF @type_name = 'Object' AND @type_semantic = '_RObject' BEGIN IF @current_Object IS NOT NULL BEGIN SET @next_depth = @max_depth - 1; EXEC [dbo].[sp_get_object_json_internal] @current_Object, @next_depth, @field_value OUTPUT; END END -- ===================================================== -- CLASS FIELD (hierarchical) -- ===================================================== ELSE IF @type_semantic = 'Object' BEGIN IF @current_Guid IS NOT NULL BEGIN EXEC [dbo].[sp_build_hierarchical_properties] @object_id, @structure_id, @object_scheme_id, @max_depth, NULL, @current_value_id, @field_value OUTPUT; END END -- ===================================================== -- PRIMITIVE TYPES -- ===================================================== ELSE IF @current_value_id IS NOT NULL BEGIN SET @field_value = CASE WHEN @db_type = 'String' THEN CASE WHEN @current_String IS NULL THEN NULL ELSE N'"' + REPLACE(REPLACE(@current_String, N'\', N'\\'), N'"', N'\"') + N'"' END WHEN @db_type = 'Long' THEN CASE WHEN @current_ListItem IS NOT NULL THEN dbo.build_listitem_json(@current_ListItem) WHEN @current_Long IS NULL THEN NULL ELSE CAST(@current_Long AS NVARCHAR(30)) END WHEN @db_type = 'Guid' THEN CASE WHEN @current_Guid IS NULL THEN NULL ELSE N'"' + CAST(@current_Guid AS NVARCHAR(50)) + N'"' END WHEN @db_type = 'Double' THEN CASE WHEN @current_Double IS NULL THEN NULL ELSE FORMAT(@current_Double, 'G', 'en-US') END WHEN @db_type = 'Numeric' THEN CASE WHEN @current_Numeric IS NULL THEN NULL ELSE REPLACE(CAST(@current_Numeric AS NVARCHAR(50)), N',', N'.') END WHEN @db_type = 'DateTimeOffset' THEN CASE WHEN @current_DateTimeOffset IS NULL THEN NULL ELSE N'"' + CONVERT(NVARCHAR(50), @current_DateTimeOffset, 127) + N'"' END WHEN @db_type = 'Boolean' THEN CASE WHEN @current_Boolean IS NULL THEN NULL WHEN @current_Boolean = 1 THEN N'true' ELSE N'false' END WHEN @db_type = 'ListItem' THEN dbo.build_listitem_json(@current_ListItem) WHEN @db_type = 'ByteArray' THEN CASE WHEN @current_ByteArray IS NULL THEN NULL ELSE N'"' + CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@current_ByteArray"))', 'NVARCHAR(MAX)') + N'"' END ELSE NULL END; END -- Add to results if not null IF @field_value IS NOT NULL BEGIN INSERT INTO @field_results ([field_name], [field_order], [field_value]) VALUES (@field_name, @field_order, @field_value); END FETCH NEXT FROM structure_cursor INTO @structure_id, @field_name, @field_order, @collection_type, @is_array, @is_dictionary, @type_name, @db_type, @type_semantic; END CLOSE structure_cursor; DEALLOCATE structure_cursor; -- Build final JSON object SELECT @result = N'{' + ISNULL(STRING_AGG( N'"' + REPLACE(REPLACE([field_name], N'\', N'\\'), N'"', N'\"') + N'":' + [field_value] , N',') WITHIN GROUP (ORDER BY [field_order], [field_name]), N'') + N'}' FROM @field_results; IF @result IS NULL OR @result = N'' SET @result = N'{}'; END GO -- ===================================================== -- MAIN: Get object as JSON (with OUTPUT for recursive calls) -- ===================================================== CREATE PROCEDURE [dbo].[sp_get_object_json_internal] @object_id BIGINT, @max_depth INT = 10, @result NVARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; DECLARE @object_scheme_id BIGINT; DECLARE @base_json NVARCHAR(MAX); DECLARE @properties_json NVARCHAR(MAX); DECLARE @is_root_call BIT = 0; -- Check if object exists - return NULL if not found (consistent with PostgreSQL). -- Soft-deleted objects (_id_scheme = -10, @@__deleted) are treated as -- non-existent: a nested _Object reference to a trashed object resolves -- to NULL instead of materializing the tombstone. The pointer in _values -- stays intact, so the soft-delete remains reversible. IF NOT EXISTS(SELECT 1 FROM [dbo].[_objects] WHERE [_id] = @object_id AND [_id_scheme] <> -10) BEGIN SET @result = NULL; RETURN; END -- Check if this is root call (need to create temp table) IF OBJECT_ID('tempdb..#all_values') IS NULL BEGIN SET @is_root_call = 1; -- Create temp table for all values CREATE TABLE #all_values ( [_id] BIGINT, [_id_structure] BIGINT, [_id_object] BIGINT, [_String] NVARCHAR(MAX), [_Long] BIGINT, [_Guid] UNIQUEIDENTIFIER, [_Double] FLOAT, [_DateTimeOffset] DATETIMEOFFSET, [_Boolean] BIT, [_ByteArray] VARBINARY(MAX), [_Numeric] DECIMAL(38,18), [_ListItem] BIGINT, [_Object] BIGINT, [_array_parent_id] BIGINT, [_array_index] NVARCHAR(430) ); END -- Load values for this object (always, for both root and recursive calls) -- Check if values for this object are already loaded IF NOT EXISTS(SELECT 1 FROM #all_values WHERE [_id_object] = @object_id) BEGIN INSERT INTO #all_values SELECT [_id], [_id_structure], [_id_object], [_String], [_Long], [_Guid], [_Double], [_DateTimeOffset], [_Boolean], [_ByteArray], [_Numeric], [_ListItem], [_Object], [_array_parent_id], [_array_index] FROM [dbo].[_values] WHERE [_id_object] = @object_id; END -- Get scheme_id SELECT @object_scheme_id = [_id_scheme] FROM [dbo].[_objects] WHERE [_id] = @object_id; -- Build base object JSON SELECT @base_json = N'{' + N'"id":' + CAST(o.[_id] AS NVARCHAR(20)) + N',"name":' + CASE WHEN o.[_name] IS NULL THEN N'null' ELSE N'"' + REPLACE(REPLACE(o.[_name], N'\', N'\\'), N'"', N'\"') + N'"' END + N',"scheme_id":' + CAST(o.[_id_scheme] AS NVARCHAR(20)) + N',"scheme_name":"' + REPLACE(REPLACE(s.[_name], N'\', N'\\'), N'"', N'\"') + N'"' + N',"parent_id":' + CASE WHEN o.[_id_parent] IS NULL THEN N'null' ELSE CAST(o.[_id_parent] AS NVARCHAR(20)) END + N',"owner_id":' + CAST(o.[_id_owner] AS NVARCHAR(20)) + N',"who_change_id":' + CAST(o.[_id_who_change] AS NVARCHAR(20)) + N',"date_create":"' + CONVERT(NVARCHAR(50), o.[_date_create], 127) + N'"' + N',"date_modify":"' + CONVERT(NVARCHAR(50), o.[_date_modify], 127) + N'"' + N',"date_begin":' + CASE WHEN o.[_date_begin] IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), o.[_date_begin], 127) + N'"' END + N',"date_complete":' + CASE WHEN o.[_date_complete] IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), o.[_date_complete], 127) + N'"' END + N',"key":' + CASE WHEN o.[_key] IS NULL THEN N'null' ELSE CAST(o.[_key] AS NVARCHAR(20)) END + N',"value_long":' + CASE WHEN o.[_value_long] IS NULL THEN N'null' ELSE CAST(o.[_value_long] AS NVARCHAR(20)) END + N',"value_string":' + CASE WHEN o.[_value_string] IS NULL THEN N'null' ELSE N'"' + REPLACE(REPLACE(o.[_value_string], N'\', N'\\'), N'"', N'\"') + N'"' END + N',"value_guid":' + CASE WHEN o.[_value_guid] IS NULL THEN N'null' ELSE N'"' + CAST(o.[_value_guid] AS NVARCHAR(50)) + N'"' END + N',"note":' + CASE WHEN o.[_note] IS NULL THEN N'null' ELSE N'"' + REPLACE(REPLACE(o.[_note], N'\', N'\\'), N'"', N'\"') + N'"' END + N',"value_bool":' + CASE WHEN o.[_value_bool] IS NULL THEN N'null' WHEN o.[_value_bool] = 1 THEN N'true' ELSE N'false' END + N',"value_double":' + CASE WHEN o.[_value_double] IS NULL THEN N'null' ELSE FORMAT(o.[_value_double], 'G', 'en-US') END + N',"value_numeric":' + CASE WHEN o.[_value_numeric] IS NULL THEN N'null' ELSE REPLACE(CAST(o.[_value_numeric] AS NVARCHAR(50)), N',', N'.') END + N',"value_datetime":' + CASE WHEN o.[_value_datetime] IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), o.[_value_datetime], 127) + N'"' END + N',"value_bytes":' + CASE WHEN o.[_value_bytes] IS NULL THEN N'null' ELSE N'"' + CAST(N'' AS XML).value('xs:base64Binary(sql:column("o.[_value_bytes]"))', 'NVARCHAR(MAX)') + N'"' END + N',"hash":' + CASE WHEN o.[_hash] IS NULL THEN N'null' ELSE N'"' + CAST(o.[_hash] AS NVARCHAR(50)) + N'"' END FROM [dbo].[_objects] o INNER JOIN [dbo].[_schemes] s ON s.[_id] = o.[_id_scheme] WHERE o.[_id] = @object_id; -- Check max_depth IF @max_depth <= 0 BEGIN SET @result = @base_json + N'}'; IF @is_root_call = 1 DROP TABLE #all_values; RETURN; END -- No _values at all = properties is null (not fake empty {}) IF NOT EXISTS(SELECT 1 FROM #all_values WHERE [_id_object] = @object_id) BEGIN SET @result = @base_json + N',"properties":null}'; IF @is_root_call = 1 DROP TABLE #all_values; RETURN; END -- Build properties EXEC [dbo].[sp_build_hierarchical_properties] @object_id, NULL, @object_scheme_id, @max_depth, NULL, NULL, @properties_json OUTPUT; -- Combine base + properties SET @result = @base_json + N',"properties":' + ISNULL(@properties_json, N'{}') + N'}'; -- Cleanup temp table if this was root call IF @is_root_call = 1 DROP TABLE #all_values; END GO -- ===================================================== -- PUBLIC WRAPPER: Get object as JSON with SELECT result -- More efficient for C# - just ExecuteScalarAsync -- ===================================================== CREATE PROCEDURE [dbo].[sp_get_object_json] @object_id BIGINT, @max_depth INT = 10 AS BEGIN SET NOCOUNT ON; DECLARE @result NVARCHAR(MAX); EXEC [dbo].[sp_get_object_json_internal] @object_id, @max_depth, @result OUTPUT; SELECT @result AS json_result; END GO -- ===================================================== -- USAGE EXAMPLES -- ===================================================== -- -- Get object as JSON (simple - SELECT result): -- EXEC get_object_json @object_id = 123; -- EXEC get_object_json @object_id = 123, @max_depth = 2; -- -- For recursive calls (internal use with OUTPUT): -- DECLARE @json NVARCHAR(MAX); -- EXEC sp_get_object_json_internal @object_id = 123, @result = @json OUTPUT; -- ===================================================== PRINT '=========================================' PRINT 'JSON object functions created!' PRINT '=========================================' GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/00_module_init.sql ---- -- ===================================================================== -- v2-pvt module init (MSSql) -- ===================================================================== -- Purpose: PVT-based search engine for REDB free (SQL Server). -- Owner : redb core team. Mirrors redb.Postgres/sql/v2-pvt/. -- Version: see dbo.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; dbo.get_object_json is module-owned, 09_core_object_json.sql). -- 2. Drops every function this module owns so the module can be -- redeployed cleanly -- dbo.pvt_module_version included, which is why -- the version is recreated LAST, in 99_module_version.sql. -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO -- ---------- 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). -- An error does not stop the later batches of SSMS or sqlcmd, so the guard also sets NOEXEC ON: the -- rest of the script is compiled, not run. DECLARE @own nvarchar(50) = N'0.2.50', @deployed nvarchar(50), @compat nvarchar(50), @package nvarchar(50), @newer bit = 0, @msg nvarchar(1000); IF OBJECT_ID(N'dbo.pvt_module_version', N'FN') IS NOT NULL BEGIN EXEC sp_executesql N'SELECT @v = dbo.pvt_module_version()', N'@v nvarchar(50) OUTPUT', @v = @deployed OUTPUT; -- Each version as a sortable key: up to four numeric parts, each padded to 20 digits; a missing part -- sorts below any present one, as System.Version compares them. WITH v AS ( SELECT which, core, LEN(core) - LEN(REPLACE(core, N'.', N'')) + 1 AS n FROM (VALUES (N'own', @own), (N'deployed', LEFT(ISNULL(@deployed, N''), CHARINDEX(N'-', ISNULL(@deployed, N'') + N'-') - 1))) x(which, core) ), k AS ( SELECT which, CASE WHEN core = N'' OR core LIKE N'%[^0-9.]%' OR core LIKE N'.%' OR core LIKE N'%.' OR core LIKE N'%..%' OR n NOT BETWEEN 2 AND 4 THEN NULL ELSE RIGHT(REPLICATE(N'0', 20) + PARSENAME(core, n), 20) + RIGHT(REPLICATE(N'0', 20) + PARSENAME(core, n - 1), 20) + CASE WHEN n >= 3 THEN RIGHT(REPLICATE(N'0', 20) + PARSENAME(core, n - 2), 20) ELSE N'' END + CASE WHEN n = 4 THEN RIGHT(REPLICATE(N'0', 20) + PARSENAME(core, 1), 20) ELSE N'' END END AS k FROM v ) SELECT @newer = CASE WHEN d.k COLLATE Latin1_General_BIN2 > o.k COLLATE Latin1_General_BIN2 THEN 1 ELSE 0 END FROM k d JOIN k o ON d.which = N'deployed' AND o.which = N'own'; END IF @newer = 1 BEGIN IF OBJECT_ID(N'dbo.pvt_module_compat', N'FN') IS NOT NULL EXEC sp_executesql N'SELECT @c = dbo.pvt_module_compat()', N'@c nvarchar(50) OUTPUT', @c = @compat OUTPUT; IF CHARINDEX(N'|', ISNULL(@compat, N'')) > 0 SET @package = NULLIF(SUBSTRING(@compat, CHARINDEX(N'|', @compat) + 1, 50), N''); SET @msg = N'The MSSql database carries the redb module ' + @deployed + N', newer than ' + @own + N' of this package, and ' + CASE WHEN @package IS NULL THEN N'it does not state which packages it serves' ELSE N'it needs redb packages from ' + @package + N' on' END + N'. Upgrade the redb packages of this application; the database was left unchanged.'; RAISERROR(N'%s', 16, 1, @msg); SET NOEXEC ON; END GO -- ---------- 0. Schema upgrades (idempotent, run on every redeploy) ---------- -- DDL for columns added after a database was created. The base DDL in -- redbMSSQL.sql stays the source of truth for fresh databases; this block is -- the delivery to existing ones (SCHEMA_DELIVERY plan, V4). GO after the -- ALTERs is mandatory: a later statement naming a new column will not -- compile in the same batch. -- V4 (UNIQUE stage 2): [RedbUnique] key metadata and the key hash column. IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._structures') AND name = N'_unique') ALTER TABLE [dbo].[_structures] ADD [_unique] BIT NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._structures') AND name = N'_unique_version') ALTER TABLE [dbo].[_structures] ADD [_unique_version] BIGINT NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'_unique') ALTER TABLE [dbo].[_values] ADD [_unique] UNIQUEIDENTIFIER NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._scheme_metadata_cache') AND name = N'_unique') ALTER TABLE [dbo].[_scheme_metadata_cache] ADD [_unique] BIT NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._scheme_metadata_cache') AND name = N'_unique_version') ALTER TABLE [dbo].[_scheme_metadata_cache] ADD [_unique_version] BIGINT NULL; -- V4 (LAZY Л2): the lazy-reference marker, read from `virtual` at synchronisation. IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._structures') AND name = N'_lazy') ALTER TABLE [dbo].[_structures] ADD [_lazy] BIT NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._scheme_metadata_cache') AND name = N'_lazy') ALTER TABLE [dbo].[_scheme_metadata_cache] ADD [_lazy] BIT NULL; -- S3 (0.2.13): element-key scope of collection keys, and the free-form _tags marker on -- schemes, structures and the metadata cache (future / custom extensions; sync never wipes it). IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._structures') AND name = N'_unique_scope') ALTER TABLE [dbo].[_structures] ADD [_unique_scope] BIGINT NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._structures') AND name = N'_tags') ALTER TABLE [dbo].[_structures] ADD [_tags] NVARCHAR(450) NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._schemes') AND name = N'_tags') ALTER TABLE [dbo].[_schemes] ADD [_tags] NVARCHAR(450) NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._scheme_metadata_cache') AND name = N'_unique_scope') ALTER TABLE [dbo].[_scheme_metadata_cache] ADD [_unique_scope] BIGINT NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._scheme_metadata_cache') AND name = N'_tags') ALTER TABLE [dbo].[_scheme_metadata_cache] ADD [_tags] NVARCHAR(450) NULL; GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._structures') AND name = N'IX__structures__tags') CREATE INDEX [IX__structures__tags] ON [dbo].[_structures]([_tags]) WHERE [_tags] IS NOT NULL; UPDATE c SET c.[_unique_scope] = s.[_unique_scope], c.[_tags] = s.[_tags] FROM [dbo].[_scheme_metadata_cache] c JOIN [dbo].[_structures] s ON s.[_id] = c.[_structure_id] WHERE ISNULL(c.[_unique_scope], -1) <> ISNULL(s.[_unique_scope], -1) OR ISNULL(c.[_tags], N'') <> ISNULL(s.[_tags], N''); -- 0.2.46: 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. IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._structures') AND name = N'_renamed_from') ALTER TABLE [dbo].[_structures] ADD [_renamed_from] NVARCHAR(MAX) NULL; IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._schemes') AND name = N'_renamed_from') ALTER TABLE [dbo].[_schemes] ADD [_renamed_from] NVARCHAR(MAX) NULL; -- 0.2.49: 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. IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._schemes') AND name = N'_version') ALTER TABLE [dbo].[_schemes] ADD [_version] INT NULL; -- V4 (UNIQUE stage 1): the object key column. IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._objects') AND name = N'_value_unique') ALTER TABLE [dbo].[_objects] ADD [_value_unique] NVARCHAR(440) NULL; GO -- V4 (LAZY L2): repair caches synced between the column upgrade and the marker write. -- Below the GO on purpose: inside the ALTER batch the new column does not compile. UPDATE c SET c.[_lazy] = s.[_lazy] FROM [dbo].[_scheme_metadata_cache] c JOIN [dbo].[_structures] s ON s.[_id] = c.[_structure_id] WHERE ISNULL(c.[_lazy], 0) <> ISNULL(s.[_lazy], 0); GO -- S2 (subtree-unique plan, 0.2.12): 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. IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'UIX__values__structure_unique' AND filter_definition LIKE N'%[_]array[_]parent[_]id%') DROP INDEX [UIX__values__structure_unique] ON [dbo].[_values]; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'UIX__values__structure_unique') CREATE UNIQUE INDEX [UIX__values__structure_unique] ON [dbo].[_values]([_id_structure], [_unique]) INCLUDE ([_id_object]) WHERE [_unique] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._objects') AND name = N'UIX__objects__scheme_unique') CREATE UNIQUE INDEX [UIX__objects__scheme_unique] ON [dbo].[_objects]([_id_scheme], [_value_unique]) INCLUDE ([_id]) WHERE [_value_unique] IS NOT NULL; GO -- 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 scans the whole -- table for the FK check. Filtered form keeps them nearly empty. NOTE: filtered indexes -- require QUOTED_IDENTIFIER ON in the creating session (ADO.NET default; sqlcmd needs -I). IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__ListItem_not_null') CREATE INDEX [IX__values__ListItem_not_null] ON [dbo].[_values]([_ListItem]) WHERE [_ListItem] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Object_not_null') CREATE INDEX [IX__values__Object_not_null] ON [dbo].[_values]([_Object]) WHERE [_Object] IS NOT NULL; GO -- Index cleanup (0.2.29, 2026-10-14): indexes another index of the same table fully replaces, the -- same set PostgreSQL dropped in its module 0.7.13. They were removed from redbMSSQL.sql, but that -- file only runs 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 filter and carries the values in INCLUDE. -- ix__objects_parent_scheme - same key and filter as IX__objects__parent_id_descendant_lookup. -- IX__structures__not_collection - a prefix of IX__structures__not_collection_enhanced, same filter. -- the rest - a single column that is the leading column of a UNIQUE constraint. -- DROP INDEX takes a short exclusive lock on its table. -- IF QUERIES GOT SLOWER AFTER THIS UPGRADE, the statements that bring them back are below. This -- block drops them again whenever the module version changes, so report the case. -- CREATE INDEX [IX__values__object_structure_array_index] ON [dbo].[_values]([_id_object], [_id_structure], [_array_index]) WHERE [_array_index] IS NOT NULL; -- CREATE INDEX [ix__objects_parent_scheme] ON [dbo].[_objects]([_id_parent], [_id_scheme]) WHERE [_id_parent] IS NOT NULL; -- CREATE INDEX [IX__structures__not_collection] ON [dbo].[_structures]([_id], [_name], [_id_scheme]) WHERE [_collection_type] IS NULL; -- CREATE INDEX [IX__functions__schemes] ON [dbo].[_functions]([_id_scheme]); -- CREATE INDEX [IX__permissions__roles] ON [dbo].[_permissions]([_id_role]); -- CREATE INDEX [IX__dependencies__schemes_1] ON [dbo].[_dependencies]([_id_scheme_1]); -- CREATE INDEX [IX__users_roles__roles] ON [dbo].[_users_roles]([_id_role]); -- IX__values__structure_object_lookup is NOT dropped here, unlike PostgreSQL: the streams form reads -- string fields through it. IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__object_structure_array_index') DROP INDEX [IX__values__object_structure_array_index] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._objects') AND name = N'ix__objects_parent_scheme') DROP INDEX [ix__objects_parent_scheme] ON [dbo].[_objects]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._structures') AND name = N'IX__structures__not_collection') DROP INDEX [IX__structures__not_collection] ON [dbo].[_structures]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._functions') AND name = N'IX__functions__schemes') DROP INDEX [IX__functions__schemes] ON [dbo].[_functions]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._permissions') AND name = N'IX__permissions__roles') DROP INDEX [IX__permissions__roles] ON [dbo].[_permissions]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._dependencies') AND name = N'IX__dependencies__schemes_1') DROP INDEX [IX__dependencies__schemes_1] ON [dbo].[_dependencies]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._users_roles') AND name = N'IX__users_roles__roles') DROP INDEX [IX__users_roles__roles] ON [dbo].[_users_roles]; GO -- 0.2.50: 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, the check of FK__values__array_parent and the -- cascade trigger TR__values__cascade_array_parent. It is dropped only where such a wider index remains: a database -- created by an old version may lack array_parent_index, and the trigger and the key check must keep an index. The -- other index must be enabled, not filtered, and have _array_parent_id as its first key column. To put it back: -- CREATE INDEX [IX__values__array_parent_id] ON [dbo].[_values]([_array_parent_id]) WITH (ONLINE = ON); -- ONLINE where the edition has it IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__array_parent_id') AND EXISTS ( SELECT 1 FROM sys.indexes i JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.key_ordinal = 1 JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE i.object_id = OBJECT_ID(N'dbo._values') AND i.name <> N'IX__values__array_parent_id' AND i.is_disabled = 0 AND i.is_hypothetical = 0 AND i.has_filter = 0 AND i.type IN (1, 2) AND c.name = N'_array_parent_id') DROP INDEX [IX__values__array_parent_id] ON [dbo].[_values]; GO -- Value-leading indexes (0.2.30, 2026-10-16), the set PostgreSQL got in 0.7.16: a filter on a field finds its -- objects by value. They replace eleven object-leading forms (_id_structure, _id_object, ), three of them -- duplicates of three others. The string has none: NVARCHAR(MAX) cannot be a key. Built before the old ones are -- dropped. Without ONLINE = ON (Enterprise only) writes to _values wait while they are built. -- An index of one of these names whose definition differs in anything (key columns or their order, INCLUDE, filter, -- uniqueness, disabled) is dropped and built again: IF NOT EXISTS alone would keep it. A research build left such -- indexes with _array_index in the filter, which a query that does not state _array_index IS NULL cannot use. -- IF QUERIES GOT SLOWER AFTER THIS UPGRADE, these bring the old ones back; this block drops them again on the next -- version change, so report the case: -- CREATE INDEX [IX__values__Long_not_null] ON [dbo].[_values]([_id_structure], [_id_object], [_Long]) WHERE [_Long] IS NOT NULL; -- CREATE INDEX [IX__values__DateTimeOffset_not_null] ON [dbo].[_values]([_id_structure], [_id_object], [_DateTimeOffset]) WHERE [_DateTimeOffset] IS NOT NULL; -- CREATE INDEX [IX__values__Numeric_not_null] ON [dbo].[_values]([_id_structure], [_id_object], [_Numeric]) WHERE [_Numeric] IS NOT NULL; -- CREATE INDEX [IX__values__Long_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Long]) WHERE [_Long] IS NOT NULL; -- CREATE INDEX [IX__values__Guid_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Guid]) WHERE [_Guid] IS NOT NULL; -- CREATE INDEX [IX__values__Double_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Double]) WHERE [_Double] IS NOT NULL; -- CREATE INDEX [IX__values__DateTimeOffset_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_DateTimeOffset]) WHERE [_DateTimeOffset] IS NOT NULL; -- CREATE INDEX [IX__values__Boolean_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Boolean]) WHERE [_Boolean] IS NOT NULL; -- CREATE INDEX [IX__values__Numeric_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Numeric]) WHERE [_Numeric] IS NOT NULL; -- CREATE INDEX [IX__values__ListItem_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_ListItem]) WHERE [_ListItem] IS NOT NULL; -- CREATE INDEX [IX__values__Object_filter] ON [dbo].[_values]([_id_structure], [_id_object], [_Object]) WHERE [_Object] IS NOT NULL; DECLARE @drop NVARCHAR(MAX); SELECT @drop = STRING_AGG(CAST(N'DROP INDEX ' + QUOTENAME(i.name) + N' ON [dbo].[_values];' AS NVARCHAR(MAX)), N' ') FROM (VALUES (N'IX__values__structure_long_object', N'_Long'), (N'IX__values__structure_numeric_object', N'_Numeric'), (N'IX__values__structure_double_object', N'_Double'), (N'IX__values__structure_datetimeoffset_object', N'_DateTimeOffset'), (N'IX__values__structure_boolean_object', N'_Boolean'), (N'IX__values__structure_guid_object', N'_Guid'), (N'IX__values__structure_listitem_object', N'_ListItem'), (N'IX__values__structure_object_object', N'_Object') ) x(name, col) JOIN sys.indexes i ON i.object_id = OBJECT_ID(N'dbo._values') AND i.name = x.name WHERE i.is_disabled = 1 OR i.is_unique = 1 OR i.type <> 2 OR ISNULL(i.filter_definition, N'') <> N'([' + x.col + N'] IS NOT NULL)' OR ISNULL((SELECT STRING_AGG(c.name + CASE WHEN ic.is_descending_key = 1 THEN N' DESC' ELSE N'' END, N',') WITHIN GROUP (ORDER BY ic.key_ordinal) FROM sys.index_columns ic JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0), N'') <> N'_id_structure,' + x.col + N',_id_object' OR ISNULL((SELECT STRING_AGG(c.name, N',') FROM sys.index_columns ic JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 1), N'') <> N'_array_index'; -- Only a role that may alter _values rebuilds an index. A role without the right (the DBA took owner rights back -- after the installation) may not see the whole definition of an index, takes a correct one for a wrong one, and -- its DROP fails with 1088 ("does not exist or you do not have permissions"), which is no privilege error to the -- caller: the start-up died with a driver error instead of RedbSchemaOutdatedException. Without the right the -- check is skipped, and the first DDL below reports the missing right as before. IF @drop IS NOT NULL AND HAS_PERMS_BY_NAME(N'dbo._values', N'OBJECT', N'ALTER') = 1 EXEC sp_executesql @drop; GO IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__structure_long_object') CREATE INDEX [IX__values__structure_long_object] ON [dbo].[_values]([_id_structure], [_Long], [_id_object]) INCLUDE ([_array_index]) WHERE [_Long] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__structure_numeric_object') CREATE INDEX [IX__values__structure_numeric_object] ON [dbo].[_values]([_id_structure], [_Numeric], [_id_object]) INCLUDE ([_array_index]) WHERE [_Numeric] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__structure_double_object') CREATE INDEX [IX__values__structure_double_object] ON [dbo].[_values]([_id_structure], [_Double], [_id_object]) INCLUDE ([_array_index]) WHERE [_Double] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__structure_datetimeoffset_object') CREATE INDEX [IX__values__structure_datetimeoffset_object] ON [dbo].[_values]([_id_structure], [_DateTimeOffset], [_id_object]) INCLUDE ([_array_index]) WHERE [_DateTimeOffset] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__structure_boolean_object') CREATE INDEX [IX__values__structure_boolean_object] ON [dbo].[_values]([_id_structure], [_Boolean], [_id_object]) INCLUDE ([_array_index]) WHERE [_Boolean] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__structure_guid_object') CREATE INDEX [IX__values__structure_guid_object] ON [dbo].[_values]([_id_structure], [_Guid], [_id_object]) INCLUDE ([_array_index]) WHERE [_Guid] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__structure_listitem_object') CREATE INDEX [IX__values__structure_listitem_object] ON [dbo].[_values]([_id_structure], [_ListItem], [_id_object]) INCLUDE ([_array_index]) WHERE [_ListItem] IS NOT NULL; IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__structure_object_object') CREATE INDEX [IX__values__structure_object_object] ON [dbo].[_values]([_id_structure], [_Object], [_id_object]) INCLUDE ([_array_index]) WHERE [_Object] IS NOT NULL; GO IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Long_not_null') DROP INDEX [IX__values__Long_not_null] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__DateTimeOffset_not_null') DROP INDEX [IX__values__DateTimeOffset_not_null] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Numeric_not_null') DROP INDEX [IX__values__Numeric_not_null] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Long_filter') DROP INDEX [IX__values__Long_filter] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Guid_filter') DROP INDEX [IX__values__Guid_filter] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Double_filter') DROP INDEX [IX__values__Double_filter] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__DateTimeOffset_filter') DROP INDEX [IX__values__DateTimeOffset_filter] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Boolean_filter') DROP INDEX [IX__values__Boolean_filter] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Numeric_filter') DROP INDEX [IX__values__Numeric_filter] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__ListItem_filter') DROP INDEX [IX__values__ListItem_filter] ON [dbo].[_values]; IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._values') AND name = N'IX__values__Object_filter') DROP INDEX [IX__values__Object_filter] ON [dbo].[_values]; GO -- ---------- 1. System infrastructure check ------------------------------ -- NOTE: dbo.get_object_json (and its helpers) is now OWNED by this module -- (defined in 09_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. IF OBJECT_ID(N'dbo._objects', N'U') IS NULL THROW 50000, N'v2-pvt: required table dbo._objects is missing.', 1; IF OBJECT_ID(N'dbo._values', N'U') IS NULL THROW 50000, N'v2-pvt: required table dbo._values is missing.', 1; IF OBJECT_ID(N'dbo._structures', N'U') IS NULL THROW 50000, N'v2-pvt: required table dbo._structures is missing.', 1; IF OBJECT_ID(N'dbo._list_items', N'U') IS NULL THROW 50000, N'v2-pvt: required table dbo._list_items is missing.', 1; IF OBJECT_ID(N'dbo._scheme_metadata_cache', N'U') IS NULL THROW 50000, N'v2-pvt: required cache table dbo._scheme_metadata_cache is missing. Deploy redb_metadata_cache.sql first.', 1; GO -- ---------- 2. DROP every pvt_* object this module owns ----------------- -- Universal drop: enumerate all functions / procedures / types in the dbo -- schema whose name starts with `pvt_` and drop them. Protects the module -- against signature drift between releases. DECLARE @drop_sql nvarchar(max) = N''; -- Scalar / inline / table-valued functions and procedures. SELECT @drop_sql = @drop_sql + N'DROP ' + CASE o.[type] WHEN 'P' THEN N'PROCEDURE ' WHEN 'FN' THEN N'FUNCTION ' WHEN 'IF' THEN N'FUNCTION ' WHEN 'TF' THEN N'FUNCTION ' END + QUOTENAME(SCHEMA_NAME(o.[schema_id])) + N'.' + QUOTENAME(o.name) + N';' + CHAR(13) + CHAR(10) FROM sys.objects o WHERE o.[type] IN ('P','FN','IF','TF') AND SCHEMA_NAME(o.[schema_id]) = N'dbo' AND o.name LIKE N'pvt[_]%'; -- User-defined types (TT = table type, others handled as needed). SELECT @drop_sql = @drop_sql + N'DROP TYPE ' + QUOTENAME(SCHEMA_NAME(t.[schema_id])) + N'.' + QUOTENAME(t.name) + N';' + CHAR(13) + CHAR(10) FROM sys.types t WHERE t.is_user_defined = 1 AND SCHEMA_NAME(t.[schema_id]) = N'dbo' AND t.name LIKE N'pvt[_]%'; IF LEN(@drop_sql) > 0 EXEC sp_executesql @drop_sql; GO -- ===================================================== -- V4 (owner decision 2026-09-02): _objects._value_string is an identifier column - NVARCHAR(450), -- the index-key width _name already uses; long text belongs in _note or in a Props field. -- NVARCHAR(MAX) cannot be an index key at all (Msg 1919), so every filter on the column scanned. -- A database holding longer values is REFUSED, loudly: silent truncation is not an option. -- ===================================================== IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo._objects') AND name = N'_value_string' AND max_length = -1) BEGIN IF EXISTS (SELECT 1 FROM [dbo].[_objects] WHERE LEN([_value_string]) > 450) RAISERROR('redb upgrade: _objects._value_string is being narrowed to NVARCHAR(450) - it is an identifier column, long text belongs in _note or in a Props field. This database holds longer values; move them first (offenders: SELECT _id, LEN(_value_string) FROM _objects WHERE LEN(_value_string) > 450), then start again. Nothing was changed.', 16, 1); ELSE ALTER TABLE [dbo].[_objects] ALTER COLUMN [_value_string] NVARCHAR(450) NULL; END GO IF COL_LENGTH('dbo._objects', '_value_string') = 900 AND NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'dbo._objects') AND name = N'IX__objects__value_string') CREATE INDEX [IX__objects__value_string] ON [dbo].[_objects]([_value_string]) WHERE [_value_string] IS NOT NULL GO -- ===================================================== -- Owner decision 2026-09-02: the full-text index on _values._String is dropped. It served no -- reader (redb translates every string predicate to LIKE, which never uses full-text) and cost a -- background reindex on every _values write (CHANGE_TRACKING AUTO). sys.fulltext_* exist whether -- or not Full-Text is installed, so the guards are safe everywhere. -- ===================================================== IF EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = OBJECT_ID(N'dbo._values')) DROP FULLTEXT INDEX ON [dbo].[_values] GO IF EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE name = 'redb_fulltext_catalog') DROP FULLTEXT CATALOG [redb_fulltext_catalog] GO -- 0.2.48: 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). After the drops above, -- so a role without schema rights stops at them, as before, and not at these rows. UPDATE [dbo].[_types] SET [_db_type] = N'Long' WHERE [_id] IN (-9223372036854775685, -9223372036854775684) AND [_db_type] <> N'Long'; UPDATE [dbo].[_scheme_metadata_cache] SET [db_type] = N'Long' WHERE [_type_id] IN (-9223372036854775685, -9223372036854775684) AND [db_type] <> N'Long'; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/01_pvt_field_path.sql ---- -- ===================================================================== -- 01_pvt_field_path.sql (MSSql) -- --------------------------------------------------------------------- -- Field-path normalization & parsing primitives. Direct port of -- redb.Postgres/sql/v2-pvt/01_pvt_field_path.sql to T-SQL. -- -- All functions are scalar UDFs returning NVARCHAR(MAX); structured -- results (table-style in PG) are encoded as JSON strings and consumed -- via OPENJSON/JSON_VALUE on the caller side. -- -- Functions: -- dbo.pvt_normalize_base_field_name(@field NVARCHAR(200)) -- -> NVARCHAR(64) | NULL -- dbo.pvt_parse_field_path(@field_path NVARCHAR(400)) -- -> NVARCHAR(MAX) JSON with { root_field, nested_field, is_array, -- is_nested, dict_key } -- dbo.pvt_normalize_field_name(@path NVARCHAR(400), @op_value NVARCHAR(400)) -- -> NVARCHAR(400) -- dbo.pvt_peek_contains_key_value(@op NVARCHAR(MAX)) -- -> NVARCHAR(400) | NULL -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_fail -------------------------------------------------------- -- The one way a builder of this module refuses input it cannot read (review SQ-5). T-SQL does not allow -- THROW or RAISERROR inside a function, so this raises a conversion error that carries the message: -- Conversion failed when converting the nvarchar value 'redb: ' to data type int. -- It stops the statement from any depth of nested calls, which a NULL or a '1=1' / '1=0' substitute -- never did: those let the query run with the condition dropped or every row cut. The PostgreSQL module -- raises in the same places. Use it in a statement branch or behind COALESCE / CASE, which evaluate it -- only when the branch is taken. CREATE OR ALTER FUNCTION dbo.pvt_fail(@message NVARCHAR(3000)) RETURNS NVARCHAR(MAX) AS BEGIN RETURN CAST(N'redb: ' + COALESCE(@message, N'(no message)') AS INT); END; GO -- ---------- pvt_json_string_or_null --------------------------------------- -- Tiny helper used by builders to serialize a NVARCHAR value as a JSON -- string with proper escaping, or the literal `null` if NULL. Required -- because T-SQL has no `quote_literal`-equivalent for JSON text. -- Defined first because subsequent builders reference it. CREATE FUNCTION dbo.pvt_json_string_or_null(@v NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN IF @v IS NULL RETURN N'null'; -- STRING_ESCAPE(.., 'json') is SQL Server 2016+. RETURN N'"' + STRING_ESCAPE(@v, N'json') + N'"'; END; GO -- ---------- pvt_json_text --------------------------------------------------- -- The text of a scalar member at the top level of a JSON object, of any length, as JSON_VALUE gives it; NULL when -- the member is missing, null, an object or an array. JSON_VALUE returns NULL in lax mode for a value over 4,000 characters, and a pushed condition -- (a SQL text built from a list of some hundreds of ids) or a long search constant read through it was dropped -- without an error: WhereRedb(ParentId in 400+ ids) with a props filter returned the whole scheme. OPENJSON gives -- the value as NVARCHAR(MAX). CREATE FUNCTION dbo.pvt_json_text(@json NVARCHAR(MAX), @key NVARCHAR(200)) RETURNS NVARCHAR(MAX) AS BEGIN IF @json IS NULL OR ISJSON(@json) = 0 RETURN NULL; RETURN (SELECT TOP (1) [value] FROM OPENJSON(@json) WHERE [key] = @key AND [type] IN (1, 2, 3)); END; GO -- ---------- pvt_normalize_base_field_name -------------------------------- -- Maps C# base field names to _objects columns. Returns NULL if the field -- is not a base column. Bare names (without `0$:` prefix and without `_` -- prefix) are NOT resolved to base columns to avoid colliding with -- legitimate user Props named "Name", "Id", etc. CREATE FUNCTION dbo.pvt_normalize_base_field_name(@field NVARCHAR(200)) RETURNS NVARCHAR(64) AS BEGIN DECLARE @had_prefix bit = 0; DECLARE @input NVARCHAR(200) = @field; DECLARE @result NVARCHAR(64) = NULL; IF @input LIKE N'0$:%' BEGIN SET @had_prefix = 1; SET @input = SUBSTRING(@input, 4, 200); END; SET @result = CASE @input WHEN N'id' THEN N'_id' WHEN N'Id' THEN N'_id' WHEN N'_id' THEN N'_id' WHEN N'parent_id' THEN N'_id_parent' WHEN N'ParentId' THEN N'_id_parent' WHEN N'id_parent' THEN N'_id_parent' WHEN N'_id_parent' THEN N'_id_parent' WHEN N'scheme_id' THEN N'_id_scheme' WHEN N'SchemeId' THEN N'_id_scheme' WHEN N'id_scheme' THEN N'_id_scheme' WHEN N'_id_scheme' THEN N'_id_scheme' WHEN N'owner_id' THEN N'_id_owner' WHEN N'OwnerId' THEN N'_id_owner' WHEN N'_id_owner' THEN N'_id_owner' WHEN N'who_change_id' THEN N'_id_who_change' WHEN N'WhoChangeId' THEN N'_id_who_change' WHEN N'_id_who_change' THEN N'_id_who_change' WHEN N'value_long' THEN N'_value_long' WHEN N'ValueLong' THEN N'_value_long' WHEN N'_value_long' THEN N'_value_long' WHEN N'value_string' THEN N'_value_string' WHEN N'ValueString' THEN N'_value_string' WHEN N'_value_string' THEN N'_value_string' WHEN N'value_unique' THEN N'_value_unique' WHEN N'ValueUnique' THEN N'_value_unique' WHEN N'_value_unique' THEN N'_value_unique' WHEN N'value_guid' THEN N'_value_guid' WHEN N'ValueGuid' THEN N'_value_guid' WHEN N'_value_guid' THEN N'_value_guid' WHEN N'key' THEN N'_key' WHEN N'Key' THEN N'_key' WHEN N'_key' THEN N'_key' WHEN N'name' THEN N'_name' WHEN N'Name' THEN N'_name' WHEN N'_name' THEN N'_name' WHEN N'note' THEN N'_note' WHEN N'Note' THEN N'_note' WHEN N'_note' THEN N'_note' WHEN N'value_bool' THEN N'_value_bool' WHEN N'ValueBool' THEN N'_value_bool' WHEN N'_value_bool' THEN N'_value_bool' WHEN N'value_double' THEN N'_value_double' WHEN N'ValueDouble' THEN N'_value_double' WHEN N'_value_double' THEN N'_value_double' WHEN N'value_numeric' THEN N'_value_numeric' WHEN N'ValueNumeric' THEN N'_value_numeric' WHEN N'_value_numeric' THEN N'_value_numeric' WHEN N'value_datetime' THEN N'_value_datetime' WHEN N'ValueDatetime' THEN N'_value_datetime' WHEN N'_value_datetime' THEN N'_value_datetime' WHEN N'value_bytes' THEN N'_value_bytes' WHEN N'ValueBytes' THEN N'_value_bytes' WHEN N'_value_bytes' THEN N'_value_bytes' WHEN N'hash' THEN N'_hash' WHEN N'Hash' THEN N'_hash' WHEN N'_hash' THEN N'_hash' WHEN N'date_create' THEN N'_date_create' WHEN N'DateCreate' THEN N'_date_create' WHEN N'_date_create' THEN N'_date_create' WHEN N'date_modify' THEN N'_date_modify' WHEN N'DateModify' THEN N'_date_modify' WHEN N'_date_modify' THEN N'_date_modify' WHEN N'date_begin' THEN N'_date_begin' WHEN N'DateBegin' THEN N'_date_begin' WHEN N'_date_begin' THEN N'_date_begin' WHEN N'date_complete' THEN N'_date_complete' WHEN N'DateComplete' THEN N'_date_complete' WHEN N'_date_complete' THEN N'_date_complete' ELSE NULL END; -- Disambiguation: bare names like `Name`, `Id`, `Key` collide with -- legitimate user-defined Props fields. Only honor the mapping if -- caller explicitly opted in via `0$:` or the input already starts -- with an underscore (system column convention). IF @result IS NOT NULL AND @had_prefix = 0 AND LEFT(@input, 1) <> N'_' RETURN NULL; RETURN @result; END; GO -- ---------- pvt_parse_field_path ----------------------------------------- -- Parses field path into JSON components. Replaces PG `RETURNS TABLE` -- with `RETURNS NVARCHAR(MAX)` JSON. Output keys mirror PG names so the -- caller can JSON_VALUE($.root_field) etc. -- -- Examples: -- 'Name' -> {"root_field":"Name","nested_field":null, -- "is_array":false,"is_nested":false, -- "dict_key":null} -- 'Contact.Name' -> {"root_field":"Contact","nested_field":"Name", -- "is_array":false,"is_nested":true, -- "dict_key":null} -- 'Tags[]' -> {"root_field":"Tags","nested_field":null, -- "is_array":true,"is_nested":false, -- "dict_key":null} -- 'Contacts[].Email' -> {"root_field":"Contacts", -- "nested_field":"Email","is_array":true, -- "is_nested":true,"dict_key":null} -- 'PhoneBook[home]' -> {"root_field":"PhoneBook","nested_field":null, -- "is_array":false,"is_nested":false, -- "dict_key":"home"} -- 'AddressBook[h].City' -> {"root_field":"AddressBook", -- "nested_field":"City","is_array":false, -- "is_nested":true,"dict_key":"h"} CREATE FUNCTION dbo.pvt_parse_field_path(@field_path NVARCHAR(400)) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @root_field NVARCHAR(200) = NULL; DECLARE @nested_field NVARCHAR(200) = NULL; DECLARE @is_array bit = 0; DECLARE @is_nested bit = 0; DECLARE @dict_key NVARCHAR(200) = NULL; DECLARE @bracket_pos int; DECLARE @key_end int; DECLARE @dot_after int; DECLARE @bracketed NVARCHAR(200); -- Detect plain array `[]` (no key inside) IF CHARINDEX(N'[]', @field_path) > 0 SET @is_array = 1; -- Detect Dictionary path: `Name[key]` or `Name[key].Child` (non-empty key). -- Plain `[]` array marker already handled above via @is_array. IF @is_array = 0 AND CHARINDEX(N'[', @field_path) > 0 BEGIN SET @bracket_pos = CHARINDEX(N'[', @field_path); SET @key_end = CHARINDEX(N']', @field_path); IF @bracket_pos > 0 AND @key_end > @bracket_pos + 1 BEGIN SET @root_field = SUBSTRING(@field_path, 1, @bracket_pos - 1); SET @dict_key = SUBSTRING(@field_path, @bracket_pos + 1, @key_end - @bracket_pos - 1); -- Look for `.` after `]` DECLARE @after_bracket NVARCHAR(400) = SUBSTRING(@field_path, @key_end + 1, 400); IF LEN(@after_bracket) > 0 AND LEFT(@after_bracket, 1) = N'.' BEGIN SET @nested_field = SUBSTRING(@after_bracket, 2, 400); SET @is_nested = 1; END; RETURN N'{"root_field":' + dbo.pvt_json_string_or_null(@root_field) + N',"nested_field":' + dbo.pvt_json_string_or_null(@nested_field) + N',"is_array":false,"is_nested":' + CASE WHEN @is_nested = 1 THEN N'true' ELSE N'false' END + N',"dict_key":' + dbo.pvt_json_string_or_null(@dict_key) + N'}'; END; END; -- Nested? (contains `.`) IF CHARINDEX(N'.', @field_path) > 0 SET @is_nested = 1; IF @is_nested = 1 BEGIN DECLARE @stripped NVARCHAR(400) = REPLACE(@field_path, N'[]', N''); DECLARE @dot int = CHARINDEX(N'.', @stripped); SET @root_field = SUBSTRING(@stripped, 1, @dot - 1); SET @nested_field = SUBSTRING(@stripped, @dot + 1, 400); END ELSE BEGIN IF @is_array = 1 SET @root_field = REPLACE(@field_path, N'[]', N''); ELSE SET @root_field = @field_path; END; RETURN N'{"root_field":' + dbo.pvt_json_string_or_null(@root_field) + N',"nested_field":' + dbo.pvt_json_string_or_null(@nested_field) + N',"is_array":' + CASE WHEN @is_array = 1 THEN N'true' ELSE N'false' END + N',"is_nested":' + CASE WHEN @is_nested = 1 THEN N'true' ELSE N'false' END + N',"dict_key":' + dbo.pvt_json_string_or_null(@dict_key) + N'}'; END; GO -- ---------- pvt_normalize_field_name -------------------------------------- -- If `.ContainsKey` is the field and an operand string is provided, -- rewrites to `[]` so dict-pivot path resolution kicks in. -- Mirrors Pro.ProSqlBuilderBase.NormalizeDictionaryFieldName. CREATE FUNCTION dbo.pvt_normalize_field_name( @path NVARCHAR(400), @op_value NVARCHAR(400) ) RETURNS NVARCHAR(400) AS BEGIN IF @path IS NULL RETURN NULL; IF RIGHT(@path, 12) <> N'.ContainsKey' RETURN @path; IF @op_value IS NULL OR @op_value = N'' RETURN @path; DECLARE @base NVARCHAR(400) = LEFT(@path, LEN(@path) - 12); RETURN @base + N'[' + @op_value + N']'; END; GO -- ---------- pvt_peek_contains_key_value ----------------------------------- -- 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 FUNCTION dbo.pvt_peek_contains_key_value(@op NVARCHAR(MAX)) RETURNS NVARCHAR(400) AS BEGIN IF @op IS NULL RETURN NULL; -- Object operand: { "$eq": "" } IF ISJSON(@op) = 1 BEGIN DECLARE @eq NVARCHAR(400) = JSON_VALUE(@op, N'$."$eq"'); IF @eq IS NOT NULL RETURN @eq; END; -- Bare key: the callers pass the value as OPENJSON returns it, and for a string that is the text -- itself, without quotes - so anything that is not JSON is the key. (Wrapping it as `[]` made -- invalid JSON for every string key, and {"Dict.ContainsKey":"home"} was never recognised.) IF ISJSON(@op) = 0 RETURN @op; RETURN NULL; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/02_pvt_type_info.sql ---- -- ===================================================================== -- 02_pvt_type_info.sql (MSSql) -- --------------------------------------------------------------------- -- ListItem type-info resolver. Mirrors PG v2-pvt/02_pvt_type_info.sql. -- Returns NVARCHAR(MAX) JSON with { db_type, type_semantic, is_array } -- or NULL if the ListItem accessor is not recognized. -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO CREATE FUNCTION dbo.pvt_get_listitem_field_type_info(@field_name NVARCHAR(100)) RETURNS NVARCHAR(MAX) AS BEGIN RETURN CASE @field_name WHEN N'Value' THEN N'{"db_type":"String","type_semantic":"String","is_array":false}' WHEN N'Alias' THEN N'{"db_type":"String","type_semantic":"String","is_array":false}' WHEN N'IdObject' THEN N'{"db_type":"Long","type_semantic":"Long","is_array":false}' WHEN N'IdList' THEN N'{"db_type":"Long","type_semantic":"Long","is_array":false}' WHEN N'Id' THEN N'{"db_type":"Long","type_semantic":"Long","is_array":false}' ELSE NULL END; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/03_pvt_structure_info.sql ---- -- ===================================================================== -- 03_pvt_structure_info.sql (MSSql) -- --------------------------------------------------------------------- -- Lookup structure metadata by field path. Mirrors PG -- v2-pvt/03_pvt_structure_info.sql. -- -- PG returns RETURNS TABLE; here we return NVARCHAR(MAX) JSON with: -- { root_structure_id, nested_structure_id, root_type_info, -- nested_type_info } -- root_structure_id / nested_structure_id may be null (JSON nulls). -- type_info objects share the shape from pvt_get_listitem_field_type_info: -- { type_name, db_type, type_semantic, is_array } -- -- Reads from _scheme_metadata_cache directly (faster than parsing the -- full get_scheme_definition JSON). MSSql free reuses the same cache -- table as Pro. -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO CREATE FUNCTION dbo.pvt_find_structure_info( @scheme_id bigint, @root_field NVARCHAR(200), @nested_field NVARCHAR(200) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @root_sid bigint = NULL; DECLARE @root_type_name NVARCHAR(200) = NULL; DECLARE @root_db_type NVARCHAR(64) = NULL; DECLARE @root_dotnet NVARCHAR(200) = NULL; DECLARE @root_is_arr bit = 0; SELECT TOP 1 @root_sid = c._structure_id, @root_db_type = c.db_type, @root_is_arr = CASE WHEN c._collection_type IS NOT NULL THEN 1 ELSE 0 END, @root_type_name = c.type_name, @root_dotnet = c.type_semantic FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @root_field AND c._parent_structure_id IS NULL; DECLARE @nested_sid bigint = NULL; DECLARE @nested_type_name NVARCHAR(200) = NULL; DECLARE @nested_db_type NVARCHAR(64) = NULL; DECLARE @nested_dotnet NVARCHAR(200) = NULL; DECLARE @nested_is_arr bit = 0; DECLARE @nested_json NVARCHAR(MAX) = NULL; IF @nested_field IS NOT NULL AND @root_sid IS NOT NULL BEGIN -- Special case: ListItem nested accessors (Value/Alias/Id...) -- are stored as columns of _list_items, not as child structures. IF @root_dotnet = N'_RListItem' BEGIN SET @nested_json = dbo.pvt_get_listitem_field_type_info(@nested_field); END ELSE BEGIN SELECT TOP 1 @nested_sid = c._structure_id, @nested_db_type = c.db_type, @nested_is_arr = CASE WHEN c._collection_type IS NOT NULL THEN 1 ELSE 0 END, @nested_type_name = c.type_name, @nested_dotnet = c.type_semantic FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @nested_field AND c._parent_structure_id = @root_sid; END; END; -- Build root_type_info JSON or `null` if root not found. DECLARE @root_ti NVARCHAR(MAX) = CASE WHEN @root_sid IS NULL THEN N'null' ELSE N'{"type_name":' + dbo.pvt_json_string_or_null(@root_type_name) + N',"db_type":' + dbo.pvt_json_string_or_null(@root_db_type) + N',"type_semantic":' + dbo.pvt_json_string_or_null(@root_dotnet) + N',"is_array":' + CASE WHEN @root_is_arr = 1 THEN N'true' ELSE N'false' END + N'}' END; DECLARE @nested_ti NVARCHAR(MAX); IF @nested_json IS NOT NULL SET @nested_ti = @nested_json; ELSE IF @nested_sid IS NULL SET @nested_ti = N'null'; ELSE SET @nested_ti = N'{"type_name":' + dbo.pvt_json_string_or_null(@nested_type_name) + N',"db_type":' + dbo.pvt_json_string_or_null(@nested_db_type) + N',"type_semantic":' + dbo.pvt_json_string_or_null(@nested_dotnet) + N',"is_array":' + CASE WHEN @nested_is_arr = 1 THEN N'true' ELSE N'false' END + N'}'; RETURN N'{"root_structure_id":' + ISNULL(CAST(@root_sid AS NVARCHAR(32)), N'null') + N',"nested_structure_id":' + ISNULL(CAST(@nested_sid AS NVARCHAR(32)), N'null') + N',"root_type_info":' + @root_ti + N',"nested_type_info":' + @nested_ti + N'}'; END; GO Path: redb/redb.MSSql/sql/v2-pvt/04_pvt_tree_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.MSSql/sql/v2-pvt/04_pvt_tree_helpers.sql ---- -- ===================================================================== -- 04_pvt_tree_helpers.sql (MSSql v2-pvt) — iterative tree traversal -- --------------------------------------------------------------------- -- Functions: -- dbo.pvt_object_depth(@id) -- Returns the depth of an object in the tree (root = 0). -- Uses an iterative WHILE loop (max 200 levels) because scalar -- UDFs in SQL Server cannot contain recursive CTEs. -- -- dbo.pvt_is_descendant_of(@id, @ancestor_id) -- Returns 1 if @id is a direct or indirect descendant of -- @ancestor_id, 0 otherwise. Also iterative. -- -- Used by pvt_build_where_from_json to emit $level, $hasAncestor, and -- $hasDescendant predicates as correlated scalar UDF calls. -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_object_depth ----------------------------------------- CREATE OR ALTER FUNCTION dbo.pvt_object_depth(@id BIGINT) RETURNS INT AS BEGIN DECLARE @depth INT = 0; DECLARE @cur_id BIGINT = @id; DECLARE @par_id BIGINT; DECLARE @iter INT = 200; WHILE @iter > 0 BEGIN SELECT @par_id = [_id_parent] FROM dbo._objects WHERE [_id] = @cur_id; IF @par_id IS NULL RETURN @depth; SET @depth += 1; SET @cur_id = @par_id; SET @iter -= 1; END; RETURN @depth; END; GO -- ---------- pvt_is_descendant_of ------------------------------------- -- Returns 1 when @id is a (direct or indirect) descendant of @ancestor_id. CREATE OR ALTER FUNCTION dbo.pvt_is_descendant_of( @id BIGINT, @ancestor_id BIGINT ) RETURNS BIT AS BEGIN IF @id IS NULL OR @ancestor_id IS NULL RETURN 0; DECLARE @cur_id BIGINT = @id; DECLARE @par_id BIGINT; DECLARE @iter INT = 200; WHILE @iter > 0 BEGIN SELECT @par_id = [_id_parent] FROM dbo._objects WHERE [_id] = @cur_id; IF @par_id IS NULL RETURN 0; IF @par_id = @ancestor_id RETURN 1; SET @cur_id = @par_id; SET @iter -= 1; END; RETURN 0; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/05_pvt_single_facet.sql ---- -- ===================================================================== -- 05_pvt_single_facet.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- Legacy facet condition builder — MSSql thin wrapper. -- In MSSql v2-pvt, pvt_build_where_from_json (14_pvt_where.sql) handles -- all filter cases inline, including property functions, hierarchical -- operators, and 0$: base-field prefixes. This function delegates to -- that engine via pvt_collect_fields + pvt_build_where_from_json. -- -- Functions: -- dbo.pvt_build_single_facet_condition( -- @facet_condition NVARCHAR(MAX), -- @scheme_id BIGINT, -- @table_alias NVARCHAR(50), -- default 'o' -- @max_depth INT -- ignored (not used in T-SQL engine) -- ) -> NVARCHAR(MAX) -- -- Returns the AND-joined SQL predicate string (no leading ' AND '). -- Returns '1=1' for empty / null input. -- -- Depends on: -- dbo.pvt_collect_fields (10_pvt_field_collection.sql) -- dbo.pvt_build_where_from_json (14_pvt_where.sql) -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.pvt_build_single_facet_condition( @facet_condition NVARCHAR(MAX), @scheme_id BIGINT, @table_alias NVARCHAR(50), @max_depth INT ) RETURNS NVARCHAR(MAX) AS BEGIN IF @facet_condition IS NULL OR ISJSON(@facet_condition) = 0 RETURN N'1=1'; DECLARE @prefix NVARCHAR(60) = ISNULL(@table_alias, N'o') + N'.'; DECLARE @fields NVARCHAR(MAX) = dbo.pvt_collect_fields(@scheme_id, @facet_condition, NULL); RETURN dbo.pvt_build_where_from_json(@facet_condition, @fields, @prefix); END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/06_pvt_hierarchical.sql ---- -- ===================================================================== -- 06_pvt_hierarchical.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- Tree predicate builder for $hasAncestor, $hasDescendant, $level, -- $isRoot, $isLeaf, $childrenOf. Mirrors PG pvt_build_hierarchical_conditions. -- -- Note: The core WHERE builder (14_pvt_where.sql) handles all these -- operators inline. This function is a focused variant that extracts -- only the hierarchical keys from a filter JSON and builds a WHERE -- fragment — useful when callers want to separate tree conditions from -- field conditions. -- -- Functions: -- dbo.pvt_build_hierarchical_conditions(@facet_filters NVARCHAR(MAX), -- @table_alias NVARCHAR(50)) -- -> NVARCHAR(MAX) SQL fragment, leading ' AND ...' or '' -- -- Depends on: -- dbo.pvt_object_depth (04_pvt_tree_helpers.sql) -- dbo.pvt_is_descendant_of (04_pvt_tree_helpers.sql) -- dbo.pvt_build_level_condition (06a_pvt_legacy_helpers.sql) -- dbo.pvt_build_level_condition_with_operators (06a) -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.pvt_build_hierarchical_conditions( @facet_filters NVARCHAR(MAX), @table_alias NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @facet_filters IS NULL OR ISJSON(@facet_filters) = 0 RETURN N''; DECLARE @alias NVARCHAR(60) = ISNULL(@table_alias, N'o'); DECLARE @result NVARCHAR(MAX) = N''; -- $isRoot DECLARE @is_root_raw NVARCHAR(10) = JSON_VALUE(@facet_filters, N'$."$isRoot"'); IF @is_root_raw IS NOT NULL BEGIN IF LOWER(@is_root_raw) = N'true' SET @result += N' AND ' + @alias + N'.[_id_parent] IS NULL'; ELSE SET @result += N' AND ' + @alias + N'.[_id_parent] IS NOT NULL'; END; -- $isLeaf DECLARE @is_leaf_raw NVARCHAR(10) = JSON_VALUE(@facet_filters, N'$."$isLeaf"'); IF @is_leaf_raw IS NOT NULL BEGIN IF LOWER(@is_leaf_raw) = N'true' SET @result += N' AND NOT EXISTS (SELECT 1 FROM dbo._objects _ch WHERE _ch.[_id_parent] = ' + @alias + N'.[_id])'; ELSE SET @result += N' AND EXISTS (SELECT 1 FROM dbo._objects _ch WHERE _ch.[_id_parent] = ' + @alias + N'.[_id])'; END; -- $level: integer (exact) or object (operators). JSON_QUERY returns NULL for a scalar, so the exact level is read -- with JSON_VALUE; it used to be tested through JSON_QUERY only, and {"$level": 1} was dropped from the filter. DECLARE @level_raw NVARCHAR(MAX) = JSON_QUERY(@facet_filters, N'$."$level"'); DECLARE @lvl_val NVARCHAR(4000) = JSON_VALUE(@facet_filters, N'$."$level"'); IF @level_raw IS NOT NULL -- Operator object: {"$gt":2,"$lt":5} SET @result += dbo.pvt_build_level_condition_with_operators(@level_raw, @alias); ELSE IF @lvl_val IS NOT NULL SET @result += dbo.pvt_build_level_condition( COALESCE(TRY_CAST(@lvl_val AS INT), CAST(dbo.pvt_fail(N'$level expects an integer') AS INT)), @alias); -- $hasAncestor: object is a descendant of the given ancestor id DECLARE @ha_raw NVARCHAR(40) = JSON_VALUE(@facet_filters, N'$."$hasAncestor"'); IF @ha_raw IS NOT NULL BEGIN DECLARE @ha_id BIGINT = TRY_CAST(@ha_raw AS BIGINT); IF @ha_id IS NOT NULL SET @result += N' AND dbo.pvt_is_descendant_of(' + @alias + N'.[_id], ' + CAST(@ha_id AS NVARCHAR(20)) + N') = 1'; END; -- $hasDescendant: given id is a descendant of this object DECLARE @hd_raw NVARCHAR(40) = JSON_VALUE(@facet_filters, N'$."$hasDescendant"'); IF @hd_raw IS NOT NULL BEGIN DECLARE @hd_id BIGINT = TRY_CAST(@hd_raw AS BIGINT); IF @hd_id IS NOT NULL SET @result += N' AND dbo.pvt_is_descendant_of(' + CAST(@hd_id AS NVARCHAR(20)) + N', ' + @alias + N'.[_id]) = 1'; END; -- $childrenOf: direct children of the given parent id DECLARE @co_raw NVARCHAR(40) = JSON_VALUE(@facet_filters, N'$."$childrenOf"'); IF @co_raw IS NOT NULL BEGIN DECLARE @co_id BIGINT = TRY_CAST(@co_raw AS BIGINT); IF @co_id IS NOT NULL SET @result += N' AND ' + @alias + N'.[_id_parent] = ' + CAST(@co_id AS NVARCHAR(20)); END; RETURN @result; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/06a_pvt_legacy_helpers.sql ---- -- ===================================================================== -- 06a_pvt_legacy_helpers.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- Level-condition helpers required by pvt_build_hierarchical_conditions. -- Mirrors pvt_build_level_condition / pvt_build_level_condition_with_operators -- from PG v2-pvt/06a_pvt_legacy_helpers.sql. -- -- Functions: -- dbo.pvt_build_level_condition(@target_level INT, @table_alias NVARCHAR(50)) -- -> NVARCHAR(MAX) SQL fragment: ' AND dbo.pvt_object_depth(alias.[_id]) = N' -- dbo.pvt_build_level_condition_with_operators(@level_operators NVARCHAR(MAX), -- @table_alias NVARCHAR(50)) -- -> NVARCHAR(MAX) SQL fragment: ' AND (depth op N [AND ...])' -- -- Depends on: dbo.pvt_object_depth (04_pvt_tree_helpers.sql) -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_build_level_condition --------------------------------- -- Returns a T-SQL predicate fragment for exact tree-depth equality. -- Level 0 = root (no parent). Level 1 = direct child of root, etc. CREATE OR ALTER FUNCTION dbo.pvt_build_level_condition( @target_level INT, @table_alias NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @alias NVARCHAR(60) = ISNULL(@table_alias, N'o'); RETURN N' AND dbo.pvt_object_depth(' + @alias + N'.[_id]) = ' + CAST(@target_level AS NVARCHAR(10)); END; GO -- ---------- pvt_build_level_condition_with_operators ------------------ -- Parses a JSON object of comparison operators ({"$gt":2,"$lt":5}) -- and builds an AND-joined depth predicate fragment. -- Returns empty string when no recognized operators are found. CREATE OR ALTER FUNCTION dbo.pvt_build_level_condition_with_operators( @level_operators NVARCHAR(MAX), @table_alias NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @level_operators IS NULL OR ISJSON(@level_operators) = 0 RETURN N''; DECLARE @alias NVARCHAR(60) = ISNULL(@table_alias, N'o'); DECLARE @depth_expr NVARCHAR(200) = N'dbo.pvt_object_depth(' + @alias + N'.[_id])'; DECLARE @parts NVARCHAR(MAX) = N''; DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value] FROM OPENJSON(@level_operators); DECLARE @opk NVARCHAR(20), @opv NVARCHAR(50); OPEN c; FETCH NEXT FROM c INTO @opk, @opv; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @sym NVARCHAR(4) = CASE @opk WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' ELSE NULL END; IF @sym IS NOT NULL AND TRY_CAST(@opv AS INT) IS NOT NULL BEGIN IF @parts <> N'' SET @parts += N' AND '; SET @parts += @depth_expr + N' ' + @sym + N' ' + CAST(CAST(@opv AS INT) AS NVARCHAR(10)); END; FETCH NEXT FROM c INTO @opk, @opv; END; CLOSE c; DEALLOCATE c; IF @parts = N'' RETURN N''; RETURN N' AND (' + @parts + N')'; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/07_pvt_base_fields.sql ---- -- ===================================================================== -- 07_pvt_base_fields.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- Return a JSON object containing all base (_objects) fields of a -- single redb object (no Props). Mirrors PG pvt_get_object_base_fields. -- -- Functions: -- dbo.pvt_get_object_base_fields(@object_id BIGINT) -- -> NVARCHAR(MAX) JSON object with all base-table columns -- -- Notes: -- - Includes [_hash] which is critical for cache validation. -- - FOR JSON PATH, WITHOUT_ARRAY_WRAPPER collapses the single row. -- - Returns NULL when no matching object is found. -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.pvt_get_object_base_fields(@object_id BIGINT) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @json NVARCHAR(MAX); SELECT @json = ( SELECT o.[_id] AS [id], o.[_name] AS [name], o.[_id_scheme] AS [scheme_id], o.[_id_parent] AS [parent_id], o.[_id_owner] AS [owner_id], o.[_id_who_change] AS [who_change_id], o.[_date_create] AS [date_create], o.[_date_modify] AS [date_modify], o.[_date_begin] AS [date_begin], o.[_date_complete] AS [date_complete], o.[_key] AS [key], o.[_value_long] AS [value_long], o.[_value_string] AS [value_string], o.[_value_unique] AS [value_unique], o.[_value_guid] AS [value_guid], o.[_note] AS [note], o.[_value_bool] AS [value_bool], o.[_value_double] AS [value_double], o.[_value_numeric] AS [value_numeric], o.[_value_datetime] AS [value_datetime], o.[_value_bytes] AS [value_bytes], o.[_hash] AS [hash] FROM dbo._objects o WHERE o.[_id] = @object_id FOR JSON PATH, WITHOUT_ARRAY_WRAPPER ); RETURN @json; END; GO Path: redb/redb.MSSql/sql/v2-pvt/08_pvt_tree_functions.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.MSSql/sql/v2-pvt/08_pvt_tree_functions.sql ---- -- ====================================================================== -- 08_pvt_tree_functions.sql (MSSql v2-pvt — Stage 2a) -- ---------------------------------------------------------------------- -- Multi-statement table-valued functions for the 5 tree-walk modes -- consumed by pvt_build_cte_sql. PG uses inline recursive CTEs in the -- generated SQL; T-SQL forbids `WITH` inside a subquery, so we wrap -- the recursive walk in TVFs and let 12_pvt_cte_builder emit -- -- o.[_id] IN (SELECT _id FROM dbo.pvt_tree_(...)) -- -- as an ordinary predicate. This keeps the contract of file 12 (a bare -- SELECT body) intact and avoids touching the 5 callers. -- -- Modes: -- pvt_tree_descendants : recursive walk DOWN from seed ids. -- depth=0 at seed; descendants depth>0. -- @include_seed=0 strips depth=0 rows. -- @max_depth NULL = unbounded. -- @polymorphic=0 restricts the recursive -- step to o._id_scheme = @scheme_id. -- pvt_tree_children : non-recursive — direct children of seed ids. -- pvt_tree_roots : non-recursive — scheme objects with -- _id_parent IS NULL. Optional seed_ids -- restricts to that root subset. -- pvt_tree_leaves : non-recursive — scheme objects with no -- children (NOT EXISTS child._id_parent = o._id). -- Optional seed_ids restricts the leaf subset. -- pvt_tree_ancestors : recursive walk UP from seed ids via _id_parent. -- Seed depth=1 = direct parent of seed objects. -- The seeds themselves are NEVER in the output. -- -- Seed input: NVARCHAR(MAX) JSON array of bigints, e.g. N'[1,42,77]'. -- NULL or N'[]' = no seeds (only valid for roots/leaves). -- -- All functions return TABLE(_id BIGINT PRIMARY KEY, depth INT NULL). -- ====================================================================== SET ANSI_NULLS ON; GO SET QUOTED_IDENTIFIER ON; GO -- ---------------------------------------------------------------- DROPS IF OBJECT_ID('dbo.pvt_tree_descendants', 'TF') IS NOT NULL DROP FUNCTION dbo.pvt_tree_descendants; GO IF OBJECT_ID('dbo.pvt_tree_children', 'TF') IS NOT NULL DROP FUNCTION dbo.pvt_tree_children; GO IF OBJECT_ID('dbo.pvt_tree_roots', 'TF') IS NOT NULL DROP FUNCTION dbo.pvt_tree_roots; GO IF OBJECT_ID('dbo.pvt_tree_leaves', 'TF') IS NOT NULL DROP FUNCTION dbo.pvt_tree_leaves; GO IF OBJECT_ID('dbo.pvt_tree_ancestors', 'TF') IS NOT NULL DROP FUNCTION dbo.pvt_tree_ancestors; GO -- ==================================================================== -- pvt_tree_descendants -- ==================================================================== CREATE FUNCTION dbo.pvt_tree_descendants( @scheme_id BIGINT, @seed_ids NVARCHAR(MAX), -- JSON array of bigints @max_depth INT = NULL, @polymorphic BIT = 1, @include_seed BIT = 1 ) RETURNS @T TABLE (_id BIGINT PRIMARY KEY, depth INT NULL) AS BEGIN IF @seed_ids IS NULL RETURN; ;WITH seeds(_id) AS ( SELECT CAST([value] AS BIGINT) FROM OPENJSON(@seed_ids) ), walk(_id, depth) AS ( SELECT s._id, 0 FROM seeds s UNION ALL SELECT o.[_id], w.depth + 1 FROM dbo._objects o JOIN walk w ON o.[_id_parent] = w._id WHERE (@max_depth IS NULL OR w.depth < @max_depth) AND (@polymorphic = 1 OR o.[_id_scheme] = @scheme_id) ) INSERT INTO @T(_id, depth) SELECT _id, MIN(depth) FROM walk WHERE @include_seed = 1 OR depth > 0 GROUP BY _id; RETURN; END; GO -- ==================================================================== -- pvt_tree_children -- ==================================================================== CREATE FUNCTION dbo.pvt_tree_children( @scheme_id BIGINT, @seed_ids NVARCHAR(MAX), @polymorphic BIT = 1 ) RETURNS @T TABLE (_id BIGINT PRIMARY KEY, depth INT NULL) AS BEGIN IF @seed_ids IS NULL RETURN; ;WITH seeds(_id) AS ( SELECT CAST([value] AS BIGINT) FROM OPENJSON(@seed_ids) ) INSERT INTO @T(_id, depth) SELECT o.[_id], 1 FROM dbo._objects o JOIN seeds s ON o.[_id_parent] = s._id WHERE (@polymorphic = 1 OR o.[_id_scheme] = @scheme_id); RETURN; END; GO -- ==================================================================== -- pvt_tree_roots -- ==================================================================== CREATE FUNCTION dbo.pvt_tree_roots( @scheme_id BIGINT, @seed_ids NVARCHAR(MAX) -- optional; NULL = all roots in scheme ) RETURNS @T TABLE (_id BIGINT PRIMARY KEY, depth INT NULL) AS BEGIN IF @seed_ids IS NULL BEGIN INSERT INTO @T(_id, depth) SELECT o.[_id], 0 FROM dbo._objects o WHERE o.[_id_parent] IS NULL AND o.[_id_scheme] = @scheme_id; END ELSE BEGIN -- 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. INSERT INTO @T(_id, depth) SELECT DISTINCT o.[_id], 0 FROM dbo._objects o JOIN (SELECT CAST([value] AS BIGINT) AS _id FROM OPENJSON(@seed_ids)) s ON s._id = o.[_id]; END; RETURN; END; GO -- ==================================================================== -- pvt_tree_leaves -- ==================================================================== CREATE FUNCTION dbo.pvt_tree_leaves( @scheme_id BIGINT, @seed_ids NVARCHAR(MAX) -- optional; NULL = all leaves in scheme ) RETURNS @T TABLE (_id BIGINT PRIMARY KEY, depth INT NULL) AS BEGIN IF @seed_ids IS NULL BEGIN INSERT INTO @T(_id, depth) SELECT o.[_id], 0 FROM dbo._objects o WHERE o.[_id_scheme] = @scheme_id AND NOT EXISTS ( SELECT 1 FROM dbo._objects c WHERE c.[_id_parent] = o.[_id] ); END ELSE BEGIN -- 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). MAXRECURSION 0 lifts the 100-level cap for deep chains (trees can't cycle). ;WITH seeds(_id) AS ( SELECT CAST([value] AS BIGINT) FROM OPENJSON(@seed_ids) ), walk(_id, depth) AS ( SELECT s._id, 0 FROM seeds s UNION ALL SELECT o.[_id], w.depth + 1 FROM dbo._objects o JOIN walk w ON o.[_id_parent] = w._id ) INSERT INTO @T(_id, depth) SELECT d._id, 0 FROM (SELECT DISTINCT _id FROM walk WHERE depth > 0) d WHERE NOT EXISTS ( SELECT 1 FROM dbo._objects c WHERE c.[_id_parent] = d._id ) OPTION (MAXRECURSION 0); END; RETURN; END; GO -- ==================================================================== -- pvt_tree_ancestors -- ==================================================================== CREATE FUNCTION dbo.pvt_tree_ancestors( @scheme_id BIGINT, @seed_ids NVARCHAR(MAX), @max_depth INT = NULL, @polymorphic BIT = 1 ) RETURNS @T TABLE (_id BIGINT PRIMARY KEY, depth INT NULL) AS BEGIN IF @seed_ids IS NULL RETURN; ;WITH seeds(_id) AS ( SELECT CAST([value] AS BIGINT) FROM OPENJSON(@seed_ids) ), walk(_id, depth) AS ( -- Seed: direct parents of the input ids (depth=1). SELECT seed.[_id_parent], 1 FROM dbo._objects seed JOIN seeds s ON s._id = seed.[_id] WHERE seed.[_id_parent] IS NOT NULL UNION ALL -- Recursive step: grandparents and so on. SELECT o.[_id_parent], w.depth + 1 FROM dbo._objects o JOIN walk w ON o.[_id] = w._id WHERE o.[_id_parent] IS NOT NULL AND (@max_depth IS NULL OR w.depth < @max_depth) AND (@polymorphic = 1 OR o.[_id_scheme] = @scheme_id) ) INSERT INTO @T(_id, depth) SELECT _id, MIN(depth) FROM walk GROUP BY _id; RETURN; END; GO Path: redb/redb.MSSql/sql/v2-pvt/09_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.MSSql/sql/v2-pvt/09_core_object_json.sql ---- -- ===================================================================== -- 09_core_object_json.sql (MSSql) — object<->JSON materializer (module-owned) -- --------------------------------------------------------------------- -- The whole object->JSON materializer (dbo.get_object_json plus its helpers -- escape_json_string / build_listitem_json / build_field_json / build_properties) -- lives in the v2-pvt module, not the core init, so that its bug fixes ride -- the versioned auto-redeploy: bumping dbo.pvt_module_version() re-applies -- this file to existing databases via EnsurePvtModuleDeployedAsync, without -- re-running the full redb_init.sql (skipped once _schemes exists). -- ===================================================================== -- ==================================================================================================== -- JSON OBJECT FUNCTION (not procedure!) -- MS SQL Server version - OPTIMIZED for use with SELECT + STRING_AGG -- ==================================================================================================== -- Key difference from get_object_json_internal (procedure): -- - This is a FUNCTION that can be called in SELECT statements -- - Reads directly from _values table (no temp tables) -- - Uses recursive function calls instead of cursors where possible -- - Designed for batch processing: SELECT dbo.get_object_json(id, 10) FROM ... -- ==================================================================================================== -- ===================================================== -- DROP EXISTING FUNCTION (if exists) -- ===================================================== IF OBJECT_ID('dbo.get_object_json', 'FN') IS NOT NULL DROP FUNCTION dbo.get_object_json GO IF OBJECT_ID('dbo.build_properties', 'FN') IS NOT NULL DROP FUNCTION dbo.build_properties GO IF OBJECT_ID('dbo.build_field_json', 'FN') IS NOT NULL DROP FUNCTION dbo.build_field_json GO IF OBJECT_ID('dbo.escape_json_string', 'FN') IS NOT NULL DROP FUNCTION dbo.escape_json_string GO IF OBJECT_ID('dbo.build_listitem_json', 'FN') IS NOT NULL DROP FUNCTION dbo.build_listitem_json GO -- ===================================================== -- HELPER: Escape string for JSON -- ===================================================== CREATE FUNCTION dbo.escape_json_string(@input NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN IF @input IS NULL RETURN NULL; RETURN REPLACE( REPLACE( REPLACE( REPLACE( REPLACE(@input, N'\', N'\\'), -- Backslash first! N'"', N'\"'), CHAR(13), N'\r'), CHAR(10), N'\n'), CHAR(9), N'\t'); END GO -- ===================================================== -- HELPER: Build ListItem JSON (DRY - used in multiple places) -- ===================================================== -- The model's keys (RedbListItem: id, id_list, value, alias, id_object). Until 0.2.16 the item was written -- as "idList" without "id_object", and every load lost the list link and the object link. CREATE FUNCTION dbo.build_listitem_json(@listitem_id BIGINT) RETURNS NVARCHAR(MAX) AS BEGIN IF @listitem_id IS NULL RETURN NULL; RETURN (SELECT N'{"id":' + CAST(li._id AS NVARCHAR(20)) + N',"id_list":' + CAST(li._id_list AS NVARCHAR(20)) + N',"value":' + CASE WHEN li._value IS NULL THEN N'null' ELSE N'"' + dbo.escape_json_string(li._value) + N'"' END + N',"alias":' + CASE WHEN li._alias IS NULL THEN N'null' ELSE N'"' + dbo.escape_json_string(li._alias) + N'"' END + N',"id_object":' + CASE WHEN li._id_object IS NULL THEN N'null' ELSE CAST(li._id_object AS NVARCHAR(20)) END + N'}' FROM _list_items li WHERE li._id = @listitem_id); END GO -- ===================================================== -- HELPER: Build single field value as JSON -- ===================================================== CREATE FUNCTION dbo.build_field_json( @object_id BIGINT, @structure_id BIGINT, @scheme_id BIGINT, @parent_structure_id BIGINT, @field_name NVARCHAR(450), @db_type NVARCHAR(50), @type_semantic NVARCHAR(50), @collection_type BIGINT, @max_depth INT, @array_index NVARCHAR(430), @parent_value_id BIGINT, @lazy BIT = 0 -- V4 (LAZY Л2): _structures._lazy of this field ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @result NVARCHAR(MAX); -- V4 (LAZY Л2): a virtual reference with the session flag on is a stub (depth 0). DECLARE @lazy_depth INT = CASE WHEN @lazy = 1 AND TRY_CAST(CAST(SESSION_CONTEXT(N'redb.lazy_refs') AS NVARCHAR(10)) AS INT) = 1 THEN 0 ELSE @max_depth - 1 END; DECLARE @is_array BIT = CASE WHEN @collection_type = -9223372036854775668 THEN 1 ELSE 0 END; DECLARE @is_dictionary BIT = CASE WHEN @collection_type = -9223372036854775667 THEN 1 ELSE 0 END; -- Get value for this field DECLARE @val_id BIGINT, @val_String NVARCHAR(MAX), @val_Long BIGINT, @val_Guid UNIQUEIDENTIFIER; DECLARE @val_Double FLOAT, @val_Numeric DECIMAL(38,18), @val_DateTimeOffset DATETIMEOFFSET; DECLARE @val_Boolean BIT, @val_ByteArray VARBINARY(MAX), @val_ListItem BIGINT, @val_Object BIGINT; -- Find the value record IF @parent_value_id IS NOT NULL BEGIN SELECT TOP 1 @val_id = _id, @val_String = _String, @val_Long = _Long, @val_Guid = _Guid, @val_Double = _Double, @val_Numeric = _Numeric, @val_DateTimeOffset = _DateTimeOffset, @val_Boolean = _Boolean, @val_ByteArray = _ByteArray, @val_ListItem = _ListItem, @val_Object = _Object FROM _values WHERE _id_object = @object_id AND _id_structure = @structure_id AND _array_parent_id = @parent_value_id; END ELSE IF @array_index IS NOT NULL BEGIN SELECT TOP 1 @val_id = _id, @val_String = _String, @val_Long = _Long, @val_Guid = _Guid, @val_Double = _Double, @val_Numeric = _Numeric, @val_DateTimeOffset = _DateTimeOffset, @val_Boolean = _Boolean, @val_ByteArray = _ByteArray, @val_ListItem = _ListItem, @val_Object = _Object FROM _values WHERE _id_object = @object_id AND _id_structure = @structure_id AND _array_index = @array_index; END ELSE BEGIN SELECT TOP 1 @val_id = _id, @val_String = _String, @val_Long = _Long, @val_Guid = _Guid, @val_Double = _Double, @val_Numeric = _Numeric, @val_DateTimeOffset = _DateTimeOffset, @val_Boolean = _Boolean, @val_ByteArray = _ByteArray, @val_ListItem = _ListItem, @val_Object = _Object FROM _values WHERE _id_object = @object_id AND _id_structure = @structure_id AND _array_index IS NULL AND _array_parent_id IS NULL; END -- ===================================================== -- ARRAYS -- ===================================================== IF @is_array = 1 BEGIN DECLARE @base_value_id BIGINT; -- For nested arrays inside array/dict elements, base record has _array_parent_id = @parent_value_id IF @parent_value_id IS NOT NULL SELECT TOP 1 @base_value_id = _id FROM _values WHERE _id_object = @object_id AND _id_structure = @structure_id AND _array_index IS NULL AND _array_parent_id = @parent_value_id; ELSE SELECT TOP 1 @base_value_id = _id FROM _values WHERE _id_object = @object_id AND _id_structure = @structure_id AND _array_index IS NULL AND _array_parent_id IS NULL; -- No head record = array property is null (not empty []) IF @base_value_id IS NULL RETURN NULL; IF @type_semantic = '_RObject' BEGIN -- Array of Object references - recursive call for each -- A reference is always materialised: at the depth boundary get_object_json -- returns the base-fields stub (id, scheme_id, hash, no properties), which is -- what PostgreSQL and SQLite do. Emitting null here instead made the three -- providers disagree on the same data. NULL only when there is no reference. -- A target in the trash makes get_object_json return NULL, and STRING_AGG skips NULL: -- the ISNULL keeps it as null in its place (0.2.17), same in the dictionary branch. SELECT @result = N'[' + ISNULL(STRING_AGG( CASE WHEN v._Object IS NOT NULL THEN ISNULL(dbo.get_object_json(v._Object, @lazy_depth), N'null') ELSE N'null' END , N',') WITHIN GROUP (ORDER BY CASE WHEN v._array_index LIKE '[0-9]%' AND ISNUMERIC(v._array_index) = 1 THEN CAST(v._array_index AS INT) ELSE 2147483647 END, v._array_index ), N'') + N']' FROM _values v WHERE v._id_object = @object_id AND v._id_structure = @structure_id AND v._array_index IS NOT NULL AND (@base_value_id IS NULL OR v._array_parent_id = @base_value_id); END ELSE IF @type_semantic = 'Object' BEGIN -- Array of Class - recursive properties for each element SELECT @result = N'[' + ISNULL(STRING_AGG( -- "null must be null" (V-1) + R-1: a null element has no _Guid AND no children. -- T-SQL forbids a subquery inside STRING_AGG - the child flag comes from OUTER APPLY. CASE WHEN v._Guid IS NULL AND ch.x IS NULL THEN N'null' ELSE dbo.build_properties(@object_id, @scheme_id, @max_depth, @structure_id, v._array_index, v._id) END , N',') WITHIN GROUP (ORDER BY CASE WHEN v._array_index LIKE '[0-9]%' AND ISNUMERIC(v._array_index) = 1 THEN CAST(v._array_index AS INT) ELSE 2147483647 END, v._array_index ), N'') + N']' FROM _values v OUTER APPLY (SELECT TOP 1 1 AS x FROM _values c WHERE c._array_parent_id = v._id) ch WHERE v._id_object = @object_id AND v._id_structure = @structure_id AND v._array_index IS NOT NULL AND (@base_value_id IS NULL OR v._array_parent_id = @base_value_id); END ELSE BEGIN -- Array of primitives (including ListItem) SELECT @result = N'[' + ISNULL(STRING_AGG( CASE WHEN @db_type = 'String' THEN CASE WHEN v._String IS NULL THEN N'null' ELSE N'"' + dbo.escape_json_string(v._String) + N'"' END WHEN @db_type = 'Long' THEN CASE WHEN v._Long IS NULL THEN N'null' ELSE CAST(v._Long AS NVARCHAR(30)) END WHEN @db_type = 'Guid' THEN CASE WHEN v._Guid IS NULL THEN N'null' ELSE N'"' + CAST(v._Guid AS NVARCHAR(50)) + N'"' END WHEN @db_type = 'Double' THEN CASE WHEN v._Double IS NULL THEN N'null' ELSE FORMAT(v._Double, 'G', 'en-US') END WHEN @db_type = 'Numeric' THEN CASE WHEN v._Numeric IS NULL THEN N'null' ELSE REPLACE(CAST(v._Numeric AS NVARCHAR(50)), N',', N'.') END WHEN @db_type = 'DateTimeOffset' THEN CASE WHEN v._DateTimeOffset IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), v._DateTimeOffset, 127) + N'"' END WHEN @db_type = 'Boolean' THEN CASE WHEN v._Boolean IS NULL THEN N'null' WHEN v._Boolean = 1 THEN N'true' ELSE N'false' END WHEN @db_type = 'ByteArray' THEN CASE WHEN v._ByteArray IS NULL THEN N'null' ELSE N'"' + b64.txt + N'"' END WHEN @db_type = 'ListItem' THEN CASE WHEN v._ListItem IS NULL THEN N'null' ELSE dbo.build_listitem_json(v._ListItem) END ELSE N'null' END , N',') WITHIN GROUP (ORDER BY CASE WHEN v._array_index LIKE '[0-9]%' AND ISNUMERIC(v._array_index) = 1 THEN CAST(v._array_index AS INT) ELSE 2147483647 END, v._array_index ), N'') + N']' FROM _values v -- base64 via FOR XML: measured 5x cheaper than an XML instance's .value() on a 1 MB -- blob (21 ms against 111). "AS [*]" suppresses the element name - without it the -- value arrives wrapped in <_ByteArray>... and the JSON is corrupt. The -- subquery cannot sit inside STRING_AGG (Msg 130), hence the APPLY. OUTER APPLY (SELECT txt = (SELECT v._ByteArray AS [*] FOR XML PATH(''), BINARY BASE64)) b64 WHERE v._id_object = @object_id AND v._id_structure = @structure_id AND v._array_index IS NOT NULL AND (@base_value_id IS NULL OR v._array_parent_id = @base_value_id); END RETURN @result; END -- ===================================================== -- DICTIONARIES -- ===================================================== IF @is_dictionary = 1 BEGIN DECLARE @dict_base_id BIGINT; -- For nested dicts inside array/dict elements, base record has _array_parent_id = @parent_value_id IF @parent_value_id IS NOT NULL SELECT TOP 1 @dict_base_id = _id FROM _values WHERE _id_object = @object_id AND _id_structure = @structure_id AND _array_index IS NULL AND _array_parent_id = @parent_value_id; ELSE SELECT TOP 1 @dict_base_id = _id FROM _values WHERE _id_object = @object_id AND _id_structure = @structure_id AND _array_index IS NULL AND _array_parent_id IS NULL; -- No head record = dictionary property is null (not empty {}) IF @dict_base_id IS NULL RETURN NULL; IF @type_semantic = '_RObject' BEGIN -- Dictionary of Object references SELECT @result = N'{' + ISNULL(STRING_AGG( N'"' + dbo.escape_json_string(v._array_index) + N'":' + CASE WHEN v._Object IS NOT NULL AND @max_depth > 0 THEN ISNULL(dbo.get_object_json(v._Object, @lazy_depth), N'null') ELSE N'null' END , N','), N'') + N'}' FROM _values v WHERE v._id_object = @object_id AND v._id_structure = @structure_id AND v._array_index IS NOT NULL AND (@dict_base_id IS NULL OR v._array_parent_id = @dict_base_id); END ELSE IF @type_semantic = 'Object' BEGIN -- Dictionary of Class SELECT @result = N'{' + ISNULL(STRING_AGG( N'"' + dbo.escape_json_string(v._array_index) + N'":' + -- R-1: no _Guid AND no children. CASE WHEN v._Guid IS NULL AND ch.x IS NULL THEN N'null' ELSE dbo.build_properties(@object_id, @scheme_id, @max_depth, @structure_id, NULL, v._id) END , N','), N'') + N'}' FROM _values v OUTER APPLY (SELECT TOP 1 1 AS x FROM _values c WHERE c._array_parent_id = v._id) ch WHERE v._id_object = @object_id AND v._id_structure = @structure_id AND v._array_index IS NOT NULL AND (@dict_base_id IS NULL OR v._array_parent_id = @dict_base_id); END ELSE BEGIN -- Dictionary of primitives SELECT @result = N'{' + ISNULL(STRING_AGG( N'"' + dbo.escape_json_string(v._array_index) + N'":' + CASE WHEN @db_type = 'String' THEN CASE WHEN v._String IS NULL THEN N'null' ELSE N'"' + dbo.escape_json_string(v._String) + N'"' END WHEN @db_type = 'Long' THEN CASE WHEN v._Long IS NULL THEN N'null' ELSE CAST(v._Long AS NVARCHAR(30)) END WHEN @db_type = 'Guid' THEN CASE WHEN v._Guid IS NULL THEN N'null' ELSE N'"' + CAST(v._Guid AS NVARCHAR(50)) + N'"' END WHEN @db_type = 'Double' THEN CASE WHEN v._Double IS NULL THEN N'null' ELSE FORMAT(v._Double, 'G', 'en-US') END WHEN @db_type = 'Numeric' THEN CASE WHEN v._Numeric IS NULL THEN N'null' ELSE REPLACE(CAST(v._Numeric AS NVARCHAR(50)), N',', N'.') END WHEN @db_type = 'DateTimeOffset' THEN CASE WHEN v._DateTimeOffset IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), v._DateTimeOffset, 127) + N'"' END WHEN @db_type = 'Boolean' THEN CASE WHEN v._Boolean IS NULL THEN N'null' WHEN v._Boolean = 1 THEN N'true' ELSE N'false' END WHEN @db_type = 'ByteArray' THEN CASE WHEN v._ByteArray IS NULL THEN N'null' ELSE N'"' + b64.txt + N'"' END ELSE N'null' END , N','), N'') + N'}' FROM _values v -- See the array branch above: FOR XML is 5x cheaper than the XML instance, "AS [*]" -- keeps the element name out, and STRING_AGG rejects the subquery (Msg 130). OUTER APPLY (SELECT txt = (SELECT v._ByteArray AS [*] FOR XML PATH(''), BINARY BASE64)) b64 WHERE v._id_object = @object_id AND v._id_structure = @structure_id AND v._array_index IS NOT NULL AND (@dict_base_id IS NULL OR v._array_parent_id = @dict_base_id); END RETURN @result; END -- ===================================================== -- _RObject reference (single) -- ===================================================== IF @type_semantic = '_RObject' BEGIN -- Same rule as the array branch: the depth boundary yields the base-fields stub, -- never null. NULL only when the reference itself is empty. IF @val_Object IS NOT NULL RETURN dbo.get_object_json(@val_Object, @lazy_depth); RETURN NULL; END -- ===================================================== -- Nested Class (hierarchical) -- ===================================================== IF @type_semantic = 'Object' BEGIN IF @val_Guid IS NOT NULL RETURN dbo.build_properties(@object_id, @scheme_id, @max_depth, @structure_id, NULL, @val_id); RETURN NULL; END -- ===================================================== -- PRIMITIVES -- ===================================================== IF @val_id IS NULL RETURN NULL; SET @result = CASE WHEN @db_type = 'String' THEN CASE WHEN @val_String IS NULL THEN NULL ELSE N'"' + dbo.escape_json_string(@val_String) + N'"' END WHEN @db_type = 'Long' THEN CASE WHEN @val_ListItem IS NOT NULL THEN dbo.build_listitem_json(@val_ListItem) WHEN @val_Long IS NULL THEN NULL ELSE CAST(@val_Long AS NVARCHAR(30)) END WHEN @db_type = 'Guid' THEN CASE WHEN @val_Guid IS NULL THEN NULL ELSE N'"' + CAST(@val_Guid AS NVARCHAR(50)) + N'"' END WHEN @db_type = 'Double' THEN CASE WHEN @val_Double IS NULL THEN NULL ELSE FORMAT(@val_Double, 'G', 'en-US') END WHEN @db_type = 'Numeric' THEN CASE WHEN @val_Numeric IS NULL THEN NULL ELSE REPLACE(CAST(@val_Numeric AS NVARCHAR(50)), N',', N'.') END WHEN @db_type = 'DateTimeOffset' THEN CASE WHEN @val_DateTimeOffset IS NULL THEN NULL ELSE N'"' + CONVERT(NVARCHAR(50), @val_DateTimeOffset, 127) + N'"' END WHEN @db_type = 'Boolean' THEN CASE WHEN @val_Boolean IS NULL THEN NULL WHEN @val_Boolean = 1 THEN N'true' ELSE N'false' END WHEN @db_type = 'ByteArray' THEN -- FOR XML instead of an XML instance: 101 ms -> 29 ms on a 1 MB blob. "AS [*]" keeps -- the element name out of the value; no aggregate here, so no APPLY is needed. CASE WHEN @val_ByteArray IS NULL THEN NULL ELSE N'"' + (SELECT @val_ByteArray AS [*] FOR XML PATH(''), BINARY BASE64) + N'"' END WHEN @db_type = 'ListItem' THEN dbo.build_listitem_json(@val_ListItem) ELSE NULL END; RETURN @result; END GO -- ===================================================== -- HELPER: Build properties JSON for an object -- ===================================================== CREATE FUNCTION dbo.build_properties( @object_id BIGINT, @scheme_id BIGINT, @max_depth INT, @parent_structure_id BIGINT, @array_index NVARCHAR(430), @parent_value_id BIGINT ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @result NVARCHAR(MAX); -- Protection against infinite recursion IF @max_depth < -100 RETURN N'{"error":"Max recursion depth reached"}'; -- Build properties object from metadata cache -- Filter out NULL values to reduce JSON size (like PostgreSQL behavior) SELECT @result = N'{' + ISNULL(( SELECT STRING_AGG(N'"' + dbo.escape_json_string(_name) + N'":' + field_value, N',') WITHIN GROUP (ORDER BY _order, _structure_id) FROM ( SELECT c._order, c._structure_id, c._name, dbo.build_field_json( @object_id, c._structure_id, @scheme_id, @parent_structure_id, c._name, c.db_type, c.type_semantic, c._collection_type, @max_depth, @array_index, @parent_value_id, ISNULL(c._lazy, 0) ) AS field_value FROM _scheme_metadata_cache c WHERE c._scheme_id = @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)) ) sub WHERE field_value IS NOT NULL ), N'') + N'}'; RETURN ISNULL(@result, N'{}'); END GO -- ===================================================== -- MAIN FUNCTION: Get object as JSON -- ===================================================== CREATE FUNCTION dbo.get_object_json( @object_id BIGINT, @max_depth INT = 10 ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @result NVARCHAR(MAX); DECLARE @scheme_id BIGINT; DECLARE @base_json NVARCHAR(MAX); DECLARE @properties_json NVARCHAR(MAX); -- Check if object exists. -- Soft-deleted objects (_id_scheme = -10, @@__deleted) are treated 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 the soft-delete remains reversible. IF NOT EXISTS(SELECT 1 FROM _objects WHERE _id = @object_id AND _id_scheme <> -10) RETURN NULL; -- Get scheme_id and base fields SELECT @scheme_id = o._id_scheme, @base_json = N'{' + N'"id":' + CAST(o._id AS NVARCHAR(20)) + N',"name":' + CASE WHEN o._name IS NULL THEN N'null' ELSE N'"' + dbo.escape_json_string(o._name) + N'"' END + N',"scheme_id":' + CAST(o._id_scheme AS NVARCHAR(20)) + N',"scheme_name":"' + dbo.escape_json_string(s._name) + N'"' + N',"parent_id":' + CASE WHEN o._id_parent IS NULL THEN N'null' ELSE CAST(o._id_parent AS NVARCHAR(20)) END + N',"owner_id":' + CAST(o._id_owner AS NVARCHAR(20)) + N',"who_change_id":' + CAST(o._id_who_change AS NVARCHAR(20)) + N',"date_create":"' + CONVERT(NVARCHAR(50), o._date_create, 127) + N'"' + N',"date_modify":"' + CONVERT(NVARCHAR(50), o._date_modify, 127) + N'"' + N',"date_begin":' + CASE WHEN o._date_begin IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), o._date_begin, 127) + N'"' END + N',"date_complete":' + CASE WHEN o._date_complete IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), o._date_complete, 127) + N'"' END + N',"key":' + CASE WHEN o._key IS NULL THEN N'null' ELSE CAST(o._key AS NVARCHAR(20)) END + N',"value_long":' + CASE WHEN o._value_long IS NULL THEN N'null' ELSE CAST(o._value_long AS NVARCHAR(20)) END + N',"value_string":' + CASE WHEN o._value_string IS NULL THEN N'null' ELSE N'"' + dbo.escape_json_string(o._value_string) + N'"' END + N',"value_unique":' + CASE WHEN o._value_unique IS NULL THEN N'null' ELSE N'"' + dbo.escape_json_string(o._value_unique) + N'"' END + N',"value_guid":' + CASE WHEN o._value_guid IS NULL THEN N'null' ELSE N'"' + CAST(o._value_guid AS NVARCHAR(50)) + N'"' END + N',"note":' + CASE WHEN o._note IS NULL THEN N'null' ELSE N'"' + dbo.escape_json_string(o._note) + N'"' END + N',"value_bool":' + CASE WHEN o._value_bool IS NULL THEN N'null' WHEN o._value_bool = 1 THEN N'true' ELSE N'false' END + N',"value_double":' + CASE WHEN o._value_double IS NULL THEN N'null' ELSE FORMAT(o._value_double, 'G', 'en-US') END + N',"value_numeric":' + CASE WHEN o._value_numeric IS NULL THEN N'null' ELSE REPLACE(CAST(o._value_numeric AS NVARCHAR(50)), N',', N'.') END + N',"value_datetime":' + CASE WHEN o._value_datetime IS NULL THEN N'null' ELSE N'"' + CONVERT(NVARCHAR(50), o._value_datetime, 127) + N'"' END + -- Root value_bytes as base64 (the XML trick). Was absent entirely: the column was -- written but reads came back null (bug report BUG_BYTES §3.3, read side). N',"value_bytes":' + CASE WHEN o._value_bytes IS NULL THEN N'null' ELSE N'"' + (SELECT o._value_bytes AS [*] FOR XML PATH(''), BINARY BASE64) + N'"' END + N',"hash":' + CASE WHEN o._hash IS NULL THEN N'null' ELSE N'"' + CAST(o._hash AS NVARCHAR(50)) + N'"' END FROM _objects o INNER JOIN _schemes s ON s._id = o._id_scheme WHERE o._id = @object_id; -- If max_depth = 0, return only base fields IF @max_depth <= 0 RETURN @base_json + N'}'; -- No _values at all = properties is null (not fake empty {}) IF NOT EXISTS(SELECT 1 FROM _values WHERE _id_object = @object_id) RETURN @base_json + N',"properties":null}'; -- Build properties SET @properties_json = dbo.build_properties(@object_id, @scheme_id, @max_depth, NULL, NULL, NULL); -- Combine base + properties RETURN @base_json + N',"properties":' + ISNULL(@properties_json, N'{}') + N'}'; END GO -- ===================================================== -- USAGE EXAMPLES -- ===================================================== -- -- Single object: -- SELECT dbo.get_object_json(123, 10); -- -- Multiple objects (batch - FAST!): -- SELECT dbo.get_object_json(o._id, 10) as json_object -- FROM _objects o -- WHERE o._id IN (123, 456, 789); -- -- With aggregation: -- SELECT '[' + STRING_AGG(dbo.get_object_json(t._id, 10), ',') + ']' -- FROM #temp_ids t; -- ===================================================== PRINT '========================================='; PRINT 'JSON object FUNCTION created!'; PRINT ''; PRINT 'FUNCTION: dbo.get_object_json(@object_id, @max_depth)'; PRINT ' - Can be used in SELECT statements'; PRINT ' - Reads directly from _values (no temp tables)'; PRINT ' - Recursive for nested objects'; PRINT ' - Use with STRING_AGG for batch processing'; PRINT '========================================='; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/10_pvt_field_collection.sql ---- -- ===================================================================== -- 10_pvt_field_collection.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- Field-name collection from filter/order JSON and metadata resolution -- via _scheme_metadata_cache. Produces the `fields` JSON consumed by -- pvt_build_column_expr / pvt_build_cte_sql / pvt_build_*_condition. -- -- Minimal-port functions: -- dbo.pvt_resolve_field_path(@scheme_id, @path) -> NVARCHAR(MAX) JSON FieldInfo -- dbo.pvt_extract_field_pairs(@filter) -> NVARCHAR(MAX) JSON array of {path,op_value} -- dbo.pvt_collect_fields(@scheme_id, @filter, @order) -> NVARCHAR(MAX) JSON object keyed by field name -- dbo.pvt_has_absence_check(@filter) -> BIT -- -- Skipped vs PG (v0.1 slice): $fts/$cast/$dateAdd branches, length/count modifier registration. -- $case is handled here; $field references inside the arms are collected (see the $case branch -- in pvt_extract_field_pairs). -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_resolve_field_path ------------------------------------ CREATE OR ALTER FUNCTION dbo.pvt_resolve_field_path( @scheme_id BIGINT, @path NVARCHAR(400) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL OR @path IS NULL OR @path = N'' RETURN NULL; -- 0. Base? DECLARE @base_col NVARCHAR(100) = dbo.pvt_normalize_base_field_name(@path); IF @base_col IS NOT NULL RETURN N'{"kind":"base","column":"' + @base_col + N'","name":' + dbo.pvt_json_string_or_null(@path) + N',"is_array":false,"list_item_prop":null,"dict_key":null,"parent_sid":null,"sid":null,"db_type":null,"db_column":null}'; DECLARE @sid BIGINT, @db_type NVARCHAR(50), @db_col NVARCHAR(50), @is_array BIT = 0, @list_prop NVARCHAR(20) = NULL, @dict_key NVARCHAR(200) = NULL, @parent_sid BIGINT = NULL, @root_name NVARCHAR(200), @child_name NVARCHAR(200), @rest NVARCHAR(400); -- 1. Dictionary path: Name[key] or Name[key].Child DECLARE @lb INT = CHARINDEX(N'[', @path); DECLARE @rb INT = CHARINDEX(N']', @path); IF @lb > 0 AND @rb > @lb + 1 BEGIN SET @root_name = SUBSTRING(@path, 1, @lb - 1); SET @dict_key = SUBSTRING(@path, @lb + 1, @rb - @lb - 1); SET @rest = SUBSTRING(@path, @rb + 1, 400); SELECT TOP 1 @sid = c._structure_id, @db_type = c.db_type FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @root_name AND c._parent_structure_id IS NULL; IF @sid IS NULL RETURN NULL; IF @rest LIKE N'.%' BEGIN SET @parent_sid = @sid; SET @child_name = SUBSTRING(@rest, 2, 400); -- T-SQL keeps the old value when SELECT @v = ... finds no row: without the reset a child the -- dictionary does not have resolved to the dictionary itself. SET @sid = NULL; SELECT TOP 1 @sid = c._structure_id, @db_type = c.db_type, @is_array = CASE WHEN c._collection_type IS NOT NULL THEN 1 ELSE 0 END FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @child_name AND c._parent_structure_id = @parent_sid; IF @sid IS NULL RETURN NULL; END; SET @db_col = dbo.pvt_db_type_to_value_column(@db_type); RETURN N'{"kind":"field","sid":' + CAST(@sid AS NVARCHAR(40)) + N',"db_type":' + dbo.pvt_json_string_or_null(@db_type) + N',"db_column":' + dbo.pvt_json_string_or_null(@db_col) + N',"name":' + dbo.pvt_json_string_or_null(@path) + N',"is_array":' + CASE WHEN @is_array = 1 THEN N'true' ELSE N'false' END + N',"list_item_prop":null' + N',"dict_key":' + dbo.pvt_json_string_or_null(@dict_key) + N',"parent_sid":' + CASE WHEN @parent_sid IS NULL THEN N'null' ELSE CAST(@parent_sid AS NVARCHAR(40)) END + N'}'; END; -- 2. Dotted nested IF CHARINDEX(N'.', @path) > 0 BEGIN DECLARE @last NVARCHAR(200), @first NVARCHAR(200); SET @last = REVERSE(LEFT(REVERSE(@path), CHARINDEX(N'.', REVERSE(@path)) - 1)); SET @first = LEFT(@path, CHARINDEX(N'.', @path) - 1); -- 2a. Foo[].Value|Alias|Id (ListItem array accessors) IF @last IN (N'Id', N'Value', N'Alias') AND RIGHT(@first, 2) = N'[]' AND CHARINDEX(N'.', @path) = LEN(@first) + 1 BEGIN DECLARE @root_li NVARCHAR(200) = LEFT(@first, LEN(@first) - 2); SELECT TOP 1 @sid = c._structure_id, @db_type = c.db_type, @is_array = CASE WHEN c._collection_type IS NOT NULL THEN 1 ELSE 0 END FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @root_li AND c._parent_structure_id IS NULL; IF @sid IS NOT NULL AND @db_type = N'ListItem' AND @is_array = 1 BEGIN SET @list_prop = @last; RETURN N'{"kind":"field","sid":' + CAST(@sid AS NVARCHAR(40)) + N',"db_type":"ListItem","db_column":"_ListItem"' + N',"name":' + dbo.pvt_json_string_or_null(@path) + N',"is_array":true' + N',"list_item_prop":' + dbo.pvt_json_string_or_null(@list_prop) + N',"dict_key":null,"parent_sid":null}'; END; END; -- 2b. Status.Value|Alias|Id (scalar ListItem accessors) IF @last IN (N'Id', N'Value', N'Alias') AND CHARINDEX(N'.', @path) = LEN(@first) + 1 BEGIN SELECT @sid = NULL, @db_type = NULL, @is_array = 0; -- not the values 2a left behind SELECT TOP 1 @sid = c._structure_id, @db_type = c.db_type, @is_array = CASE WHEN c._collection_type IS NOT NULL THEN 1 ELSE 0 END FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @first AND c._parent_structure_id IS NULL; IF @sid IS NOT NULL AND @db_type = N'ListItem' BEGIN SET @list_prop = @last; RETURN N'{"kind":"field","sid":' + CAST(@sid AS NVARCHAR(40)) + N',"db_type":"ListItem","db_column":"_ListItem"' + N',"name":' + dbo.pvt_json_string_or_null(@path) + N',"is_array":' + CASE WHEN @is_array = 1 THEN N'true' ELSE N'false' END + N',"list_item_prop":' + dbo.pvt_json_string_or_null(@list_prop) + N',"dict_key":null,"parent_sid":null}'; END; END; -- 2c. Generic nested walk DECLARE @cur_sid BIGINT, @segment NVARCHAR(200), @rem NVARCHAR(400), @cut INT; SET @rem = @path; SET @cut = CHARINDEX(N'.', @rem); SET @segment = LEFT(@rem, @cut - 1); -- Strip trailing "[]" so element-of-struct-array paths like -- "Contacts[].Type" walk into the nested "Type" field of the -- Contacts struct-array element. IF RIGHT(@segment, 2) = N'[]' SET @segment = LEFT(@segment, LEN(@segment) - 2); SELECT TOP 1 @cur_sid = c._structure_id FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @segment AND c._parent_structure_id IS NULL; IF @cur_sid IS NULL RETURN NULL; SET @rem = SUBSTRING(@rem, @cut + 1, 400); WHILE @rem IS NOT NULL AND @rem <> N'' BEGIN SET @cut = CHARINDEX(N'.', @rem); IF @cut = 0 BEGIN SET @segment = @rem; SET @rem = N''; END ELSE BEGIN SET @segment = LEFT(@rem, @cut - 1); SET @rem = SUBSTRING(@rem, @cut + 1, 400); END; IF RIGHT(@segment, 2) = N'[]' SET @segment = LEFT(@segment, LEN(@segment) - 2); -- T-SQL keeps the old value when SELECT @v = ... finds no row: an unknown child used to -- resolve to its parent (Contacts[].NoSuchField became the Contacts array). DECLARE @next_sid BIGINT = NULL; SET @next_sid = NULL; SELECT TOP 1 @next_sid = c._structure_id FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @segment AND c._parent_structure_id = @cur_sid; IF @next_sid IS NULL RETURN NULL; SET @cur_sid = @next_sid; END; SELECT TOP 1 @db_type = c.db_type, @is_array = CASE WHEN c._collection_type IS NOT NULL THEN 1 ELSE 0 END FROM dbo._scheme_metadata_cache c WHERE c._structure_id = @cur_sid; SET @db_col = dbo.pvt_db_type_to_value_column(@db_type); RETURN N'{"kind":"field","sid":' + CAST(@cur_sid AS NVARCHAR(40)) + N',"db_type":' + dbo.pvt_json_string_or_null(@db_type) + N',"db_column":' + dbo.pvt_json_string_or_null(@db_col) + N',"name":' + dbo.pvt_json_string_or_null(@path) + N',"is_array":' + CASE WHEN @is_array = 1 THEN N'true' ELSE N'false' END + N',"list_item_prop":null,"dict_key":null,"parent_sid":null}'; END; -- 3. Bare root field (possibly Foo[] for arrays) DECLARE @base_name NVARCHAR(200) = @path; DECLARE @force_array BIT = 0; IF RIGHT(@path, 2) = N'[]' BEGIN SET @base_name = LEFT(@path, LEN(@path) - 2); SET @force_array = 1; END; SELECT TOP 1 @sid = c._structure_id, @db_type = c.db_type, @is_array = CASE WHEN c._collection_type IS NOT NULL THEN 1 ELSE 0 END FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @base_name AND c._parent_structure_id IS NULL; IF @sid IS NULL RETURN NULL; IF @force_array = 1 SET @is_array = 1; IF @db_type = N'ListItem' BEGIN SET @db_col = N'_ListItem'; SET @list_prop = N'Id'; END ELSE SET @db_col = dbo.pvt_db_type_to_value_column(@db_type); RETURN N'{"kind":"field","sid":' + CAST(@sid AS NVARCHAR(40)) + N',"db_type":' + dbo.pvt_json_string_or_null(@db_type) + N',"db_column":' + dbo.pvt_json_string_or_null(@db_col) + N',"name":' + dbo.pvt_json_string_or_null(@path) + N',"is_array":' + CASE WHEN @is_array = 1 THEN N'true' ELSE N'false' END + N',"list_item_prop":' + dbo.pvt_json_string_or_null(@list_prop) + N',"dict_key":null,"parent_sid":null}'; END; GO -- ---------- pvt_extract_field_pairs ----------------------------------- -- Walks a filter JSON recursively and returns JSON array of {path, op_value}. -- Logical ops ($and/$or/$not) are descended into; their child arrays/objects -- contribute pairs but the operator keys themselves never appear as paths. CREATE OR ALTER FUNCTION dbo.pvt_extract_field_pairs(@filter NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN IF @filter IS NULL OR ISJSON(@filter) = 0 RETURN N'[]'; DECLARE @out NVARCHAR(MAX) = N'['; DECLARE @first BIT = 1; DECLARE c_keys CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@filter); DECLARE @k NVARCHAR(400), @v NVARCHAR(MAX), @t INT; OPEN c_keys; FETCH NEXT FROM c_keys INTO @k, @v, @t; WHILE @@FETCH_STATUS = 0 BEGIN IF LEFT(@k, 1) = N'$' BEGIN -- Logical operator: descend -- The generic array descent must NOT swallow $case: its value is an array of -- {when,then} arm objects, and walking those as plain objects harvested -- "when"/"then"/"else" as field paths while the $field references inside the arms -- were never reached, so pvt_b2_expr_sql could not find the field. The dedicated -- $case branch below walks the arm VALUES instead, mirroring -- pvt_extract_field_names in the PostgreSQL module (10, :52). IF @t = 4 AND LOWER(@k) <> N'$case' BEGIN DECLARE @elem NVARCHAR(MAX); DECLARE c_arr CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@v); OPEN c_arr; FETCH NEXT FROM c_arr INTO @elem; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @sub NVARCHAR(MAX) = dbo.pvt_extract_field_pairs(@elem); IF @sub <> N'[]' AND LEN(@sub) > 2 BEGIN IF @first = 0 SET @out = @out + N','; SET @out = @out + SUBSTRING(@sub, 2, LEN(@sub) - 2); SET @first = 0; END; FETCH NEXT FROM c_arr INTO @elem; END; CLOSE c_arr; DEALLOCATE c_arr; END ELSE IF @t = 5 -- object: descend into it BEGIN DECLARE @sub2 NVARCHAR(MAX) = dbo.pvt_extract_field_pairs(@v); IF @sub2 <> N'[]' AND LEN(@sub2) > 2 BEGIN IF @first = 0 SET @out = @out + N','; SET @out = @out + SUBSTRING(@sub2, 2, LEN(@sub2) - 2); SET @first = 0; END; END ELSE IF LOWER(@k) = N'$field' AND @t = 1 BEGIN -- B2-expr $field: the string value is the field path to collect IF @first = 0 SET @out = @out + N','; SET @out = @out + N'{"path":' + dbo.pvt_json_string_or_null(@v) + N',"op_value":null}'; SET @first = 0; END ELSE IF LOWER(@k) = N'$case' AND @t = 4 BEGIN -- $case arms: descend into each {when, then, else} object DECLARE @ca_arm NVARCHAR(MAX); DECLARE c_ca2 CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@v); OPEN c_ca2; FETCH NEXT FROM c_ca2 INTO @ca_arm; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @ca_sub NVARCHAR(MAX); -- descend into 'when', 'then', 'else' branches DECLARE @ca_w NVARCHAR(MAX) = JSON_QUERY(@ca_arm, N'$.when'); DECLARE @ca_t NVARCHAR(MAX) = JSON_QUERY(@ca_arm, N'$.then'); DECLARE @ca_e NVARCHAR(MAX) = JSON_QUERY(@ca_arm, N'$.else'); IF @ca_w IS NOT NULL BEGIN SET @ca_sub = dbo.pvt_extract_field_pairs(@ca_w); IF @ca_sub <> N'[]' AND LEN(@ca_sub) > 2 BEGIN IF @first = 0 SET @out = @out + N','; SET @out = @out + SUBSTRING(@ca_sub, 2, LEN(@ca_sub) - 2); SET @first = 0; END; END; IF @ca_t IS NOT NULL BEGIN SET @ca_sub = dbo.pvt_extract_field_pairs(@ca_t); IF @ca_sub <> N'[]' AND LEN(@ca_sub) > 2 BEGIN IF @first = 0 SET @out = @out + N','; SET @out = @out + SUBSTRING(@ca_sub, 2, LEN(@ca_sub) - 2); SET @first = 0; END; END; IF @ca_e IS NOT NULL BEGIN SET @ca_sub = dbo.pvt_extract_field_pairs(@ca_e); IF @ca_sub <> N'[]' AND LEN(@ca_sub) > 2 BEGIN IF @first = 0 SET @out = @out + N','; SET @out = @out + SUBSTRING(@ca_sub, 2, LEN(@ca_sub) - 2); SET @first = 0; END; END; FETCH NEXT FROM c_ca2 INTO @ca_arm; END; CLOSE c_ca2; DEALLOCATE c_ca2; END; END ELSE BEGIN -- Field reference; strip property-function suffixes so the base name -- is used for metadata resolution (.$length, .$count, [].$count). DECLARE @raw_path NVARCHAR(400) = @k; DECLARE @field_path NVARCHAR(400) = @k; IF RIGHT(@field_path, 9) = N'[].$count' SET @field_path = LEFT(@field_path, LEN(@field_path) - 9); ELSE IF RIGHT(@field_path, 8) = N'.$length' SET @field_path = LEFT(@field_path, LEN(@field_path) - 8); ELSE IF RIGHT(@field_path, 7) = N'.$count' SET @field_path = LEFT(@field_path, LEN(@field_path) - 7); DECLARE @opv NVARCHAR(MAX) = NULL; IF RIGHT(@raw_path, 12) = N'.ContainsKey' SET @opv = dbo.pvt_peek_contains_key_value(@v); IF @first = 0 SET @out = @out + N','; SET @out = @out + N'{"path":' + dbo.pvt_json_string_or_null(@field_path) + N',"op_value":' + dbo.pvt_json_string_or_null(@opv) + N'}'; SET @first = 0; END; FETCH NEXT FROM c_keys INTO @k, @v, @t; END; CLOSE c_keys; DEALLOCATE c_keys; SET @out = @out + N']'; RETURN @out; END; GO -- ---------- pvt_collect_fields ---------------------------------------- -- Resolves metadata for every field referenced in filter/order JSON. -- Returns JSON object {field_name: }. -- ContainsKey-rewritten entries carry "was_contains_key": true. CREATE OR ALTER FUNCTION dbo.pvt_collect_fields( @scheme_id BIGINT, @filter NVARCHAR(MAX), @order NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN N'{}'; DECLARE @seen TABLE (name NVARCHAR(400) PRIMARY KEY, meta NVARCHAR(MAX) NOT NULL); -- ---- From filter (via extract_field_pairs) ---- DECLARE @pairs NVARCHAR(MAX) = dbo.pvt_extract_field_pairs(@filter); IF @pairs IS NOT NULL AND @pairs <> N'[]' BEGIN DECLARE c_p CURSOR LOCAL FAST_FORWARD FOR SELECT JSON_VALUE([value], '$.path'), JSON_VALUE([value], '$.op_value') FROM OPENJSON(@pairs); DECLARE @path NVARCHAR(400), @opv NVARCHAR(MAX); OPEN c_p; FETCH NEXT FROM c_p INTO @path, @opv; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @norm NVARCHAR(400) = dbo.pvt_normalize_field_name(@path, @opv); IF NOT EXISTS (SELECT 1 FROM @seen WHERE name = @norm) BEGIN DECLARE @meta NVARCHAR(MAX) = dbo.pvt_resolve_field_path(@scheme_id, @norm); IF @meta IS NOT NULL BEGIN IF @norm <> @path SET @meta = LEFT(@meta, LEN(@meta) - 1) + N',"was_contains_key":true}'; INSERT INTO @seen(name, meta) VALUES (@norm, @meta); END; END; FETCH NEXT FROM c_p INTO @path, @opv; END; CLOSE c_p; DEALLOCATE c_p; END; -- ---- From order (plain {field|field_path}; also walks $expr nodes) ---- IF @order IS NOT NULL AND ISJSON(@order) = 1 BEGIN DECLARE c_o CURSOR LOCAL FAST_FORWARD FOR SELECT COALESCE(JSON_VALUE([value], '$.field'), JSON_VALUE([value], '$.field_path')), JSON_QUERY([value], '$."$expr"') FROM OPENJSON(@order); DECLARE @ofp NVARCHAR(400), @oexpr NVARCHAR(MAX); OPEN c_o; FETCH NEXT FROM c_o INTO @ofp, @oexpr; WHILE @@FETCH_STATUS = 0 BEGIN IF @ofp IS NOT NULL AND NOT EXISTS (SELECT 1 FROM @seen WHERE name = @ofp) BEGIN DECLARE @ometa NVARCHAR(MAX) = dbo.pvt_resolve_field_path(@scheme_id, @ofp); IF @ometa IS NOT NULL INSERT INTO @seen(name, meta) VALUES (@ofp, @ometa); END; IF @oexpr IS NOT NULL BEGIN DECLARE @oepairs NVARCHAR(MAX) = dbo.pvt_extract_field_pairs(@oexpr); IF @oepairs IS NOT NULL AND @oepairs <> N'[]' BEGIN DECLARE c_oe CURSOR LOCAL FAST_FORWARD FOR SELECT JSON_VALUE([value], '$.path'), JSON_VALUE([value], '$.op_value') FROM OPENJSON(@oepairs); DECLARE @oepath NVARCHAR(400), @oeopv NVARCHAR(MAX); OPEN c_oe; FETCH NEXT FROM c_oe INTO @oepath, @oeopv; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @oenorm NVARCHAR(400) = dbo.pvt_normalize_field_name(@oepath, @oeopv); IF NOT EXISTS (SELECT 1 FROM @seen WHERE name = @oenorm) BEGIN DECLARE @oemeta NVARCHAR(MAX) = dbo.pvt_resolve_field_path(@scheme_id, @oenorm); IF @oemeta IS NOT NULL BEGIN IF @oenorm <> @oepath SET @oemeta = LEFT(@oemeta, LEN(@oemeta) - 1) + N',"was_contains_key":true}'; INSERT INTO @seen(name, meta) VALUES (@oenorm, @oemeta); END; END; FETCH NEXT FROM c_oe INTO @oepath, @oeopv; END; CLOSE c_oe; DEALLOCATE c_oe; END; END; FETCH NEXT FROM c_o INTO @ofp, @oexpr; END; CLOSE c_o; DEALLOCATE c_o; END; DECLARE @out NVARCHAR(MAX) = N'{'; DECLARE @first BIT = 1; DECLARE c_s CURSOR LOCAL FAST_FORWARD FOR SELECT name, meta FROM @seen ORDER BY name; DECLARE @n NVARCHAR(400), @m NVARCHAR(MAX); OPEN c_s; FETCH NEXT FROM c_s INTO @n, @m; WHILE @@FETCH_STATUS = 0 BEGIN IF @first = 0 SET @out = @out + N','; SET @out = @out + dbo.pvt_json_string_or_null(@n) + N':' + @m; SET @first = 0; FETCH NEXT FROM c_s INTO @n, @m; END; CLOSE c_s; DEALLOCATE c_s; SET @out = @out + N'}'; RETURN @out; END; GO -- ---------- pvt_has_absence_check ------------------------------------- -- Strict subset of "has null check": returns 1 only for predicates that -- require detecting absent _values rows ($null/$isNull/$exists/{$eq:null}). -- $notNull / {$ne:null} are NOT flagged (INNER JOIN already drops absent). CREATE OR ALTER FUNCTION dbo.pvt_has_absence_check(@filter NVARCHAR(MAX)) RETURNS BIT AS BEGIN IF @filter IS NULL OR ISJSON(@filter) = 0 RETURN 0; DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@filter); DECLARE @k NVARCHAR(400), @v NVARCHAR(MAX), @t INT; DECLARE @hit BIT = 0; OPEN c; FETCH NEXT FROM c INTO @k, @v, @t; WHILE @@FETCH_STATUS = 0 AND @hit = 0 BEGIN IF LEFT(@k, 1) = N'$' BEGIN IF LOWER(@k) IN (N'$null', N'$isnull', N'$exists') SET @hit = 1; ELSE IF @t = 4 -- array BEGIN DECLARE c_a CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@v); DECLARE @e NVARCHAR(MAX); OPEN c_a; FETCH NEXT FROM c_a INTO @e; WHILE @@FETCH_STATUS = 0 AND @hit = 0 BEGIN IF dbo.pvt_has_absence_check(@e) = 1 SET @hit = 1; FETCH NEXT FROM c_a INTO @e; END; CLOSE c_a; DEALLOCATE c_a; END ELSE IF @t = 5 -- object IF dbo.pvt_has_absence_check(@v) = 1 SET @hit = 1; END ELSE BEGIN IF @t = 5 -- object operand BEGIN DECLARE c_op CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@v); DECLARE @sk NVARCHAR(400), @sv NVARCHAR(MAX), @st INT; OPEN c_op; FETCH NEXT FROM c_op INTO @sk, @sv, @st; WHILE @@FETCH_STATUS = 0 AND @hit = 0 BEGIN IF LOWER(@sk) IN (N'$null', N'$isnull', N'$exists') SET @hit = 1; ELSE IF LOWER(@sk) = N'$eq' AND @st = 0 -- null literal SET @hit = 1; FETCH NEXT FROM c_op INTO @sk, @sv, @st; END; CLOSE c_op; DEALLOCATE c_op; END ELSE IF @t = 0 -- null literal directly SET @hit = 1; END; FETCH NEXT FROM c INTO @k, @v, @t; END; CLOSE c; DEALLOCATE c; RETURN @hit; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/11_pvt_column_expr.sql ---- -- ===================================================================== -- 11_pvt_column_expr.sql (MSSql) -- --------------------------------------------------------------------- -- Build a single SELECT-list expression for the PVT pivot CTE. -- Mirrors PG v2-pvt/11_pvt_column_expr.sql. -- -- T-SQL replaces PG's `(array_agg(v.) FILTER (WHERE ...))[1]` -- idiom with a correlated subquery that returns the matching value. -- For arrays we use `(SELECT ... FOR JSON PATH)` to materialize a -- JSON array of values (caller decides how to parse it). -- -- Functions: -- dbo.pvt_db_type_to_value_column(@db_type NVARCHAR(64)) -- -> NVARCHAR(64) | NULL -- dbo.pvt_build_column_expr(@field_name NVARCHAR(400), -- @field_meta NVARCHAR(MAX)) -- FieldInfo JSON -- -> NVARCHAR(MAX) -- T-SQL fragment for the outer SELECT list -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_db_type_to_value_column ---------------------------------- -- Maps a logical db_type to the physical typed column name on _values. -- Returns NULL if the type is unknown. CREATE OR ALTER FUNCTION dbo.pvt_db_type_to_value_column(@db_type NVARCHAR(64)) RETURNS NVARCHAR(64) AS BEGIN RETURN CASE @db_type WHEN N'String' THEN N'_String' WHEN N'Long' THEN N'_Long' WHEN N'Double' THEN N'_Double' WHEN N'Numeric' THEN N'_Numeric' WHEN N'Boolean' THEN N'_Boolean' WHEN N'Guid' THEN N'_Guid' WHEN N'DateTimeOffset' THEN N'_DateTimeOffset' WHEN N'ByteArray' THEN N'_ByteArray' WHEN N'ListItem' THEN N'_ListItem' WHEN N'Object' THEN N'_Object' WHEN N'TimeSpan' THEN N'_Long' -- Ticks WHEN N'TimeOnly' THEN N'_Long' -- Ticks WHEN N'DateTime' THEN N'_DateTimeOffset' ELSE NULL END; END; GO -- ---------- pvt_build_column_expr ---------------------------------------- -- Build one SELECT-list expression for the PVT inner pivot scan. -- -- Mirrors PG `pvt_build_column_expr` Pro-shape: scalars become -- `MAX(CASE WHEN v._id_structure = AND v._array_index IS NULL -- THEN v. END) AS [field]` aggregates over a single -- `LEFT JOIN _values v ON v._id_object = o._id` scan. Arrays remain -- correlated `(SELECT ... FOR JSON PATH)` subqueries because MAX -- collapses arrays and loses order. -- -- Output context: the inner pivot SELECT body emitted by -- pvt_build_cte_sql, with one or two scans available: -- * `v` : dbo._values, the pivot source (always present) -- * `li` : dbo._list_items, LEFT JOIN'd by pvt_build_cte_sql when -- any field is ListItem.Value/.Alias -- -- Output examples (alias = QUOTENAME(field_name)): -- base: o.[_id_parent] AS [ParentId] -- scalar prop: MAX(CASE WHEN v.[_id_structure] = 42 AND v.[_array_index] IS NULL THEN v.[_Long] END) AS [Age] -- array prop: (SELECT v2.[_Long] FROM dbo._values v2 -- WHERE v2._id_object = v.[_id_object] AND v2._id_structure = 42 -- AND v2._array_index IS NOT NULL -- ORDER BY v2._array_index FOR JSON PATH) AS [Tags] -- simple dict[home]: MAX(CASE WHEN v.[_id_structure] = 42 AND v.[_array_index] = N'home' THEN v.[_String] END) AS [PhoneBook[home]] -- ListItem.Value: MAX(CASE WHEN v.[_id_structure] = 42 AND v.[_array_index] IS NULL THEN li.[_value] END) AS [Status] -- ListItem.Id: MAX(CASE WHEN v.[_id_structure] = 42 AND v.[_array_index] IS NULL THEN v.[_ListItem] END) AS [StatusId] -- -- @array_index_in_outer (Pro parity): when 1, drop `AND v._array_index IS NULL` -- from the scalar CASE filter; caller hoists the index predicate to an -- outer WHERE for inline-pivot shape. Defaults to 0 (CTE-style). -- -- Nested-dict fields (parent_sid AND dict_key) return NULL: they are -- handled via a side CTE emitted by pvt_build_cte_sql (Stage 3 of the -- MSSql port). CREATE OR ALTER FUNCTION dbo.pvt_build_column_expr( @field_name NVARCHAR(400), @field_meta NVARCHAR(MAX), @array_index_in_outer BIT = 0, @row_ref NVARCHAR(40) = N'o.[_id]' ) RETURNS NVARCHAR(MAX) AS BEGIN IF @field_meta IS NULL OR ISJSON(@field_meta) = 0 RETURN N'/* pvt_build_column_expr: meta is NULL or not JSON for field "' + ISNULL(@field_name, N'') + N'" */'; DECLARE @kind NVARCHAR(32) = JSON_VALUE(@field_meta, N'$.kind'); DECLARE @li_prop NVARCHAR(32) = JSON_VALUE(@field_meta, N'$.list_item_prop'); DECLARE @dict_key NVARCHAR(400) = JSON_VALUE(@field_meta, N'$.dict_key'); DECLARE @parent_sid NVARCHAR(32) = JSON_VALUE(@field_meta, N'$.parent_sid'); DECLARE @is_array_s NVARCHAR(10) = JSON_VALUE(@field_meta, N'$.is_array'); DECLARE @is_array bit = CASE WHEN @is_array_s = N'true' THEN 1 ELSE 0 END; DECLARE @alias NVARCHAR(420) = QUOTENAME(@field_name); -- ---- Base field: straight projection from _objects. ------------- IF @kind = N'base' BEGIN DECLARE @col NVARCHAR(64) = JSON_VALUE(@field_meta, N'$.column'); RETURN N'o.' + QUOTENAME(@col) + N' AS ' + @alias; END; DECLARE @sid NVARCHAR(32) = JSON_VALUE(@field_meta, N'$.sid'); DECLARE @db_type NVARCHAR(64) = JSON_VALUE(@field_meta, N'$.db_type'); -- ---- Nested-dict: handled by side CTE (Stage 3); caller skips. -- IF @parent_sid IS NOT NULL AND @dict_key IS NOT NULL RETURN NULL; -- Scalar CASE filter prefix. Drop _array_index predicate when -- caller hoists it to an outer WHERE (inline-pivot Pro parity). DECLARE @scalar_filter NVARCHAR(200) = N'v.[_id_structure] = ' + @sid + CASE WHEN @array_index_in_outer = 1 THEN N'' ELSE N' AND v.[_array_index] IS NULL' END; -- ---- ListItem.Value (scalar via li join, array via correlated) -- IF @li_prop = N'Value' BEGIN IF @is_array = 1 RETURN N'(SELECT li2.[_value] FROM dbo._values v2' + N' JOIN dbo._list_items li2 ON li2._id = v2.[_ListItem]' + N' WHERE v2._id_object = ' + @row_ref + N' AND v2._id_structure = ' + @sid + N' AND v2._array_index IS NOT NULL' + N' ORDER BY v2._array_index FOR JSON PATH) AS ' + @alias; RETURN N'MAX(CASE WHEN ' + @scalar_filter + N' THEN li.[_value] END) AS ' + @alias; END; -- ---- ListItem.Alias (scalar via li join, array via correlated) -- IF @li_prop = N'Alias' BEGIN IF @is_array = 1 RETURN N'(SELECT li2.[_alias] FROM dbo._values v2' + N' JOIN dbo._list_items li2 ON li2._id = v2.[_ListItem]' + N' WHERE v2._id_object = ' + @row_ref + N' AND v2._id_structure = ' + @sid + N' AND v2._array_index IS NOT NULL' + N' ORDER BY v2._array_index FOR JSON PATH) AS ' + @alias; RETURN N'MAX(CASE WHEN ' + @scalar_filter + N' THEN li.[_alias] END) AS ' + @alias; END; -- ---- Resolve typed column --------------------------------------- DECLARE @vcol NVARCHAR(64) = dbo.pvt_db_type_to_value_column(@db_type); IF @vcol IS NULL RETURN N'/* pvt_build_column_expr: unsupported db_type "' + ISNULL(@db_type, N'') + N'" for field "' + @field_name + N'" */'; -- ListItem.Id: project the foreign key column itself (bigint). IF @li_prop = N'Id' SET @vcol = N'_ListItem'; -- ---- Simple dictionary: PhoneBook[home] --> _array_index='' IF @dict_key IS NOT NULL AND @parent_sid IS NULL BEGIN DECLARE @dict_lit NVARCHAR(MAX) = N'N''' + REPLACE(@dict_key, N'''', N'''''') + N''''; IF @vcol = N'_Boolean' RETURN N'CONVERT(BIT, MAX(CASE WHEN v.[_id_structure] = ' + @sid + N' AND v.[_array_index] = ' + @dict_lit + N' THEN CAST(v.[_Boolean] AS TINYINT) END)) AS ' + @alias; RETURN N'MAX(CASE WHEN v.[_id_structure] = ' + @sid + N' AND v.[_array_index] = ' + @dict_lit + N' THEN v.' + QUOTENAME(@vcol) + N' END) AS ' + @alias; END; -- ---- Array pivot: correlated FOR JSON PATH subquery ------------- IF @is_array = 1 RETURN N'(SELECT v2.' + QUOTENAME(@vcol) + N' FROM dbo._values v2' + N' WHERE v2._id_object = ' + @row_ref + N' AND v2._id_structure = ' + @sid + N' AND v2._array_index IS NOT NULL' + N' ORDER BY v2._array_index FOR JSON PATH) AS ' + @alias; -- ---- Scalar pivot: MAX(CASE WHEN ... THEN v. END) ---------- IF @vcol = N'_Boolean' RETURN N'CONVERT(BIT, MAX(CASE WHEN ' + @scalar_filter + N' THEN CAST(v.[_Boolean] AS TINYINT) END)) AS ' + @alias; RETURN N'MAX(CASE WHEN ' + @scalar_filter + N' THEN v.' + QUOTENAME(@vcol) + N' END) AS ' + @alias; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/12_pvt_cte_builder.sql ---- -- ===================================================================== -- 12_pvt_cte_builder.sql (MSSql v2-pvt) — Pro-shape pivot body -- --------------------------------------------------------------------- -- Build the INNER pivot SELECT body (NO `WITH _pvt_cte AS (...)` wrap, -- NO alias). T-SQL forbids `WITH` inside a subquery, so unlike PG we -- return ONLY the SELECT body and let every orchestrator wrap it as a -- derived table: `FROM () _pvt_cte`. -- -- Two pivot shapes (Pro parity, mirrors PG 12): -- -- WIDE (default, projects every _objects base col): -- SELECT -- o.[_id], ... <21 base cols>, -- MAX(CASE WHEN v._id_structure = AND v._array_index IS NULL -- THEN v. END) AS [Field1], -- ... -- FROM dbo._objects o -- JOIN dbo._values v ON v._id_object = o._id -- [LEFT JOIN dbo._list_items li ON li._id = v._ListItem] -- WHERE o._id_scheme = [AND ] -- GROUP BY o.[_id], ... <21 base cols> -- -- NARROW (Pro-shape, when @narrow=1 AND @force_outer=0 AND there are -- pivot sids AND no nested-dict groups): -- SELECT -- v._id_object, -- MAX(CASE WHEN ... THEN v. END) AS [Field1], -- ... -- FROM dbo._values v [LEFT JOIN dbo._list_items li ...] -- WHERE v._id_structure IN (, , ...) -- AND v._id_object IN (SELECT o.[_id] FROM dbo._objects o -- WHERE o.[_id_scheme] = -- [AND ]) -- GROUP BY v._id_object -- -- Narrow drops the heavy GROUP BY (1 col vs 21), narrows the _values -- scan via the structure-id index, and lets the planner prune by base -- predicates BEFORE touching _values. Outer SELECT in the orchestrator -- MUST `JOIN dbo._objects o ON o._id = _pvt_cte._id_object` to expose -- base columns when narrow is chosen. -- -- WARNING (T-SQL, by design): wide-shape GROUP BY includes _objects -- columns of MAX-types (_note NVARCHAR(MAX), _value_string NVARCHAR(MAX), -- _value_bytes VARBINARY(MAX)). T-SQL forbids GROUP BY on those, so a -- scheme that touches one of those base cols via a pivot field will -- fail at execution time. Mirrors PG by design — caller's responsibility. -- Use narrow shape to dodge entirely (groups by v._id_object only). -- -- Tree modes (tree / tree_descendants / tree_children / tree_roots / -- tree_leaves / tree_ancestors) and nested-dict side CTEs are deferred -- to Stage 2 and Stage 3 of the MSSql port. Caller passing -- @source_mode <> 'flat' (or schemes with nested-dict accessors) get -- the wide shape with those fields silently dropped from the pivot. -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.pvt_build_cte_sql( @scheme_id BIGINT, @fields NVARCHAR(MAX), @source_mode NVARCHAR(50) = N'flat', @tree_ids NVARCHAR(MAX) = NULL, -- JSON array of bigints (Stage 2) @max_depth INT = NULL, @force_outer BIT = 1, @extra_where NVARCHAR(MAX) = NULL, -- Pro-style base-field pushdown @narrow BIT = 0, @include_seed BIT = 1, -- tree mode (Stage 2) @polymorphic BIT = 1, -- tree mode (Stage 2) @residual_where NVARCHAR(MAX) = NULL -- post-pivot WHERE wrap (Pro parity) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN NULL; IF @source_mode IS NULL SET @source_mode = N'flat'; IF @source_mode NOT IN (N'flat', N'tree', N'tree_descendants', N'tree_children', N'tree_roots', N'tree_leaves', N'tree_ancestors') RETURN NULL; -- ------ Tree-mode object-set restriction -------------------------- -- Builds @tree_filter as an `o.[_id] IN (SELECT _id FROM dbo.pvt_tree_(...))` -- predicate. Wide shape ANDs it into the WHERE; narrow shape folds -- it into the inner IN-subquery so the recursive walk runs BEFORE -- the _values scan. T-SQL forbids `WITH` inside a subquery, so the -- recursive CTEs live inside the multi-statement TVFs defined in -- 08_pvt_tree_functions.sql. DECLARE @tree_filter NVARCHAR(MAX) = N''; IF @source_mode <> N'flat' BEGIN DECLARE @seed_arg NVARCHAR(MAX) = CASE WHEN @tree_ids IS NULL THEN N'NULL' ELSE N'N''' + REPLACE(@tree_ids, N'''', N'''''') + N'''' END; DECLARE @scheme_arg NVARCHAR(40) = CAST(@scheme_id AS NVARCHAR(40)); DECLARE @depth_arg NVARCHAR(20) = CASE WHEN @max_depth IS NULL THEN N'NULL' ELSE CAST(@max_depth AS NVARCHAR(20)) END; DECLARE @poly_arg NVARCHAR(1) = CASE WHEN @polymorphic = 0 THEN N'0' ELSE N'1' END; DECLARE @seed_inc NVARCHAR(1) = CASE WHEN @include_seed = 0 THEN N'0' ELSE N'1' END; IF @source_mode IN (N'tree', N'tree_descendants') BEGIN IF @tree_ids IS NULL RETURN NULL; -- seed required SET @tree_filter = N'o.[_id] IN (SELECT _id FROM dbo.pvt_tree_descendants(' + @scheme_arg + N', ' + @seed_arg + N', ' + @depth_arg + N', ' + @poly_arg + N', ' + @seed_inc + N'))'; END ELSE IF @source_mode = N'tree_children' BEGIN IF @tree_ids IS NULL RETURN NULL; SET @tree_filter = N'o.[_id] IN (SELECT _id FROM dbo.pvt_tree_children(' + @scheme_arg + N', ' + @seed_arg + N', ' + @poly_arg + N'))'; END ELSE IF @source_mode = N'tree_roots' BEGIN SET @tree_filter = N'o.[_id] IN (SELECT _id FROM dbo.pvt_tree_roots(' + @scheme_arg + N', ' + @seed_arg + N'))'; END ELSE IF @source_mode = N'tree_leaves' BEGIN SET @tree_filter = N'o.[_id] IN (SELECT _id FROM dbo.pvt_tree_leaves(' + @scheme_arg + N', ' + @seed_arg + N'))'; -- Down to a depth: the leaves of the whole tree that lie within it; pvt_tree_leaves walks without one. IF @tree_ids IS NOT NULL AND @max_depth IS NOT NULL SET @tree_filter += N' AND o.[_id] IN (SELECT _id FROM dbo.pvt_tree_descendants(' + @scheme_arg + N', ' + @seed_arg + N', ' + @depth_arg + N', ' + @poly_arg + N', 0))'; END ELSE IF @source_mode = N'tree_ancestors' BEGIN IF @tree_ids IS NULL RETURN NULL; SET @tree_filter = N'o.[_id] IN (SELECT _id FROM dbo.pvt_tree_ancestors(' + @scheme_arg + N', ' + @seed_arg + N', ' + @depth_arg + N', ' + @poly_arg + N'))'; END; END; DECLARE @base_cols NVARCHAR(MAX) = N'o.[_id], o.[_id_parent], o.[_id_scheme], o.[_id_owner], o.[_id_who_change], ' + N'o.[_name], o.[_date_create], o.[_date_modify], o.[_date_begin], o.[_date_complete], ' + N'o.[_key], o.[_note], o.[_hash], ' + N'o.[_value_long], o.[_value_string], o.[_value_guid], o.[_value_bool], ' + N'o.[_value_double], o.[_value_numeric], o.[_value_datetime], o.[_value_bytes], o.[_value_unique]'; -- Iterate field metadata: collect pivot sids, exprs, aliases. DECLARE @pivot_cols NVARCHAR(MAX) = N''; DECLARE @pivot_aliases NVARCHAR(MAX) = N''; -- comma-sep QUOTENAME'd DECLARE @sids NVARCHAR(MAX) = N''; -- comma-sep bigints DECLARE @has_listitem BIT = 0; DECLARE @has_nested BIT = 0; -- Per-(parent_sid, dict_key) nested-dict field bucket. Mirrors -- PG v_nested_groups: each row is one nested-dict child field to -- be projected from a per-group derived table (Pro parity, see -- redb.Postgres/sql/v2-pvt/12_pvt_cte_builder.sql nested_dict_N). DECLARE @nested_tbl TABLE( parent_sid NVARCHAR(40), dict_key NVARCHAR(400), field_sid NVARCHAR(40), db_column NVARCHAR(50), is_array BIT, field_name NVARCHAR(400) ); -- First pass: detect nested-dict presence so the second pass below -- can pick the correct row-reference for pvt_build_column_expr -- (`v.[_id_object]` for pure-narrow vs `o.[_id]` for wide / -- narrow-with-nested). Without this, the order of fields in -- OPENJSON could leave a stale row-ref baked into @pivot_cols. IF @fields IS NOT NULL AND ISJSON(@fields) = 1 AND @fields <> N'{}' BEGIN IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.parent_sid') IS NOT NULL AND JSON_VALUE([value], N'$.dict_key') IS NOT NULL ) SET @has_nested = 1; END; -- narrow_nest = the slim shape that keeps FROM _objects o (so nested -- LEFT JOINs on o.[_id] still resolve) but collapses GROUP BY to a -- single column. Outer SELECT JOINs _objects via _id_object alias. DECLARE @narrow_nest BIT = CASE WHEN @narrow = 1 AND @has_nested = 1 THEN 1 ELSE 0 END; DECLARE @row_ref NVARCHAR(20) = CASE WHEN @narrow = 1 AND @has_nested = 0 THEN N'v.[_id_object]' ELSE N'o.[_id]' END; IF @fields IS NOT NULL AND ISJSON(@fields) = 1 AND @fields <> N'{}' BEGIN DECLARE @fname NVARCHAR(400), @fmeta NVARCHAR(MAX); DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value] FROM OPENJSON(@fields); OPEN c; FETCH NEXT FROM c INTO @fname, @fmeta; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @kind NVARCHAR(32) = JSON_VALUE(@fmeta, N'$.kind'); DECLARE @lenmod NVARCHAR(10) = JSON_VALUE(@fmeta, N'$.length_modifier'); DECLARE @fsid NVARCHAR(32) = JSON_VALUE(@fmeta, N'$.sid'); DECLARE @fparent_sid NVARCHAR(32) = JSON_VALUE(@fmeta, N'$.parent_sid'); DECLARE @fdict_key NVARCHAR(400) = JSON_VALUE(@fmeta, N'$.dict_key'); DECLARE @fli_prop NVARCHAR(32) = JSON_VALUE(@fmeta, N'$.list_item_prop'); -- Base cols are already in @base_cols; modifier-only entries -- (.$length / .$count) project no col of their own. IF @kind = N'base' OR @lenmod = N'true' BEGIN FETCH NEXT FROM c INTO @fname, @fmeta; CONTINUE; END; -- Nested-dict (parent_sid + dict_key): collected per group -- and projected from a derived table joined on _id_object. -- Pro parity: see PG nested_dict_N CTE in 12_pvt_cte_builder.sql. IF @fparent_sid IS NOT NULL AND @fdict_key IS NOT NULL BEGIN SET @has_nested = 1; INSERT INTO @nested_tbl(parent_sid, dict_key, field_sid, db_column, is_array, field_name) VALUES( @fparent_sid, @fdict_key, @fsid, JSON_VALUE(@fmeta, N'$.db_column'), CASE WHEN JSON_VALUE(@fmeta, N'$.is_array') = N'true' THEN 1 ELSE 0 END, @fname); FETCH NEXT FROM c INTO @fname, @fmeta; CONTINUE; END; -- Collect sid for narrow-shape IN (...) filter. Skip nested -- children (parent_sid set: they project from a side CTE -- scoped to the parent dict row, not the main _values scan). -- Simple-dict (dict_key set, parent_sid NULL) keep their sid -- because pvt_build_column_expr's CASE reads straight from -- the main scan with _array_index = '' filter. IF @fsid IS NOT NULL AND @fparent_sid IS NULL BEGIN IF @sids = N'' SET @sids = @fsid; ELSE SET @sids = @sids + N', ' + @fsid; END; DECLARE @expr NVARCHAR(MAX) = dbo.pvt_build_column_expr(@fname, @fmeta, 0, @row_ref); IF @expr IS NOT NULL BEGIN SET @pivot_cols = @pivot_cols + N',' + CHAR(13) + CHAR(10) + N' ' + @expr; DECLARE @qalias NVARCHAR(420) = QUOTENAME(@fname); IF @pivot_aliases = N'' SET @pivot_aliases = @qalias; ELSE SET @pivot_aliases = @pivot_aliases + N', ' + @qalias; END; IF @fli_prop IN (N'Value', N'Alias') SET @has_listitem = 1; FETCH NEXT FROM c INTO @fname, @fmeta; END; CLOSE c; DEALLOCATE c; END; -- 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. DECLARE @join_kind NVARCHAR(20) = N'LEFT JOIN'; DECLARE @li_join NVARCHAR(MAX) = CASE WHEN @has_listitem = 1 THEN CHAR(13) + CHAR(10) + N' LEFT JOIN dbo._list_items li ON li.[_id] = v.[_ListItem]' ELSE N'' END; -- Pushdown predicates assembled early so nested derived tables can -- fold them into their own IN-subquery on _objects (Pro parity). DECLARE @extra_pred NVARCHAR(MAX) = CASE WHEN @extra_where IS NOT NULL AND @extra_where <> N'' THEN N' AND ' + @extra_where ELSE N'' END; DECLARE @tree_pred NVARCHAR(MAX) = CASE WHEN @tree_filter <> N'' THEN N' AND ' + @tree_filter ELSE N'' END; -- ------ Nested-dict derived tables (Stage 2c.E, PG parity) ------- -- For each (parent_sid, dict_key) group, emit a derived table that -- joins the parent dict row (dp) to its child rows (nv via -- _array_parent_id) and projects one MAX-CASE per requested child -- field. The outer pivot LEFT JOINs the derived table on _id_object -- and projects each child column via MAX(ndN.col) so the existing -- GROUP BY stays valid. Mirrors PG nested_dict_N CTE -- in redb.Postgres/sql/v2-pvt/12_pvt_cte_builder.sql; scalar takes -- the single non-array row, array fields are aggregated via a -- correlated FOR JSON PATH subselect (no native array_agg). DECLARE @nested_joins NVARCHAR(MAX) = N''; IF @has_nested = 1 BEGIN DECLARE @group_idx INT = 0; DECLARE @g_parent NVARCHAR(40), @g_key NVARCHAR(400); DECLARE gc CURSOR LOCAL FAST_FORWARD FOR SELECT DISTINCT parent_sid, dict_key FROM @nested_tbl; OPEN gc; FETCH NEXT FROM gc INTO @g_parent, @g_key; WHILE @@FETCH_STATUS = 0 BEGIN SET @group_idx = @group_idx + 1; DECLARE @alias NVARCHAR(40) = N'nd' + CAST(@group_idx AS NVARCHAR(10)); DECLARE @inner_cols NVARCHAR(MAX) = N''; DECLARE @g_sid NVARCHAR(40), @g_col NVARCHAR(50), @g_arr BIT, @g_name NVARCHAR(400); DECLARE fc CURSOR LOCAL FAST_FORWARD FOR SELECT field_sid, db_column, is_array, field_name FROM @nested_tbl WHERE parent_sid = @g_parent AND dict_key = @g_key; OPEN fc; FETCH NEXT FROM fc INTO @g_sid, @g_col, @g_arr, @g_name; WHILE @@FETCH_STATUS = 0 BEGIN IF @g_arr = 1 BEGIN SET @inner_cols = @inner_cols + CASE WHEN @inner_cols = N'' THEN N'' ELSE N', ' END + N'(SELECT nv2.[' + @g_col + N']' + N' FROM dbo._values nv2' + N' WHERE nv2.[_array_parent_id] = MAX(dp.[_id])' + N' AND nv2.[_id_structure] = ' + @g_sid + N' AND nv2.[_array_index] IS NOT NULL' + N' ORDER BY nv2.[_array_index]' + N' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS ' + QUOTENAME(@g_name); END ELSE BEGIN SET @inner_cols = @inner_cols + CASE WHEN @inner_cols = N'' THEN N'' ELSE N', ' END + N'MAX(CASE WHEN nv.[_id_structure] = ' + @g_sid + N' AND nv.[_array_index] IS NULL THEN nv.[' + @g_col + N'] END) AS ' + QUOTENAME(@g_name); END; SET @pivot_cols = @pivot_cols + N',' + CHAR(13) + CHAR(10) + N' MAX(' + @alias + N'.' + QUOTENAME(@g_name) + N') AS ' + QUOTENAME(@g_name); IF @pivot_aliases = N'' SET @pivot_aliases = QUOTENAME(@g_name); ELSE SET @pivot_aliases = @pivot_aliases + N', ' + QUOTENAME(@g_name); FETCH NEXT FROM fc INTO @g_sid, @g_col, @g_arr, @g_name; END; CLOSE fc; DEALLOCATE fc; SET @nested_joins = @nested_joins + CHAR(13) + CHAR(10) + N' LEFT JOIN (' + N' SELECT dp.[_id_object], ' + @inner_cols + N' FROM dbo._values dp' + N' LEFT JOIN dbo._values nv ON nv.[_array_parent_id] = dp.[_id]' + N' WHERE dp.[_id_structure] = ' + @g_parent + N' AND dp.[_array_index] = N''' + REPLACE(@g_key, N'''', N'''''') + N'''' -- Pro-parity: schema (and any pushdown predicates) folds -- into the nested CTE itself so the planner can prune dp -- rows by _id_scheme BEFORE the LEFT JOIN nv expands. -- Mirrors PG PRO 12_pvt_cte_builder.sql nested_dict_N. + N' AND dp.[_id_object] IN (SELECT o.[_id] FROM dbo._objects o' + N' WHERE o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + @extra_pred + @tree_pred + N')' + N' GROUP BY dp.[_id_object]' + N' ) ' + @alias + N' ON ' + @alias + N'.[_id_object] = o.[_id]'; FETCH NEXT FROM gc INTO @g_parent, @g_key; END; CLOSE gc; DEALLOCATE gc; END; DECLARE @body NVARCHAR(MAX); -- ------ Narrow Pro-shape ----------------------------------------- -- Eligible when: narrow flag set, no forced outer, no nested-dict groups, and at least one pivot sid was -- collected. The pivot of the value rows (p), and every object of the source (scheme, base pushdown, tree -- restriction) 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 keeps the pivot as fast as it was (see the PG module). IF @narrow = 1 AND @force_outer = 0 AND @has_nested = 0 AND @sids <> N'' BEGIN DECLARE @obj_where NVARCHAR(MAX) = N'o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + @extra_pred + @tree_pred; -- A tree source: the walk (a multi-statement function) is called once, in the WHERE of the objects, and each -- object reads its values through OUTER APPLY. With the pivot joined to the objects the walk ran twice, once -- per side, and a filter over a 100 thousand node subtree took 3.3 s instead of 1.8 s. IF @tree_filter <> N'' SET @body = N'SELECT o.[_id] AS [_id_object], p.' + REPLACE(@pivot_aliases, N', ', N', p.') + CHAR(13) + CHAR(10) + N' FROM dbo._objects o' + CHAR(13) + CHAR(10) + N' OUTER APPLY (' -- Array columns are subqueries on the row's object: here that is the outer object, not v. + CHAR(13) + CHAR(10) + N' SELECT' + STUFF(REPLACE(@pivot_cols, N'v.[_id_object]', N'o.[_id]'), 1, 1, N'') + CHAR(13) + CHAR(10) + N' FROM dbo._values v' + @li_join + CHAR(13) + CHAR(10) + N' WHERE v.[_id_object] = o.[_id] AND v.[_id_structure] IN (' + @sids + N')' + CHAR(13) + CHAR(10) + N' ) p' + CHAR(13) + CHAR(10) + N' WHERE ' + @obj_where; ELSE SET @body = N'SELECT o.[_id] AS [_id_object], p.' + REPLACE(@pivot_aliases, N', ', N', p.') + CHAR(13) + CHAR(10) + N' FROM dbo._objects o' + CHAR(13) + CHAR(10) + N' LEFT JOIN (' + CHAR(13) + CHAR(10) + N' SELECT' + CHAR(13) + CHAR(10) + N' v.[_id_object]' + @pivot_cols + CHAR(13) + CHAR(10) + N' FROM dbo._values v' + @li_join + CHAR(13) + CHAR(10) + N' WHERE v.[_id_structure] IN (' + @sids + N')' + CHAR(13) + CHAR(10) + N' AND v.[_id_object] IN (SELECT o.[_id] FROM dbo._objects o WHERE ' + @obj_where + N')' + CHAR(13) + CHAR(10) + N' GROUP BY v.[_id_object]' + CHAR(13) + CHAR(10) + N' ) p ON p.[_id_object] = o.[_id]' + CHAR(13) + CHAR(10) + N' WHERE ' + @obj_where; END ELSE IF @narrow_nest = 1 AND @force_outer = 0 BEGIN -- ------ Narrow-with-nested Pro-shape --------------------------- -- Slim pivot for schemes that touch nested-dict accessors: keep -- FROM _objects o (nested LEFT JOIN binds to o.[_id]) but drop -- the 21-col base GROUP BY in favour of GROUP BY o.[_id]. The -- outer SELECT JOINs _objects via _pvt_cte.[_id_object] just -- like the regular narrow shape. Pivot CASEs already use -- @row_ref = 'o.[_id]' (set in the first pass above), so array -- sub-queries resolve correctly. DECLARE @where_nn NVARCHAR(MAX) = N'o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + @extra_pred + @tree_pred; -- Skip the main _values join entirely when nothing scalar-pivot -- needs it (@sids = ''). Without this, INNER JOIN _values v -- multiplies o rows by their _values cardinality only to be -- collapsed by the GROUP BY — pure overhead. Pro-parity: -- mirrors the standalone-nested branch in PG PRO 12. DECLARE @main_join_nn NVARCHAR(MAX) = CASE WHEN @sids = N'' THEN N'' ELSE CHAR(13) + CHAR(10) + N' ' + @join_kind + N' dbo._values v ON v.[_id_object] = o.[_id]' + @li_join END; SET @body = N'SELECT' + CHAR(13) + CHAR(10) + N' o.[_id] AS [_id_object]' + @pivot_cols + CHAR(13) + CHAR(10) + N' FROM dbo._objects o' + @main_join_nn + @nested_joins + CHAR(13) + CHAR(10) + N' WHERE ' + @where_nn + CHAR(13) + CHAR(10) + N' GROUP BY o.[_id]'; END ELSE BEGIN -- ------ Wide legacy -------------------------------------------- DECLARE @where NVARCHAR(MAX) = N'o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + @extra_pred + @tree_pred; SET @body = N'SELECT' + CHAR(13) + CHAR(10) + N' ' + @base_cols + @pivot_cols + CHAR(13) + CHAR(10) + N' FROM dbo._objects o' + CHAR(13) + CHAR(10) + N' ' + @join_kind + N' dbo._values v ON v.[_id_object] = o.[_id]' + @li_join + @nested_joins + CHAR(13) + CHAR(10) + N' WHERE ' + @where + CHAR(13) + CHAR(10) + N' GROUP BY ' + @base_cols; END; -- ------ 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 the inner pivot body lets the planner prune rows BEFORE -- the outer JOIN _objects (when narrow shape is in use). IF @residual_where IS NOT NULL AND @residual_where <> N'' AND @residual_where <> N'TRUE' BEGIN SET @body = N'SELECT pvt.* FROM (' + CHAR(13) + CHAR(10) + N' ' + @body + CHAR(13) + CHAR(10) + N' ) pvt WHERE ' + @residual_where; END; RETURN @body; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/13_pvt_condition.sql ---- -- ===================================================================== -- 13_pvt_condition.sql (MSSql v2-pvt) — single-leaf predicate builder -- --------------------------------------------------------------------- -- Functions: -- dbo.pvt_sql_string_literal(@val) -> NVARCHAR escape ' -> '' -- dbo.pvt_jsonb_to_sql_literal(@val NVARCHAR(MAX), @type INT) -- -> raw token (strings escaped + quoted, numbers bare, booleans 1/0) -- dbo.pvt_build_field_condition(@field_name, @field_meta, @op_json, @base_prefix) -- -> NVARCHAR(MAX) SQL fragment -- -- Slice operators (v0.1): -- $eq $ne $gt $gte $lt $lte -- $in $nin -- $like -- $startsWith $endsWith $contains -- $startsWithIgnoreCase $endsWithIgnoreCase $containsIgnoreCase -- $null $isNull $notNull $exists -- Scalar-literal shorthand: { Field: 5 } == { Field: { $eq: 5 } } -- -- Skipped: $regex/$iregex/$fts/$array*/length modifier. -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_sql_string_literal: escape and quote for T-SQL -------- CREATE OR ALTER FUNCTION dbo.pvt_sql_string_literal(@v NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN IF @v IS NULL RETURN N'NULL'; RETURN N'N''' + REPLACE(@v, N'''', N'''''') + N''''; END; GO -- ---------- pvt_like_escape: make a sugar operand LITERAL under LIKE -- -- BR-7 (2026-09-02): $startsWith/$endsWith/$contains (+IgnoreCase; field, dict, listitem, -- array and expression sugar) splice their operand into a LIKE pattern. The operand is a -- LITERAL by contract: '%'/'_' must not act as wildcards and '[' must not open a character -- class. Every escaped site pairs the pattern with ESCAPE '\'. The raw $like/$arrayMatches -- operators do NOT pass through here - their pattern belongs to the caller. CREATE OR ALTER FUNCTION dbo.pvt_like_escape(@v NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN RETURN REPLACE(REPLACE(REPLACE(REPLACE(@v, N'\', N'\\'), N'%', N'\%'), N'_', N'\_'), N'[', N'\['); END; GO -- ---------- pvt_jsonb_to_sql_literal ---------------------------------- -- @type follows OPENJSON convention: 0=null, 1=string, 2=number, 3=true/false, -- 4=array, 5=object. For arrays/objects, callers must use OPENJSON themselves. CREATE OR ALTER FUNCTION dbo.pvt_jsonb_to_sql_literal(@val NVARCHAR(MAX), @type INT) RETURNS NVARCHAR(MAX) AS BEGIN IF @val IS NULL OR @type = 0 RETURN N'NULL'; IF @type = 3 -- boolean: T-SQL has no boolean literal in expressions, use 1/0 RETURN CASE WHEN LOWER(@val) = N'true' THEN N'1' ELSE N'0' END; IF @type = 2 -- number RETURN @val; -- strings (1) or unspecified: quote RETURN dbo.pvt_sql_string_literal(@val); END; GO -- ---------- pvt_array_element_equals -------------------------------- -- Typed equality of an array element row `av` with a JSON value (@val as OPENJSON gives it, @val_type its -- OPENJSON type code). Shared by $arrayContains, $arrayFirst / $arrayLast and $arrayAt; it used to be copied -- into each of them. CREATE OR ALTER FUNCTION dbo.pvt_array_element_equals( @db_type NVARCHAR(50), @val NVARCHAR(MAX), @val_type INT ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @lit NVARCHAR(MAX) = dbo.pvt_jsonb_to_sql_literal(@val, @val_type); RETURN CASE @db_type WHEN N'Long' THEN N'av.[_Long] = CAST(' + @lit + N' AS BIGINT)' WHEN N'Double' THEN N'av.[_Double] = CAST(' + @lit + N' AS FLOAT)' WHEN N'Numeric' THEN N'av.[_Numeric] = CAST(' + @lit + N' AS DECIMAL(28,10))' WHEN N'Boolean' THEN N'av.[_Boolean] = ' + @lit WHEN N'DateTimeOffset' THEN N'av.[_DateTimeOffset] = CAST(' + @lit + N' AS DATETIMEOFFSET)' ELSE N'av.[_String] = ' + @lit END; END; GO -- ---------- pvt_build_field_condition --------------------------------- CREATE OR ALTER FUNCTION dbo.pvt_build_field_condition( @field_name NVARCHAR(400), @field_meta NVARCHAR(MAX), @op_json NVARCHAR(MAX), @op_type INT, -- OPENJSON type code of @op_json @base_prefix NVARCHAR(10) -- '' or 'o.' or '_pvt_cte.' ) RETURNS NVARCHAR(MAX) AS BEGIN IF @field_meta IS NULL RETURN NULL; DECLARE @kind NVARCHAR(50) = JSON_VALUE(@field_meta, '$.kind'); DECLARE @col_name NVARCHAR(100); IF @kind = N'base' SET @col_name = ISNULL(@base_prefix, N'') + QUOTENAME(JSON_VALUE(@field_meta, '$.column')); ELSE SET @col_name = QUOTENAME(@field_name); -- Array-operator support: resolve field metadata for _values lookups. DECLARE @sid NVARCHAR(32) = JSON_VALUE(@field_meta, N'$.sid'); DECLARE @db_type_f NVARCHAR(64) = JSON_VALUE(@field_meta, N'$.db_type'); -- Derive the outer table alias used in EXISTS subqueries against dbo._values. -- Shape A: base_prefix = 'o.' -> alias 'o' -- Shape C: base_prefix = '_pvt_cte.' -> alias '_pvt_cte' DECLARE @obj_alias NVARCHAR(50) = CASE WHEN @base_prefix = N'o.' THEN N'o' ELSE N'_pvt_cte' END; -- ---- Dictionary indexer: Field[key] or Field[key].NestedProp ---- -- When dict_key is set in field metadata, emit an EXISTS correlated -- subquery against dbo._values filtering both structure and _array_index. DECLARE @dict_key_val NVARCHAR(200) = JSON_VALUE(@field_meta, N'$.dict_key'); IF @dict_key_val IS NOT NULL AND (@base_prefix = N'_pvt_cte.' OR @base_prefix = N'o.') BEGIN -- Post-pivot context: dict-key field is materialized as a pivot column -- on _pvt_cte by the nested-dict CTE builder (12_pvt_cte_builder.sql). -- Reference that column directly instead of re-running an EXISTS over -- dbo._values, which would duplicate the lookup work the CTE already did. SET @col_name = N'_pvt_cte.' + QUOTENAME(@field_name); SET @dict_key_val = NULL; -- fall through to normal column-comparison flow END; IF @dict_key_val IS NOT NULL BEGIN DECLARE @dict_db_col NVARCHAR(200) = N'av.' + QUOTENAME(ISNULL(JSON_VALUE(@field_meta, N'$.db_column'), N'_String')); DECLARE @dict_key_esc NVARCHAR(400) = REPLACE(@dict_key_val, N'''', N''''''); DECLARE @dict_parent_sid NVARCHAR(32) = JSON_VALUE(@field_meta, N'$.parent_sid'); DECLARE @dict_exist_pfx NVARCHAR(MAX); IF @dict_parent_sid IS NOT NULL -- Nested dict: Foo[key].Child -> dp holds the dict key on parent_sid, -- av is the child row joined through _array_parent_id. SET @dict_exist_pfx = N'EXISTS (SELECT 1 FROM dbo._values dp' + N' INNER JOIN dbo._values av ON av._array_parent_id = dp._id' + N' WHERE dp._id_object = ' + @obj_alias + N'.[_id]' + N' AND dp._id_structure = ' + @dict_parent_sid + N' AND dp._array_index = N''' + @dict_key_esc + N'''' + N' AND av._id_structure = ' + COALESCE(@sid, dbo.pvt_fail(N'dictionary field "' + @field_name + N'" has no structure id')) + N' AND av._array_index IS NULL'; ELSE SET @dict_exist_pfx = N'EXISTS (SELECT 1 FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + COALESCE(@sid, dbo.pvt_fail(N'dictionary field "' + @field_name + N'" has no structure id')) + N' AND av._array_index = N''' + @dict_key_esc + N''''; -- Scalar-literal shorthand (non-object operand) IF @op_type <> 5 BEGIN IF @op_type = 0 RETURN @dict_exist_pfx + N' AND ' + @dict_db_col + N' IS NULL)'; RETURN @dict_exist_pfx + N' AND ' + @dict_db_col + N' = ' + dbo.pvt_jsonb_to_sql_literal(@op_json, @op_type) + N')'; END; -- Operator object: walk and AND-join DECLARE @dparts NVARCHAR(MAX) = N''; DECLARE @dcnt INT = 0; DECLARE c_dict CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@op_json); DECLARE @dok NVARCHAR(50), @dov NVARCHAR(MAX), @dot INT; OPEN c_dict; FETCH NEXT FROM c_dict INTO @dok, @dov, @dot; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @don NVARCHAR(50) = LOWER(@dok); DECLARE @dpiece NVARCHAR(MAX) = NULL; IF @don IN (N'$null', N'$isnull') SET @dpiece = CASE WHEN LOWER(@dov) = N'true' THEN N'NOT ' + @dict_exist_pfx + N')' ELSE @dict_exist_pfx + N')' END; ELSE IF @don IN (N'$notnull', N'$exists') SET @dpiece = CASE WHEN LOWER(@dov) = N'true' THEN @dict_exist_pfx + N')' ELSE N'NOT ' + @dict_exist_pfx + N')' END; ELSE IF @don IN (N'$eq', N'$ne', N'$gt', N'$gte', N'$lt', N'$lte') BEGIN DECLARE @dcmp NVARCHAR(4) = CASE @don WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' END; IF @dot = 0 SET @dpiece = CASE @don WHEN N'$eq' THEN @dict_exist_pfx + N' AND ' + @dict_db_col + N' IS NULL)' WHEN N'$ne' THEN @dict_exist_pfx + N' AND ' + @dict_db_col + N' IS NOT NULL)' ELSE @dict_exist_pfx + N' AND ' + @dict_db_col + N' ' + @dcmp + N' NULL)' END; ELSE SET @dpiece = @dict_exist_pfx + N' AND ' + @dict_db_col + N' ' + @dcmp + N' ' + dbo.pvt_jsonb_to_sql_literal(@dov, @dot) + N')'; END ELSE IF @don = N'$like' SET @dpiece = @dict_exist_pfx + N' AND ' + @dict_db_col + N' LIKE ' + dbo.pvt_sql_string_literal(@dov) + N')'; ELSE IF @don = N'$contains' SET @dpiece = @dict_exist_pfx + N' AND ' + @dict_db_col + N' LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(@dov) + N'%') + N' ESCAPE ''\'')'; ELSE IF @don = N'$startswith' SET @dpiece = @dict_exist_pfx + N' AND ' + @dict_db_col + N' LIKE ' + dbo.pvt_sql_string_literal(dbo.pvt_like_escape(@dov) + N'%') + N' ESCAPE ''\'')'; ELSE IF @don = N'$endswith' SET @dpiece = @dict_exist_pfx + N' AND ' + @dict_db_col + N' LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(@dov)) + N' ESCAPE ''\'')'; ELSE IF @don = N'$containsignorecase' SET @dpiece = @dict_exist_pfx + N' AND LOWER(' + @dict_db_col + N') LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(LOWER(@dov)) + N'%') + N' ESCAPE ''\'')'; ELSE IF @don = N'$startswithignorecase' SET @dpiece = @dict_exist_pfx + N' AND LOWER(' + @dict_db_col + N') LIKE ' + dbo.pvt_sql_string_literal(dbo.pvt_like_escape(LOWER(@dov)) + N'%') + N' ESCAPE ''\'')'; ELSE IF @don = N'$endswithignorecase' SET @dpiece = @dict_exist_pfx + N' AND LOWER(' + @dict_db_col + N') LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(LOWER(@dov))) + N' ESCAPE ''\'')'; ELSE IF @don IN (N'$in', N'$nin') BEGIN IF @dot <> 4 SET @dpiece = dbo.pvt_fail(N'$in on dictionary field "' + @field_name + N'" expects an array'); ELSE BEGIN DECLARE @dlst NVARCHAR(MAX) = N''; DECLARE c_di CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@dov); DECLARE @div NVARCHAR(MAX), @dit INT; OPEN c_di; FETCH NEXT FROM c_di INTO @div, @dit; WHILE @@FETCH_STATUS = 0 BEGIN IF @dlst <> N'' SET @dlst += N', '; SET @dlst += dbo.pvt_jsonb_to_sql_literal(@div, @dit); FETCH NEXT FROM c_di INTO @div, @dit; END; CLOSE c_di; DEALLOCATE c_di; IF @dlst = N'' SET @dlst = N'NULL'; SET @dpiece = @dict_exist_pfx + N' AND ' + @dict_db_col + CASE WHEN @don = N'$in' THEN N' IN (' ELSE N' NOT IN (' END + @dlst + N'))'; END; END ELSE SET @dpiece = dbo.pvt_fail(N'unsupported dictionary operator ' + @dok + N' on field "' + @field_name + N'"'); IF @dpiece IS NOT NULL BEGIN IF @dcnt > 0 SET @dparts += N' AND '; SET @dparts += @dpiece; SET @dcnt += 1; END; FETCH NEXT FROM c_dict INTO @dok, @dov, @dot; END; CLOSE c_dict; DEALLOCATE c_dict; IF @dcnt = 0 RETURN N'1=1'; IF @dcnt = 1 RETURN @dparts; RETURN N'(' + @dparts + N')'; END; -- ---- ListItem accessor (list_item_prop set): Status.Value / .Alias / .Id -- Emits EXISTS subquery against _values [JOIN _list_items] instead of -- a plain column comparison so that it works in both Shape A and C. DECLARE @li_prop_val NVARCHAR(50) = JSON_VALUE(@field_meta, N'$.list_item_prop'); DECLARE @li_is_array BIT = CASE WHEN JSON_VALUE(@field_meta, N'$.is_array') = N'true' THEN 1 ELSE 0 END; IF @li_prop_val IS NOT NULL AND @sid IS NOT NULL BEGIN DECLARE @li_join NVARCHAR(MAX) = N''; DECLARE @li_cmp_col NVARCHAR(100); DECLARE @li_idx_cond NVARCHAR(60) = CASE WHEN @li_is_array = 1 THEN N' AND av._array_index IS NOT NULL' ELSE N' AND av._array_index IS NULL' END; IF @li_prop_val = N'Id' BEGIN -- No join; compare the raw list-item foreign key (BIGINT) SET @li_join = N''; SET @li_cmp_col = N'av.[_ListItem]'; END ELSE IF @li_prop_val = N'Value' BEGIN SET @li_join = N' JOIN dbo._list_items li ON li._id = av.[_ListItem]'; SET @li_cmp_col = N'li.[_value]'; END ELSE -- Alias BEGIN SET @li_join = N' JOIN dbo._list_items li ON li._id = av.[_ListItem]'; SET @li_cmp_col = N'li.[_alias]'; END; DECLARE @li_pfx NVARCHAR(MAX) = N'EXISTS (SELECT 1 FROM dbo._values av' + @li_join + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + @li_idx_cond; -- Scalar shorthand: equality IF @op_type <> 5 BEGIN IF @op_type = 0 RETURN @li_pfx + N' AND ' + @li_cmp_col + N' IS NULL)'; RETURN @li_pfx + N' AND ' + @li_cmp_col + N' = ' + dbo.pvt_jsonb_to_sql_literal(@op_json, @op_type) + N')'; END; -- Operator object DECLARE @li_parts NVARCHAR(MAX) = N''; DECLARE @li_cnt INT = 0; DECLARE c_li CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@op_json); DECLARE @li_ok NVARCHAR(50), @li_ov NVARCHAR(MAX), @li_ot INT; OPEN c_li; FETCH NEXT FROM c_li INTO @li_ok, @li_ov, @li_ot; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @li_on NVARCHAR(50) = LOWER(@li_ok); DECLARE @li_piece NVARCHAR(MAX) = NULL; IF @li_on IN (N'$eq', N'$ne', N'$gt', N'$gte', N'$lt', N'$lte') BEGIN DECLARE @li_cmp NVARCHAR(4) = CASE @li_on WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' END; IF @li_ot = 0 SET @li_piece = CASE @li_on WHEN N'$eq' THEN @li_pfx + N' AND ' + @li_cmp_col + N' IS NULL)' WHEN N'$ne' THEN @li_pfx + N' AND ' + @li_cmp_col + N' IS NOT NULL)' ELSE @li_pfx + N' AND ' + @li_cmp_col + N' ' + @li_cmp + N' NULL)' END; ELSE SET @li_piece = @li_pfx + N' AND ' + @li_cmp_col + N' ' + @li_cmp + N' ' + dbo.pvt_jsonb_to_sql_literal(@li_ov, @li_ot) + N')'; END ELSE IF @li_on IN (N'$in', N'$nin') BEGIN IF @li_ot <> 4 SET @li_piece = dbo.pvt_fail(N'$in on list-item field "' + @field_name + N'" expects an array'); ELSE BEGIN DECLARE @li_lst NVARCHAR(MAX) = N''; DECLARE c_li_in CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@li_ov); DECLARE @li_iv NVARCHAR(MAX), @li_it INT; OPEN c_li_in; FETCH NEXT FROM c_li_in INTO @li_iv, @li_it; WHILE @@FETCH_STATUS = 0 BEGIN IF @li_lst <> N'' SET @li_lst += N', '; SET @li_lst += dbo.pvt_jsonb_to_sql_literal(@li_iv, @li_it); FETCH NEXT FROM c_li_in INTO @li_iv, @li_it; END; CLOSE c_li_in; DEALLOCATE c_li_in; IF @li_lst = N'' SET @li_lst = N'NULL'; -- $nin: NOT EXISTS any matching element SET @li_piece = CASE WHEN @li_on = N'$nin' THEN N'NOT ' ELSE N'' END + @li_pfx + N' AND ' + @li_cmp_col + N' IN (' + @li_lst + N'))'; END; END ELSE IF @li_on IN (N'$null', N'$isnull') SET @li_piece = CASE WHEN LOWER(@li_ov) = N'true' THEN N'NOT ' + @li_pfx + N')' ELSE @li_pfx + N')' END; ELSE IF @li_on IN (N'$notnull', N'$exists') SET @li_piece = CASE WHEN LOWER(@li_ov) = N'true' THEN @li_pfx + N')' ELSE N'NOT ' + @li_pfx + N')' END; ELSE IF @li_on = N'$like' SET @li_piece = @li_pfx + N' AND ' + @li_cmp_col + N' LIKE ' + dbo.pvt_sql_string_literal(@li_ov) + N')'; ELSE IF @li_on = N'$contains' SET @li_piece = @li_pfx + N' AND ' + @li_cmp_col + N' LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(@li_ov) + N'%') + N' ESCAPE ''\'')'; ELSE IF @li_on = N'$startswith' SET @li_piece = @li_pfx + N' AND ' + @li_cmp_col + N' LIKE ' + dbo.pvt_sql_string_literal(dbo.pvt_like_escape(@li_ov) + N'%') + N' ESCAPE ''\'')'; -- Array ops on ListItem-array accessor (parity with PG `= ANY(arr)`): -- the @li_pfx already restricts to array elements when @li_is_array=1, -- so $arrayContains is just an equality on the per-element column. ELSE IF @li_on = N'$arraycontains' AND @li_is_array = 1 SET @li_piece = @li_pfx + N' AND ' + @li_cmp_col + N' = ' + dbo.pvt_jsonb_to_sql_literal(@li_ov, @li_ot) + N')'; ELSE IF @li_on IN (N'$arrayany', N'$arrayempty') AND @li_is_array = 1 BEGIN DECLARE @li_want BIT = CASE WHEN @li_on = N'$arrayany' AND LOWER(@li_ov) = N'true' THEN 1 WHEN @li_on = N'$arrayany' AND LOWER(@li_ov) = N'false' THEN 0 WHEN @li_on = N'$arrayempty' AND LOWER(@li_ov) = N'true' THEN 0 WHEN @li_on = N'$arrayempty' AND LOWER(@li_ov) = N'false' THEN 1 ELSE 1 END; SET @li_piece = CASE WHEN @li_want = 1 THEN @li_pfx + N')' ELSE N'NOT ' + @li_pfx + N')' END; END ELSE SET @li_piece = dbo.pvt_fail(N'unsupported list-item operator ' + @li_ok + N' on field "' + @field_name + N'"'); IF @li_piece IS NOT NULL BEGIN IF @li_cnt > 0 SET @li_parts += N' AND '; SET @li_parts += @li_piece; SET @li_cnt += 1; END; FETCH NEXT FROM c_li INTO @li_ok, @li_ov, @li_ot; END; CLOSE c_li; DEALLOCATE c_li; IF @li_cnt = 0 RETURN N'1=1'; IF @li_cnt = 1 RETURN @li_parts; RETURN N'(' + @li_parts + N')'; END; -- Scalar-literal shorthand IF @op_type <> 5 BEGIN IF @op_type = 0 RETURN @col_name + N' IS NULL'; RETURN @col_name + N' = ' + dbo.pvt_jsonb_to_sql_literal(@op_json, @op_type); END; -- Walk operator object: collect AND-joined parts DECLARE @parts NVARCHAR(MAX) = N''; DECLARE @cnt INT = 0; DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@op_json); DECLARE @opk NVARCHAR(50), @opv NVARCHAR(MAX), @opt INT; OPEN c; FETCH NEXT FROM c INTO @opk, @opv, @opt; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @on NVARCHAR(50) = LOWER(@opk); DECLARE @piece NVARCHAR(MAX) = NULL; IF @on IN (N'$eq', N'$ne', N'$gt', N'$gte', N'$lt', N'$lte') BEGIN DECLARE @cmp NVARCHAR(4) = CASE @on WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' END; IF @opt = 0 -- null SET @piece = CASE @on WHEN N'$eq' THEN @col_name + N' IS NULL' WHEN N'$ne' THEN @col_name + N' IS NOT NULL' ELSE @col_name + N' ' + @cmp + N' NULL' END; ELSE SET @piece = @col_name + N' ' + @cmp + N' ' + dbo.pvt_jsonb_to_sql_literal(@opv, @opt); END ELSE IF @on IN (N'$in', N'$nin') BEGIN IF @opt <> 4 SET @piece = dbo.pvt_fail(N'$in / $nin on field "' + @field_name + N'" expects an array'); ELSE BEGIN DECLARE @lst NVARCHAR(MAX) = N''; DECLARE c_in CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@opv); DECLARE @iv NVARCHAR(MAX), @it INT; OPEN c_in; FETCH NEXT FROM c_in INTO @iv, @it; WHILE @@FETCH_STATUS = 0 BEGIN IF @lst <> N'' SET @lst = @lst + N', '; SET @lst = @lst + dbo.pvt_jsonb_to_sql_literal(@iv, @it); FETCH NEXT FROM c_in INTO @iv, @it; END; CLOSE c_in; DEALLOCATE c_in; IF @lst = N'' SET @lst = N'NULL'; SET @piece = @col_name + CASE WHEN @on = N'$in' THEN N' IN (' ELSE N' NOT IN (' END + @lst + N')'; END; END ELSE IF @on = N'$like' SET @piece = @col_name + N' LIKE ' + dbo.pvt_sql_string_literal(@opv); ELSE IF @on = N'$ilike' -- the caller's pattern, case folded on both sides (PostgreSQL: ILIKE) SET @piece = N'LOWER(' + @col_name + N') LIKE LOWER(' + dbo.pvt_sql_string_literal(@opv) + N')'; ELSE IF @on = N'$startswith' SET @piece = @col_name + N' LIKE ' + dbo.pvt_sql_string_literal(dbo.pvt_like_escape(@opv) + N'%') + N' ESCAPE ''\'''; ELSE IF @on = N'$endswith' SET @piece = @col_name + N' LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(@opv)) + N' ESCAPE ''\'''; ELSE IF @on = N'$contains' SET @piece = @col_name + N' LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(@opv) + N'%') + N' ESCAPE ''\'''; -- T-SQL has no ILIKE; use COLLATE for case-insensitive matching. ELSE IF @on = N'$startswithignorecase' SET @piece = N'LOWER(' + @col_name + N') LIKE ' + dbo.pvt_sql_string_literal(dbo.pvt_like_escape(LOWER(@opv)) + N'%') + N' ESCAPE ''\'''; ELSE IF @on = N'$endswithignorecase' SET @piece = N'LOWER(' + @col_name + N') LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(LOWER(@opv))) + N' ESCAPE ''\'''; ELSE IF @on = N'$containsignorecase' SET @piece = N'LOWER(' + @col_name + N') LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(LOWER(@opv)) + N'%') + N' ESCAPE ''\'''; ELSE IF @on IN (N'$null', N'$isnull') SET @piece = CASE WHEN @opv = N'true' THEN @col_name + N' IS NULL' ELSE @col_name + N' IS NOT NULL' END; ELSE IF @on IN (N'$notnull', N'$exists') SET @piece = CASE WHEN @opv = N'true' THEN @col_name + N' IS NOT NULL' ELSE @col_name + N' IS NULL' END; -- ---- Array operators ($arrayContains / $arrayAny / etc.) ------- -- These emit EXISTS / COUNT subqueries against dbo._values using the -- structure id (sid) from the field meta. They require kind='field' -- and a valid sid; for base fields they fall through to unsupported. ELSE IF @on = N'$arraycontains' BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(N'$arrayContains needs an array field; "' + @field_name + N'" has no structure'); ELSE BEGIN DECLARE @ac_cmp NVARCHAR(MAX) = dbo.pvt_array_element_equals(@db_type_f, @opv, @opt); SET @piece = N'EXISTS (SELECT 1 FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index IS NOT NULL' + N' AND ' + @ac_cmp + N')'; END; END ELSE IF @on IN (N'$arrayany', N'$arrayempty') BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(@opk + N' needs an array field; "' + @field_name + N'" has no structure'); ELSE BEGIN DECLARE @aae_base NVARCHAR(MAX) = N'EXISTS (SELECT 1 FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index IS NOT NULL)'; -- $arrayAny: true -> EXISTS, false -> NOT EXISTS -- $arrayEmpty: true -> NOT EXISTS, false -> EXISTS DECLARE @aae_want BIT = CASE WHEN @on = N'$arrayany' AND LOWER(@opv) = N'true' THEN 1 WHEN @on = N'$arrayany' AND LOWER(@opv) = N'false' THEN 0 WHEN @on = N'$arrayempty' AND LOWER(@opv) = N'true' THEN 0 WHEN @on = N'$arrayempty' AND LOWER(@opv) = N'false' THEN 1 ELSE 1 END; SET @piece = CASE WHEN @aae_want = 1 THEN @aae_base ELSE N'NOT ' + @aae_base END; END; END ELSE IF @on IN (N'$arraycount', N'$arraycountgt', N'$arraycountgte', N'$arraycountlt', N'$arraycountlte') BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(@opk + N' needs an array field; "' + @field_name + N'" has no structure'); ELSE BEGIN DECLARE @acc_cnt NVARCHAR(MAX) = N'(SELECT COUNT(*) FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index IS NOT NULL)'; DECLARE @acc_val NVARCHAR(20) = COALESCE(CAST(TRY_CAST(@opv AS BIGINT) AS NVARCHAR(20)), dbo.pvt_fail(@on + N' on field "' + @field_name + N'" expects an integer')); DECLARE @acc_op NVARCHAR(3) = CASE @on WHEN N'$arraycount' THEN N'=' WHEN N'$arraycountgt' THEN N'>' WHEN N'$arraycountgte' THEN N'>=' WHEN N'$arraycountlt' THEN N'<' WHEN N'$arraycountlte' THEN N'<=' ELSE dbo.pvt_fail(N'unsupported array count operator ' + @on) END; SET @piece = @acc_cnt + N' ' + @acc_op + N' ' + @acc_val; END; END ELSE IF @on = N'$arrayat' BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(N'$arrayAt needs an array field; "' + @field_name + N'" has no structure'); ELSE BEGIN -- Operand {"index": N, "value": V}, as in PostgreSQL: the element at index N equals V -- (_array_index is NVARCHAR). It used to read the operand as the index itself - the object -- did not convert and became index 0 - and never compared the value. DECLARE @aat_idx NVARCHAR(20) = CASE WHEN @opt = 5 THEN CAST(TRY_CAST(JSON_VALUE(@opv, N'$.index') AS BIGINT) AS NVARCHAR(20)) END; DECLARE @aat_val NVARCHAR(MAX) = NULL, @aat_type INT = NULL; IF @opt = 5 SELECT @aat_val = [value], @aat_type = [type] FROM OPENJSON(@opv) WHERE [key] = N'value'; IF @aat_idx IS NULL OR @aat_type IS NULL SET @piece = dbo.pvt_fail(N'$arrayAt on field "' + @field_name + N'" expects {"index":N,"value":V}'); ELSE SET @piece = N'EXISTS (SELECT 1 FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index = N''' + @aat_idx + N'''' + N' AND ' + dbo.pvt_array_element_equals(@db_type_f, @aat_val, @aat_type) + N')'; END; END ELSE IF @on IN (N'$arrayfirst', N'$arraylast') BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(@opk + N' needs an array field; "' + @field_name + N'" has no structure'); ELSE BEGIN DECLARE @afl_cmp NVARCHAR(MAX) = dbo.pvt_array_element_equals(@db_type_f, @opv, @opt); DECLARE @afl_idx NVARCHAR(MAX) = CASE @on WHEN N'$arrayfirst' THEN N'N''0''' ELSE N'(SELECT TOP 1 CAST(av2._array_index AS NVARCHAR(20))' + N' FROM dbo._values av2' + N' WHERE av2._id_object = ' + @obj_alias + N'.[_id]' + N' AND av2._id_structure = ' + @sid + N' AND av2._array_index IS NOT NULL' + N' ORDER BY TRY_CAST(av2._array_index AS INT) DESC)' END; SET @piece = N'EXISTS (SELECT 1 FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index = ' + @afl_idx + N' AND ' + @afl_cmp + N')'; END; END ELSE IF @on = N'$arraystartswith' BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(N'$arrayStartsWith needs an array field; "' + @field_name + N'" has no structure'); ELSE SET @piece = N'EXISTS (SELECT 1 FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index IS NOT NULL' + N' AND av.[_String] LIKE ' + dbo.pvt_sql_string_literal(dbo.pvt_like_escape(@opv) + N'%') + N' ESCAPE ''\'')'; END ELSE IF @on = N'$arrayendswith' BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(N'$arrayEndsWith needs an array field; "' + @field_name + N'" has no structure'); ELSE SET @piece = N'EXISTS (SELECT 1 FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index IS NOT NULL' + N' AND av.[_String] LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(@opv)) + N' ESCAPE ''\'')'; END -- ---- $arrayMatches: LIKE pattern against array element strings ---- ELSE IF @on = N'$arraymatches' BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(N'$arrayMatches needs an array field; "' + @field_name + N'" has no structure'); ELSE SET @piece = N'EXISTS (SELECT 1 FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index IS NOT NULL' + N' AND av.[_String] LIKE ' + dbo.pvt_sql_string_literal(@opv) + N')'; END -- ---- $arraySum / $arrayMin / $arrayMax / $arrayAvg --------------- -- Scalar operand: shorthand for = @value. -- Object operand: comparison operators ($eq/$ne/$gt/$gte/$lt/$lte). ELSE IF @on IN (N'$arraysum', N'$arraymin', N'$arraymax', N'$arrayavg') BEGIN IF @sid IS NULL SET @piece = dbo.pvt_fail(@opk + N' needs an array field; "' + @field_name + N'" has no structure'); ELSE BEGIN DECLARE @agg_fn NVARCHAR(10) = CASE @on WHEN N'$arraysum' THEN N'SUM' WHEN N'$arraymin' THEN N'MIN' WHEN N'$arraymax' THEN N'MAX' WHEN N'$arrayavg' THEN N'AVG' ELSE N'SUM' END; DECLARE @agg_col NVARCHAR(100) = CASE @db_type_f WHEN N'Long' THEN N'av.[_Long]' WHEN N'Double' THEN N'av.[_Double]' WHEN N'Numeric' THEN N'av.[_Numeric]' ELSE N'CAST(av.[_String] AS DECIMAL(28,10))' END; DECLARE @agg_sub NVARCHAR(MAX) = N'(SELECT ' + @agg_fn + N'(' + @agg_col + N') FROM dbo._values av' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND av._id_structure = ' + @sid + N' AND av._array_index IS NOT NULL)'; -- Scalar shorthand: equality check IF @opt <> 5 SET @piece = @agg_sub + N' = ' + dbo.pvt_jsonb_to_sql_literal(@opv, @opt); ELSE BEGIN -- Operator object: walk and AND-join comparison ops DECLARE @ag_parts NVARCHAR(MAX) = N''; DECLARE @ag_cnt INT = 0; DECLARE c_ag CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@opv); DECLARE @ag_ok NVARCHAR(50), @ag_ov NVARCHAR(MAX), @ag_ot INT; OPEN c_ag; FETCH NEXT FROM c_ag INTO @ag_ok, @ag_ov, @ag_ot; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @ag_cmp NVARCHAR(4) = CASE LOWER(@ag_ok) WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' ELSE NULL END; IF @ag_cmp IS NOT NULL BEGIN IF @ag_cnt > 0 SET @ag_parts += N' AND '; SET @ag_parts += @agg_sub + N' ' + @ag_cmp + N' ' + dbo.pvt_jsonb_to_sql_literal(@ag_ov, @ag_ot); SET @ag_cnt += 1; END; FETCH NEXT FROM c_ag INTO @ag_ok, @ag_ov, @ag_ot; END; CLOSE c_ag; DEALLOCATE c_ag; SET @piece = CASE WHEN @ag_cnt = 0 THEN N'1=1' WHEN @ag_cnt = 1 THEN @ag_parts ELSE N'(' + @ag_parts + N')' END; END; END; END ELSE SET @piece = dbo.pvt_fail(N'unsupported operator ' + @opk + N' on field "' + @field_name + N'"'); IF @piece IS NOT NULL BEGIN IF @cnt > 0 SET @parts = @parts + N' AND '; SET @parts = @parts + @piece; SET @cnt = @cnt + 1; END; FETCH NEXT FROM c INTO @opk, @opv, @opt; END; CLOSE c; DEALLOCATE c; IF @cnt = 0 RETURN N'1=1'; IF @cnt = 1 RETURN @parts; RETURN N'(' + @parts + N')'; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/14_pvt_where.sql ---- -- ===================================================================== -- 14_pvt_where.sql (MSSql v2-pvt) — recursive filter walker -- --------------------------------------------------------------------- -- Build a single WHERE expression from filter JSON. -- -- Grammar (slice): -- { "$and": [ ... ] } -> ( ... AND ... ) -- { "$or": [ ... ] } -> ( ... OR ... ) -- { "$not": { ... } } -> NOT ( ... ) -- { "$isRoot": true } -> alias._id_parent IS NULL -- { "$isLeaf": true } -> NOT EXISTS (children) -- { "$childrenOf": N } -> alias._id_parent = N -- { "$level": N } -> dbo.pvt_object_depth(alias._id) = N -- { "$level": {"$gt":N} } -> dbo.pvt_object_depth(alias._id) > N -- { "$hasAncestor": N } -> dbo.pvt_is_descendant_of(alias._id, N) = 1 -- { "$hasDescendant": N } -> dbo.pvt_is_descendant_of(N, alias._id) = 1 -- { "Field.$length": {op} } -> EXISTS LENGTH(fv._String) op N -- { "Field[].$count": {op} } -> (SELECT COUNT(*) ...) op N -- { "": } -> AND of per-field predicates -- { "$gt": [expr, expr] } -> B2-expr comparison (see pvt_b2_expr_sql) -- { "$between": [expr, lo, hi] } -> B2-expr range check -- { "$in": [expr, [v1,...]] } -> B2-expr IN list -- { "$null": expr } -> expr IS NULL -- { "$contains": [expr, str] } -> expr LIKE '%str%' -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO -- ===================================================================== -- pvt_b2_expr_sql — translate one B2 expression node to a T-SQL fragment -- ===================================================================== -- expr: JSON node e.g. {"$field":"Age"} or {"$add":[...]} -- fields: field metadata from pvt_collect_fields -- obj_alias: 'o' (Shape A) or '_pvt_cte' (Shape C) -- Handles: $field, $const, $gt/$gte/$lt/$lte/$eq/$ne, -- $add/$sub/$mul, $abs, $power, $upper, $concat, -- $coalesce, $length, $year, $trimStart, -- $substring, $replace, $dateAdd, $if CREATE OR ALTER FUNCTION dbo.pvt_b2_expr_sql( @expr NVARCHAR(MAX), @fields NVARCHAR(MAX), @obj_alias NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @expr IS NULL OR ISJSON(@expr) = 0 RETURN N'NULL'; DECLARE @nk NVARCHAR(100), @nv NVARCHAR(MAX), @nt INT; SELECT TOP 1 @nk = LOWER([key]), @nv = [value], @nt = [type] FROM OPENJSON(@expr); IF @nk IS NULL RETURN N'NULL'; -- ---- Leaf nodes -------------------------------------------------- IF @nk = N'$field' BEGIN DECLARE @b2_fm NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@nv, 'json') + N'"'); -- Fail closed, like the PostgreSQL module (RAISE EXCEPTION there): never echo the -- unescaped name into the SQL text. A '*/' in the name used to close this comment -- and turn the rest of the name into live T-SQL (SQLI-PoC p.1). IF @b2_fm IS NULL RETURN dbo.pvt_fail(N'unknown props field in $field: ' + @nv); IF JSON_VALUE(@b2_fm, N'$.kind') = N'base' RETURN @obj_alias + N'.' + QUOTENAME(JSON_VALUE(@b2_fm, N'$.column')); RETURN QUOTENAME(@nv); -- props field resolved as CTE column in Shape C END; IF @nk = N'$const' RETURN dbo.pvt_jsonb_to_sql_literal(@nv, @nt); -- ---- Comparison operators (used in $if conditions) --------------- IF @nk IN (N'$gt', N'$gte', N'$lt', N'$lte', N'$eq', N'$ne') BEGIN DECLARE @cmp_1 NVARCHAR(MAX), @cmp_2 NVARCHAR(MAX); SELECT @cmp_1 = MIN(CASE WHEN [key] = '0' THEN [value] END), @cmp_2 = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@nv); DECLARE @cmp_op NVARCHAR(4) = CASE @nk WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' END; DECLARE @cmp_l NVARCHAR(MAX) = dbo.pvt_b2_expr_sql(@cmp_1, @fields, @obj_alias); DECLARE @cmp_r NVARCHAR(MAX) = dbo.pvt_b2_expr_sql(@cmp_2, @fields, @obj_alias); -- Null-aware rewrite for $eq / $ne (parity with PG IS [NOT] DISTINCT FROM) -- For ordering ops vs NULL the result is UNKNOWN in T-SQL anyway, but at -- least don't emit `expr = NULL` / `expr <> NULL` which silently never match. IF @nk IN (N'$eq', N'$ne') BEGIN IF @cmp_r = N'NULL' AND @cmp_l <> N'NULL' RETURN @cmp_l + CASE WHEN @nk = N'$eq' THEN N' IS NULL' ELSE N' IS NOT NULL' END; IF @cmp_l = N'NULL' AND @cmp_r <> N'NULL' RETURN @cmp_r + CASE WHEN @nk = N'$eq' THEN N' IS NULL' ELSE N' IS NOT NULL' END; IF @cmp_l = N'NULL' AND @cmp_r = N'NULL' RETURN CASE WHEN @nk = N'$eq' THEN N'1=1' ELSE N'1=0' END; END; RETURN @cmp_l + N' ' + @cmp_op + N' ' + @cmp_r; END; -- ---- Arithmetic -------------------------------------------------- IF @nk IN (N'$add', N'$sub', N'$mul', N'$div', N'$mod') BEGIN DECLARE @bx_1 NVARCHAR(MAX), @bx_2 NVARCHAR(MAX); SELECT @bx_1 = MIN(CASE WHEN [key] = '0' THEN [value] END), @bx_2 = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@nv); DECLARE @bx_op NVARCHAR(3) = CASE @nk WHEN N'$add' THEN N'+' WHEN N'$sub' THEN N'-' WHEN N'$mul' THEN N'*' WHEN N'$div' THEN N'/' ELSE N'%' END; RETURN N'(' + dbo.pvt_b2_expr_sql(@bx_1, @fields, @obj_alias) + N' ' + @bx_op + N' ' + dbo.pvt_b2_expr_sql(@bx_2, @fields, @obj_alias) + N')'; END; -- ---- Unary functions (single-arg, array or object form) ---------- -- Accept { $op: expr } or { $op: [expr] } like PG. IF @nk IN (N'$abs', N'$neg', N'$floor', N'$ceil', N'$lower', N'$trim', N'$trimend', N'$sqrt', N'$sign', N'$exp', N'$ln', N'$log10') BEGIN DECLARE @un_a NVARCHAR(MAX); IF @nt = 4 SELECT TOP 1 @un_a = [value] FROM OPENJSON(@nv); ELSE SET @un_a = @nv; DECLARE @un_x NVARCHAR(MAX) = dbo.pvt_b2_expr_sql(@un_a, @fields, @obj_alias); IF @nk = N'$abs' RETURN N'ABS(' + @un_x + N')'; IF @nk = N'$neg' RETURN N'(-' + @un_x + N')'; IF @nk = N'$floor' RETURN N'FLOOR(' + @un_x + N')'; IF @nk = N'$ceil' RETURN N'CEILING(' + @un_x + N')'; IF @nk = N'$lower' RETURN N'LOWER(' + @un_x + N')'; IF @nk = N'$trim' RETURN N'LTRIM(RTRIM(' + @un_x + N'))'; IF @nk = N'$trimend' RETURN N'RTRIM(' + @un_x + N')'; IF @nk = N'$sqrt' RETURN N'SQRT(CAST(' + @un_x + N' AS FLOAT))'; IF @nk = N'$sign' RETURN N'SIGN(' + @un_x + N')'; IF @nk = N'$exp' RETURN N'EXP(CAST(' + @un_x + N' AS FLOAT))'; IF @nk = N'$ln' RETURN N'LOG(CAST(' + @un_x + N' AS FLOAT))'; IF @nk = N'$log10' RETURN N'LOG10(CAST(' + @un_x + N' AS FLOAT))'; END; -- ---- $min / $max: n-ary LEAST / GREATEST (SQL Server 2022+) ----- IF @nk IN (N'$min', N'$max') BEGIN DECLARE @mm_parts NVARCHAR(MAX) = N''; DECLARE c_mm CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@nv) ORDER BY CAST([key] AS INT); DECLARE @mm_v NVARCHAR(MAX); OPEN c_mm; FETCH NEXT FROM c_mm INTO @mm_v; WHILE @@FETCH_STATUS = 0 BEGIN IF @mm_parts <> N'' SET @mm_parts += N', '; SET @mm_parts += dbo.pvt_b2_expr_sql(@mm_v, @fields, @obj_alias); FETCH NEXT FROM c_mm INTO @mm_v; END; CLOSE c_mm; DEALLOCATE c_mm; RETURN CASE WHEN @nk = N'$min' THEN N'LEAST(' + @mm_parts + N')' ELSE N'GREATEST(' + @mm_parts + N')' END; END; IF @nk = N'$power' BEGIN DECLARE @pw_1 NVARCHAR(MAX), @pw_2 NVARCHAR(MAX); SELECT @pw_1 = MIN(CASE WHEN [key] = '0' THEN [value] END), @pw_2 = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@nv); RETURN N'POWER(CAST(' + dbo.pvt_b2_expr_sql(@pw_1, @fields, @obj_alias) + N' AS FLOAT),' + dbo.pvt_b2_expr_sql(@pw_2, @fields, @obj_alias) + N')'; END; -- ---- String / general functions ---------------------------------- IF @nk = N'$upper' BEGIN DECLARE @up_a NVARCHAR(MAX); IF @nt = 4 SELECT TOP 1 @up_a = [value] FROM OPENJSON(@nv); ELSE SET @up_a = @nv; RETURN N'UPPER(' + dbo.pvt_b2_expr_sql(@up_a, @fields, @obj_alias) + N')'; END; IF @nk = N'$concat' BEGIN DECLARE @cc_parts NVARCHAR(MAX) = N''; DECLARE c_cc CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@nv) ORDER BY CAST([key] AS INT); DECLARE @cc_v NVARCHAR(MAX); OPEN c_cc; FETCH NEXT FROM c_cc INTO @cc_v; WHILE @@FETCH_STATUS = 0 BEGIN IF @cc_parts <> N'' SET @cc_parts += N' + '; SET @cc_parts += N'CAST(' + dbo.pvt_b2_expr_sql(@cc_v, @fields, @obj_alias) + N' AS NVARCHAR(MAX))'; FETCH NEXT FROM c_cc INTO @cc_v; END; CLOSE c_cc; DEALLOCATE c_cc; RETURN CASE WHEN @cc_parts = N'' THEN N'N'''' ' ELSE @cc_parts END; END; IF @nk = N'$coalesce' BEGIN DECLARE @co_parts NVARCHAR(MAX) = N''; DECLARE c_co CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@nv) ORDER BY CAST([key] AS INT); DECLARE @co_v NVARCHAR(MAX); OPEN c_co; FETCH NEXT FROM c_co INTO @co_v; WHILE @@FETCH_STATUS = 0 BEGIN IF @co_parts <> N'' SET @co_parts += N', '; SET @co_parts += dbo.pvt_b2_expr_sql(@co_v, @fields, @obj_alias); FETCH NEXT FROM c_co INTO @co_v; END; CLOSE c_co; DEALLOCATE c_co; RETURN CASE WHEN @co_parts = N'' THEN N'NULL' ELSE N'COALESCE(' + @co_parts + N')' END; END; IF @nk = N'$length' BEGIN DECLARE @len_a NVARCHAR(MAX); IF @nt = 4 SELECT TOP 1 @len_a = [value] FROM OPENJSON(@nv); ELSE SET @len_a = @nv; RETURN N'LEN(' + dbo.pvt_b2_expr_sql(@len_a, @fields, @obj_alias) + N')'; END; -- ---- Date / advanced functions ----------------------------------- -- $year/$month/$day: T-SQL date part functions IF @nk = N'$year' RETURN N'YEAR(' + dbo.pvt_b2_expr_sql(@nv, @fields, @obj_alias) + N')'; IF @nk = N'$month' RETURN N'MONTH(' + dbo.pvt_b2_expr_sql(@nv, @fields, @obj_alias) + N')'; IF @nk = N'$day' RETURN N'DAY(' + dbo.pvt_b2_expr_sql(@nv, @fields, @obj_alias) + N')'; IF @nk = N'$hour' RETURN N'DATEPART(HOUR, ' + dbo.pvt_b2_expr_sql(@nv, @fields, @obj_alias) + N')'; IF @nk = N'$minute' RETURN N'DATEPART(MINUTE, ' + dbo.pvt_b2_expr_sql(@nv, @fields, @obj_alias) + N')'; IF @nk = N'$second' RETURN N'DATEPART(SECOND, ' + dbo.pvt_b2_expr_sql(@nv, @fields, @obj_alias) + N')'; -- $trimStart/$trimEnd: LTRIM/RTRIM (unary object or array form) IF @nk = N'$trimstart' RETURN N'LTRIM(' + dbo.pvt_b2_expr_sql(@nv, @fields, @obj_alias) + N')'; IF @nk = N'$substring' BEGIN DECLARE @ss0 NVARCHAR(MAX), @ss1 NVARCHAR(MAX), @ss2 NVARCHAR(MAX); SELECT @ss0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @ss1 = MIN(CASE WHEN [key] = '1' THEN [value] END), @ss2 = MIN(CASE WHEN [key] = '2' THEN [value] END) FROM OPENJSON(@nv); RETURN N'SUBSTRING(' + dbo.pvt_b2_expr_sql(@ss0, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@ss1, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@ss2, @fields, @obj_alias) + N')'; END; IF @nk = N'$replace' BEGIN DECLARE @re0 NVARCHAR(MAX), @re1 NVARCHAR(MAX), @re2 NVARCHAR(MAX); SELECT @re0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @re1 = MIN(CASE WHEN [key] = '1' THEN [value] END), @re2 = MIN(CASE WHEN [key] = '2' THEN [value] END) FROM OPENJSON(@nv); RETURN N'REPLACE(' + dbo.pvt_b2_expr_sql(@re0, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@re1, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@re2, @fields, @obj_alias) + N')'; END; -- $regexReplace: [str, pattern, replacement(, flags)] (Regex.Replace). REGEXP_REPLACE (SQL Server 2025, -- compatibility level 170) replaces every match by default, as .NET does; the 'g' flag the builder -- appends for PostgreSQL is not needed and not passed. IF @nk = N'$regexreplace' BEGIN DECLARE @rr0 NVARCHAR(MAX), @rr1 NVARCHAR(MAX), @rr2 NVARCHAR(MAX); SELECT @rr0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @rr1 = MIN(CASE WHEN [key] = '1' THEN [value] END), @rr2 = MIN(CASE WHEN [key] = '2' THEN [value] END) FROM OPENJSON(@nv); RETURN N'REGEXP_REPLACE(' + dbo.pvt_b2_expr_sql(@rr0, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@rr1, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@rr2, @fields, @obj_alias) + N')'; END; -- $dateAdd / $dateSub: JSON args = ["unit", date_expr, amount] -- T-SQL: DATEADD(unit, [+/-]amount, CAST(date_expr AS DATETIMEOFFSET)) IF @nk IN (N'$dateadd', N'$datesub') BEGIN DECLARE @da0 NVARCHAR(MAX), @da1 NVARCHAR(MAX), @da2 NVARCHAR(MAX); SELECT @da0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @da1 = MIN(CASE WHEN [key] = '1' THEN [value] END), @da2 = MIN(CASE WHEN [key] = '2' THEN [value] END) FROM OPENJSON(@nv); DECLARE @da_n NVARCHAR(MAX) = dbo.pvt_b2_expr_sql(@da2, @fields, @obj_alias); IF @nk = N'$datesub' SET @da_n = N'-(' + @da_n + N')'; RETURN N'DATEADD(' + @da0 + N', ' + @da_n + N', CAST(' + dbo.pvt_b2_expr_sql(@da1, @fields, @obj_alias) + N' AS DATETIMEOFFSET))'; END; -- $round: [value] or [value, digits] IF @nk = N'$round' BEGIN DECLARE @ro0 NVARCHAR(MAX), @ro1 NVARCHAR(MAX); SELECT @ro0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @ro1 = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@nv); IF @ro1 IS NULL RETURN N'ROUND(' + dbo.pvt_b2_expr_sql(@ro0, @fields, @obj_alias) + N', 0)'; RETURN N'ROUND(' + dbo.pvt_b2_expr_sql(@ro0, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@ro1, @fields, @obj_alias) + N')'; END; -- $log: [base, value] — T-SQL LOG(number, base) has reversed args vs PG IF @nk = N'$log' BEGIN DECLARE @lg0 NVARCHAR(MAX), @lg1 NVARCHAR(MAX); SELECT @lg0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @lg1 = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@nv); RETURN N'LOG(CAST(' + dbo.pvt_b2_expr_sql(@lg1, @fields, @obj_alias) + N' AS FLOAT), CAST(' + dbo.pvt_b2_expr_sql(@lg0, @fields, @obj_alias) + N' AS FLOAT))'; END; -- $indexOf: [str, needle] — T-SQL CHARINDEX(needle, str) IF @nk = N'$indexof' BEGIN DECLARE @io0 NVARCHAR(MAX), @io1 NVARCHAR(MAX); SELECT @io0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @io1 = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@nv); RETURN N'CHARINDEX(' + dbo.pvt_b2_expr_sql(@io1, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@io0, @fields, @obj_alias) + N')'; END; -- $if: CASE WHEN cond THEN then_expr ELSE else_expr END -- Condition is itself a B2 expression (comparison returns boolean T-SQL text). IF @nk = N'$if' BEGIN DECLARE @if0 NVARCHAR(MAX), @if1 NVARCHAR(MAX), @if2 NVARCHAR(MAX); SELECT @if0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @if1 = MIN(CASE WHEN [key] = '1' THEN [value] END), @if2 = MIN(CASE WHEN [key] = '2' THEN [value] END) FROM OPENJSON(@nv); RETURN N'CASE WHEN ' + dbo.pvt_b2_expr_sql(@if0, @fields, @obj_alias) + N' THEN ' + dbo.pvt_b2_expr_sql(@if1, @fields, @obj_alias) + N' ELSE ' + dbo.pvt_b2_expr_sql(@if2, @fields, @obj_alias) + N' END'; END; -- $case: [{"when":,"then":},...,{"else":}?] IF @nk = N'$case' BEGIN DECLARE @ca_sb NVARCHAR(MAX) = N'(CASE'; DECLARE @ca_else NVARCHAR(MAX) = N'NULL'; DECLARE c_ca CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@nv) ORDER BY CAST([key] AS INT); DECLARE @ca_entry NVARCHAR(MAX); OPEN c_ca; FETCH NEXT FROM c_ca INTO @ca_entry; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @ca_when NVARCHAR(MAX) = JSON_QUERY(@ca_entry, N'$.when'); DECLARE @ca_then NVARCHAR(MAX) = JSON_QUERY(@ca_entry, N'$.then'); DECLARE @ca_el NVARCHAR(MAX) = JSON_QUERY(@ca_entry, N'$.else'); IF @ca_el IS NOT NULL SET @ca_else = dbo.pvt_b2_expr_sql(@ca_el, @fields, @obj_alias); ELSE IF @ca_when IS NOT NULL AND @ca_then IS NOT NULL SET @ca_sb += N' WHEN ' + dbo.pvt_b2_expr_sql(@ca_when, @fields, @obj_alias) + N' THEN ' + dbo.pvt_b2_expr_sql(@ca_then, @fields, @obj_alias); FETCH NEXT FROM c_ca INTO @ca_entry; END; CLOSE c_ca; DEALLOCATE c_ca; RETURN @ca_sb + N' ELSE ' + @ca_else + N' END)'; END; -- Fail closed: the node name is data, not SQL. It used to be echoed inside a comment, -- so a crafted name could close it and inject live T-SQL (SQLI-PoC p.1). RETURN dbo.pvt_fail(N'unknown expression node in $expr: ' + @nk); END; GO CREATE OR ALTER FUNCTION dbo.pvt_build_where_from_json( @filter NVARCHAR(MAX), @fields NVARCHAR(MAX), @base_prefix NVARCHAR(10) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @filter IS NULL OR @filter = N'{}' OR ISJSON(@filter) = 0 RETURN N'1=1'; -- Derive outer table alias for EXISTS subqueries and tree predicates. -- Shape A: base_prefix = 'o.' -> alias 'o' -- Shape C: base_prefix = '_pvt_cte.' -> alias '_pvt_cte' DECLARE @obj_alias NVARCHAR(50) = CASE WHEN @base_prefix = N'o.' THEN N'o' ELSE N'_pvt_cte' END; DECLARE @parts NVARCHAR(MAX) = N''; DECLARE @cnt INT = 0; DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@filter); DECLARE @k NVARCHAR(400), @v NVARCHAR(MAX), @t INT; OPEN c; FETCH NEXT FROM c INTO @k, @v, @t; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @lk NVARCHAR(50) = LOWER(@k); DECLARE @piece NVARCHAR(MAX) = NULL; IF @lk = N'$and' AND @t = 4 BEGIN DECLARE @children NVARCHAR(MAX) = N''; DECLARE @ccnt INT = 0; DECLARE c_a CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@v); DECLARE @e NVARCHAR(MAX); OPEN c_a; FETCH NEXT FROM c_a INTO @e; WHILE @@FETCH_STATUS = 0 BEGIN IF @ccnt > 0 SET @children = @children + N' AND '; SET @children = @children + dbo.pvt_build_where_from_json(@e, @fields, @base_prefix); SET @ccnt = @ccnt + 1; FETCH NEXT FROM c_a INTO @e; END; CLOSE c_a; DEALLOCATE c_a; SET @piece = CASE WHEN @ccnt = 0 THEN N'1=1' ELSE N'(' + @children + N')' END; END ELSE IF @lk = N'$or' AND @t = 4 BEGIN DECLARE @ochildren NVARCHAR(MAX) = N''; DECLARE @occnt INT = 0; DECLARE c_o CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@v); DECLARE @oe NVARCHAR(MAX); OPEN c_o; FETCH NEXT FROM c_o INTO @oe; WHILE @@FETCH_STATUS = 0 BEGIN IF @occnt > 0 SET @ochildren = @ochildren + N' OR '; SET @ochildren = @ochildren + dbo.pvt_build_where_from_json(@oe, @fields, @base_prefix); SET @occnt = @occnt + 1; FETCH NEXT FROM c_o INTO @oe; END; CLOSE c_o; DEALLOCATE c_o; SET @piece = CASE WHEN @occnt = 0 THEN N'1=0' ELSE N'(' + @ochildren + N')' END; END ELSE IF @lk = N'$not' SET @piece = N'NOT (' + dbo.pvt_build_where_from_json(@v, @fields, @base_prefix) + N')'; -- $expr: arbitrary boolean expression subtree. Delegates back to -- the same walker so $and/$or/$not + leaf predicates are handled -- uniformly. Pro/PG parity (see 17_pvt_expr.sql commentary). ELSE IF @lk = N'$expr' SET @piece = N'(' + dbo.pvt_build_where_from_json(@v, @fields, @base_prefix) + N')'; -- ---- Hierarchical operators ------------------------------------ ELSE IF @lk = N'$isroot' SET @piece = CASE WHEN LOWER(@v) = N'false' THEN @obj_alias + N'.[_id_parent] IS NOT NULL' ELSE @obj_alias + N'.[_id_parent] IS NULL' END; ELSE IF @lk = N'$isleaf' SET @piece = CASE WHEN LOWER(@v) = N'false' THEN N'EXISTS (SELECT 1 FROM dbo._objects _leaf WHERE _leaf.[_id_parent] = ' + @obj_alias + N'.[_id])' ELSE N'NOT EXISTS (SELECT 1 FROM dbo._objects _leaf WHERE _leaf.[_id_parent] = ' + @obj_alias + N'.[_id])' END; ELSE IF @lk = N'$childrenof' BEGIN DECLARE @co_id BIGINT = TRY_CAST(@v AS BIGINT); SET @piece = CASE WHEN @co_id IS NOT NULL THEN @obj_alias + N'.[_id_parent] = ' + CAST(@co_id AS NVARCHAR(20)) ELSE dbo.pvt_fail(N'$childrenOf expects an object id') END; END ELSE IF @lk = N'$level' BEGIN DECLARE @lvl_expr NVARCHAR(100) = N'dbo.pvt_object_depth(' + @obj_alias + N'.[_id])'; IF @t = 2 OR @t = 3 -- direct number: exact equality SET @piece = @lvl_expr + N' = ' + COALESCE(CAST(TRY_CAST(@v AS BIGINT) AS NVARCHAR(20)), dbo.pvt_fail(N'$level expects an integer')); ELSE IF @t = 5 -- operator object: {"$gt":2} etc. BEGIN DECLARE @lvl_parts NVARCHAR(MAX) = N''; DECLARE @lvl_cnt INT = 0; DECLARE c_lvl CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value] FROM OPENJSON(@v); DECLARE @lvlk NVARCHAR(50), @lvlv NVARCHAR(MAX); OPEN c_lvl; FETCH NEXT FROM c_lvl INTO @lvlk, @lvlv; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @lvl_cmp NVARCHAR(3) = CASE LOWER(@lvlk) WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' ELSE dbo.pvt_fail(N'unsupported $level comparison ' + @lvlk) END; IF @lvl_cnt > 0 SET @lvl_parts = @lvl_parts + N' AND '; SET @lvl_parts += @lvl_expr + N' ' + @lvl_cmp + N' ' + COALESCE(CAST(TRY_CAST(@lvlv AS BIGINT) AS NVARCHAR(20)), dbo.pvt_fail(N'$level expects an integer')); SET @lvl_cnt += 1; FETCH NEXT FROM c_lvl INTO @lvlk, @lvlv; END; CLOSE c_lvl; DEALLOCATE c_lvl; SET @piece = CASE WHEN @lvl_cnt > 0 THEN @lvl_parts ELSE N'1=1' END; END; ELSE SET @piece = dbo.pvt_fail(N'$level expects an integer or an operator object'); END ELSE IF @lk = N'$hasancestor' BEGIN -- Value can be a bare bigint or {"id": N} DECLARE @ha_id BIGINT = TRY_CAST(@v AS BIGINT); IF @ha_id IS NULL AND @t = 5 SET @ha_id = TRY_CAST(JSON_VALUE(@v, N'$.id') AS BIGINT); SET @piece = CASE WHEN @ha_id IS NOT NULL THEN N'dbo.pvt_is_descendant_of(' + @obj_alias + N'.[_id], ' + CAST(@ha_id AS NVARCHAR(20)) + N') = 1' ELSE dbo.pvt_fail(N'$hasAncestor expects an object id') END; END ELSE IF @lk = N'$hasdescendant' BEGIN -- Object has descendant X == X is descendant of this object DECLARE @hd_id BIGINT = TRY_CAST(@v AS BIGINT); IF @hd_id IS NULL AND @t = 5 SET @hd_id = TRY_CAST(JSON_VALUE(@v, N'$.id') AS BIGINT); SET @piece = CASE WHEN @hd_id IS NOT NULL THEN N'dbo.pvt_is_descendant_of(' + CAST(@hd_id AS NVARCHAR(20)) + N', ' + @obj_alias + N'.[_id]) = 1' ELSE dbo.pvt_fail(N'$hasDescendant expects an object id') END; END -- ---- B2-expr: comparison operators with expression operands ---- ELSE IF @lk IN (N'$gt', N'$gte', N'$lt', N'$lte', N'$eq', N'$ne', N'$ilike') AND @t = 4 BEGIN DECLARE @b2_op1 NVARCHAR(MAX), @b2_op2 NVARCHAR(MAX); SELECT @b2_op1 = MIN(CASE WHEN [key] = '0' THEN [value] END), @b2_op2 = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@v); DECLARE @b2_cmp NVARCHAR(5) = CASE @lk WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' WHEN N'$ilike' THEN N'LIKE' END; DECLARE @b2_l NVARCHAR(MAX) = dbo.pvt_b2_expr_sql(@b2_op1, @fields, @obj_alias); DECLARE @b2_r NVARCHAR(MAX) = dbo.pvt_b2_expr_sql(@b2_op2, @fields, @obj_alias); -- Null-aware rewrite for $eq / $ne (parity with PG IS [NOT] DISTINCT FROM) IF @lk = N'$eq' AND @b2_r = N'NULL' AND @b2_l <> N'NULL' SET @piece = @b2_l + N' IS NULL'; ELSE IF @lk = N'$ne' AND @b2_r = N'NULL' AND @b2_l <> N'NULL' SET @piece = @b2_l + N' IS NOT NULL'; ELSE IF @lk = N'$eq' AND @b2_l = N'NULL' AND @b2_r <> N'NULL' SET @piece = @b2_r + N' IS NULL'; ELSE IF @lk = N'$ne' AND @b2_l = N'NULL' AND @b2_r <> N'NULL' SET @piece = @b2_r + N' IS NOT NULL'; ELSE IF @lk = N'$eq' AND @b2_l = N'NULL' AND @b2_r = N'NULL' SET @piece = N'1=1'; ELSE IF @lk = N'$ne' AND @b2_l = N'NULL' AND @b2_r = N'NULL' SET @piece = N'1=0'; ELSE SET @piece = @b2_l + N' ' + @b2_cmp + N' ' + @b2_r; END -- ---- B2-expr: $between [expr, lo, hi] ----------------------- ELSE IF @lk = N'$between' AND @t = 4 BEGIN DECLARE @bw_0 NVARCHAR(MAX), @bw_1 NVARCHAR(MAX), @bw_2 NVARCHAR(MAX); SELECT @bw_0 = MIN(CASE WHEN [key] = '0' THEN [value] END), @bw_1 = MIN(CASE WHEN [key] = '1' THEN [value] END), @bw_2 = MIN(CASE WHEN [key] = '2' THEN [value] END) FROM OPENJSON(@v); SET @piece = dbo.pvt_b2_expr_sql(@bw_0, @fields, @obj_alias) + N' BETWEEN ' + dbo.pvt_b2_expr_sql(@bw_1, @fields, @obj_alias) + N' AND ' + dbo.pvt_b2_expr_sql(@bw_2, @fields, @obj_alias); END -- ---- B2-expr: $in / $nin [expr, [v1, v2, ...]] -------------- ELSE IF @lk IN (N'$in', N'$nin') AND @t = 4 BEGIN DECLARE @iq_e NVARCHAR(MAX), @iq_vs NVARCHAR(MAX); SELECT @iq_e = MIN(CASE WHEN [key] = '0' THEN [value] END), @iq_vs = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@v); DECLARE @iq_list NVARCHAR(MAX) = N''; DECLARE c_iq CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@iq_vs); DECLARE @iq_iv NVARCHAR(MAX), @iq_it INT; OPEN c_iq; FETCH NEXT FROM c_iq INTO @iq_iv, @iq_it; WHILE @@FETCH_STATUS = 0 BEGIN IF @iq_list <> N'' SET @iq_list += N', '; SET @iq_list += dbo.pvt_jsonb_to_sql_literal(@iq_iv, @iq_it); FETCH NEXT FROM c_iq INTO @iq_iv, @iq_it; END; CLOSE c_iq; DEALLOCATE c_iq; IF @iq_list = N'' SET @iq_list = N'NULL'; DECLARE @iq_not NVARCHAR(5) = CASE WHEN @lk = N'$nin' THEN N'NOT ' ELSE N'' END; SET @piece = dbo.pvt_b2_expr_sql(@iq_e, @fields, @obj_alias) + N' ' + @iq_not + N'IN (' + @iq_list + N')'; END -- ---- B2-expr: $null / $notNull {expr} ----------------------- ELSE IF @lk = N'$null' AND @t = 5 SET @piece = dbo.pvt_b2_expr_sql(@v, @fields, @obj_alias) + N' IS NULL'; ELSE IF @lk = N'$notnull' AND @t = 5 SET @piece = dbo.pvt_b2_expr_sql(@v, @fields, @obj_alias) + N' IS NOT NULL'; -- ---- B2-expr: $contains / $startsWith [expr, literal_str] -- -- Second arg may be a bare JSON string OR a {"$const":"..."} wrapper -- (the .NET expression builder always emits constants as $const). ELSE IF @lk = N'$contains' AND @t = 4 BEGIN DECLARE @ct_e NVARCHAR(MAX), @ct_s NVARCHAR(MAX); SELECT @ct_e = MIN(CASE WHEN [key] = '0' THEN [value] END), @ct_s = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@v); IF @ct_s IS NOT NULL AND ISJSON(@ct_s) = 1 SET @ct_s = COALESCE(dbo.pvt_json_text(@ct_s, N'$const'), @ct_s); SET @piece = dbo.pvt_b2_expr_sql(@ct_e, @fields, @obj_alias) + N' LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(@ct_s) + N'%') + N' ESCAPE ''\'''; END ELSE IF @lk = N'$startswith' AND @t = 4 BEGIN DECLARE @sw_e NVARCHAR(MAX), @sw_s NVARCHAR(MAX); SELECT @sw_e = MIN(CASE WHEN [key] = '0' THEN [value] END), @sw_s = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@v); IF @sw_s IS NOT NULL AND ISJSON(@sw_s) = 1 SET @sw_s = COALESCE(dbo.pvt_json_text(@sw_s, N'$const'), @sw_s); SET @piece = dbo.pvt_b2_expr_sql(@sw_e, @fields, @obj_alias) + N' LIKE ' + dbo.pvt_sql_string_literal(dbo.pvt_like_escape(@sw_s) + N'%') + N' ESCAPE ''\'''; END ELSE IF @lk = N'$endswith' AND @t = 4 BEGIN DECLARE @es_e NVARCHAR(MAX), @es_s NVARCHAR(MAX); SELECT @es_e = MIN(CASE WHEN [key] = '0' THEN [value] END), @es_s = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@v); IF @es_s IS NOT NULL AND ISJSON(@es_s) = 1 SET @es_s = COALESCE(dbo.pvt_json_text(@es_s, N'$const'), @es_s); SET @piece = dbo.pvt_b2_expr_sql(@es_e, @fields, @obj_alias) + N' LIKE ' + dbo.pvt_sql_string_literal(N'%' + dbo.pvt_like_escape(@es_s)) + N' ESCAPE ''\'''; END -- ---- B2-expr: $regex / $iregex [expr, pattern] (Regex.IsMatch) -- -- REGEXP_LIKE: SQL Server 2025, compatibility level 170; an older server refuses it by name. ELSE IF @lk IN (N'$regex', N'$iregex') AND @t = 4 BEGIN DECLARE @rx_e NVARCHAR(MAX), @rx_p NVARCHAR(MAX); SELECT @rx_e = MIN(CASE WHEN [key] = '0' THEN [value] END), @rx_p = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@v); SET @piece = N'REGEXP_LIKE(' + dbo.pvt_b2_expr_sql(@rx_e, @fields, @obj_alias) + N', ' + dbo.pvt_b2_expr_sql(@rx_p, @fields, @obj_alias) + CASE WHEN @lk = N'$iregex' THEN N', ''i'')' ELSE N')' END; END -- $like: raw LIKE with full pattern from second arg expression ELSE IF @lk = N'$like' AND @t = 4 BEGIN DECLARE @lk_e NVARCHAR(MAX), @lk_p NVARCHAR(MAX); SELECT @lk_e = MIN(CASE WHEN [key] = '0' THEN [value] END), @lk_p = MIN(CASE WHEN [key] = '1' THEN [value] END) FROM OPENJSON(@v); SET @piece = dbo.pvt_b2_expr_sql(@lk_e, @fields, @obj_alias) + N' LIKE ' + dbo.pvt_b2_expr_sql(@lk_p, @fields, @obj_alias); END -- ---- Other unsupported top-level $* keys ---------------------- ELSE IF LEFT(@k, 1) = N'$' SET @piece = dbo.pvt_fail(N'unsupported operator ' + @k); ELSE BEGIN -- ---- Property function keys: Field.$length / Field[].$count ---- IF RIGHT(@k, 8) = N'.$length' OR RIGHT(@k, 7) = N'.$count' OR RIGHT(@k, 9) = N'[].$count' BEGIN DECLARE @pf_is_len BIT = CASE WHEN RIGHT(@k, 8) = N'.$length' THEN 1 ELSE 0 END; DECLARE @pf_base NVARCHAR(400); IF @pf_is_len = 1 SET @pf_base = LEFT(@k, LEN(@k) - 8); -- strip '.$length' ELSE IF RIGHT(@k, 9) = N'[].$count' SET @pf_base = LEFT(@k, LEN(@k) - 9); -- strip '[].$count' ELSE SET @pf_base = LEFT(@k, LEN(@k) - 7); -- strip '.$count' DECLARE @pf_meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@pf_base, 'json') + N'"'); IF @pf_meta IS NOT NULL BEGIN DECLARE @pf_sid NVARCHAR(32) = JSON_VALUE(@pf_meta, N'$.sid'); IF @pf_sid IS NOT NULL AND @t = 5 BEGIN DECLARE @pf_parts NVARCHAR(MAX) = N''; DECLARE @pf_cnt INT = 0; DECLARE c_pf CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value] FROM OPENJSON(@v); DECLARE @pfk NVARCHAR(50), @pfv NVARCHAR(MAX); OPEN c_pf; FETCH NEXT FROM c_pf INTO @pfk, @pfv; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @pf_cmp NVARCHAR(3) = CASE LOWER(@pfk) WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' ELSE dbo.pvt_fail(N'unsupported comparison ' + @pfk + N' on ' + @k) END; DECLARE @pf_num NVARCHAR(20) = COALESCE(CAST(TRY_CAST(@pfv AS INT) AS NVARCHAR(20)), dbo.pvt_fail(@k + N' expects an integer')); DECLARE @pf_frag NVARCHAR(MAX); IF @pf_is_len = 1 SET @pf_frag = N'EXISTS (SELECT 1 FROM dbo._values fv' + N' WHERE fv._id_object = ' + @obj_alias + N'.[_id]' + N' AND fv._id_structure = ' + @pf_sid + N' AND fv._array_index IS NULL' + N' AND LEN(fv.[_String]) ' + @pf_cmp + N' ' + @pf_num + N')'; ELSE SET @pf_frag = N'(SELECT COUNT(*) FROM dbo._values fv' + N' WHERE fv._id_object = ' + @obj_alias + N'.[_id]' + N' AND fv._id_structure = ' + @pf_sid + N' AND fv._array_index IS NOT NULL)' + N' ' + @pf_cmp + N' ' + @pf_num; IF @pf_cnt > 0 SET @pf_parts = @pf_parts + N' AND '; SET @pf_parts += @pf_frag; SET @pf_cnt += 1; FETCH NEXT FROM c_pf INTO @pfk, @pfv; END; CLOSE c_pf; DEALLOCATE c_pf; SET @piece = CASE WHEN @pf_cnt > 0 THEN @pf_parts ELSE N'1=1' END; END; END; IF @piece IS NULL SET @piece = dbo.pvt_fail(@k + N': field "' + @pf_base + N'" is not an array or string field of the scheme'); END ELSE BEGIN -- ---- Regular field leaf: ContainsKey rewrite + lookup ------- DECLARE @peek NVARCHAR(MAX) = dbo.pvt_peek_contains_key_value(@v); DECLARE @norm NVARCHAR(400) = dbo.pvt_normalize_field_name(@k, @peek); DECLARE @meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$.' + N'"' + STRING_ESCAPE(@norm, 'json') + N'"'); IF @meta IS NULL SET @piece = dbo.pvt_fail(N'field "' + @norm + N'" is not a field of the scheme'); ELSE IF @norm <> @k AND JSON_VALUE(@meta, '$.was_contains_key') = N'true' BEGIN -- ContainsKey: emit EXISTS checking _array_index = key. -- Covers both Dictionary (rows in struct itself) -- and Dictionary (rows in child structs). DECLARE @ck_sid NVARCHAR(32) = JSON_VALUE(@meta, N'$.sid'); DECLARE @ck_dict_key NVARCHAR(200) = JSON_VALUE(@meta, N'$.dict_key'); SET @piece = N'EXISTS (SELECT 1 FROM dbo._values av' + N' JOIN dbo._structures ds ON av._id_structure = ds._id' + N' WHERE av._id_object = ' + @obj_alias + N'.[_id]' + N' AND (ds._id = ' + COALESCE(@ck_sid, dbo.pvt_fail(N'ContainsKey on "' + @norm + N'": the dictionary has no structure id')) + N' OR ds._id_parent = ' + COALESCE(@ck_sid, dbo.pvt_fail(N'ContainsKey on "' + @norm + N'": the dictionary has no structure id')) + N')' + N' AND av._array_index = N''' + REPLACE(ISNULL(@ck_dict_key, N''), N'''', N'''''') + N''')'; END ELSE SET @piece = dbo.pvt_build_field_condition(@norm, @meta, @v, @t, @base_prefix); END; END; IF @piece IS NOT NULL BEGIN IF @cnt > 0 SET @parts = @parts + N' AND '; SET @parts = @parts + @piece; SET @cnt = @cnt + 1; END; FETCH NEXT FROM c INTO @k, @v, @t; END; CLOSE c; DEALLOCATE c; IF @cnt = 0 RETURN N'1=1'; IF @cnt = 1 RETURN @parts; RETURN N'(' + @parts + N')'; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/15_pvt_order.sql ---- -- ===================================================================== -- 15_pvt_order.sql (MSSql v2-pvt) — ORDER BY builder -- --------------------------------------------------------------------- -- Supports {field|field_path,dir,nulls} and {"$expr":{...},"dir",...} -- entries. $expr delegates to pvt_b2_expr_sql. No DISTINCT ON. -- Returns either '' or '\nORDER BY '. T-SQL has no `NULLS FIRST/LAST` -- syntax; emulate via CASE WHEN ... IS NULL THEN 0 ELSE 1 END prefix. -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.pvt_build_order_conditions( @order NVARCHAR(MAX), @fields NVARCHAR(MAX), @base_prefix NVARCHAR(10) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @order IS NULL OR ISJSON(@order) = 0 RETURN N''; DECLARE @parts NVARCHAR(MAX) = N''; DECLARE @cnt INT = 0; DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@order); DECLARE @e NVARCHAR(MAX); OPEN c; FETCH NEXT FROM c INTO @e; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @fld NVARCHAR(400) = COALESCE(JSON_VALUE(@e, '$.field'), JSON_VALUE(@e, '$.field_path')); DECLARE @dir NVARCHAR(10) = LOWER(COALESCE(JSON_VALUE(@e, '$.dir'), JSON_VALUE(@e, '$.direction'), N'asc')); DECLARE @nulls NVARCHAR(10) = LOWER(COALESCE(JSON_VALUE(@e, '$.nulls'), N'')); IF @dir NOT IN (N'asc', N'desc') SET @dir = N'asc'; DECLARE @expr_node NVARCHAR(MAX) = JSON_QUERY(@e, N'$."$expr"'); IF @expr_node IS NOT NULL BEGIN -- $expr ORDER BY: delegate to pvt_b2_expr_sql. -- pvt_b2_expr_sql expects @obj_alias WITHOUT trailing dot -- (matches pvt_build_where_from_json convention). DECLARE @b2_alias NVARCHAR(50) = CASE WHEN @base_prefix = N'o.' THEN N'o' ELSE N'_pvt_cte' END; DECLARE @eprt NVARCHAR(MAX) = dbo.pvt_b2_expr_sql(@expr_node, @fields, @b2_alias); IF @eprt IS NOT NULL AND @eprt <> N'' BEGIN IF @cnt > 0 SET @parts = @parts + N', '; DECLARE @eterm NVARCHAR(MAX) = N'(' + @eprt + N') ' + UPPER(@dir); IF @nulls = N'first' SET @parts = @parts + N'CASE WHEN (' + @eprt + N') IS NULL THEN 0 ELSE 1 END, ' + @eterm; ELSE IF @nulls = N'last' SET @parts = @parts + N'CASE WHEN (' + @eprt + N') IS NULL THEN 1 ELSE 0 END, ' + @eterm; ELSE SET @parts = @parts + @eterm; SET @cnt = @cnt + 1; END; END ELSE IF @fld IS NOT NULL AND @fld <> N'' BEGIN DECLARE @meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$.' + N'"' + STRING_ESCAPE(@fld, 'json') + N'"'); DECLARE @col NVARCHAR(200); IF @meta IS NOT NULL AND JSON_VALUE(@meta, '$.kind') = N'base' SET @col = ISNULL(@base_prefix, N'') + QUOTENAME(JSON_VALUE(@meta, '$.column')); ELSE SET @col = QUOTENAME(@fld); IF @cnt > 0 SET @parts = @parts + N', '; IF @nulls = N'first' SET @parts = @parts + N'CASE WHEN ' + @col + N' IS NULL THEN 0 ELSE 1 END, '; ELSE IF @nulls = N'last' SET @parts = @parts + N'CASE WHEN ' + @col + N' IS NULL THEN 1 ELSE 0 END, '; SET @parts = @parts + @col + N' ' + UPPER(@dir); SET @cnt = @cnt + 1; END; FETCH NEXT FROM c INTO @e; END; CLOSE c; DEALLOCATE c; IF @cnt = 0 RETURN N''; RETURN CHAR(10) + N'ORDER BY ' + @parts; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/16_pvt_split.sql ---- -- ===================================================================== -- 16_pvt_split.sql (MSSql v2-pvt) — Pro-parity base pushdown optimizer -- --------------------------------------------------------------------- -- Walks the filter JSON and splits it into two parts: -- -- * push — SQL predicate over `_objects o.*` safe to AND with -- `o._id_scheme = X` inside the pivot CTE; lets the -- optimizer narrow _objects BEFORE the expensive pivot -- JOIN with _values + GROUP BY. -- * residual — 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: -- dbo.pvt_split_filter(@filter NVARCHAR(MAX), @fields NVARCHAR(MAX)) -- RETURNS NVARCHAR(MAX) — JSON: {"push": "", -- "residual": } -- -- T-SQL scalar UDFs cannot have OUT parameters, hence the JSON-encoded -- composite return. Callers parse via JSON_VALUE / JSON_QUERY. -- -- 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. -- -- Phase 1 + 2 (parity with PG / Pro): -- * Hierarchical + field-leaf pushdown (Phase 1). -- * Expression-form predicates at top level ($eq/$ne/.../$between/$in -- and $expr) — pushable iff every $field reference inside resolves -- to kind='base' (see dbo.pvt_expr_is_base_only in 17_pvt_expr.sql). -- * Common form {Field: {$op: value}} is covered via the field-leaf -- branch and benefits from the same kind='base' gating. -- -- Recursion: T-SQL scalar UDFs support nesting up to @@NESTLEVEL = 32, -- which is sufficient for any realistic filter tree. -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.pvt_split_filter( @filter NVARCHAR(MAX), @fields NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN -- ----- Empty / null filter ----- IF @filter IS NULL OR @filter = N'' OR @filter = N'{}' RETURN N'{"push":null,"residual":null}'; IF ISJSON(@filter) = 0 RETURN N'{"push":null,"residual":null}'; -- ----- Scan top-level keys ----- DECLARE @key_count INT = (SELECT COUNT(*) FROM OPENJSON(@filter)); IF @key_count = 0 RETURN N'{"push":null,"residual":null}'; -- Detect logical singleton: $and / $or / $not (case-insensitive). DECLARE @op_key NVARCHAR(50) = ( SELECT TOP 1 [key] FROM OPENJSON(@filter) WHERE LOWER([key]) IN (N'$and', N'$or', N'$not') ); DECLARE @is_logical BIT = CASE WHEN @op_key IS NOT NULL AND @key_count = 1 THEN 1 ELSE 0 END; -- Helpers used in many branches. DECLARE @push_sql NVARCHAR(MAX) = NULL; DECLARE @residual NVARCHAR(MAX) = NULL; DECLARE @push_buf NVARCHAR(MAX) = N''; DECLARE @push_cnt INT = 0; DECLARE @res_buf NVARCHAR(MAX) = N''; DECLARE @res_cnt INT = 0; -- Recursion scratch. DECLARE @elem_val NVARCHAR(MAX); DECLARE @child NVARCHAR(MAX); DECLARE @cpush NVARCHAR(MAX); DECLARE @cres NVARCHAR(MAX); -- ============================================================ -- 1) Logical singleton: $and / $or / $not -- ============================================================ IF @is_logical = 1 BEGIN DECLARE @op_lower NVARCHAR(50) = LOWER(@op_key); DECLARE @op_val NVARCHAR(MAX) = JSON_QUERY(@filter, N'$."' + STRING_ESCAPE(@op_key, 'json') + N'"'); -- ---- $and ---- IF @op_lower = N'$and' BEGIN IF @op_val IS NULL OR ISJSON(@op_val) = 0 RETURN N'{"push":null,"residual":null}'; DECLARE cAnd CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@op_val); OPEN cAnd; FETCH NEXT FROM cAnd INTO @elem_val; WHILE @@FETCH_STATUS = 0 BEGIN SET @child = dbo.pvt_split_filter(@elem_val, @fields); SET @cpush = dbo.pvt_json_text(@child, N'push'); SET @cres = JSON_QUERY(@child, N'$.residual'); IF @cpush IS NOT NULL BEGIN IF @push_cnt > 0 SET @push_buf = @push_buf + N' AND '; SET @push_buf = @push_buf + @cpush; SET @push_cnt = @push_cnt + 1; END; IF @cres IS NOT NULL BEGIN IF @res_cnt > 0 SET @res_buf = @res_buf + N','; SET @res_buf = @res_buf + @cres; SET @res_cnt = @res_cnt + 1; END; FETCH NEXT FROM cAnd INTO @elem_val; END; CLOSE cAnd; DEALLOCATE cAnd; IF @push_cnt = 1 SET @push_sql = @push_buf; ELSE IF @push_cnt > 1 SET @push_sql = N'(' + @push_buf + N')'; IF @res_cnt = 1 SET @residual = @res_buf; ELSE IF @res_cnt > 1 SET @residual = N'{"$and":[' + @res_buf + N']}'; GOTO ret; END; -- ---- $or ---- IF @op_lower = N'$or' BEGIN IF @op_val IS NULL OR ISJSON(@op_val) = 0 RETURN N'{"push":null,"residual":null}'; DECLARE @all_pushable BIT = 1; DECLARE @or_buf NVARCHAR(MAX) = N''; DECLARE @or_cnt INT = 0; DECLARE cOr CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@op_val); OPEN cOr; FETCH NEXT FROM cOr INTO @elem_val; WHILE @@FETCH_STATUS = 0 AND @all_pushable = 1 BEGIN SET @child = dbo.pvt_split_filter(@elem_val, @fields); SET @cpush = dbo.pvt_json_text(@child, N'push'); SET @cres = JSON_QUERY(@child, N'$.residual'); IF @cres IS NOT NULL OR @cpush IS NULL SET @all_pushable = 0; ELSE BEGIN IF @or_cnt > 0 SET @or_buf = @or_buf + N' OR '; SET @or_buf = @or_buf + @cpush; SET @or_cnt = @or_cnt + 1; END; FETCH NEXT FROM cOr INTO @elem_val; END; CLOSE cOr; DEALLOCATE cOr; IF @all_pushable = 1 AND @or_cnt > 0 BEGIN SET @push_sql = N'(' + @or_buf + N')'; SET @residual = NULL; END ELSE BEGIN SET @push_sql = NULL; SET @residual = @filter; END; GOTO ret; END; -- ---- $not ---- IF @op_lower = N'$not' BEGIN IF @op_val IS NULL BEGIN SET @residual = @filter; GOTO ret; END; SET @child = dbo.pvt_split_filter(@op_val, @fields); SET @cpush = dbo.pvt_json_text(@child, N'push'); SET @cres = JSON_QUERY(@child, N'$.residual'); IF @cres IS NULL AND @cpush IS NOT NULL BEGIN SET @push_sql = N'NOT (' + @cpush + N')'; SET @residual = NULL; END ELSE BEGIN SET @push_sql = NULL; SET @residual = @filter; END; GOTO ret; END; END; -- ============================================================ -- 2) Multi-key object: implicit $and of singletons. -- ============================================================ IF @key_count > 1 BEGIN DECLARE @ek NVARCHAR(400); DECLARE @ev NVARCHAR(MAX); DECLARE @et INT; DECLARE @singleton NVARCHAR(MAX); DECLARE @ev_json NVARCHAR(MAX); DECLARE cM CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@filter); OPEN cM; FETCH NEXT FROM cM INTO @ek, @ev, @et; WHILE @@FETCH_STATUS = 0 BEGIN -- Re-encode value as JSON literal for singleton object. -- type codes: 1=string, 2=number, 3=bool, 4=array, 5=object, 0=null. SET @ev_json = CASE @et WHEN 0 THEN N'null' WHEN 1 THEN N'"' + STRING_ESCAPE(@ev, 'json') + N'"' WHEN 2 THEN @ev WHEN 3 THEN @ev WHEN 4 THEN @ev WHEN 5 THEN @ev ELSE @ev END; SET @singleton = N'{"' + STRING_ESCAPE(@ek, 'json') + N'":' + @ev_json + N'}'; SET @child = dbo.pvt_split_filter(@singleton, @fields); SET @cpush = dbo.pvt_json_text(@child, N'push'); SET @cres = JSON_QUERY(@child, N'$.residual'); IF @cpush IS NOT NULL BEGIN IF @push_cnt > 0 SET @push_buf = @push_buf + N' AND '; SET @push_buf = @push_buf + @cpush; SET @push_cnt = @push_cnt + 1; END; IF @cres IS NOT NULL BEGIN IF @res_cnt > 0 SET @res_buf = @res_buf + N','; SET @res_buf = @res_buf + @cres; SET @res_cnt = @res_cnt + 1; END; FETCH NEXT FROM cM INTO @ek, @ev, @et; END; CLOSE cM; DEALLOCATE cM; IF @push_cnt = 1 SET @push_sql = @push_buf; ELSE IF @push_cnt > 1 SET @push_sql = N'(' + @push_buf + N')'; IF @res_cnt = 1 SET @residual = @res_buf; ELSE IF @res_cnt > 1 SET @residual = N'{"$and":[' + @res_buf + N']}'; GOTO ret; END; -- ============================================================ -- 3) Single-key leaf: hierarchical / expression / field. -- ============================================================ DECLARE @k NVARCHAR(400); DECLARE @v NVARCHAR(MAX); DECLARE @t INT; SELECT TOP 1 @k = [key], @v = [value], @t = [type] FROM OPENJSON(@filter); DECLARE @k_lower NVARCHAR(400) = LOWER(@k); -- ---- Hierarchical operators: always pushable ---- IF @k_lower IN (N'$hasancestor', N'$hasdescendant', N'$level', N'$isroot', N'$isleaf', N'$childrenof') BEGIN DECLARE @v_json_h NVARCHAR(MAX) = CASE @t WHEN 0 THEN N'null' WHEN 1 THEN N'"' + STRING_ESCAPE(@v, 'json') + N'"' ELSE @v END; DECLARE @h_in NVARCHAR(MAX) = N'{"' + STRING_ESCAPE(@k, 'json') + N'":' + @v_json_h + N'}'; DECLARE @h_out NVARCHAR(MAX) = dbo.pvt_build_hierarchical_conditions(@h_in, N'o'); IF @h_out IS NOT NULL AND @h_out <> N'' BEGIN SET @h_out = LTRIM(@h_out); IF LEN(@h_out) >= 4 AND UPPER(LEFT(@h_out, 4)) = N'AND ' SET @h_out = LTRIM(SUBSTRING(@h_out, 5, LEN(@h_out))); IF @h_out <> N'' SET @push_sql = @h_out; END; SET @residual = NULL; GOTO ret; END; -- ---- Expression-form predicate / $expr at root (Phase 2 parity) ---- -- Pushable iff every $field reference inside resolves to kind='base'. -- When pushable we reuse the regular WHERE walker against the inner -- `_objects o.*` alias (base_prefix='o.') so emitted SQL is exactly -- what runs in the outer Shape A path -- no duplicate compiler. IF @k_lower IN ( N'$eq', N'$ne', N'$lt', N'$lte', N'$gt', N'$gte', N'$like', N'$ilike', N'$regex', N'$iregex', N'$in', N'$nin', N'$between', N'$null', N'$notnull', N'$contains', N'$startswith', N'$endswith' ) BEGIN IF dbo.pvt_expr_is_base_only(@v, @fields) = 1 BEGIN DECLARE @push_pred NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@filter, @fields, N'o.'); IF @push_pred IS NOT NULL AND @push_pred <> N'' AND @push_pred <> N'1=1' SET @push_sql = @push_pred; SET @residual = NULL; END ELSE BEGIN SET @push_sql = NULL; SET @residual = @filter; END; GOTO ret; END; IF @k_lower = N'$expr' BEGIN IF dbo.pvt_expr_is_base_only(@v, @fields) = 1 BEGIN DECLARE @push_expr NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@v, @fields, N'o.'); IF @push_expr IS NOT NULL AND @push_expr <> N'' AND @push_expr <> N'1=1' SET @push_sql = @push_expr; SET @residual = NULL; END ELSE BEGIN SET @push_sql = NULL; SET @residual = @filter; END; GOTO ret; END; -- ---- Field leaf: look up metadata; push only if kind='base' ---- DECLARE @peek NVARCHAR(MAX) = dbo.pvt_peek_contains_key_value(@v); DECLARE @norm NVARCHAR(400) = dbo.pvt_normalize_field_name(@k, @peek); DECLARE @meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@norm, 'json') + N'"'); IF @meta IS NULL BEGIN -- Unknown field: leave to the outer walker so its error message fires. SET @push_sql = NULL; SET @residual = @filter; GOTO ret; END; DECLARE @kind NVARCHAR(50) = JSON_VALUE(@meta, N'$.kind'); IF @kind = N'base' BEGIN -- ContainsKey rewrites are dict-pivot only, never base; safe here. -- pvt_build_field_condition needs op-type code; @t already captured. DECLARE @cond NVARCHAR(MAX) = dbo.pvt_build_field_condition( @norm, @meta, @v, @t, N'o.'); IF @cond IS NOT NULL AND @cond <> N'' AND @cond <> N'1=1' SET @push_sql = @cond; ELSE SET @push_sql = NULL; SET @residual = NULL; END ELSE BEGIN SET @push_sql = NULL; SET @residual = @filter; END; ret: DECLARE @out_push NVARCHAR(MAX) = CASE WHEN @push_sql IS NULL THEN N'null' ELSE N'"' + STRING_ESCAPE(@push_sql, 'json') + N'"' END; DECLARE @out_res NVARCHAR(MAX) = ISNULL(@residual, N'null'); RETURN N'{"push":' + @out_push + N',"residual":' + @out_res + N'}'; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/17_pvt_expr.sql ---- -- ===================================================================== -- 17_pvt_expr.sql (MSSql v2-pvt) — expression-form pushdown classifier -- --------------------------------------------------------------------- -- Port of PG's `pvt_expr_field_names` / `pvt_expr_is_base_only` -- (see redb.Postgres/sql/v2-pvt/17_pvt_expr.sql), tailored for T-SQL -- scalar UDF constraints. -- -- Unlike PG we DO NOT reintroduce a separate scalar-expression compiler -- here. T-SQL already has the proven `pvt_b2_expr_sql` (file 14) and -- `pvt_build_where_from_json` (file 14) which together cover the same -- scalar + predicate surface used by Pro/PG. The split optimizer -- (file 16) reuses them to emit the pushed-down SQL once -- pvt_expr_is_base_only confirms every `$field` reference resolves to -- a base column. -- -- Function: -- dbo.pvt_expr_is_base_only(@node, @fields) RETURNS BIT -- 1 iff every "$field" reference inside @node has metadata with -- kind='base' in @fields. NULL / non-JSON nodes are vacuously base. -- Returns 0 if a referenced field has no metadata at all (so a -- mistyped $field name does not silently get pushed down). -- -- Walker rules: -- * Recurses into every object / array value via OPENJSON. -- * Treats a `$const` key as opaque (its value is a literal and may -- contain strings shaped like field names — must not be walked). -- * Treats a `$field` STRING value as a field reference. -- -- Limitations vs the PG walker: -- * Does not special-case unit-string literals of $cast / $dateAdd / -- $dateDiff / $dateTrunc / $fts.language. In practice those are -- plain JSON strings (type=1 in OPENJSON), never objects with a -- `$field` key, so the naive walk does not generate false positives. -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.pvt_expr_is_base_only( @node NVARCHAR(MAX), @fields NVARCHAR(MAX) ) RETURNS BIT AS BEGIN -- Vacuously base: NULL / non-JSON / bare scalar literal. IF @node IS NULL RETURN 1; IF ISJSON(@node) = 0 RETURN 1; DECLARE @k NVARCHAR(400), @v NVARCHAR(MAX), @t INT; DECLARE @lk NVARCHAR(50); DECLARE @meta NVARCHAR(MAX); DECLARE @kind NVARCHAR(50); DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@node); OPEN c; FETCH NEXT FROM c INTO @k, @v, @t; WHILE @@FETCH_STATUS = 0 BEGIN SET @lk = LOWER(@k); -- $const subtree: opaque literal, never walked. IF @lk = N'$const' BEGIN FETCH NEXT FROM c INTO @k, @v, @t; CONTINUE; END; -- $field leaf: must resolve to kind='base'. IF @lk = N'$field' AND @t = 1 BEGIN SET @meta = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@v, 'json') + N'"'); IF @meta IS NULL BEGIN CLOSE c; DEALLOCATE c; RETURN 0; END; SET @kind = JSON_VALUE(@meta, N'$.kind'); IF @kind IS NULL OR @kind <> N'base' BEGIN CLOSE c; DEALLOCATE c; RETURN 0; END; END -- Object / array value: recurse. ELSE IF @t IN (4, 5) BEGIN IF dbo.pvt_expr_is_base_only(@v, @fields) = 0 BEGIN CLOSE c; DEALLOCATE c; RETURN 0; END; END; -- String / number / bool / null leaves not under $field: ignore. FETCH NEXT FROM c INTO @k, @v, @t; END; CLOSE c; DEALLOCATE c; RETURN 1; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/20_pvt_build_query_sql.sql ---- -- ===================================================================== -- 20_pvt_build_query_sql.sql (MSSql v2-pvt) — orchestrator -- --------------------------------------------------------------------- -- Pure SQL string generation. Output yields two columns: `_id` and `_ord`, the position of the row in the order of -- the query. The caller wraps it as a derived table and sorts by `_ord` (since 0.2.45). -- -- Shapes: -- A) pure-base (no PROPS field referenced): -- SELECT o.[_id] AS [_id], ROW_NUMBER() OVER (ORDER BY ..., o.[_id]) AS [_ord] FROM dbo._objects o -- WHERE o.[_id_scheme] = X AND -- [ORDER BY ...] [OFFSET ... ROWS FETCH NEXT ... ROWS ONLY] -- -- C) wide CTE (any PROPS field referenced): -- SELECT [_id], ROW_NUMBER() OVER (...) AS [_ord] FROM (...) _pvt_cte -- WHERE -- [ORDER BY ...] [OFFSET ... ROWS FETCH NEXT ... ROWS ONLY] -- -- Slice limits: no narrow, no tree, no pushdown. -- DistinctBy: emulated via ROW_NUMBER() OVER (PARTITION BY key) = 1. -- MSSql paging: OFFSET/FETCH requires ORDER BY -> inject 'ORDER BY (SELECT 1)' -- when none specified and paging requested. -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.pvt_build_query_sql( @scheme_id BIGINT, @filter NVARCHAR(MAX), @limit INT, @offset INT, @order NVARCHAR(MAX), @max_depth INT, @distinct BIT, @source_mode NVARCHAR(50), @tree_ids NVARCHAR(MAX), @include_seed BIT, @polymorphic BIT, @distinct_on NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN NULL; IF @source_mode IS NULL SET @source_mode = N'flat'; -- WhereLevel of a tree query that starts from nodes counts from them (the start is 0, its children 1), as the -- maxDepth of the same query and Pro count it: $level leaves the filter and becomes a condition on the walk depth -- of pvt_tree_descendants (the first depth of a node reached from two starts). Without start nodes (the whole -- scheme) the level stays absolute, counted from the root. DECLARE @seed_level_sql NVARCHAR(MAX) = NULL; IF @source_mode IN (N'tree', N'tree_descendants', N'tree_children', N'tree_roots', N'tree_leaves') AND @tree_ids IS NOT NULL AND ISJSON(@tree_ids) = 1 AND ISJSON(@filter) = 1 AND EXISTS (SELECT 1 FROM OPENJSON(@filter) WHERE [key] = N'$level') BEGIN DECLARE @lvl_value NVARCHAR(MAX), @lvl_type INT, @lvl_cond NVARCHAR(MAX); SELECT @lvl_value = [value], @lvl_type = [type] FROM OPENJSON(@filter) WHERE [key] = N'$level'; IF @lvl_type = 2 SET @lvl_cond = N'depth = ' + CAST(CAST(@lvl_value AS INT) AS NVARCHAR(20)); ELSE IF @lvl_type = 5 SELECT @lvl_cond = STRING_AGG(N'depth ' + CASE [key] WHEN N'$gt' THEN N'>' WHEN N'$gte' THEN N'>=' WHEN N'$lt' THEN N'<' WHEN N'$lte' THEN N'<=' WHEN N'$eq' THEN N'=' WHEN N'$ne' THEN N'<>' ELSE dbo.pvt_fail(N'unsupported $level operator ' + [key]) END + N' ' + CAST(CAST([value] AS INT) AS NVARCHAR(20)), N' AND ') FROM OPENJSON(@lvl_value); ELSE SET @lvl_cond = dbo.pvt_fail(N'$level expects a number or an operator object'); SET @seed_level_sql = N'o.[_id] IN (SELECT _id FROM dbo.pvt_tree_descendants(' + CAST(@scheme_id AS NVARCHAR(40)) + N', N''' + REPLACE(@tree_ids, N'''', N'''''') + N''', ' + CASE WHEN @max_depth IS NULL THEN N'NULL' ELSE CAST(@max_depth AS NVARCHAR(20)) END + N', ' + CAST(COALESCE(@polymorphic, 1) AS NVARCHAR(1)) + N', 1) WHERE ' + COALESCE(@lvl_cond, N'1 = 1') + N')'; SET @filter = JSON_MODIFY(@filter, N'$."$level"', NULL); END; -- Guard: @distinct=1 and @distinct_on not null are mutually exclusive. -- Scalar UDFs cannot THROW; force a runtime cast error whose message -- contains 'mutually exclusive' so callers can detect the guard. IF @distinct = 1 AND @distinct_on IS NOT NULL AND ISJSON(@distinct_on) = 1 BEGIN DECLARE @_guard INT = CAST(N'p_distinct and p_distinct_on are mutually exclusive' AS INT); END; -- Merge @distinct_on entries into @order for field collection so that -- any PROPS field referenced in @distinct_on triggers Shape C correctly. DECLARE @collect_order NVARCHAR(MAX) = CASE WHEN @distinct_on IS NULL OR ISJSON(@distinct_on) = 0 THEN @order WHEN @order IS NULL OR ISJSON(@order) = 0 THEN @distinct_on ELSE LEFT(@order, LEN(@order) - 1) + N',' + SUBSTRING(@distinct_on, 2, LEN(@distinct_on) - 1) END; DECLARE @fields NVARCHAR(MAX) = dbo.pvt_collect_fields(@scheme_id, @filter, @collect_order); -- Pure-base shortcut: every collected field has kind='base' DECLARE @has_props BIT = 0; DECLARE @has_nested BIT = 0; -- any nested-dict field (parent_sid + dict_key) DECLARE @has_scalar BIT = 0; -- any PROPS field that is NOT nested-dict IF @fields IS NOT NULL AND ISJSON(@fields) = 1 AND @fields <> N'{}' BEGIN IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], '$.kind') <> N'base' ) SET @has_props = 1; IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], '$.parent_sid') IS NOT NULL AND JSON_VALUE([value], '$.dict_key') IS NOT NULL ) SET @has_nested = 1; IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], '$.kind') <> N'base' AND NOT ( JSON_VALUE([value], '$.parent_sid') IS NOT NULL AND JSON_VALUE([value], '$.dict_key') IS NOT NULL ) ) SET @has_scalar = 1; END; -- Narrow vs wide decision (PG parity, see redb.Postgres/sql/v2-pvt/20_pvt_build_query_sql.sql). -- @force_outer = 1 means the wide LEFT JOIN shape is mandatory: -- - any absence check ($null / $isNull) needs LEFT JOIN to surface NULL pivot rows, -- - pure-base / empty-field queries do not need a pivot at all. -- @narrow = 1 means we can use the Pro-shape narrow pivot -- (FROM _values v / GROUP BY 1 / IN (SELECT FROM _objects)) and JOIN _objects in the outer SELECT. -- Mixed (scalar + nested-dict in the same query) forces wide because the nested side CTE expects pi.* projection. DECLARE @has_null BIT = dbo.pvt_has_absence_check(@filter); DECLARE @force_outer BIT = CASE WHEN @has_null = 1 OR @has_props = 0 THEN 1 ELSE 0 END; -- Narrow with nested: 12 emits a slim pivot (GROUP BY o.[_id]) and -- the orchestrator JOINs _objects in the outer SELECT, so the heavy -- 21-col GROUP BY is gone even when nested-dict fields are present. DECLARE @narrow BIT = CASE WHEN @force_outer = 0 THEN 1 ELSE 0 END; DECLARE @paging NVARCHAR(MAX) = N''; IF @limit IS NOT NULL AND @limit >= 0 BEGIN IF COALESCE(@offset, 0) = 0 SET @paging = CHAR(10) + N'OFFSET 0 ROWS FETCH NEXT ' + CAST(@limit AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @paging = CHAR(10) + N'OFFSET ' + CAST(@offset AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit AS NVARCHAR(20)) + N' ROWS ONLY'; END ELSE IF COALESCE(@offset, 0) > 0 SET @paging = CHAR(10) + N'OFFSET ' + CAST(@offset AS NVARCHAR(20)) + N' ROWS'; -- Outer alias prefix for base columns: Shape A and narrow Shape B both expose -- base columns on alias `o` (via JOIN _objects); legacy wide Shape C exposes -- them on `_pvt_cte` (projected by the wide GROUP BY). Pivot/scalar columns -- always render unprefixed (pvt_build_field_condition/_order skip the prefix -- for kind <> 'base'), so unique pivot names resolve to _pvt_cte automatically. DECLARE @base_prefix NVARCHAR(10) = CASE WHEN @has_props = 0 OR @narrow = 1 THEN N'o.' ELSE N'_pvt_cte.' END; DECLARE @order_sql NVARCHAR(MAX) = dbo.pvt_build_order_conditions(@order, @fields, @base_prefix); -- The ordering columns alone (no "ORDER BY"), for the ROW_NUMBER of the DistinctBy branches: they rank -- inside the row source, where pivot columns are visible, and are kept even without paging. DECLARE @order_cols NVARCHAR(MAX) = CASE WHEN @order_sql = N'' THEN N'' ELSE SUBSTRING(@order_sql, 11, LEN(@order_sql)) + N', ' -- skip CHAR(10) + N'ORDER BY ' (10 chars) END; -- T-SQL forbids ORDER BY inside subqueries unless paired with TOP/OFFSET-FETCH, -- and the C# layer always wraps the output as a derived table. Paging without an -- order gets a stable default (@base_prefix + [_id]); an order without paging -- gets OFFSET 0 ROWS, which keeps it. It used to be dropped, and OrderBy without -- Take came back in whatever order the plan produced. IF @paging <> N'' AND @order_sql = N'' SET @order_sql = CHAR(10) + N'ORDER BY ' + @base_prefix + N'[_id]'; ELSE IF @paging = N'' AND @order_sql <> N'' SET @order_sql = @order_sql + CHAR(10) + N'OFFSET 0 ROWS'; -- @paging stays empty: the DISTINCT branches are as before -- DISTINCT (@distinct=1) wraps the row-source in a derived table `_dist` that -- projects only [_id]; the OUTER ORDER BY must reference that projected column, -- NOT the inner alias prefix (`o.`/`_pvt_cte.` don't exist outside the wrapper — -- that caused "The multi-part identifier 'o._id' could not be bound" with .Take()). -- T-SQL also forbids ORDER BY on columns absent from a DISTINCT SELECT, so only -- the projected [_id] is orderable here; use it for deterministic paging. DECLARE @order_sql_dist NVARCHAR(MAX) = CASE WHEN @paging <> N'' THEN CHAR(10) + N'ORDER BY [_id]' ELSE N'' END; -- Every statement returns [_id] and [_ord], the position of the row in the order of the query (its ORDER BY, the -- object id after it). A derived table keeps no order in T-SQL: the caller sorts by [_ord] outside. Numbering the -- rows outside, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), may run before the inner sort, and -- OrderByDescending(key).DistinctBy(key) came back ascending. DECLARE @ord_dist NVARCHAR(MAX) = N'ROW_NUMBER() OVER (ORDER BY [_id]) AS [_ord]'; -- DistinctBy emulation: T-SQL has no SELECT DISTINCT ON. The row source gets -- _rn = ROW_NUMBER() OVER (PARTITION BY ORDER BY , ) -- first row of a key by the query order -- _ord = ROW_NUMBER() OVER (ORDER BY , ) -- the query order itself -- and the wrapper keeps _rn = 1 ordered by _ord. The ordering is evaluated inside the row source, where -- pivot columns resolve (an outer ORDER BY on a Props field failed: "Invalid column name"), and it is kept -- without paging (OFFSET 0 ROWS). Every key of @distinct_on is partitioned by (DistinctRedb sends the -- object's columns); up to 0.2.30 the first key only, ranked by (SELECT 1), with the order applied outside. -- Keys are stored alias-qualified per current shape: -- base col -> @base_prefix + [DbCol] (e.g. o.[_name] / _pvt_cte.[_name]) -- props col -> _pvt_cte.[FieldName] (pivot cols always live in _pvt_cte) DECLARE @rn_col NVARCHAR(MAX) = NULL; IF @distinct_on IS NOT NULL AND ISJSON(@distinct_on) = 1 BEGIN SELECT @rn_col = STRING_AGG( CASE WHEN JSON_VALUE(m.meta, '$.kind') = N'base' THEN @base_prefix + QUOTENAME(JSON_VALUE(m.meta, '$.column')) ELSE N'_pvt_cte.' + QUOTENAME(d.field) END, N', ') WITHIN GROUP (ORDER BY d.pos) FROM (SELECT CAST([key] AS INT) AS pos, JSON_VALUE([value], '$.field') AS field FROM OPENJSON(@distinct_on)) d CROSS APPLY (SELECT JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(d.field, 'json') + N'"') AS meta) m WHERE d.field IS NOT NULL AND d.field <> N''; END; DECLARE @rn_paging NVARCHAR(MAX) = CASE WHEN @paging = N'' THEN CHAR(10) + N'OFFSET 0 ROWS' ELSE @paging END; -- ---------- Tree mode branch ---------- -- Handles tree_roots, tree_leaves, tree_children, tree_descendants, tree_ancestors. -- When @has_props = 0: emit a flat subquery-safe SELECT against _objects using -- the corresponding tree predicate; no WITH-CTE prefix so the result can be -- wrapped in a derived table by the C# layer. -- When @has_props = 1: delegate to pvt_build_cte_sql which natively supports -- every tree mode (it injects o.[_id] IN (SELECT _id FROM dbo.pvt_tree_*(...))) -- and then wrap with the Shape C outer SELECT / residual WHERE. IF @source_mode IN (N'tree_roots', N'tree_leaves', N'tree_children', N'tree_descendants', N'tree_ancestors') BEGIN IF @has_props = 1 BEGIN DECLARE @splitT NVARCHAR(MAX) = dbo.pvt_split_filter(@filter, @fields); DECLARE @pushT NVARCHAR(MAX) = dbo.pvt_json_text(@splitT, N'push'); IF @seed_level_sql IS NOT NULL SET @pushT = CASE WHEN @pushT IS NULL OR @pushT = N'' THEN @seed_level_sql ELSE N'(' + @pushT + N') AND ' + @seed_level_sql END; DECLARE @resT NVARCHAR(MAX) = JSON_QUERY(@splitT, N'$.residual'); DECLARE @innerT NVARCHAR(MAX) = dbo.pvt_build_cte_sql( @scheme_id, @fields, @source_mode, @tree_ids, @max_depth, @force_outer, @pushT, @narrow, COALESCE(@include_seed, 1), COALESCE(@polymorphic, 1), DEFAULT); IF @innerT IS NULL RETURN NULL; DECLARE @whereTp NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@resT, @fields, @base_prefix); DECLARE @joinT NVARCHAR(MAX) = CASE WHEN @narrow = 1 THEN CHAR(10) + N'JOIN dbo._objects o ON o.[_id] = _pvt_cte.[_id_object]' ELSE N'' END; DECLARE @rowSelT NVARCHAR(MAX) = CASE WHEN @narrow = 1 THEN N'o.[_id]' ELSE N'_pvt_cte.[_id]' END; IF @rn_col IS NOT NULL RETURN N'SELECT [_id], [_ord] FROM (' + CHAR(10) + N'SELECT ' + @rowSelT + N' AS [_id], ' + N'ROW_NUMBER() OVER (PARTITION BY ' + @rn_col + N' ORDER BY ' + @order_cols + @rowSelT + N') AS [_rn], ' + N'ROW_NUMBER() OVER (ORDER BY ' + @order_cols + @rowSelT + N') AS [_ord]' + CHAR(10) + N'FROM (' + CHAR(10) + @innerT + CHAR(10) + N') _pvt_cte' + @joinT + CHAR(10) + N'WHERE ' + @whereTp + CHAR(10) + N') _ranked' + CHAR(10) + N'WHERE _ranked.[_rn] = 1' + CHAR(10) + N'ORDER BY _ranked.[_ord]' + @rn_paging; -- T-SQL forbids ORDER BY items not in SELECT when DISTINCT. -- Wrap so paging-ORDER applies outside the DISTINCT. IF @distinct = 1 RETURN N'SELECT [_id], ' + @ord_dist + N' FROM (' + CHAR(10) + N'SELECT DISTINCT ' + @rowSelT + N' AS [_id] FROM (' + CHAR(10) + @innerT + CHAR(10) + N') _pvt_cte' + @joinT + CHAR(10) + N'WHERE ' + @whereTp + CHAR(10) + N') _dist' + @order_sql_dist + @paging; RETURN N'SELECT ' + @rowSelT + N' AS [_id], ROW_NUMBER() OVER (ORDER BY ' + @order_cols + @rowSelT + N') AS [_ord]' + N' FROM (' + CHAR(10) + @innerT + CHAR(10) + N') _pvt_cte' + @joinT + CHAR(10) + N'WHERE ' + @whereTp + @order_sql + @paging; END; DECLARE @whereT NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@filter, @fields, N'o.'); DECLARE @filterT NVARCHAR(MAX) = CASE WHEN @whereT IS NULL OR @whereT = N'' OR @whereT = N'1=1' THEN N'' ELSE N' AND ' + @whereT END; DECLARE @escapedIds NVARCHAR(MAX) = NULL; IF @tree_ids IS NOT NULL AND ISJSON(@tree_ids) = 1 SET @escapedIds = REPLACE(@tree_ids, N'''', N''''''); DECLARE @treeWhere NVARCHAR(MAX); IF @source_mode = N'tree_roots' BEGIN -- 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 (the cross-tree leak). IF @escapedIds IS NOT NULL SET @treeWhere = N'o.[_id] IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @escapedIds + N'''))'; ELSE SET @treeWhere = N'o.[_id_parent] IS NULL'; END; ELSE IF @source_mode = N'tree_leaves' BEGIN -- Root-scoped: WhereLeaves() on TreeQuery(rootObj) must return leaves of THAT subtree — -- childless descendants of the seed — not every leaf in the scheme (the cross-tree leak). -- pvt_is_descendant_of() is inclusive, so exclude the seed root itself (empty tree => none). SET @treeWhere = N'NOT EXISTS (SELECT 1 FROM dbo._objects _lc WHERE _lc.[_id_parent] = o.[_id])'; -- Down to a depth: the leaves of the whole tree that lie within it (a node at the cut that has children -- is not a leaf). pvt_is_descendant_of below has no depth. IF @escapedIds IS NOT NULL AND @max_depth IS NOT NULL SET @treeWhere += N' AND o.[_id] IN (SELECT _id FROM dbo.pvt_tree_descendants(' + CAST(@scheme_id AS NVARCHAR(40)) + N', N''' + @escapedIds + N''', ' + CAST(@max_depth AS NVARCHAR(20)) + N', ' + CAST(COALESCE(@polymorphic, 1) AS NVARCHAR(1)) + N', 0))'; ELSE IF @escapedIds IS NOT NULL SET @treeWhere += N' AND o.[_id] NOT IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @escapedIds + N'''))' + N' AND EXISTS (SELECT 1 FROM OPENJSON(N''' + @escapedIds + N''') _s WHERE dbo.pvt_is_descendant_of(o.[_id], CAST(_s.[value] AS BIGINT)) = 1)'; END; ELSE IF @source_mode = N'tree_children' BEGIN IF @escapedIds IS NULL RETURN NULL; SET @treeWhere = N'o.[_id_parent] IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @escapedIds + N'''))'; END; ELSE IF @source_mode = N'tree_ancestors' BEGIN IF @escapedIds IS NULL RETURN NULL; SET @treeWhere = N'o.[_id] IN (SELECT _id FROM dbo.pvt_tree_ancestors(' + CAST(@scheme_id AS NVARCHAR(40)) + N', N''' + @escapedIds + N''', ' + CASE WHEN @max_depth IS NULL THEN N'NULL' ELSE CAST(@max_depth AS NVARCHAR(20)) END + N', ' + CAST(COALESCE(@polymorphic, 1) AS NVARCHAR(1)) + N'))'; END; ELSE IF @max_depth IS NOT NULL -- tree_descendants down to a depth: the walk that counts levels BEGIN -- pvt_is_descendant_of below has no depth: with it TreeQuery(root, maxDepth) returned the whole subtree. IF @escapedIds IS NULL RETURN NULL; SET @treeWhere = N'o.[_id] IN (SELECT _id FROM dbo.pvt_tree_descendants(' + CAST(@scheme_id AS NVARCHAR(40)) + N', N''' + @escapedIds + N''', ' + CAST(@max_depth AS NVARCHAR(20)) + N', ' + CAST(COALESCE(@polymorphic, 1) AS NVARCHAR(1)) + N', ' + CAST(COALESCE(@include_seed, 1) AS NVARCHAR(1)) + N'))'; END; ELSE -- tree_descendants: correlated pvt_is_descendant_of, no CTE BEGIN IF @escapedIds IS NULL RETURN NULL; SET @treeWhere = N'EXISTS (SELECT 1 FROM OPENJSON(N''' + @escapedIds + N''') _s WHERE dbo.pvt_is_descendant_of(o.[_id], CAST(_s.[value] AS BIGINT)) = 1)'; IF COALESCE(@include_seed, 1) = 0 SET @treeWhere += N' AND o.[_id] NOT IN (SELECT CAST([value] AS BIGINT) FROM OPENJSON(N''' + @escapedIds + N'''))'; END; IF @seed_level_sql IS NOT NULL SET @treeWhere = N'(' + @treeWhere + N') AND ' + @seed_level_sql; DECLARE @baseFromT NVARCHAR(MAX) = N'FROM dbo._objects o' + CHAR(10) + N'WHERE o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + N' AND ' + @treeWhere + @filterT; -- Distinct as in the flat Shape A. This branch used to ignore both: DistinctByRedb on a base -- field (no props in the query) returned every node of the tree. IF @rn_col IS NOT NULL RETURN N'SELECT [_id], [_ord] FROM (' + CHAR(10) + N'SELECT o.[_id] AS [_id], ' + N'ROW_NUMBER() OVER (PARTITION BY ' + @rn_col + N' ORDER BY ' + @order_cols + N'o.[_id]) AS [_rn], ' + N'ROW_NUMBER() OVER (ORDER BY ' + @order_cols + N'o.[_id]) AS [_ord]' + CHAR(10) + @baseFromT + CHAR(10) + N') _ranked' + CHAR(10) + N'WHERE _ranked.[_rn] = 1' + CHAR(10) + N'ORDER BY _ranked.[_ord]' + @rn_paging; IF @distinct = 1 RETURN N'SELECT [_id], ' + @ord_dist + N' FROM (' + CHAR(10) + N'SELECT DISTINCT o.[_id] AS [_id] ' + @baseFromT + CHAR(10) + N') _dist' + @order_sql_dist + @paging; RETURN N'SELECT o.[_id] AS [_id], ROW_NUMBER() OVER (ORDER BY ' + @order_cols + N'o.[_id]) AS [_ord] ' + @baseFromT + @order_sql + @paging; END; -- Unrecognized non-flat source mode: not yet implemented IF @source_mode <> N'flat' RETURN NULL; -- ---------- Shape A (pure-base) ---------- IF @has_props = 0 BEGIN DECLARE @whereA NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@filter, @fields, N'o.'); DECLARE @baseFrom NVARCHAR(MAX) = N'FROM dbo._objects o' + CHAR(10) + N'WHERE o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + CASE WHEN @whereA <> N'1=1' THEN N' AND ' + @whereA ELSE N'' END; IF @rn_col IS NOT NULL RETURN N'SELECT [_id], [_ord] FROM (' + CHAR(10) + N'SELECT o.[_id] AS [_id], ' + N'ROW_NUMBER() OVER (PARTITION BY ' + @rn_col + N' ORDER BY ' + @order_cols + N'o.[_id]) AS [_rn], ' + N'ROW_NUMBER() OVER (ORDER BY ' + @order_cols + N'o.[_id]) AS [_ord]' + CHAR(10) + @baseFrom + CHAR(10) + N') _ranked' + CHAR(10) + N'WHERE _ranked.[_rn] = 1' + CHAR(10) + N'ORDER BY _ranked.[_ord]' + @rn_paging; IF @distinct = 1 RETURN N'SELECT [_id], ' + @ord_dist + N' FROM (' + CHAR(10) + N'SELECT DISTINCT o.[_id] AS [_id] ' + @baseFrom + CHAR(10) + N') _dist' + @order_sql_dist + @paging; RETURN N'SELECT o.[_id] AS [_id], ROW_NUMBER() OVER (ORDER BY ' + @order_cols + N'o.[_id]) AS [_ord] ' + @baseFrom + @order_sql + @paging; END; -- ---------- Shape B (narrow Pro-parity) / Shape C (wide pivot) ---------- -- Pro-parity base pushdown: peel off base/hierarchical predicates so -- they narrow _objects BEFORE the correlated pivot subqueries execute -- per row. Residual stays on the outer WHERE. DECLARE @splitC NVARCHAR(MAX) = dbo.pvt_split_filter(@filter, @fields); DECLARE @pushC NVARCHAR(MAX) = dbo.pvt_json_text(@splitC, N'push'); DECLARE @resC NVARCHAR(MAX) = JSON_QUERY(@splitC, N'$.residual'); DECLARE @inner NVARCHAR(MAX) = dbo.pvt_build_cte_sql( @scheme_id, @fields, N'flat', NULL, NULL, @force_outer, @pushC, @narrow, DEFAULT, DEFAULT, DEFAULT); DECLARE @whereC NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@resC, @fields, @base_prefix); DECLARE @joinC NVARCHAR(MAX) = CASE WHEN @narrow = 1 THEN CHAR(10) + N'JOIN dbo._objects o ON o.[_id] = _pvt_cte.[_id_object]' ELSE N'' END; DECLARE @rowSelC NVARCHAR(MAX) = CASE WHEN @narrow = 1 THEN N'o.[_id]' ELSE N'_pvt_cte.[_id]' END; IF @rn_col IS NOT NULL RETURN N'SELECT [_id], [_ord] FROM (' + CHAR(10) + N'SELECT ' + @rowSelC + N' AS [_id], ' + N'ROW_NUMBER() OVER (PARTITION BY ' + @rn_col + N' ORDER BY ' + @order_cols + @rowSelC + N') AS [_rn], ' + N'ROW_NUMBER() OVER (ORDER BY ' + @order_cols + @rowSelC + N') AS [_ord]' + CHAR(10) + N'FROM (' + CHAR(10) + @inner + CHAR(10) + N') _pvt_cte' + @joinC + CHAR(10) + N'WHERE ' + @whereC + CHAR(10) + N') _ranked' + CHAR(10) + N'WHERE _ranked.[_rn] = 1' + CHAR(10) + N'ORDER BY _ranked.[_ord]' + @rn_paging; IF @distinct = 1 RETURN N'SELECT [_id], ' + @ord_dist + N' FROM (' + CHAR(10) + N'SELECT DISTINCT ' + @rowSelC + N' AS [_id] FROM (' + CHAR(10) + @inner + CHAR(10) + N') _pvt_cte' + @joinC + CHAR(10) + N'WHERE ' + @whereC + CHAR(10) + N') _dist' + @order_sql_dist + @paging; RETURN N'SELECT ' + @rowSelC + N' AS [_id], ROW_NUMBER() OVER (ORDER BY ' + @order_cols + @rowSelC + N') AS [_ord]' + N' FROM (' + CHAR(10) + @inner + CHAR(10) + N') _pvt_cte' + @joinC + CHAR(10) + N'WHERE ' + @whereC + @order_sql + @paging; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/21_pvt_aggregate.sql ---- -- ===================================================================== -- 21_pvt_aggregate.sql (MSSql v2-pvt) — terminal aggregation orchestrator -- --------------------------------------------------------------------- -- Mirrors PG redb.Postgres/sql/v2-pvt/21_pvt_aggregate.sql, slimmed to -- the operand grammar consumed by RedbQueryable.AggregateAsync and the -- legacy ExecuteAggregateAsync / ExecuteAggregateBatchAsync paths. -- -- Aggregation entry shape (per element of @aggs JSON array): -- -- { "alias": "", "$": "*" | {"$field": ""} } -- -- Where is one of: count / sum / avg / min / max. -- -- NOT in this slice (matches MSSql free deliberate cuts): -- * per-aggregate `distinct` (a `filter` is supported on $count of "*": the conditional count) -- * $string_agg / $bool_and / $bool_or -- * arithmetic / function operands ($add/$mul/$upper/...) -- * narrow shape (always Shape A or Shape C wide) -- * pushdown / tree / polymorphic flags -- -- Output shapes: -- Shape A (every collected field is kind='base', flat mode): -- SELECT AS [], ... FROM dbo._objects o -- WHERE o.[_id_scheme] = X [AND ] -- -- Shape C (any PROPS field referenced anywhere): -- SELECT AS [], ... FROM () _pvt_cte -- WHERE -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_json_field_refs -------------------------------------- -- Every {"$field": ""} inside a JSON expression (a filter of a conditional count, a HAVING). CREATE OR ALTER FUNCTION dbo.pvt_json_field_refs(@node NVARCHAR(MAX)) RETURNS TABLE AS RETURN ( WITH n AS ( SELECT [key], [value], [type] FROM OPENJSON(@node) UNION ALL SELECT j.[key], j.[value], j.[type] FROM n CROSS APPLY OPENJSON(n.[value]) j WHERE n.[type] IN (4, 5) ) SELECT DISTINCT CAST([value] AS NVARCHAR(400)) AS name FROM n WHERE [key] = N'$field' AND [type] = 1 ); GO -- ---------- pvt_build_groupby_having_expr (declaration) -------------- -- The boolean translator of 22_pvt_groupby.sql, declared here so the filter of a conditional count in -- pvt_build_agg_expr can call it: a function must exist before a function that calls it is created. -- 22_pvt_groupby.sql replaces this body. CREATE OR ALTER FUNCTION dbo.pvt_build_groupby_having_expr( @node NVARCHAR(MAX), @fields NVARCHAR(MAX), @base_prefix NVARCHAR(20) ) RETURNS NVARCHAR(MAX) AS BEGIN RETURN NULL; END; GO -- ---------- pvt_extend_fields_with_aggs ------------------------------ -- Start from @existing fields-map (output of pvt_collect_fields on the -- filter) and APPEND metadata for every $field path referenced inside -- @aggs that is not already present. Returns a new fields-map JSON. -- Paths absent from scheme metadata are silently skipped. CREATE OR ALTER FUNCTION dbo.pvt_extend_fields_with_aggs( @scheme_id BIGINT, @existing NVARCHAR(MAX), @aggs NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @out NVARCHAR(MAX) = CASE WHEN @existing IS NULL OR ISJSON(@existing) = 0 THEN N'{}' ELSE @existing END; IF @scheme_id IS NULL OR @aggs IS NULL OR ISJSON(@aggs) = 0 RETURN @out; DECLARE entries CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@aggs); DECLARE @entry NVARCHAR(MAX); OPEN entries; FETCH NEXT FROM entries INTO @entry; WHILE @@FETCH_STATUS = 0 BEGIN IF @entry IS NOT NULL AND ISJSON(@entry) = 1 BEGIN DECLARE props CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@entry); DECLARE @k NVARCHAR(100), @v NVARCHAR(MAX), @t INT; OPEN props; FETCH NEXT FROM props INTO @k, @v, @t; WHILE @@FETCH_STATUS = 0 BEGIN IF LEFT(@k, 1) = N'$' AND @t = 5 BEGIN DECLARE @path NVARCHAR(400) = JSON_VALUE(@v, N'$."$field"'); IF @path IS NOT NULL AND JSON_QUERY(@out, N'$."' + STRING_ESCAPE(@path, 'json') + N'"') IS NULL BEGIN DECLARE @meta NVARCHAR(MAX) = dbo.pvt_resolve_field_path(@scheme_id, @path); IF @meta IS NOT NULL BEGIN IF @out = N'{}' SET @out = N'{"' + STRING_ESCAPE(@path, 'json') + N'":' + @meta + N'}'; ELSE SET @out = LEFT(@out, LEN(@out) - 1) + N',"' + STRING_ESCAPE(@path, 'json') + N'":' + @meta + N'}'; END; END; END; FETCH NEXT FROM props INTO @k, @v, @t; END; CLOSE props; DEALLOCATE props; -- Fields of the condition of a conditional count ({"$count":"*","filter":{...}}). DECLARE refs CURSOR LOCAL FAST_FORWARD FOR SELECT name FROM dbo.pvt_json_field_refs(JSON_QUERY(@entry, N'$.filter')); DECLARE @ref NVARCHAR(400); OPEN refs; FETCH NEXT FROM refs INTO @ref; WHILE @@FETCH_STATUS = 0 BEGIN IF JSON_QUERY(@out, N'$."' + STRING_ESCAPE(@ref, 'json') + N'"') IS NULL BEGIN DECLARE @ref_meta NVARCHAR(MAX) = dbo.pvt_resolve_field_path(@scheme_id, @ref); IF @ref_meta IS NOT NULL SET @out = CASE WHEN @out = N'{}' THEN N'{"' + STRING_ESCAPE(@ref, 'json') + N'":' + @ref_meta + N'}' ELSE LEFT(@out, LEN(@out) - 1) + N',"' + STRING_ESCAPE(@ref, 'json') + N'":' + @ref_meta + N'}' END; END; FETCH NEXT FROM refs INTO @ref; END; CLOSE refs; DEALLOCATE refs; END; FETCH NEXT FROM entries INTO @entry; END; CLOSE entries; DEALLOCATE entries; RETURN @out; END; GO -- ---------- pvt_agg_field_ref ---------------------------------------- -- Resolve a single $field operand to its column expression. Returns -- NULL when meta is missing (caller emits a comment marker). CREATE OR ALTER FUNCTION dbo.pvt_agg_field_ref( @path NVARCHAR(400), @fields NVARCHAR(MAX), @base_prefix NVARCHAR(20) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @path IS NULL OR @fields IS NULL OR ISJSON(@fields) = 0 RETURN NULL; DECLARE @meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@path, 'json') + N'"'); IF @meta IS NULL RETURN NULL; DECLARE @kind NVARCHAR(32) = JSON_VALUE(@meta, N'$.kind'); IF @kind = N'base' BEGIN DECLARE @col NVARCHAR(64) = JSON_VALUE(@meta, N'$.column'); IF @col IS NULL RETURN NULL; RETURN COALESCE(@base_prefix, N'') + QUOTENAME(@col); END; -- Prop / list_item / dict — exposed as a pivot-CTE column under its field-name alias. -- Narrow shape (base_prefix='o.') JOINs _objects so the outer SELECT has both -- `o.*` (base) and `_pvt_cte.` (pivot). Pivot cols must NOT carry `o.` -- — they are unprefixed (resolved to _pvt_cte by scope). In wide shape -- (base_prefix='_pvt_cte.') both base and pivot live on _pvt_cte, so the -- same prefix applies. RETURN CASE WHEN @base_prefix = N'o.' THEN N'' ELSE COALESCE(@base_prefix, N'') END + QUOTENAME(@path); END; GO -- ---------- pvt_build_agg_expr --------------------------------------- -- Compile a single aggregate entry into a SQL fragment WITHOUT alias. -- Supports $count / $sum / $avg / $min / $max with operand: -- "*" (count only) -- { "$field": "" } -- -- Array-field operands (is_array=true, kind <> 'base') route through a -- correlated subquery against dbo._values so SUM/AVG/MIN/MAX/COUNT -- aggregate element values instead of failing on the JSON-array string -- emitted by the wide pivot. Mirrors PG pvt_build_agg_expr unnest path -- (redb.Postgres/sql/v2-pvt/19_pvt_agg_expr.sql), using @base_prefix to -- resolve the per-row object id (`[_id]`) for the correlation. CREATE OR ALTER FUNCTION dbo.pvt_build_agg_expr( @entry NVARCHAR(MAX), @fields NVARCHAR(MAX), @base_prefix NVARCHAR(20) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @entry IS NULL OR ISJSON(@entry) = 0 RETURN dbo.pvt_fail(N'aggregate entry is not JSON'); DECLARE @op NVARCHAR(50) = NULL, @arg NVARCHAR(MAX) = NULL, @arg_t INT = NULL; DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [key], [value], [type] FROM OPENJSON(@entry) WHERE LEFT([key], 1) = N'$'; OPEN c; FETCH NEXT FROM c INTO @op, @arg, @arg_t; CLOSE c; DEALLOCATE c; IF @op IS NULL RETURN dbo.pvt_fail(N'aggregate entry has no $ key'); DECLARE @lo NVARCHAR(50) = LOWER(@op); DECLARE @func NVARCHAR(20) = CASE @lo WHEN N'$count' THEN N'COUNT' WHEN N'$sum' THEN N'SUM' WHEN N'$avg' THEN N'AVG' WHEN N'$min' THEN N'MIN' WHEN N'$max' THEN N'MAX' ELSE NULL END; IF @func IS NULL RETURN dbo.pvt_fail(N'unsupported aggregate ' + @op); -- Conditional count {"$count":"*","filter":} -> COUNT(CASE WHEN THEN 1 END). DECLARE @filter NVARCHAR(MAX) = JSON_QUERY(@entry, N'$.filter'); IF @filter IS NOT NULL BEGIN IF @lo <> N'$count' OR @arg_t <> 1 OR @arg <> N'*' RETURN dbo.pvt_fail(N'only $count of "*" takes a filter'); DECLARE @cond NVARCHAR(MAX) = dbo.pvt_build_groupby_having_expr(@filter, @fields, @base_prefix); IF @cond IS NULL RETURN dbo.pvt_fail(N'the filter of a count does not translate'); RETURN N'COUNT(CASE WHEN ' + @cond + N' THEN 1 END)'; END; -- $count "*" → COUNT(*) IF @lo = N'$count' AND @arg_t = 1 AND @arg = N'*' RETURN N'COUNT(*)'; -- Operand must be {"$field": ""}. DECLARE @path NVARCHAR(400) = NULL; IF @arg_t = 5 AND ISJSON(@arg) = 1 SET @path = JSON_VALUE(@arg, N'$."$field"'); IF @path IS NULL RETURN dbo.pvt_fail(N'operand of ' + @op + N' must be "*" or {"$field":"..."}'); -- Array-field branch: detect is_array=true & non-base. The pivot -- column would project the array as JSON, so the orchestrator -- emits an OUTER APPLY against _values that pre-computes the -- per-row aggregates (sum/cnt/min/max) under the alias -- `_aa_`; each aggregate then references the precomputed -- column rather than nesting an aggregate subquery (which T-SQL -- forbids). Mirrors PG's unnest path semantically. DECLARE @meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@path, 'json') + N'"'); IF @meta IS NOT NULL AND JSON_VALUE(@meta, N'$.is_array') = N'true' AND COALESCE(JSON_VALUE(@meta, N'$.kind'), N'') <> N'base' BEGIN DECLARE @sid NVARCHAR(40) = JSON_VALUE(@meta, N'$.sid'); IF @sid IS NULL RETURN dbo.pvt_fail(N'array field "' + @path + N'" has no structure id'); DECLARE @aa NVARCHAR(80) = N'_aa_' + @sid; IF @lo = N'$sum' RETURN N'SUM(' + @aa + N'.[sum])'; IF @lo = N'$count' RETURN N'SUM(' + @aa + N'.[cnt])'; IF @lo = N'$min' RETURN N'MIN(' + @aa + N'.[min])'; IF @lo = N'$max' RETURN N'MAX(' + @aa + N'.[max])'; IF @lo = N'$avg' RETURN N'(SUM(' + @aa + N'.[sum]) / NULLIF(SUM(' + @aa + N'.[cnt]), 0))'; RETURN dbo.pvt_fail(N'unsupported array aggregate ' + @op); END; DECLARE @col NVARCHAR(MAX) = dbo.pvt_agg_field_ref(@path, @fields, @base_prefix); IF @col IS NULL RETURN dbo.pvt_fail(N'aggregate field "' + @path + N'" is not a field of the scheme'); -- Promote SUM / AVG operands to NUMERIC(38,10) for overflow safety and -- to match Pro's decimal-typed public surface. IF @lo = N'$sum' RETURN N'SUM(CAST(' + @col + N' AS NUMERIC(38, 10)))'; IF @lo = N'$avg' RETURN N'AVG(CAST(' + @col + N' AS NUMERIC(38, 10)))'; RETURN @func + N'(' + @col + N')'; END; GO -- ---------- pvt_build_agg_projection --------------------------------- -- Compile an array of aggregate entries into a ` AS [], ...` -- projection fragment. Defaults aliases to positional `_agg_`. CREATE OR ALTER FUNCTION dbo.pvt_build_agg_projection( @aggs NVARCHAR(MAX), @fields NVARCHAR(MAX), @base_prefix NVARCHAR(20) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @aggs IS NULL OR ISJSON(@aggs) = 0 RETURN NULL; DECLARE @out NVARCHAR(MAX) = N''; DECLARE @idx INT = 0; DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@aggs); DECLARE @entry NVARCHAR(MAX); OPEN c; FETCH NEXT FROM c INTO @entry; WHILE @@FETCH_STATUS = 0 BEGIN SET @idx = @idx + 1; DECLARE @alias NVARCHAR(200) = NULL; IF @entry IS NOT NULL AND ISJSON(@entry) = 1 SET @alias = JSON_VALUE(@entry, N'$.alias'); IF @alias IS NULL OR @alias = N'' SET @alias = N'_agg_' + CAST(@idx AS NVARCHAR(20)); DECLARE @sql NVARCHAR(MAX) = dbo.pvt_build_agg_expr(@entry, @fields, @base_prefix); IF @idx > 1 SET @out = @out + N', '; SET @out = @out + @sql + N' AS ' + QUOTENAME(@alias); FETCH NEXT FROM c INTO @entry; END; CLOSE c; DEALLOCATE c; IF @idx = 0 RETURN NULL; RETURN @out; END; GO -- ---------- pvt_build_aggregate_sql ---------------------------------- -- Orchestrator. Returns a single-row terminal SELECT projecting N -- aggregate columns over the (filtered) PVT source for @scheme_id. CREATE OR ALTER FUNCTION dbo.pvt_build_aggregate_sql( @scheme_id BIGINT, @filter NVARCHAR(MAX), @aggs NVARCHAR(MAX), @source_mode NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN NULL; IF @aggs IS NULL OR ISJSON(@aggs) = 0 RETURN NULL; IF @source_mode IS NULL SET @source_mode = N'flat'; IF @source_mode <> N'flat' RETURN NULL; -- 1. Collect fields from filter; extend with fields referenced inside -- aggregate operands so kind/column metadata is available downstream. DECLARE @filter_fields NVARCHAR(MAX) = dbo.pvt_collect_fields(@scheme_id, @filter, NULL); DECLARE @fields NVARCHAR(MAX) = dbo.pvt_extend_fields_with_aggs(@scheme_id, @filter_fields, @aggs); -- 2. Decide shape — pure-base flat shortcut (Shape A) vs Shape B/C. -- Mirrors PG redb.Postgres/sql/v2-pvt/21_pvt_aggregate.sql narrow/wide selection. DECLARE @has_props BIT = 0; DECLARE @has_nested BIT = 0; DECLARE @has_scalar BIT = 0; IF @fields IS NOT NULL AND ISJSON(@fields) = 1 AND @fields <> N'{}' BEGIN IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.kind') <> N'base' ) SET @has_props = 1; IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.parent_sid') IS NOT NULL AND JSON_VALUE([value], N'$.dict_key') IS NOT NULL ) SET @has_nested = 1; IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.kind') <> N'base' AND NOT ( JSON_VALUE([value], N'$.parent_sid') IS NOT NULL AND JSON_VALUE([value], N'$.dict_key') IS NOT NULL ) ) SET @has_scalar = 1; END; -- ---------- Shape A: pure-base flat aggregation ---------- IF @has_props = 0 BEGIN DECLARE @whereA NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@filter, @fields, N'o.'); DECLARE @projA NVARCHAR(MAX) = dbo.pvt_build_agg_projection(@aggs, @fields, N'o.'); RETURN N'SELECT ' + @projA + N' FROM dbo._objects o' + CHAR(10) + N'WHERE o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + CASE WHEN @whereA <> N'1=1' THEN N' AND ' + @whereA ELSE N'' END; END; -- ---------- Shape B (narrow) or Shape C (wide) ---------- -- PG-parity narrow/wide decision (mirrors file 20). -- @force_outer = 1 -> wide is mandatory (absence checks, no props). -- @narrow = 1 -> Pro-shape: narrow GROUP BY pivot + JOIN _objects. -- Pro-parity base pushdown: base/hierarchical predicates narrow -- _objects BEFORE correlated pivot subqueries; residual stays outer. -- Aggregations over array fields are routed via OUTER APPLY blocks -- that pre-compute per-row sum/cnt/min/max of element values -- (T-SQL forbids aggregate-of-aggregate-subquery, unlike PG which -- can SUM((SELECT SUM(_x) FROM unnest(arr))) directly). DECLARE @splitC NVARCHAR(MAX) = dbo.pvt_split_filter(@filter, @fields); DECLARE @pushC NVARCHAR(MAX) = dbo.pvt_json_text(@splitC, N'push'); DECLARE @resC NVARCHAR(MAX) = JSON_QUERY(@splitC, N'$.residual'); DECLARE @has_null BIT = dbo.pvt_has_absence_check(@resC); DECLARE @force_outer BIT = CASE WHEN @has_null = 1 OR @has_props = 0 THEN 1 ELSE 0 END; -- PG parity: narrow body in 12 currently does NOT support nested-dict. DECLARE @narrow BIT = CASE WHEN @force_outer = 0 AND @has_nested = 0 THEN 1 ELSE 0 END; -- Base alias: narrow JOINs _objects, wide projects base cols from _pvt_cte. DECLARE @base_prefix NVARCHAR(20) = CASE WHEN @narrow = 1 THEN N'o.' ELSE N'_pvt_cte.' END; -- Per-row correlation for OUTER APPLY: narrow uses o.[_id] (joined), -- wide uses _pvt_cte.[_id] (projected by the wide GROUP BY). DECLARE @aa_row_ref NVARCHAR(40) = CASE WHEN @narrow = 1 THEN N'o.[_id]' ELSE N'_pvt_cte.[_id]' END; DECLARE @inner NVARCHAR(MAX) = dbo.pvt_build_cte_sql( @scheme_id, @fields, N'flat', NULL, NULL, @force_outer, @pushC, @narrow, DEFAULT, DEFAULT, DEFAULT); DECLARE @whereC NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@resC, @fields, @base_prefix); DECLARE @projC NVARCHAR(MAX) = dbo.pvt_build_agg_projection(@aggs, @fields, @base_prefix); -- Collect distinct array fields referenced by aggregations and -- emit one OUTER APPLY per (sid, db_column). Each APPLY exposes -- columns [sum]/[cnt]/[min]/[max] keyed on the row's [_id]. DECLARE @apply_sql NVARCHAR(MAX) = N''; DECLARE @seen_sids TABLE(sid NVARCHAR(40) PRIMARY KEY); DECLARE ac CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@aggs); DECLARE @aentry NVARCHAR(MAX); OPEN ac; FETCH NEXT FROM ac INTO @aentry; WHILE @@FETCH_STATUS = 0 BEGIN IF @aentry IS NOT NULL AND ISJSON(@aentry) = 1 BEGIN DECLARE pc CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@aentry) WHERE LEFT([key], 1) = N'$'; DECLARE @opv NVARCHAR(MAX), @opt INT; OPEN pc; FETCH NEXT FROM pc INTO @opv, @opt; CLOSE pc; DEALLOCATE pc; IF @opt = 5 AND ISJSON(@opv) = 1 BEGIN DECLARE @apath NVARCHAR(400) = JSON_VALUE(@opv, N'$."$field"'); IF @apath IS NOT NULL BEGIN DECLARE @ameta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@apath, 'json') + N'"'); IF @ameta IS NOT NULL AND JSON_VALUE(@ameta, N'$.is_array') = N'true' AND COALESCE(JSON_VALUE(@ameta, N'$.kind'), N'') <> N'base' BEGIN DECLARE @asid NVARCHAR(40) = JSON_VALUE(@ameta, N'$.sid'); DECLARE @adbcol NVARCHAR(64) = JSON_VALUE(@ameta, N'$.db_column'); IF @asid IS NOT NULL AND @adbcol IS NOT NULL AND NOT EXISTS (SELECT 1 FROM @seen_sids WHERE sid = @asid) BEGIN INSERT INTO @seen_sids(sid) VALUES(@asid); SET @apply_sql = @apply_sql + CHAR(10) + N'OUTER APPLY (SELECT ' + N'SUM(CAST(va.' + QUOTENAME(@adbcol) + N' AS NUMERIC(38, 10))) AS [sum], ' + N'COUNT(va.' + QUOTENAME(@adbcol) + N') AS [cnt], ' + N'MIN(va.' + QUOTENAME(@adbcol) + N') AS [min], ' + N'MAX(va.' + QUOTENAME(@adbcol) + N') AS [max] ' + N'FROM dbo._values va ' + N'WHERE va.[_id_object] = ' + @aa_row_ref + N' ' + N'AND va.[_id_structure] = ' + @asid + N' ' + N'AND va.[_array_index] IS NOT NULL) _aa_' + @asid; END; END; END; END; END; FETCH NEXT FROM ac INTO @aentry; END; CLOSE ac; DEALLOCATE ac; RETURN N'SELECT ' + @projC + N' FROM (' + CHAR(10) + @inner + CHAR(10) + N') _pvt_cte' + CASE WHEN @narrow = 1 THEN CHAR(10) + N'JOIN dbo._objects o ON o.[_id] = _pvt_cte.[_id_object]' ELSE N'' END + @apply_sql + CHAR(10) + N'WHERE ' + @whereC; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/22_pvt_groupby.sql ---- -- ===================================================================== -- 22_pvt_groupby.sql (MSSql v2-pvt) — GROUP BY orchestrator -- --------------------------------------------------------------------- -- Mirrors redb.Postgres/sql/v2-pvt/22_pvt_groupby.sql, slimmed to -- the flat-shape grammar consumed by RedbQueryable.GroupBy().SelectAsync(). -- -- Group-by entry shape (per element of @group_by JSON array): -- { "field": "", "alias": "" } -- Base fields carry the "0$:" prefix on the field path; alias is always set. -- -- Aggregation entries: same grammar as file 21 (pvt_build_aggregate_sql). -- @having: optional boolean node (HavingPredicateParser grammar), see -- pvt_build_groupby_having_expr below; unknown shape -> NULL. -- @order: optional ORDER BY entries (same {field,dir,nulls} grammar as file 15). -- -- NOT in this slice: -- * narrow shape (always Shape A or Shape C wide) -- * pushdown / tree / polymorphic -- * $expr group keys -- -- Output shapes: -- Shape A (every field is kind='base'): -- SELECT AS [alias], ..., AS [alias] -- FROM dbo._objects o -- WHERE o.[_id_scheme] = X [AND ] -- GROUP BY , ... -- [ORDER BY ...] [OFFSET ... FETCH ...] -- -- Shape C (any PROPS field referenced): -- SELECT AS [alias], ..., AS [alias] -- FROM () _pvt_cte -- WHERE -- GROUP BY , ... -- [ORDER BY ...] [OFFSET ... FETCH ...] -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_having_agg_entries ----------------------------------- -- Every aggregate node of a HAVING tree, comma-joined (no brackets), so -- the orchestrator can feed them to pvt_extend_fields_with_aggs: a field -- that only HAVING aggregates must still be pivoted. An aggregate node -- ({"$sum":{"$field":"X"}}, {"$count":"*"}) has the shape of an -- aggregation entry already. CREATE OR ALTER FUNCTION dbo.pvt_having_agg_entries(@node NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN IF @node IS NULL OR ISJSON(@node) = 0 RETURN N''; DECLARE @k NVARCHAR(200), @v NVARCHAR(MAX), @t INT; SELECT TOP 1 @k = [key], @v = [value], @t = [type] FROM OPENJSON(@node); IF @k IN (N'$count', N'$sum', N'$avg', N'$min', N'$max') RETURN @node; IF @k = N'$not' RETURN dbo.pvt_having_agg_entries(@v); IF @t <> 4 RETURN N''; DECLARE @acc NVARCHAR(MAX) = N'', @child NVARCHAR(MAX), @part NVARCHAR(MAX); DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@v) WHERE [type] = 5; OPEN c; FETCH NEXT FROM c INTO @child; WHILE @@FETCH_STATUS = 0 BEGIN SET @part = dbo.pvt_having_agg_entries(@child); IF @part <> N'' SET @acc = CASE WHEN @acc = N'' THEN @part ELSE @acc + N',' + @part END; FETCH NEXT FROM c INTO @child; END; CLOSE c; DEALLOCATE c; RETURN @acc; END; GO -- ---------- pvt_build_groupby_having_expr ---------------------------- -- HAVING node -> T-SQL predicate. The grammar is what -- HavingPredicateParser writes: -- {"$and":[...]} / {"$or":[...]} / {"$not":{...}} -- {"$gt"|"$gte"|"$lt"|"$lte"|"$eq"|"$ne": [, ]} -- ::= {"$count":"*"} | {"$count"|"$sum"|"$avg"|"$min"|"$max":{"$field":"X"}} -- | {"$const": } -- Aggregates compile through pvt_build_agg_expr, exactly as in the SELECT -- list. Anything else returns NULL, and NULL propagates to the whole -- query: the orchestrator returns NULL and the caller refuses. A HAVING -- this function does not understand is never replaced by 1=1. CREATE OR ALTER FUNCTION dbo.pvt_build_groupby_having_expr( @node NVARCHAR(MAX), @fields NVARCHAR(MAX), @base_prefix NVARCHAR(20) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @node IS NULL OR ISJSON(@node) = 0 RETURN NULL; DECLARE @k NVARCHAR(200), @v NVARCHAR(MAX), @t INT; SELECT TOP 1 @k = [key], @v = [value], @t = [type] FROM OPENJSON(@node) WHERE [key] <> N'filter'; IF @k IS NULL RETURN NULL; IF @k = N'$and' OR @k = N'$or' BEGIN IF @t <> 4 RETURN NULL; DECLARE @op NVARCHAR(5) = CASE @k WHEN N'$and' THEN N' AND ' ELSE N' OR ' END; DECLARE @acc NVARCHAR(MAX) = N'', @child NVARCHAR(MAX), @child_t INT, @part NVARCHAR(MAX); DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@v); OPEN c; FETCH NEXT FROM c INTO @child, @child_t; WHILE @@FETCH_STATUS = 0 BEGIN SET @part = CASE WHEN @child_t = 5 THEN dbo.pvt_build_groupby_having_expr(@child, @fields, @base_prefix) ELSE NULL END; -- NULL + anything is NULL: one unknown child makes the whole node unknown. SET @acc = CASE WHEN @acc = N'' THEN @part ELSE @acc + @op + @part END; FETCH NEXT FROM c INTO @child, @child_t; END; CLOSE c; DEALLOCATE c; IF @acc = N'' RETURN NULL; RETURN N'(' + @acc + N')'; END; IF @k = N'$not' RETURN CASE WHEN @t = 5 THEN N'NOT (' + dbo.pvt_build_groupby_having_expr(@v, @fields, @base_prefix) + N')' ELSE NULL END; -- A null test and a bare field: the filter of a conditional count reads fields of the row. IF @k IN (N'$isnull', N'$notnull') RETURN CASE WHEN @t = 5 THEN N'(' + dbo.pvt_build_groupby_having_expr(@v, @fields, @base_prefix) + CASE @k WHEN N'$isnull' THEN N' IS NULL)' ELSE N' IS NOT NULL)' END ELSE NULL END; IF @k = N'$field' RETURN CASE WHEN @t = 1 THEN dbo.pvt_agg_field_ref(@v, @fields, @base_prefix) ELSE NULL END; IF @k IN (N'$count', N'$sum', N'$avg', N'$min', N'$max') BEGIN -- pvt_build_agg_expr refuses what it cannot compile (dbo.pvt_fail), so its result is SQL. RETURN dbo.pvt_build_agg_expr(@node, @fields, @base_prefix); END; IF @k = N'$const' RETURN CASE WHEN @t IN (0, 4, 5) THEN NULL ELSE dbo.pvt_jsonb_to_sql_literal(@v, @t) END; DECLARE @symbol NVARCHAR(5) = CASE @k WHEN N'$eq' THEN N' = ' WHEN N'$ne' THEN N' <> ' WHEN N'$gt' THEN N' > ' WHEN N'$gte' THEN N' >= ' WHEN N'$lt' THEN N' < ' WHEN N'$lte' THEN N' <= ' ELSE NULL END; IF @symbol IS NULL OR @t <> 4 RETURN NULL; IF (SELECT COUNT(*) FROM OPENJSON(@v)) <> 2 RETURN NULL; DECLARE @lhs NVARCHAR(MAX), @lhs_t INT, @rhs NVARCHAR(MAX), @rhs_t INT; SELECT @lhs = [value], @lhs_t = [type] FROM OPENJSON(@v) WHERE [key] = N'0'; SELECT @rhs = [value], @rhs_t = [type] FROM OPENJSON(@v) WHERE [key] = N'1'; IF @lhs_t <> 5 OR @rhs_t <> 5 RETURN NULL; RETURN N'(' + dbo.pvt_build_groupby_having_expr(@lhs, @fields, @base_prefix) + @symbol + dbo.pvt_build_groupby_having_expr(@rhs, @fields, @base_prefix) + N')'; END; GO CREATE OR ALTER FUNCTION dbo.pvt_build_groupby_sql( @scheme_id BIGINT, @filter NVARCHAR(MAX), @group_by NVARCHAR(MAX), @aggregations NVARCHAR(MAX), @having NVARCHAR(MAX), -- optional; see pvt_build_groupby_having_expr @order NVARCHAR(MAX), @limit INT, @offset INT, @source_mode NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN NULL; IF @group_by IS NULL OR ISJSON(@group_by) = 0 RETURN NULL; IF @source_mode IS NULL SET @source_mode = N'flat'; IF @source_mode <> N'flat' RETURN NULL; IF @having IS NOT NULL AND (ISJSON(@having) = 0 OR @having = N'{}') RETURN NULL; -- 1. Collect fields: merge group_by + order so that every referenced -- field is resolved to kind/column metadata before shape decision. DECLARE @collect_order NVARCHAR(MAX) = CASE WHEN @order IS NULL OR ISJSON(@order) = 0 THEN @group_by ELSE LEFT(@group_by, LEN(@group_by) - 1) + N',' + SUBSTRING(@order, 2, LEN(@order) - 1) END; DECLARE @fields NVARCHAR(MAX) = dbo.pvt_collect_fields(@scheme_id, @filter, @collect_order); -- Extend fields map with aggregation operand fields (from file 21). IF @aggregations IS NOT NULL AND ISJSON(@aggregations) = 1 SET @fields = dbo.pvt_extend_fields_with_aggs(@scheme_id, @fields, @aggregations); -- ... and with the fields only HAVING aggregates, so they are pivoted too. IF @having IS NOT NULL BEGIN DECLARE @having_aggs NVARCHAR(MAX) = dbo.pvt_having_agg_entries(@having); IF @having_aggs <> N'' SET @fields = dbo.pvt_extend_fields_with_aggs(@scheme_id, @fields, N'[' + @having_aggs + N']'); END; -- 2. Decide shape: Shape A (pure base) vs Shape B narrow vs Shape C wide. -- Mirrors PG/file-20 narrow/wide selection. DECLARE @has_props BIT = 0; DECLARE @has_nested BIT = 0; DECLARE @has_scalar BIT = 0; IF @fields IS NOT NULL AND ISJSON(@fields) = 1 AND @fields <> N'{}' BEGIN IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.kind') <> N'base' ) SET @has_props = 1; IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.parent_sid') IS NOT NULL AND JSON_VALUE([value], N'$.dict_key') IS NOT NULL ) SET @has_nested = 1; IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.kind') <> N'base' AND NOT ( JSON_VALUE([value], N'$.parent_sid') IS NOT NULL AND JSON_VALUE([value], N'$.dict_key') IS NOT NULL ) ) SET @has_scalar = 1; END; -- Split filter / narrow vs wide decision (only relevant when has_props=1; -- when has_props=0 we go to Shape A path below). DECLARE @splitC NVARCHAR(MAX) = dbo.pvt_split_filter(@filter, @fields); DECLARE @pushC NVARCHAR(MAX) = dbo.pvt_json_text(@splitC, N'push'); DECLARE @resC NVARCHAR(MAX) = JSON_QUERY(@splitC, N'$.residual'); DECLARE @has_null BIT = dbo.pvt_has_absence_check(@resC); DECLARE @force_outer BIT = CASE WHEN @has_null = 1 OR @has_props = 0 THEN 1 ELSE 0 END; -- PG parity: narrow body in 12 currently does NOT support nested-dict. DECLARE @narrow BIT = CASE WHEN @force_outer = 0 AND @has_nested = 0 THEN 1 ELSE 0 END; -- 3. ORDER BY (uses the same per-shape prefix convention as file 20). DECLARE @order_sql NVARCHAR(MAX) = dbo.pvt_build_order_conditions( @order, @fields, CASE WHEN @has_props = 0 OR @narrow = 1 THEN N'o.' ELSE N'_pvt_cte.' END); -- 4. Paging. DECLARE @paging NVARCHAR(MAX) = N''; IF @limit IS NOT NULL AND @limit >= 0 BEGIN IF COALESCE(@offset, 0) = 0 SET @paging = CHAR(10) + N'OFFSET 0 ROWS FETCH NEXT ' + CAST(@limit AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @paging = CHAR(10) + N'OFFSET ' + CAST(@offset AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit AS NVARCHAR(20)) + N' ROWS ONLY'; END ELSE IF COALESCE(@offset, 0) > 0 SET @paging = CHAR(10) + N'OFFSET ' + CAST(@offset AS NVARCHAR(20)) + N' ROWS'; -- Paging requires ORDER BY in T-SQL. IF @paging <> N'' AND @order_sql = N'' SET @order_sql = CHAR(10) + N'ORDER BY (SELECT 1)'; -- 5. Iterate group_by entries: build SELECT projection and GROUP BY list. -- Base-field prefix: N'o.' when going against _objects directly -- (Shape A, or narrow Shape B via JOIN); -- N'' in legacy wide Shape C (_pvt_cte projects base cols). -- Props-field: always QUOTENAME(@grp_fld) — _pvt_cte hoists props columns. DECLARE @grp_base_prefix NVARCHAR(20) = CASE WHEN @has_props = 0 OR @narrow = 1 THEN N'o.' ELSE N'' END; DECLARE @select_parts NVARCHAR(MAX) = N''; DECLARE @groupby_parts NVARCHAR(MAX) = N''; DECLARE @grp_cnt INT = 0; DECLARE gc CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@group_by); DECLARE @grp_entry NVARCHAR(MAX); OPEN gc; FETCH NEXT FROM gc INTO @grp_entry; WHILE @@FETCH_STATUS = 0 BEGIN SET @grp_cnt = @grp_cnt + 1; DECLARE @grp_fld NVARCHAR(400) = COALESCE( JSON_VALUE(@grp_entry, N'$.field'), JSON_VALUE(@grp_entry, N'$.field_path')); DECLARE @grp_alias NVARCHAR(200) = COALESCE( JSON_VALUE(@grp_entry, N'$.alias'), @grp_fld, N'_grp_' + CAST(@grp_cnt AS NVARCHAR(10))); IF @grp_fld IS NOT NULL AND @grp_fld <> N'' BEGIN DECLARE @grp_meta NVARCHAR(MAX) = JSON_QUERY( @fields, N'$."' + STRING_ESCAPE(@grp_fld, N'json') + N'"'); DECLARE @grp_col NVARCHAR(MAX); IF @grp_meta IS NOT NULL AND JSON_VALUE(@grp_meta, N'$.kind') = N'base' SET @grp_col = @grp_base_prefix + QUOTENAME(JSON_VALUE(@grp_meta, N'$.column')); ELSE SET @grp_col = QUOTENAME(@grp_fld); IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; IF @groupby_parts <> N'' SET @groupby_parts = @groupby_parts + N', '; SET @select_parts = @select_parts + @grp_col + N' AS ' + QUOTENAME(@grp_alias); SET @groupby_parts = @groupby_parts + @grp_col; END; FETCH NEXT FROM gc INTO @grp_entry; END; CLOSE gc; DEALLOCATE gc; IF @grp_cnt = 0 RETURN NULL; -- 6. Append aggregate SELECT projection (reuses pvt_build_agg_projection from file 21). IF @aggregations IS NOT NULL AND ISJSON(@aggregations) = 1 BEGIN DECLARE @agg_proj NVARCHAR(MAX) = dbo.pvt_build_agg_projection(@aggregations, @fields, @grp_base_prefix); IF @agg_proj IS NOT NULL AND LEN(@agg_proj) > 0 BEGIN IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @agg_proj; END; END; -- 7. WHERE clause. DECLARE @where_sql NVARCHAR(MAX) = dbo.pvt_build_where_from_json( @filter, @fields, CASE WHEN @has_props = 0 OR @narrow = 1 THEN N'o.' ELSE N'_pvt_cte.' END); -- 8. HAVING. Aggregates use the same prefix as the SELECT list. A node the -- translator does not know makes the whole query NULL: the caller refuses. DECLARE @having_sql NVARCHAR(MAX) = N''; IF @having IS NOT NULL BEGIN DECLARE @having_expr NVARCHAR(MAX) = dbo.pvt_build_groupby_having_expr(@having, @fields, @grp_base_prefix); IF @having_expr IS NULL RETURN NULL; SET @having_sql = CHAR(10) + N'HAVING ' + @having_expr; END; -- 9. Assemble. -- Shape A: pure-base, query directly against dbo._objects. IF @has_props = 0 RETURN N'SELECT ' + @select_parts + CHAR(10) + N'FROM dbo._objects o' + CHAR(10) + N'WHERE o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + CASE WHEN @where_sql <> N'1=1' THEN N' AND ' + @where_sql ELSE N'' END + CHAR(10) + N'GROUP BY ' + @groupby_parts + @having_sql + @order_sql + @paging; -- Shape B (narrow) / Shape C (wide): props present — wrap pvt_build_cte_sql as derived table. -- Pro-parity base pushdown: base/hierarchical predicates narrow -- _objects BEFORE correlated pivot subqueries; residual stays outer. DECLARE @inner NVARCHAR(MAX) = dbo.pvt_build_cte_sql( @scheme_id, @fields, N'flat', NULL, NULL, @force_outer, @pushC, @narrow, DEFAULT, DEFAULT, DEFAULT); DECLARE @where_sql_c NVARCHAR(MAX) = dbo.pvt_build_where_from_json( @resC, @fields, CASE WHEN @narrow = 1 THEN N'o.' ELSE N'_pvt_cte.' END); RETURN N'SELECT ' + @select_parts + CHAR(10) + N'FROM (' + CHAR(10) + @inner + CHAR(10) + N') _pvt_cte' + CASE WHEN @narrow = 1 THEN CHAR(10) + N'JOIN dbo._objects o ON o.[_id] = _pvt_cte.[_id_object]' ELSE N'' END + CHAR(10) + N'WHERE ' + @where_sql_c + CHAR(10) + N'GROUP BY ' + @groupby_parts + @having_sql + @order_sql + @paging; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/23_pvt_window.sql ---- -- ===================================================================== -- 23_pvt_window.sql (MSSql v2-pvt) — Window functions orchestrator -- --------------------------------------------------------------------- -- Mirrors redb.Postgres/sql/v2-pvt/23_pvt_window.sql, rewritten for -- T-SQL. The $over node shape is identical to PG so C# callers can -- share BuildPvtWindowSelectJson between dialects. -- -- Window node shape (identical to PG): -- { -- "func": "row_number"|"rank"|"dense_rank"|"percent_rank" -- | "cume_dist"|"ntile"|"lag"|"lead" -- | "first_value"|"last_value" -- | "sum"|"avg"|"min"|"max"|"count", -- "args": [, ...]?, -- {"$field":"..."} | {"$const":N} | "*" -- "partition_by": [{"field":"..."}, ...]?, -- "order_by": [{"field":"...","dir":"asc"|"desc"}, ...]?, -- "frame": { -- "type": "rows"|"range", -- "groups" not in T-SQL, degrades to ROWS -- "start": , -- "end": ? -- -- "exclude" not in T-SQL, silently ignored -- }? -- } -- -- Frame bound forms (same as PG): -- "unbounded_preceding" | "current_row" | "unbounded_following" -- {"preceding": N} | {"following": N} -- -- T-SQL omissions vs PG: -- * NTH_VALUE — not in SQL Server; raises error comment in output -- * GROUPS frame type — silently demoted to ROWS -- * EXCLUDE clause — not in SQL Server; silently dropped -- * FILTER (WHERE ...) — not in SQL Server; no-op (not in C# API anyway) -- -- Functions: -- dbo.pvt_compile_frame_bound(@str NVARCHAR(200), @obj NVARCHAR(MAX)) -- -> NVARCHAR(100) -- dbo.pvt_build_window_expr(@node NVARCHAR(MAX), -- @fields NVARCHAR(MAX), -- @base_prefix NVARCHAR(20)) -- -> NVARCHAR(MAX) -- dbo.pvt_build_window_sql(@scheme_id BIGINT, -- @filter NVARCHAR(MAX), -- @select NVARCHAR(MAX), -- @order NVARCHAR(MAX), -- @limit INT, -- @offset INT, -- @source_mode NVARCHAR(50)) -- -> NVARCHAR(MAX) -- -- Select entries shape (same as order entries + optional $expr.$over): -- {"field":"", "alias":""} -- plain projection -- {"alias":"", "$expr":{"$over":{...}}} -- window expression -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_compile_frame_bound ---------------------------------- -- Converts a JSON frame-bound value to T-SQL OVER-clause syntax. -- The caller extracts both the scalar form (@str via JSON_VALUE) and the -- object form (@obj via JSON_QUERY) for the same JSON property. Exactly -- one of them will be non-NULL for any valid bound. -- @str – result of JSON_VALUE(frame, '$.start') (non-NULL when bound is a string) -- @obj – result of JSON_QUERY(frame, '$.start') (non-NULL when bound is an object) CREATE OR ALTER FUNCTION dbo.pvt_compile_frame_bound( @str NVARCHAR(200), @obj NVARCHAR(MAX) ) RETURNS NVARCHAR(100) AS BEGIN IF @str IS NOT NULL BEGIN DECLARE @s NVARCHAR(200) = LOWER(@str); IF @s = N'unbounded_preceding' RETURN N'UNBOUNDED PRECEDING'; IF @s = N'current_row' RETURN N'CURRENT ROW'; IF @s = N'unbounded_following' RETURN N'UNBOUNDED FOLLOWING'; RETURN N'CURRENT ROW'; END; IF @obj IS NOT NULL BEGIN DECLARE @prec NVARCHAR(20) = JSON_VALUE(@obj, N'$.preceding'); IF @prec IS NOT NULL RETURN @prec + N' PRECEDING'; DECLARE @foll NVARCHAR(20) = JSON_VALUE(@obj, N'$.following'); IF @foll IS NOT NULL RETURN @foll + N' FOLLOWING'; END; RETURN N'CURRENT ROW'; END; GO -- ---------- pvt_build_window_expr ------------------------------------ -- Compiles one window-function $over node into: -- FUNC(args) OVER (PARTITION BY ... ORDER BY ... ROWS/RANGE ...) -- -- @node – the $over JSON object -- @fields – resolved fields map (from pvt_collect_fields) -- @base_prefix – 'o.' (Shape A) or '' (Shape C) CREATE OR ALTER FUNCTION dbo.pvt_build_window_expr( @node NVARCHAR(MAX), @fields NVARCHAR(MAX), @base_prefix NVARCHAR(20) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @node IS NULL OR ISJSON(@node) = 0 RETURN N'NULL /* pvt_build_window_expr: invalid node */'; DECLARE @func NVARCHAR(50) = LOWER(JSON_VALUE(@node, N'$.func')); IF @func IS NULL RETURN N'NULL /* pvt_build_window_expr: missing func */'; -- Fail closed: a function name outside the whitelist below is not supported, and the name -- must not travel into the SQL text. It used to be echoed inside a comment, so a crafted -- name could close it and inject live T-SQL (SQLI-PoC: window function name). IF @func NOT IN ( N'row_number', N'rank', N'dense_rank', N'percent_rank', N'cume_dist', N'ntile', N'lag', N'lead', N'first_value', N'last_value', N'sum', N'avg', N'min', N'max', N'count' ) RETURN dbo.pvt_fail(N'unsupported window function: ' + @func); -- nth_value is not available in SQL Server IF @func = N'nth_value' RETURN N'NULL /* pvt_build_window_expr: nth_value not supported in T-SQL */'; -- ---------------------------------------------------------------- -- Build the function call: FUNC(args) -- ---------------------------------------------------------------- DECLARE @call NVARCHAR(MAX); -- Ranking / navigation functions with no user-supplied args IF @func IN (N'row_number', N'rank', N'dense_rank', N'percent_rank', N'cume_dist') BEGIN -- T-SQL uses ROW_NUMBER, DENSE_RANK etc. (underscores) DECLARE @ufunc NVARCHAR(50) = CASE @func WHEN N'row_number' THEN N'ROW_NUMBER' WHEN N'rank' THEN N'RANK' WHEN N'dense_rank' THEN N'DENSE_RANK' WHEN N'percent_rank' THEN N'PERCENT_RANK' WHEN N'cume_dist' THEN N'CUME_DIST' ELSE UPPER(@func) END; SET @call = @ufunc + N'()'; END ELSE BEGIN -- Build arg list from args JSON array DECLARE @args_json NVARCHAR(MAX) = JSON_QUERY(@node, N'$.args'); DECLARE @args_sql NVARCHAR(MAX) = N''; IF @args_json IS NOT NULL AND ISJSON(@args_json) = 1 BEGIN -- COUNT(*) shorthand: args = ["*"] IF @func = N'count' AND JSON_VALUE(@args_json, N'$[0]') = N'*' BEGIN SET @args_sql = N'*'; END ELSE BEGIN DECLARE args_c CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@args_json); DECLARE @av NVARCHAR(MAX), @at INT; OPEN args_c; FETCH NEXT FROM args_c INTO @av, @at; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @ae NVARCHAR(MAX); IF @at = 1 -- JSON string literal BEGIN IF @av = N'*' SET @ae = N'*'; ELSE SET @ae = N'N''' + REPLACE(@av, N'''', N'''''') + N''''; END ELSE IF @at IN (2, 3) -- number SET @ae = @av; ELSE IF @at = 5 -- object: {"$field":"..."} or {"$const":...} BEGIN DECLARE @arg_fp NVARCHAR(400) = JSON_VALUE(@av, N'$."$field"'); IF @arg_fp IS NOT NULL BEGIN DECLARE @am NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@arg_fp, N'json') + N'"'); IF @am IS NOT NULL AND JSON_VALUE(@am, N'$.kind') = N'base' SET @ae = ISNULL(@base_prefix, N'') + QUOTENAME(JSON_VALUE(@am, N'$.column')); ELSE SET @ae = QUOTENAME(@arg_fp); END ELSE BEGIN DECLARE @cv NVARCHAR(MAX) = dbo.pvt_json_text(@av, N'$const'); SET @ae = ISNULL(@cv, N'NULL'); END; END ELSE SET @ae = N'NULL'; IF @args_sql <> N'' SET @args_sql = @args_sql + N', '; SET @args_sql = @args_sql + @ae; FETCH NEXT FROM args_c INTO @av, @at; END; CLOSE args_c; DEALLOCATE args_c; END; END; -- NTILE requires exactly one integer arg IF @func = N'ntile' SET @call = N'NTILE(' + ISNULL(@args_sql, N'4') + N')'; ELSE IF @func = N'count' SET @call = N'COUNT(' + CASE WHEN @args_sql = N'' THEN N'*' ELSE @args_sql END + N')'; -- AVG keeps the type of its operand in T-SQL: over a bigint field it cut the fraction off (32 for 32.25). -- Cast as pvt_agg_expr does for the aggregate form. ELSE IF @func = N'avg' SET @call = N'AVG(CAST(' + @args_sql + N' AS NUMERIC(38, 10)))'; ELSE SET @call = UPPER(@func) + N'(' + @args_sql + N')'; END; -- ---------------------------------------------------------------- -- Build OVER clause parts -- ---------------------------------------------------------------- DECLARE @over_parts NVARCHAR(MAX) = N''; -- PARTITION BY DECLARE @pb_json NVARCHAR(MAX) = JSON_QUERY(@node, N'$.partition_by'); IF @pb_json IS NOT NULL AND ISJSON(@pb_json) = 1 BEGIN DECLARE @pb_parts NVARCHAR(MAX) = N''; DECLARE pb_c CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@pb_json); DECLARE @pbe NVARCHAR(MAX); OPEN pb_c; FETCH NEXT FROM pb_c INTO @pbe; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @pb_fld NVARCHAR(400) = COALESCE( JSON_VALUE(@pbe, N'$.field'), JSON_VALUE(@pbe, N'$.field_path')); IF @pb_fld IS NOT NULL BEGIN DECLARE @pb_meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@pb_fld, N'json') + N'"'); DECLARE @pb_col NVARCHAR(MAX); IF @pb_meta IS NOT NULL AND JSON_VALUE(@pb_meta, N'$.kind') = N'base' SET @pb_col = ISNULL(@base_prefix, N'') + QUOTENAME(JSON_VALUE(@pb_meta, N'$.column')); ELSE SET @pb_col = QUOTENAME(@pb_fld); IF @pb_parts <> N'' SET @pb_parts = @pb_parts + N', '; SET @pb_parts = @pb_parts + @pb_col; END; FETCH NEXT FROM pb_c INTO @pbe; END; CLOSE pb_c; DEALLOCATE pb_c; IF @pb_parts <> N'' BEGIN IF @over_parts <> N'' SET @over_parts = @over_parts + N' '; SET @over_parts = @over_parts + N'PARTITION BY ' + @pb_parts; END; END; -- ORDER BY DECLARE @ob_json NVARCHAR(MAX) = JSON_QUERY(@node, N'$.order_by'); IF @ob_json IS NOT NULL AND ISJSON(@ob_json) = 1 BEGIN DECLARE @ob_parts NVARCHAR(MAX) = N''; DECLARE ob_c CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@ob_json); DECLARE @obe NVARCHAR(MAX); OPEN ob_c; FETCH NEXT FROM ob_c INTO @obe; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @ob_fld NVARCHAR(400) = COALESCE( JSON_VALUE(@obe, N'$.field'), JSON_VALUE(@obe, N'$.field_path')); DECLARE @ob_dir NVARCHAR(10) = LOWER(COALESCE( JSON_VALUE(@obe, N'$.dir'), N'asc')); IF @ob_dir NOT IN (N'asc', N'desc') SET @ob_dir = N'asc'; IF @ob_fld IS NOT NULL BEGIN DECLARE @ob_meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@ob_fld, N'json') + N'"'); DECLARE @ob_col NVARCHAR(MAX); IF @ob_meta IS NOT NULL AND JSON_VALUE(@ob_meta, N'$.kind') = N'base' SET @ob_col = ISNULL(@base_prefix, N'') + QUOTENAME(JSON_VALUE(@ob_meta, N'$.column')); ELSE SET @ob_col = QUOTENAME(@ob_fld); IF @ob_parts <> N'' SET @ob_parts = @ob_parts + N', '; SET @ob_parts = @ob_parts + @ob_col + N' ' + UPPER(@ob_dir); END; FETCH NEXT FROM ob_c INTO @obe; END; CLOSE ob_c; DEALLOCATE ob_c; IF @ob_parts <> N'' BEGIN IF @over_parts <> N'' SET @over_parts = @over_parts + N' '; SET @over_parts = @over_parts + N'ORDER BY ' + @ob_parts; END; END; -- FRAME (T-SQL: ROWS|RANGE BETWEEN ... AND ...) DECLARE @fr_json NVARCHAR(MAX) = JSON_QUERY(@node, N'$.frame'); IF @fr_json IS NOT NULL AND ISJSON(@fr_json) = 1 BEGIN DECLARE @fr_type NVARCHAR(20) = UPPER(COALESCE(JSON_VALUE(@fr_json, N'$.type'), N'rows')); -- GROUPS is not supported in T-SQL; demote to ROWS IF @fr_type NOT IN (N'ROWS', N'RANGE') SET @fr_type = N'ROWS'; DECLARE @fs_str NVARCHAR(200) = JSON_VALUE(@fr_json, N'$.start'); DECLARE @fs_obj NVARCHAR(MAX) = JSON_QUERY(@fr_json, N'$.start'); DECLARE @fs_sql NVARCHAR(100) = dbo.pvt_compile_frame_bound(@fs_str, @fs_obj); DECLARE @fe_str NVARCHAR(200) = JSON_VALUE(@fr_json, N'$.end'); DECLARE @fe_obj NVARCHAR(MAX) = JSON_QUERY(@fr_json, N'$.end'); DECLARE @frame_sql NVARCHAR(200); IF @fe_str IS NOT NULL OR @fe_obj IS NOT NULL BEGIN DECLARE @fe_sql NVARCHAR(100) = dbo.pvt_compile_frame_bound(@fe_str, @fe_obj); SET @frame_sql = @fr_type + N' BETWEEN ' + @fs_sql + N' AND ' + @fe_sql; END ELSE SET @frame_sql = @fr_type + N' ' + @fs_sql; -- EXCLUDE clause: not supported in T-SQL, silently dropped. IF @over_parts <> N'' SET @over_parts = @over_parts + N' '; SET @over_parts = @over_parts + @frame_sql; END; RETURN @call + N' OVER (' + @over_parts + N')'; END; GO -- ---------- pvt_build_window_sql ------------------------------------ -- Window-function orchestrator. Mirrors pvt_build_window_sql in PG. -- -- @scheme_id – required -- @filter – facet JSON or NULL -- @select – non-empty JSON array of select entries: -- {"field":"","alias":""} OR -- {"alias":"","$expr":{"$over":{...}}} -- @order – optional ORDER BY array (outer, for paging) -- @limit / @offset – optional paging -- @source_mode – 'flat' (only supported value) -- -- Output shapes: -- Shape A (every referenced field is kind='base'): -- SELECT -- FROM dbo._objects o -- WHERE o.[_id_scheme] = X [AND ] -- [ORDER BY ...] [OFFSET ... FETCH ...] -- -- Shape C (any props field referenced): -- SELECT -- FROM () _pvt_cte -- WHERE -- [ORDER BY ...] [OFFSET ... FETCH ...] CREATE OR ALTER FUNCTION dbo.pvt_build_window_sql( @scheme_id BIGINT, @filter NVARCHAR(MAX), @select NVARCHAR(MAX), @order NVARCHAR(MAX), @limit INT, @offset INT, @source_mode NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN NULL; IF @select IS NULL OR ISJSON(@select) = 0 OR @select = N'[]' RETURN NULL; IF @source_mode IS NULL SET @source_mode = N'flat'; IF @source_mode <> N'flat' RETURN NULL; -- ---------------------------------------------------------------- -- 1. Collect ALL field paths needed for the fields map: -- plain select "field" entries + window node args/$field + -- partition_by + order_by + outer @order -- ---------------------------------------------------------------- DECLARE @all_flds NVARCHAR(MAX) = N'['; DECLARE @af_first BIT = 1; DECLARE s1 CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@select); DECLARE @s1e NVARCHAR(MAX); OPEN s1; FETCH NEXT FROM s1 INTO @s1e; WHILE @@FETCH_STATUS = 0 BEGIN -- Plain field entry DECLARE @s1_plain NVARCHAR(400) = COALESCE( JSON_VALUE(@s1e, N'$.field'), JSON_VALUE(@s1e, N'$.field_path')); IF @s1_plain IS NOT NULL BEGIN IF @af_first = 0 SET @all_flds = @all_flds + N','; SET @all_flds = @all_flds + N'{"field":"' + STRING_ESCAPE(@s1_plain, N'json') + N'"}'; SET @af_first = 0; END; -- $over node: harvest partition_by / order_by / args fields DECLARE @s1_over NVARCHAR(MAX) = JSON_QUERY(@s1e, N'$."$expr"."$over"'); IF @s1_over IS NOT NULL BEGIN -- partition_by DECLARE pb1 CURSOR LOCAL FAST_FORWARD FOR SELECT JSON_VALUE([value], N'$.field') FROM OPENJSON(JSON_QUERY(@s1_over, N'$.partition_by')) WHERE JSON_VALUE([value], N'$.field') IS NOT NULL; DECLARE @pb1f NVARCHAR(400); OPEN pb1; FETCH NEXT FROM pb1 INTO @pb1f; WHILE @@FETCH_STATUS = 0 BEGIN IF @af_first = 0 SET @all_flds = @all_flds + N','; SET @all_flds = @all_flds + N'{"field":"' + STRING_ESCAPE(@pb1f, N'json') + N'"}'; SET @af_first = 0; FETCH NEXT FROM pb1 INTO @pb1f; END; CLOSE pb1; DEALLOCATE pb1; -- order_by DECLARE ob1 CURSOR LOCAL FAST_FORWARD FOR SELECT JSON_VALUE([value], N'$.field') FROM OPENJSON(JSON_QUERY(@s1_over, N'$.order_by')) WHERE JSON_VALUE([value], N'$.field') IS NOT NULL; DECLARE @ob1f NVARCHAR(400); OPEN ob1; FETCH NEXT FROM ob1 INTO @ob1f; WHILE @@FETCH_STATUS = 0 BEGIN IF @af_first = 0 SET @all_flds = @all_flds + N','; SET @all_flds = @all_flds + N'{"field":"' + STRING_ESCAPE(@ob1f, N'json') + N'"}'; SET @af_first = 0; FETCH NEXT FROM ob1 INTO @ob1f; END; CLOSE ob1; DEALLOCATE ob1; -- args: {"$field":"..."} references. -- Use CASE in projection to gate JSON_VALUE: a raw scalar -- like `*` (COUNT(*) shorthand, type=1) makes JSON_VALUE -- error out, and SQL Server's WHERE-clause evaluation -- order is unspecified — even a derived-table type filter -- can be folded back into the same scope by the optimizer. -- CASE in SELECT is the only reliable per-row guard. DECLARE ar1 CURSOR LOCAL FAST_FORWARD FOR SELECT v FROM ( SELECT CASE WHEN [type] = 5 THEN JSON_VALUE([value], N'$."$field"') END AS v FROM OPENJSON(JSON_QUERY(@s1_over, N'$.args')) ) t WHERE v IS NOT NULL; DECLARE @ar1f NVARCHAR(400); OPEN ar1; FETCH NEXT FROM ar1 INTO @ar1f; WHILE @@FETCH_STATUS = 0 BEGIN IF @af_first = 0 SET @all_flds = @all_flds + N','; SET @all_flds = @all_flds + N'{"field":"' + STRING_ESCAPE(@ar1f, N'json') + N'"}'; SET @af_first = 0; FETCH NEXT FROM ar1 INTO @ar1f; END; CLOSE ar1; DEALLOCATE ar1; END; FETCH NEXT FROM s1 INTO @s1e; END; CLOSE s1; DEALLOCATE s1; -- Append outer @order field paths IF @order IS NOT NULL AND ISJSON(@order) = 1 BEGIN DECLARE o1 CURSOR LOCAL FAST_FORWARD FOR SELECT COALESCE(JSON_VALUE([value], N'$.field'), JSON_VALUE([value], N'$.field_path')) FROM OPENJSON(@order) WHERE COALESCE(JSON_VALUE([value], N'$.field'), JSON_VALUE([value], N'$.field_path')) IS NOT NULL; DECLARE @o1f NVARCHAR(400); OPEN o1; FETCH NEXT FROM o1 INTO @o1f; WHILE @@FETCH_STATUS = 0 BEGIN IF @af_first = 0 SET @all_flds = @all_flds + N','; SET @all_flds = @all_flds + N'{"field":"' + STRING_ESCAPE(@o1f, N'json') + N'"}'; SET @af_first = 0; FETCH NEXT FROM o1 INTO @o1f; END; CLOSE o1; DEALLOCATE o1; END; SET @all_flds = @all_flds + N']'; -- ---------------------------------------------------------------- -- 2. Resolve field metadata -- ---------------------------------------------------------------- DECLARE @fields NVARCHAR(MAX) = dbo.pvt_collect_fields( @scheme_id, @filter, CASE WHEN @all_flds = N'[]' THEN NULL ELSE @all_flds END); -- ---------------------------------------------------------------- -- 3. Shape decision: Shape A (pure base) vs Shape B narrow vs Shape C wide. -- Mirrors PG/file-20 narrow/wide selection. -- ---------------------------------------------------------------- DECLARE @has_props BIT = 0; DECLARE @has_nested BIT = 0; DECLARE @has_scalar BIT = 0; IF @fields IS NOT NULL AND ISJSON(@fields) = 1 AND @fields <> N'{}' BEGIN IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.kind') <> N'base' ) SET @has_props = 1; IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.parent_sid') IS NOT NULL AND JSON_VALUE([value], N'$.dict_key') IS NOT NULL ) SET @has_nested = 1; IF EXISTS ( SELECT 1 FROM OPENJSON(@fields) WHERE JSON_VALUE([value], N'$.kind') <> N'base' AND NOT ( JSON_VALUE([value], N'$.parent_sid') IS NOT NULL AND JSON_VALUE([value], N'$.dict_key') IS NOT NULL ) ) SET @has_scalar = 1; END; -- Split filter / narrow vs wide decision. DECLARE @splitC NVARCHAR(MAX) = dbo.pvt_split_filter(@filter, @fields); DECLARE @pushC NVARCHAR(MAX) = dbo.pvt_json_text(@splitC, N'push'); DECLARE @resC NVARCHAR(MAX) = JSON_QUERY(@splitC, N'$.residual'); DECLARE @has_null BIT = dbo.pvt_has_absence_check(@resC); DECLARE @force_outer BIT = CASE WHEN @has_null = 1 OR @has_props = 0 THEN 1 ELSE 0 END; -- PG parity: narrow body in 12 currently does NOT support nested-dict. DECLARE @narrow BIT = CASE WHEN @force_outer = 0 AND @has_nested = 0 THEN 1 ELSE 0 END; DECLARE @base_prefix NVARCHAR(20) = CASE WHEN @has_props = 0 OR @narrow = 1 THEN N'o.' ELSE N'' END; -- ---------------------------------------------------------------- -- 4. Outer ORDER BY / paging -- ---------------------------------------------------------------- DECLARE @order_sql NVARCHAR(MAX) = dbo.pvt_build_order_conditions( @order, @fields, CASE WHEN @has_props = 0 OR @narrow = 1 THEN N'o.' ELSE N'_pvt_cte.' END); DECLARE @paging NVARCHAR(MAX) = N''; IF @limit IS NOT NULL AND @limit >= 0 BEGIN IF COALESCE(@offset, 0) = 0 SET @paging = CHAR(10) + N'OFFSET 0 ROWS FETCH NEXT ' + CAST(@limit AS NVARCHAR(20)) + N' ROWS ONLY'; ELSE SET @paging = CHAR(10) + N'OFFSET ' + CAST(@offset AS NVARCHAR(20)) + N' ROWS FETCH NEXT ' + CAST(@limit AS NVARCHAR(20)) + N' ROWS ONLY'; END ELSE IF COALESCE(@offset, 0) > 0 SET @paging = CHAR(10) + N'OFFSET ' + CAST(@offset AS NVARCHAR(20)) + N' ROWS'; IF @paging <> N'' AND @order_sql = N'' SET @order_sql = CHAR(10) + N'ORDER BY (SELECT 1)'; -- ---------------------------------------------------------------- -- 5. Build SELECT projection (second pass over @select) -- ---------------------------------------------------------------- DECLARE @select_parts NVARCHAR(MAX) = N''; DECLARE @sel_cnt INT = 0; DECLARE s2 CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@select); DECLARE @s2e NVARCHAR(MAX); OPEN s2; FETCH NEXT FROM s2 INTO @s2e; WHILE @@FETCH_STATUS = 0 BEGIN SET @sel_cnt = @sel_cnt + 1; DECLARE @s2_alias NVARCHAR(200) = JSON_VALUE(@s2e, N'$.alias'); DECLARE @s2_col NVARCHAR(MAX); -- Window $over expression? DECLARE @s2_over NVARCHAR(MAX) = JSON_QUERY(@s2e, N'$."$expr"."$over"'); IF @s2_over IS NOT NULL BEGIN SET @s2_col = dbo.pvt_build_window_expr(@s2_over, @fields, @base_prefix); IF @s2_alias IS NULL SET @s2_alias = LOWER(ISNULL(JSON_VALUE(@s2_over, N'$.func'), N'_win')) + N'_' + CAST(@sel_cnt AS NVARCHAR(10)); END ELSE BEGIN -- Plain field projection DECLARE @s2_fld NVARCHAR(400) = COALESCE( JSON_VALUE(@s2e, N'$.field'), JSON_VALUE(@s2e, N'$.field_path')); IF @s2_fld IS NOT NULL BEGIN DECLARE @s2_meta NVARCHAR(MAX) = JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@s2_fld, N'json') + N'"'); IF @s2_meta IS NOT NULL AND JSON_VALUE(@s2_meta, N'$.kind') = N'base' SET @s2_col = ISNULL(@base_prefix, N'') + QUOTENAME(JSON_VALUE(@s2_meta, N'$.column')); ELSE SET @s2_col = QUOTENAME(@s2_fld); IF @s2_alias IS NULL SET @s2_alias = @s2_fld; END ELSE BEGIN SET @s2_col = N'NULL'; IF @s2_alias IS NULL SET @s2_alias = N'_sel_' + CAST(@sel_cnt AS NVARCHAR(10)); END; END; IF @s2_alias IS NULL SET @s2_alias = N'_sel_' + CAST(@sel_cnt AS NVARCHAR(10)); IF @select_parts <> N'' SET @select_parts = @select_parts + N', '; SET @select_parts = @select_parts + @s2_col + N' AS ' + QUOTENAME(@s2_alias); FETCH NEXT FROM s2 INTO @s2e; END; CLOSE s2; DEALLOCATE s2; IF @sel_cnt = 0 RETURN NULL; -- ---------------------------------------------------------------- -- 6. WHERE clause -- ---------------------------------------------------------------- DECLARE @where_pfx NVARCHAR(20) = CASE WHEN @has_props = 0 OR @narrow = 1 THEN N'o.' ELSE N'_pvt_cte.' END; DECLARE @where_sql NVARCHAR(MAX) = dbo.pvt_build_where_from_json( @filter, @fields, @where_pfx); -- ---------------------------------------------------------------- -- 7. Assemble final SQL -- ---------------------------------------------------------------- IF @has_props = 0 RETURN N'SELECT ' + @select_parts + CHAR(10) + N'FROM dbo._objects o' + CHAR(10) + N'WHERE o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(40)) + CASE WHEN @where_sql <> N'1=1' THEN N' AND ' + @where_sql ELSE N'' END + @order_sql + @paging; -- Shape B (narrow) / Shape C (wide). -- Pro-parity base pushdown: base/hierarchical predicates narrow -- _objects BEFORE correlated pivot subqueries; residual stays outer. DECLARE @inner NVARCHAR(MAX) = dbo.pvt_build_cte_sql( @scheme_id, @fields, N'flat', NULL, NULL, @force_outer, @pushC, @narrow, DEFAULT, DEFAULT, DEFAULT); DECLARE @where_sql_c NVARCHAR(MAX) = dbo.pvt_build_where_from_json( @resC, @fields, @where_pfx); RETURN N'SELECT ' + @select_parts + CHAR(10) + N'FROM (' + CHAR(10) + @inner + CHAR(10) + N') _pvt_cte' + CASE WHEN @narrow = 1 THEN CHAR(10) + N'JOIN dbo._objects o ON o.[_id] = _pvt_cte.[_id_object]' ELSE N'' END + CHAR(10) + N'WHERE ' + @where_sql_c + @order_sql + @paging; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/24_pvt_projection.sql ---- -- ===================================================================== -- 24_pvt_projection.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- Projection orchestrator. Returns a complete T-SQL SELECT statement -- for a given projection spec (arbitrary columns from redb scheme). -- -- pvt_build_projection_sql( -- @scheme_id BIGINT, -- @filter NVARCHAR(MAX), -- optional PVT filter JSON -- @limit INT, -- optional paging -- @offset INT, -- @projection NVARCHAR(MAX), -- JSON array of string | {field,alias?} -- @source_mode NVARCHAR(50) -- 'flat' (others return NULL) -- ) RETURNS NVARCHAR(MAX) -- -- Projection entry shapes: -- "FieldName" -- simple string -- {"field": "FieldName"} -- object with 'field' key -- {"field": "FieldName", "alias": "MyCol"} -- aliased -- {"field_path": "FieldName"} -- alternative key -- -- Output shapes: -- Shape A (all projected fields are base _objects columns): -- SELECT FROM dbo._objects o -- WHERE o.[_id_scheme] = X [AND ] [OFFSET/FETCH] -- -- Shape C (any projected field is a props field): -- SELECT -- FROM () _pvt_cte -- WHERE [ORDER BY (SELECT 1) OFFSET/FETCH] -- -- Depends on: -- dbo.pvt_collect_fields (10_pvt_field_collection.sql) -- dbo.pvt_resolve_field_path (10_pvt_field_collection.sql) -- dbo.pvt_build_where_from_json (14_pvt_where.sql) -- dbo.pvt_build_cte_sql (12_pvt_cte_builder.sql) -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO -- ---------- pvt_collect_extra_fields ---------------------------------- -- Resolve metadata for a flat JSON array of field paths and merge the -- results into an existing fields-map JSON. Paths that are absent from -- the scheme metadata are silently skipped. CREATE OR ALTER FUNCTION dbo.pvt_collect_extra_fields( @scheme_id BIGINT, @paths_json NVARCHAR(MAX) -- JSON array of strings ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN N'{}'; IF @paths_json IS NULL OR ISJSON(@paths_json) = 0 RETURN N'{}'; DECLARE @out NVARCHAR(MAX) = N'{}'; DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@paths_json) WHERE [type] = 1; -- strings only DECLARE @path NVARCHAR(400); OPEN c; FETCH NEXT FROM c INTO @path; WHILE @@FETCH_STATUS = 0 BEGIN IF @path IS NOT NULL AND @path <> N'' BEGIN DECLARE @meta NVARCHAR(MAX) = dbo.pvt_resolve_field_path(@scheme_id, @path); IF @meta IS NOT NULL BEGIN IF @out = N'{}' SET @out = N'{"' + STRING_ESCAPE(@path, 'json') + N'":' + @meta + N'}'; ELSE SET @out = LEFT(@out, LEN(@out) - 1) + N',"' + STRING_ESCAPE(@path, 'json') + N'":' + @meta + N'}'; END; END; FETCH NEXT FROM c INTO @path; END; CLOSE c; DEALLOCATE c; RETURN @out; END; GO -- ---------- pvt_build_projection_sql ---------------------------------- CREATE OR ALTER FUNCTION dbo.pvt_build_projection_sql( @scheme_id BIGINT, @filter NVARCHAR(MAX), @limit INT, @offset INT, @projection NVARCHAR(MAX), @source_mode NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN NULL; IF @projection IS NULL OR ISJSON(@projection) = 0 RETURN NULL; IF @source_mode IS NULL SET @source_mode = N'flat'; IF @source_mode <> N'flat' RETURN NULL; -- Collect fields from @filter (may return '{}' when filter is NULL) DECLARE @fields NVARCHAR(MAX) = dbo.pvt_collect_fields(@scheme_id, @filter, NULL); IF @fields IS NULL OR ISJSON(@fields) = 0 SET @fields = N'{}'; -- ---------- Parse projection entries ----------------------------------------- -- Build two SELECT lists in parallel: -- @proj_c — for Shape C (_pvt_cte.col references) -- @proj_a — for Shape A (o.[col] references, valid only when kind='base') -- Also track @has_props to choose the final shape. DECLARE @proj_c NVARCHAR(MAX) = N''; DECLARE @proj_a NVARCHAR(MAX) = N''; DECLARE @has_props BIT = 0; DECLARE c_p CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@projection); DECLARE @pentry NVARCHAR(MAX), @ptype INT; OPEN c_p; FETCH NEXT FROM c_p INTO @pentry, @ptype; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @fpath NVARCHAR(400) = NULL; DECLARE @falias NVARCHAR(200) = NULL; IF @ptype = 1 -- plain string entry: "FieldName" BEGIN SET @fpath = @pentry; SET @falias = @pentry; END ELSE IF @ptype = 5 -- object entry: {"field":...,"alias":...} BEGIN SET @fpath = ISNULL( JSON_VALUE(@pentry, N'$.field'), JSON_VALUE(@pentry, N'$.field_path')); SET @falias = ISNULL(JSON_VALUE(@pentry, N'$.alias'), @fpath); END; IF @fpath IS NOT NULL AND @fpath <> N'' BEGIN -- Resolve metadata for this field DECLARE @fm NVARCHAR(MAX) = dbo.pvt_resolve_field_path(@scheme_id, @fpath); IF @fm IS NOT NULL BEGIN -- Merge into @fields when not already present IF JSON_QUERY(@fields, N'$."' + STRING_ESCAPE(@fpath, 'json') + N'"') IS NULL BEGIN IF @fields = N'{}' SET @fields = N'{"' + STRING_ESCAPE(@fpath, 'json') + N'":' + @fm + N'}'; ELSE SET @fields = LEFT(@fields, LEN(@fields) - 1) + N',"' + STRING_ESCAPE(@fpath, 'json') + N'":' + @fm + N'}'; END; DECLARE @fkind NVARCHAR(50) = JSON_VALUE(@fm, N'$.kind'); IF @fkind <> N'base' SET @has_props = 1; -- Build SELECT expressions DECLARE @alias_q NVARCHAR(200) = QUOTENAME(@falias); DECLARE @expr_c NVARCHAR(MAX); DECLARE @expr_a NVARCHAR(MAX) = NULL; IF @fkind = N'base' BEGIN DECLARE @bcol NVARCHAR(100) = JSON_VALUE(@fm, N'$.column'); SET @expr_c = N'_pvt_cte.[' + @bcol + N'] AS ' + @alias_q; SET @expr_a = N'o.[' + @bcol + N'] AS ' + @alias_q; END ELSE BEGIN -- Props field: the CTE names the column after @fpath SET @expr_c = N'_pvt_cte.' + QUOTENAME(@fpath) + N' AS ' + @alias_q; -- @expr_a stays NULL; Shape A is invalid for props fields END; IF @proj_c <> N'' SET @proj_c += N', '; SET @proj_c += @expr_c; IF @expr_a IS NOT NULL BEGIN IF @proj_a <> N'' SET @proj_a += N', '; SET @proj_a += @expr_a; END; END; END; FETCH NEXT FROM c_p INTO @pentry, @ptype; END; CLOSE c_p; DEALLOCATE c_p; IF @proj_c = N'' RETURN NULL; -- Paging clause DECLARE @paging NVARCHAR(MAX) = N''; IF @limit IS NOT NULL AND @limit >= 0 BEGIN DECLARE @off INT = ISNULL(@offset, 0); SET @paging = CHAR(10) + N'ORDER BY (SELECT 1)' + N' OFFSET ' + CAST(@off AS NVARCHAR(10)) + N' ROWS' + N' FETCH NEXT ' + CAST(@limit AS NVARCHAR(10)) + N' ROWS ONLY'; END; -- ---- Shape A: all projected fields are base _objects columns ---- IF @has_props = 0 AND @proj_a <> N'' BEGIN DECLARE @wa NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@filter, @fields, N'o.'); RETURN N'SELECT ' + @proj_a + CHAR(10) + N'FROM dbo._objects o' + CHAR(10) + N'WHERE o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(20)) + CASE WHEN @wa <> N'1=1' THEN N' AND ' + @wa ELSE N'' END + @paging; END; -- ---- Shape C: at least one props field (wide pivot CTE) ---------- DECLARE @inner NVARCHAR(MAX) = dbo.pvt_build_cte_sql( @scheme_id, @fields, N'flat', NULL, NULL, 1, NULL, 0, DEFAULT, DEFAULT, DEFAULT); IF @inner IS NULL RETURN NULL; DECLARE @wc NVARCHAR(MAX) = dbo.pvt_build_where_from_json(@filter, @fields, N'_pvt_cte.'); RETURN N'SELECT ' + @proj_c + CHAR(10) + N'FROM (' + CHAR(10) + @inner + CHAR(10) + N') _pvt_cte' + CHAR(10) + N'WHERE ' + @wc + @paging; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/25_object_props_v2.sql ---- -- ===================================================================== -- 25_object_props_v2.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- PG-specific functions build_hierarchical_properties_sql and -- get_object_json_v2 rely on PostgreSQL composite-type arrays (_values[]) -- which have no direct T-SQL equivalent. The MSSql architecture uses -- separate correlated subqueries and the wide-pivot CTE machinery -- (pvt_build_cte_sql, pvt_build_query_sql) to surface all props. -- -- These stubs allow the file to be deployed without error. Actual -- structured JSON for a single object is composed from the _objects row -- plus _values lookups at the application layer (RedbServiceBase). -- -- Functions: -- dbo.build_hierarchical_properties_sql(@object_id BIGINT) -- -> NVARCHAR(MAX) Always NULL (not implemented in MSSql slice) -- dbo.get_object_json_v2(@object_id BIGINT) -- -> NVARCHAR(MAX) Always NULL (not implemented in MSSql slice) -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER FUNCTION dbo.build_hierarchical_properties_sql(@object_id BIGINT) RETURNS NVARCHAR(MAX) AS BEGIN -- Not implemented: PG-specific composite-type array approach. -- MSSql returns props via the wide-pivot CTE (pvt_build_cte_sql). RETURN NULL; END; GO CREATE OR ALTER FUNCTION dbo.get_object_json_v2(@object_id BIGINT) RETURNS NVARCHAR(MAX) AS BEGIN -- Not implemented: PG-specific function. -- MSSql surfaces single-object props via correlated _values subqueries. RETURN NULL; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/26_pvt_array_groupby.sql ---- -- ===================================================================== -- 26_pvt_array_groupby.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- GROUP BY over the elements of an array (GroupByArray of the free provider). Returns a complete -- T-SQL SELECT ready to be used as a derived table. -- -- dbo.pvt_build_array_groupby_sql( -- @scheme_id BIGINT, -- @array_path NVARCHAR(400), -- path to the array through classes and arrays: -- -- 'Contacts', 'Contacts.Metadata', 'HomeAddress.Building.Amenities' -- @filter NVARCHAR(MAX), -- optional condition on the owning objects (PVT JSON) -- @group_by NVARCHAR(MAX), -- non-empty JSON array of {field, alias} -- @aggregations NVARCHAR(MAX), -- optional JSON array of {field, func, alias, filter?} -- @having NVARCHAR(MAX), -- optional boolean expression (see pvt_build_array_having_expr) -- @source_mode NVARCHAR(50) -- 'flat' -- ) RETURNS NVARCHAR(MAX) -- -- 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 PostgreSQL module, the SQLite extension and the Pro builder): the elements of -- the last array of the path are found by its structure; with a condition they are reached from the ids -- of the objects that satisfy it; every field is joined to its element (or to its class inside the -- element) by _array_parent_id with "_array_parent_id IS NOT NULL", which lets SQL Server read the -- filtered covering index IX__values__structure_parent_batch instead of scanning an index led by _array_parent_id. -- -- A scalar function cannot raise. Everything it cannot answer comes back as -- N'--error: ' and the provider throws with that text: 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, a condition that does not translate, an outer filter that does not compile. -- ===================================================================== SET QUOTED_IDENTIFIER ON; GO -- --------------------------------------------------------------------- -- pvt_build_array_having_expr - boolean expressions of the array GROUP BY (HAVING and the filter -- of a conditional count). -- -- Element paths are read through @cols, a JSON map {"": ""} built by the -- orchestrator - the same columns the SELECT list reads. -- -- Grammar: -- { "$and": [ ... ] } / { "$or": [ ... ] } / { "$not": { ... } } -- { "$isnull": } / { "$notnull": } -- { "$gt"|"$gte"|"$lt"|"$lte"|"$eq"|"$ne": [ , ] } -- ::= -- { "$field": "X" } -> -- { "$count": "*" } -> COUNT(*) -- { "$count": "*", "filter": } -> COUNT(CASE WHEN THEN 1 END) -- { "$count"|"$sum"|"$avg"|"$min"|"$max": { "$field": "X" } } -> FUNC() -- { "$const": } -> literal -- -- Anything else - an unknown node, a path with no joined column, a null constant - returns NULL, -- and the orchestrator refuses the whole query. -- --------------------------------------------------------------------- CREATE OR ALTER FUNCTION dbo.pvt_build_array_having_expr( @node NVARCHAR(MAX), @cols NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @node IS NULL OR ISJSON(@node) = 0 RETURN NULL; DECLARE @k NVARCHAR(200), @v NVARCHAR(MAX), @t INT; SELECT TOP 1 @k = [key], @v = [value], @t = [type] FROM OPENJSON(@node) WHERE [key] <> N'filter'; IF @k IS NULL RETURN NULL; -- ---- Logical connectives ----------------------------------------- IF @k = N'$and' OR @k = N'$or' BEGIN IF @t <> 4 RETURN NULL; DECLARE @op NVARCHAR(5) = CASE @k WHEN N'$and' THEN N' AND ' ELSE N' OR ' END; DECLARE @acc NVARCHAR(MAX) = N'', @child NVARCHAR(MAX), @child_t INT, @part NVARCHAR(MAX); DECLARE c_l CURSOR LOCAL FAST_FORWARD FOR SELECT [value], [type] FROM OPENJSON(@v); OPEN c_l; FETCH NEXT FROM c_l INTO @child, @child_t; WHILE @@FETCH_STATUS = 0 BEGIN SET @part = CASE WHEN @child_t = 5 THEN dbo.pvt_build_array_having_expr(@child, @cols) ELSE NULL END; -- NULL + anything is NULL: one unknown child makes the whole node unknown. SET @acc = CASE WHEN @acc = N'' THEN @part ELSE @acc + @op + @part END; FETCH NEXT FROM c_l INTO @child, @child_t; END; CLOSE c_l; DEALLOCATE c_l; IF @acc = N'' RETURN NULL; RETURN N'(' + @acc + N')'; END; IF @k = N'$not' RETURN CASE WHEN @t = 5 THEN N'NOT (' + dbo.pvt_build_array_having_expr(@v, @cols) + N')' ELSE NULL END; IF @k IN (N'$isnull', N'$notnull') RETURN CASE WHEN @t = 5 THEN N'(' + dbo.pvt_build_array_having_expr(@v, @cols) + CASE @k WHEN N'$isnull' THEN N' IS NULL)' ELSE N' IS NOT NULL)' END ELSE NULL END; IF @k = N'$field' BEGIN IF @t <> 1 OR @cols IS NULL RETURN NULL; RETURN JSON_VALUE(@cols, N'$."' + STRING_ESCAPE(@v, 'json') + N'"'); END; -- ---- Aggregates -------------------------------------------------- IF @k IN (N'$count', N'$sum', N'$avg', N'$min', N'$max') BEGIN DECLARE @fn NVARCHAR(10) = CASE @k WHEN N'$count' THEN N'COUNT' WHEN N'$sum' THEN N'SUM' WHEN N'$avg' THEN N'AVG' WHEN N'$min' THEN N'MIN' ELSE N'MAX' END; DECLARE @cond NVARCHAR(MAX) = JSON_QUERY(@node, N'$.filter'); IF @cond IS NOT NULL BEGIN IF @k <> N'$count' OR @t <> 1 OR @v <> N'*' RETURN NULL; RETURN N'COUNT(CASE WHEN ' + dbo.pvt_build_array_having_expr(@cond, @cols) + N' THEN 1 END)'; END; IF @k = N'$count' AND @t = 1 AND @v = N'*' RETURN N'COUNT(*)'; IF @t <> 5 RETURN NULL; DECLARE @col NVARCHAR(400) = dbo.pvt_build_array_having_expr(@v, @cols); IF @col IS NULL RETURN NULL; RETURN @fn + N'(' + @col + N')'; END; IF @k = N'$const' RETURN CASE WHEN @t IN (0, 4, 5) THEN NULL ELSE dbo.pvt_jsonb_to_sql_literal(@v, @t) END; -- ---- Comparison operators ---------------------------------------- DECLARE @symbol NVARCHAR(5) = CASE @k WHEN N'$eq' THEN N' = ' WHEN N'$ne' THEN N' <> ' WHEN N'$gt' THEN N' > ' WHEN N'$gte' THEN N' >= ' WHEN N'$lt' THEN N' < ' WHEN N'$lte' THEN N' <= ' ELSE NULL END; IF @symbol IS NULL OR @t <> 4 RETURN NULL; IF (SELECT COUNT(*) FROM OPENJSON(@v)) <> 2 RETURN NULL; DECLARE @lhs NVARCHAR(MAX), @lhs_t INT, @rhs NVARCHAR(MAX), @rhs_t INT; SELECT @lhs = [value], @lhs_t = [type] FROM OPENJSON(@v) WHERE [key] = N'0'; SELECT @rhs = [value], @rhs_t = [type] FROM OPENJSON(@v) WHERE [key] = N'1'; IF @lhs_t <> 5 OR @rhs_t <> 5 RETURN NULL; RETURN N'(' + dbo.pvt_build_array_having_expr(@lhs, @cols) + @symbol + dbo.pvt_build_array_having_expr(@rhs, @cols) + N')'; END; GO -- --------------------------------------------------------------------- -- pvt_build_array_groupby_sql - main orchestrator (7 positional params). -- --------------------------------------------------------------------- CREATE OR ALTER FUNCTION dbo.pvt_build_array_groupby_sql( @scheme_id BIGINT, @array_path NVARCHAR(400), @filter NVARCHAR(MAX), @group_by NVARCHAR(MAX), @aggregations NVARCHAR(MAX), @having NVARCHAR(MAX), @source_mode NVARCHAR(50) ) RETURNS NVARCHAR(MAX) AS BEGIN IF @scheme_id IS NULL RETURN N'--error: the scheme id is required'; IF @array_path IS NULL OR @array_path = N'' RETURN N'--error: the array path is required'; IF ISNULL(@source_mode, N'flat') <> N'flat' RETURN N'--error: only the flat source is supported'; IF @group_by IS NULL OR ISJSON(@group_by) = 0 OR (SELECT COUNT(*) FROM OPENJSON(@group_by)) = 0 RETURN N'--error: the grouping needs at least one key'; -- ---- the array: every segment exists, none is a dictionary, the last one is an array DECLARE @parent BIGINT = NULL, @arr_sid BIGINT = NULL, @arr_db_type NVARCHAR(50), @arr_type NVARCHAR(100), @arr_coll NVARCHAR(100), @seg NVARCHAR(400); DECLARE c_seg CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(N'["' + REPLACE(STRING_ESCAPE(@array_path, 'json'), N'.', N'","') + N'"]') ORDER BY CAST([key] AS INT); OPEN c_seg; FETCH NEXT FROM c_seg INTO @seg; WHILE @@FETCH_STATUS = 0 BEGIN SET @arr_sid = NULL; SELECT TOP 1 @arr_sid = c._structure_id, @arr_db_type = c.db_type, @arr_type = c.type_name, @arr_coll = c.collection_type_name FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @seg AND ((@parent IS NULL AND c._parent_structure_id IS NULL) OR c._parent_structure_id = @parent); IF @arr_sid IS NULL BEGIN CLOSE c_seg; DEALLOCATE c_seg; RETURN N'--error: "' + @seg + N'" of the array path "' + @array_path + N'" is not a field of scheme ' + CAST(@scheme_id AS NVARCHAR(20)); END; IF @arr_coll = N'Dictionary' BEGIN CLOSE c_seg; DEALLOCATE c_seg; RETURN N'--error: "' + @seg + N'" in the array path "' + @array_path + N'" is a dictionary; dictionaries are not supported in the array path'; END; SET @parent = @arr_sid; FETCH NEXT FROM c_seg INTO @seg; END; CLOSE c_seg; DEALLOCATE c_seg; IF ISNULL(@arr_coll, N'') <> N'Array' RETURN N'--error: "' + @array_path + N'" is not an array'; DECLARE @is_class BIT = CASE WHEN @arr_type = N'Class' THEN 1 ELSE 0 END; -- ---- every element path the statement reads DECLARE @paths TABLE(path NVARCHAR(400) PRIMARY KEY); INSERT @paths(path) SELECT DISTINCT JSON_VALUE([value], N'$.field') FROM OPENJSON(@group_by) WHERE JSON_VALUE([value], N'$.field') IS NOT NULL; IF EXISTS (SELECT 1 FROM OPENJSON(@group_by) WHERE ISNULL(JSON_VALUE([value], N'$.field'), N'') = N'') RETURN N'--error: a key has no field'; IF @aggregations IS NOT NULL BEGIN IF ISJSON(@aggregations) = 0 RETURN N'--error: the aggregations are not JSON'; INSERT @paths(path) SELECT DISTINCT p FROM ( SELECT JSON_VALUE([value], N'$.field') AS p FROM OPENJSON(@aggregations) UNION SELECT r.name FROM OPENJSON(@aggregations) a CROSS APPLY dbo.pvt_json_field_refs(JSON_QUERY(a.[value], N'$.filter')) r ) x WHERE p IS NOT NULL AND p <> N'*' AND p NOT IN (SELECT path FROM @paths); END; IF @having IS NOT NULL BEGIN IF ISJSON(@having) = 0 OR @having = N'{}' RETURN N'--error: the HAVING is not a JSON expression'; INSERT @paths(path) SELECT name FROM dbo.pvt_json_field_refs(@having) WHERE name NOT IN (SELECT path FROM @paths); END; -- ---- the column of every path, with its joins DECLARE @joins TABLE(ord INT PRIMARY KEY, alias NVARCHAR(10), parent NVARCHAR(10), sid BIGINT); DECLARE @cols TABLE(path NVARCHAR(400) PRIMARY KEY, col NVARCHAR(400)); DECLARE @path NVARCHAR(400), @col NVARCHAR(64), @alias NVARCHAR(10), @fparent BIGINT, @fsid BIGINT, @fdb NVARCHAR(50), @ftype NVARCHAR(100), @fcoll NVARCHAR(100), @i INT, @n INT, @prefix NVARCHAR(400); DECLARE c_path CURSOR LOCAL FAST_FORWARD FOR SELECT path FROM @paths; OPEN c_path; FETCH NEXT FROM c_path INTO @path; WHILE @@FETCH_STATUS = 0 BEGIN IF @path = N'$element' BEGIN IF @is_class = 1 BEGIN CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: "$element" names the element itself, but the elements of "' + @array_path + N'" are classes; name a field of the element'; END; SET @col = dbo.pvt_db_type_to_value_column(@arr_db_type); IF @col IS NULL BEGIN CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: the elements of "' + @array_path + N'" are stored as ' + ISNULL(@arr_db_type, N'?') + N', which cannot be grouped or aggregated'; END; INSERT @cols(path, col) VALUES (@path, N'v.[' + @col + N']'); END ELSE IF LEFT(@path, 1) = N'$' BEGIN CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: "' + @path + N'" is not a field of the elements of "' + @array_path + N'"'; END ELSE IF @is_class = 0 BEGIN CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: the elements of "' + @array_path + N'" are simple values and have no field "' + @path + N'"; use the element itself'; END ELSE BEGIN SET @fparent = @arr_sid; SET @alias = N'v'; SET @prefix = N''; SELECT @n = COUNT(*) FROM STRING_SPLIT(@path, N'.'); SET @i = 0; DECLARE c_fs CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(N'["' + REPLACE(STRING_ESCAPE(@path, 'json'), N'.', N'","') + N'"]') ORDER BY CAST([key] AS INT); OPEN c_fs; FETCH NEXT FROM c_fs INTO @seg; WHILE @@FETCH_STATUS = 0 BEGIN SET @i += 1; SET @prefix = CASE WHEN @prefix = N'' THEN @seg ELSE @prefix + N'.' + @seg END; SET @fsid = NULL; SELECT TOP 1 @fsid = c._structure_id, @fdb = c.db_type, @ftype = c.type_name, @fcoll = c.collection_type_name FROM dbo._scheme_metadata_cache c WHERE c._scheme_id = @scheme_id AND c._name = @seg AND c._parent_structure_id = @fparent; IF @fsid IS NULL BEGIN CLOSE c_fs; DEALLOCATE c_fs; CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: "' + @prefix + N'" is not a field of the elements of "' + @array_path + N'"'; END; IF @fcoll IS NOT NULL BEGIN CLOSE c_fs; DEALLOCATE c_fs; CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: "' + @prefix + N'" is a collection inside the element of "' + @array_path + N'"; group the inner collection instead'; END; IF @i < @n AND ISNULL(@ftype, N'') <> N'Class' BEGIN CLOSE c_fs; DEALLOCATE c_fs; CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: "' + @prefix + N'" is a value, not a class with fields'; END; IF @i = @n AND @ftype = N'Class' BEGIN CLOSE c_fs; DEALLOCATE c_fs; CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: "' + @path + N'" is a class; a key or aggregate reads a stored value'; END; DECLARE @existing NVARCHAR(10) = (SELECT alias FROM @joins WHERE parent = @alias AND sid = @fsid); IF @existing IS NULL BEGIN DECLARE @ord INT = (SELECT COUNT(*) FROM @joins) + 1; SET @existing = N'e' + CAST(@ord AS NVARCHAR(5)); INSERT @joins(ord, alias, parent, sid) VALUES (@ord, @existing, @alias, @fsid); END; SET @alias = @existing; SET @fparent = @fsid; FETCH NEXT FROM c_fs INTO @seg; END; CLOSE c_fs; DEALLOCATE c_fs; SET @col = dbo.pvt_db_type_to_value_column(@fdb); IF @col IS NULL BEGIN CLOSE c_path; DEALLOCATE c_path; RETURN N'--error: "' + @path + N'" is stored as ' + ISNULL(@fdb, N'?') + N', which cannot be grouped or aggregated'; END; INSERT @cols(path, col) VALUES (@path, @alias + N'.[' + @col + N']'); END; FETCH NEXT FROM c_path INTO @path; END; CLOSE c_path; DEALLOCATE c_path; DECLARE @cols_json NVARCHAR(MAX) = N'{' + COALESCE( (SELECT STRING_AGG(N'"' + STRING_ESCAPE(path, 'json') + N'":"' + STRING_ESCAPE(col, 'json') + N'"', N',') FROM @cols), N'') + N'}'; DECLARE @join_sql NVARCHAR(MAX) = COALESCE(( SELECT STRING_AGG(CAST(CHAR(10) + N'LEFT JOIN dbo._values ' + alias + N' ON ' + alias + N'.[_array_parent_id] = ' + parent + N'.[_id]' + N' AND ' + alias + N'.[_id_structure] = ' + CAST(sid AS NVARCHAR(20)) + N' AND ' + alias + N'.[_array_parent_id] IS NOT NULL' AS NVARCHAR(MAX)), N'') WITHIN GROUP (ORDER BY ord) FROM @joins), N''); -- ---- keys DECLARE @select NVARCHAR(MAX) = N'', @group_cols NVARCHAR(MAX) = N''; SELECT @select = STRING_AGG(CAST(c.col + N' AS ' + QUOTENAME(ISNULL(JSON_VALUE(g.[value], N'$.alias'), JSON_VALUE(g.[value], N'$.field'))) AS NVARCHAR(MAX)), N', ') WITHIN GROUP (ORDER BY CAST(g.[key] AS INT)) FROM OPENJSON(@group_by) g JOIN @cols c ON c.path = JSON_VALUE(g.[value], N'$.field'); SELECT @group_cols = STRING_AGG(CAST(c.col AS NVARCHAR(MAX)), N', ') WITHIN GROUP (ORDER BY CAST(g.[key] AS INT)) FROM OPENJSON(@group_by) g JOIN @cols c ON c.path = JSON_VALUE(g.[value], N'$.field'); -- ---- aggregates IF @aggregations IS NOT NULL BEGIN DECLARE @a NVARCHAR(MAX), @af NVARCHAR(400), @afn NVARCHAR(20), @aal NVARCHAR(200), @afilter NVARCHAR(MAX), @expr NVARCHAR(MAX); DECLARE c_agg CURSOR LOCAL FAST_FORWARD FOR SELECT [value] FROM OPENJSON(@aggregations) ORDER BY CAST([key] AS INT); OPEN c_agg; FETCH NEXT FROM c_agg INTO @a; WHILE @@FETCH_STATUS = 0 BEGIN SET @af = ISNULL(JSON_VALUE(@a, N'$.field'), N'*'); SET @afn = UPPER(ISNULL(JSON_VALUE(@a, N'$.func'), N'')); SET @aal = ISNULL(JSON_VALUE(@a, N'$.alias'), @afn); SET @afilter = JSON_QUERY(@a, N'$.filter'); IF @afn NOT IN (N'COUNT', N'SUM', N'AVG', N'MIN', N'MAX') BEGIN CLOSE c_agg; DEALLOCATE c_agg; RETURN N'--error: unknown aggregate function "' + ISNULL(JSON_VALUE(@a, N'$.func'), N'') + N'"'; END; IF @afilter IS NOT NULL BEGIN IF @afn <> N'COUNT' OR @af <> N'*' BEGIN CLOSE c_agg; DEALLOCATE c_agg; RETURN N'--error: only COUNT(*) takes a filter ("' + @aal + N'")'; END; SET @expr = dbo.pvt_build_array_having_expr(@afilter, @cols_json); IF @expr IS NULL BEGIN CLOSE c_agg; DEALLOCATE c_agg; RETURN N'--error: the condition of "' + @aal + N'" does not translate'; END; SET @expr = N'COUNT(CASE WHEN ' + @expr + N' THEN 1 END)'; END ELSE IF @af = N'*' BEGIN IF @afn <> N'COUNT' BEGIN CLOSE c_agg; DEALLOCATE c_agg; RETURN N'--error: ' + @afn + N' needs a field ("' + @aal + N'")'; END; SET @expr = N'COUNT(*)'; END ELSE SET @expr = @afn + N'(' + (SELECT col FROM @cols WHERE path = @af) + N')'; SET @select += N', ' + @expr + N' AS ' + QUOTENAME(@aal); FETCH NEXT FROM c_agg INTO @a; END; CLOSE c_agg; DEALLOCATE c_agg; END; -- ---- HAVING DECLARE @having_clause NVARCHAR(MAX) = N''; IF @having IS NOT NULL BEGIN DECLARE @having_sql NVARCHAR(MAX) = dbo.pvt_build_array_having_expr(@having, @cols_json); IF @having_sql IS NULL RETURN N'--error: the HAVING does not translate'; SET @having_clause = CHAR(10) + N'HAVING ' + @having_sql; END; -- ---- source of the elements DECLARE @from NVARCHAR(MAX); IF @filter IS NOT NULL AND ISJSON(@filter) = 1 AND @filter <> N'{}' BEGIN DECLARE @filter_sql NVARCHAR(MAX) = dbo.pvt_build_query_sql( @scheme_id, @filter, NULL, NULL, NULL, NULL, 0, N'flat', NULL, NULL, 0, NULL); IF @filter_sql IS NULL RETURN N'--error: the condition on the objects did not compile'; SET @from = N'FROM (SELECT DISTINCT [_id] FROM (' + @filter_sql + N') _filt) f' + CHAR(10) + N'INNER JOIN dbo._objects o ON o.[_id] = f.[_id] AND o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(20)) + CHAR(10) + N'INNER JOIN dbo._values v ON v.[_id_object] = f.[_id] AND v.[_id_structure] = ' + CAST(@arr_sid AS NVARCHAR(20)) + N' AND v.[_array_index] IS NOT NULL' + @join_sql; END ELSE SET @from = N'FROM dbo._values v' + CHAR(10) + N'INNER JOIN dbo._objects o ON o.[_id] = v.[_id_object] AND o.[_id_scheme] = ' + CAST(@scheme_id AS NVARCHAR(20)) + @join_sql + CHAR(10) + N'WHERE v.[_id_structure] = ' + CAST(@arr_sid AS NVARCHAR(20)) + N' AND v.[_array_index] IS NOT NULL'; RETURN N'SELECT ' + @select + CHAR(10) + @from + CHAR(10) + N'GROUP BY ' + @group_cols + @having_clause; END; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/27_migrate_structure_type.sql ---- -- ============================================================ -- MIGRATE STRUCTURE TYPE -- MS SQL Server version -- Atomic data migration when changing structure type -- ============================================================ -- ===================================================== -- DROP EXISTING OBJECTS -- ===================================================== IF OBJECT_ID('dbo.get_value_column', 'FN') IS NOT NULL DROP FUNCTION dbo.get_value_column; GO IF OBJECT_ID('dbo.migrate_structure_type', 'P') IS NOT NULL DROP PROCEDURE dbo.migrate_structure_type; GO -- ===================================================== -- HELPER FUNCTION: get_value_column -- Returns column name for type -- ===================================================== CREATE FUNCTION dbo.get_value_column(@type_name NVARCHAR(100)) RETURNS NVARCHAR(50) WITH SCHEMABINDING AS BEGIN RETURN CASE LOWER(@type_name) -- String types (base + derived) WHEN 'string' THEN '_String' WHEN 'text' THEN '_String' WHEN 'mimetype' THEN '_String' WHEN 'filepath' THEN '_String' WHEN 'filename' THEN '_String' -- Long types WHEN 'long' THEN '_Long' WHEN 'int' THEN '_Long' WHEN 'int32' THEN '_Long' WHEN 'int64' THEN '_Long' WHEN 'short' THEN '_Long' WHEN 'byte' THEN '_Long' WHEN 'timespan' THEN '_Long' -- Double types WHEN 'double' THEN '_Double' WHEN 'float' THEN '_Double' -- Numeric types WHEN 'numeric' THEN '_Numeric' WHEN 'decimal' THEN '_Numeric' -- Boolean types WHEN 'boolean' THEN '_Boolean' WHEN 'bool' THEN '_Boolean' -- DateTime types WHEN 'datetimeoffset' THEN '_DateTimeOffset' WHEN 'datetime' THEN '_DateTimeOffset' WHEN 'dateonly' THEN '_DateTimeOffset' WHEN 'timeonly' THEN '_Long' -- Ticks, as TimeSpan -- Guid types WHEN 'guid' THEN '_Guid' WHEN 'uuid' THEN '_Guid' -- Binary types WHEN 'bytearray' THEN '_ByteArray' WHEN 'bytes' THEN '_ByteArray' -- Object/List types WHEN 'object' THEN '_Object' WHEN 'listitem' THEN '_ListItem' ELSE NULL END; END; GO -- ===================================================== -- MAIN PROCEDURE: migrate_structure_type -- Migrates data when changing structure type -- ===================================================== CREATE PROCEDURE dbo.migrate_structure_type @p0 BIGINT, -- structure_id @p1 NVARCHAR(100), -- old_type_name @p2 NVARCHAR(100), -- new_type_name @p3 BIT = 0 -- dry_run AS BEGIN SET NOCOUNT ON; DECLARE @v_source_col NVARCHAR(50); DECLARE @v_target_col NVARCHAR(50); DECLARE @v_affected_rows INT = 0; DECLARE @v_success_count INT = 0; DECLARE @v_has_collision BIT = 0; DECLARE @v_conversion_sql NVARCHAR(MAX); DECLARE @v_count_sql NVARCHAR(MAX); DECLARE @v_collision_sql NVARCHAR(MAX); -- Get column names SET @v_source_col = dbo.get_value_column(@p1); SET @v_target_col = dbo.get_value_column(@p2); -- Validate source type IF @v_source_col IS NULL BEGIN SELECT 0 AS affected_rows, 0 AS success_count, 0 AS error_count, N'Unknown source type: ' + @p1 AS errors; RETURN; END; -- Validate target type IF @v_target_col IS NULL BEGIN SELECT 0 AS affected_rows, 0 AS success_count, 0 AS error_count, N'Unknown target type: ' + @p2 AS errors; RETURN; END; -- Same columns - no migration needed (e.g. Int->Long both in _Long) IF @v_source_col = @v_target_col BEGIN SELECT 0 AS affected_rows, 0 AS success_count, 0 AS error_count, CAST(NULL AS NVARCHAR(MAX)) AS errors; RETURN; END; -- Check structure exists IF NOT EXISTS (SELECT 1 FROM _structures WHERE _id = @p0) BEGIN SELECT 0 AS affected_rows, 0 AS success_count, 0 AS error_count, N'Structure ' + CAST(@p0 AS NVARCHAR(20)) + N' not found' AS errors; RETURN; END; -- Count affected rows SET @v_count_sql = N'SELECT @cnt = COUNT(*) FROM _values WHERE _id_structure = @sid AND ' + QUOTENAME(@v_source_col) + N' IS NOT NULL'; EXEC sp_executesql @v_count_sql, N'@sid BIGINT, @cnt INT OUTPUT', @sid = @p0, @cnt = @v_affected_rows OUTPUT; -- Dry run - only count IF @p3 = 1 BEGIN SELECT @v_affected_rows AS affected_rows, 0 AS success_count, 0 AS error_count, CAST(NULL AS NVARCHAR(MAX)) AS errors; RETURN; END; -- ======================================== -- COLLISION CHECK (key point!) -- If target is filled but source is empty - data already migrated manually -- ======================================== SET @v_collision_sql = N'SELECT @has_collision = CASE WHEN EXISTS( SELECT 1 FROM _values WHERE _id_structure = @sid AND ' + QUOTENAME(@v_target_col) + N' IS NOT NULL AND ' + QUOTENAME(@v_source_col) + N' IS NULL ) THEN 1 ELSE 0 END'; EXEC sp_executesql @v_collision_sql, N'@sid BIGINT, @has_collision BIT OUTPUT', @sid = @p0, @has_collision = @v_has_collision OUTPUT; IF @v_has_collision = 1 BEGIN SELECT @v_affected_rows AS affected_rows, 0 AS success_count, @v_affected_rows AS error_count, N'TYPE_MIGRATION_COLLISION: Data already in ' + @v_target_col + N' but _id_type = ' + @p1 + N'. Fix manually: UPDATE _structures SET _id_type = (SELECT _id FROM _types WHERE _name = ''' + @p2 + N''') WHERE _id = ' + CAST(@p0 AS NVARCHAR(20)) AS errors; RETURN; END; -- No data to migrate IF @v_affected_rows = 0 BEGIN SELECT 0 AS affected_rows, 0 AS success_count, 0 AS error_count, CAST(NULL AS NVARCHAR(MAX)) AS errors; RETURN; END; -- ======================================== -- CONVERSION MATRIX -- ======================================== SET @v_conversion_sql = NULL; -- STRING -> * IF @v_source_col = '_String' BEGIN IF @v_target_col = '_Long' SET @v_conversion_sql = N'UPDATE _values SET _Long = TRY_CAST(_String AS BIGINT), _String = NULL WHERE _id_structure = @sid AND _String IS NOT NULL AND TRY_CAST(_String AS BIGINT) IS NOT NULL'; ELSE IF @v_target_col = '_Double' SET @v_conversion_sql = N'UPDATE _values SET [_Double] = TRY_CAST(_String AS FLOAT), _String = NULL WHERE _id_structure = @sid AND _String IS NOT NULL AND TRY_CAST(_String AS FLOAT) IS NOT NULL'; ELSE IF @v_target_col = '_Numeric' SET @v_conversion_sql = N'UPDATE _values SET _Numeric = TRY_CAST(_String AS DECIMAL(38,18)), _String = NULL WHERE _id_structure = @sid AND _String IS NOT NULL AND TRY_CAST(_String AS DECIMAL(38,18)) IS NOT NULL'; ELSE IF @v_target_col = '_Boolean' -- Guarded like every other text conversion in this procedure. Without the predicate the -- CASE fell through to NULL for anything unrecognised while the same statement cleared -- _String, so a value like 'maybe' was DESTROYED — and counted as a success, because -- success is measured by rows updated. SET @v_conversion_sql = N'UPDATE _values SET _Boolean = CASE WHEN LOWER(_String) IN (''true'', ''1'', ''yes'', ''t'', ''y'') THEN 1 ELSE 0 END, _String = NULL WHERE _id_structure = @sid AND _String IS NOT NULL AND LOWER(_String) IN (''true'', ''1'', ''yes'', ''t'', ''y'', ''false'', ''0'', ''no'', ''f'', ''n'')'; ELSE IF @v_target_col = '_DateTimeOffset' SET @v_conversion_sql = N'UPDATE _values SET _DateTimeOffset = TRY_CAST(_String AS DATETIMEOFFSET), _String = NULL WHERE _id_structure = @sid AND _String IS NOT NULL AND TRY_CAST(_String AS DATETIMEOFFSET) IS NOT NULL'; ELSE IF @v_target_col = '_Guid' SET @v_conversion_sql = N'UPDATE _values SET _Guid = TRY_CAST(_String AS UNIQUEIDENTIFIER), _String = NULL WHERE _id_structure = @sid AND _String IS NOT NULL AND TRY_CAST(_String AS UNIQUEIDENTIFIER) IS NOT NULL'; END -- LONG -> * ELSE IF @v_source_col = '_Long' BEGIN IF @v_target_col = '_String' SET @v_conversion_sql = N'UPDATE _values SET _String = CAST(_Long AS NVARCHAR(MAX)), _Long = NULL WHERE _id_structure = @sid AND _Long IS NOT NULL'; ELSE IF @v_target_col = '_Double' SET @v_conversion_sql = N'UPDATE _values SET [_Double] = CAST(_Long AS FLOAT), _Long = NULL WHERE _id_structure = @sid AND _Long IS NOT NULL'; ELSE IF @v_target_col = '_Numeric' SET @v_conversion_sql = N'UPDATE _values SET _Numeric = CAST(_Long AS DECIMAL(38,18)), _Long = NULL WHERE _id_structure = @sid AND _Long IS NOT NULL'; ELSE IF @v_target_col = '_Boolean' SET @v_conversion_sql = N'UPDATE _values SET _Boolean = CASE WHEN _Long != 0 THEN 1 ELSE 0 END, _Long = NULL WHERE _id_structure = @sid AND _Long IS NOT NULL'; ELSE IF @v_target_col = '_DateTimeOffset' SET @v_conversion_sql = N'UPDATE _values SET _DateTimeOffset = DATEADD(SECOND, _Long, ''1970-01-01''), _Long = NULL WHERE _id_structure = @sid AND _Long IS NOT NULL'; END -- DOUBLE -> * ELSE IF @v_source_col = '_Double' BEGIN IF @v_target_col = '_String' SET @v_conversion_sql = N'UPDATE _values SET _String = FORMAT([_Double], ''G'', ''en-US''), [_Double] = NULL WHERE _id_structure = @sid AND [_Double] IS NOT NULL'; ELSE IF @v_target_col = '_Long' SET @v_conversion_sql = N'UPDATE _values SET _Long = CAST(ROUND([_Double], 0) AS BIGINT), [_Double] = NULL WHERE _id_structure = @sid AND [_Double] IS NOT NULL'; ELSE IF @v_target_col = '_Numeric' SET @v_conversion_sql = N'UPDATE _values SET _Numeric = CAST([_Double] AS DECIMAL(38,18)), [_Double] = NULL WHERE _id_structure = @sid AND [_Double] IS NOT NULL'; END -- NUMERIC -> * ELSE IF @v_source_col = '_Numeric' BEGIN IF @v_target_col = '_String' SET @v_conversion_sql = N'UPDATE _values SET _String = CAST(_Numeric AS NVARCHAR(MAX)), _Numeric = NULL WHERE _id_structure = @sid AND _Numeric IS NOT NULL'; ELSE IF @v_target_col = '_Long' SET @v_conversion_sql = N'UPDATE _values SET _Long = CAST(ROUND(_Numeric, 0) AS BIGINT), _Numeric = NULL WHERE _id_structure = @sid AND _Numeric IS NOT NULL'; ELSE IF @v_target_col = '_Double' SET @v_conversion_sql = N'UPDATE _values SET [_Double] = CAST(_Numeric AS FLOAT), _Numeric = NULL WHERE _id_structure = @sid AND _Numeric IS NOT NULL'; END -- BOOLEAN -> * ELSE IF @v_source_col = '_Boolean' BEGIN IF @v_target_col = '_String' SET @v_conversion_sql = N'UPDATE _values SET _String = CASE WHEN _Boolean = 1 THEN ''true'' ELSE ''false'' END, _Boolean = NULL WHERE _id_structure = @sid AND _Boolean IS NOT NULL'; ELSE IF @v_target_col = '_Long' SET @v_conversion_sql = N'UPDATE _values SET _Long = CASE WHEN _Boolean = 1 THEN 1 ELSE 0 END, _Boolean = NULL WHERE _id_structure = @sid AND _Boolean IS NOT NULL'; END -- DATETIMEOFFSET -> * ELSE IF @v_source_col = '_DateTimeOffset' BEGIN IF @v_target_col = '_String' SET @v_conversion_sql = N'UPDATE _values SET _String = CONVERT(NVARCHAR(50), _DateTimeOffset, 127), _DateTimeOffset = NULL WHERE _id_structure = @sid AND _DateTimeOffset IS NOT NULL'; ELSE IF @v_target_col = '_Long' SET @v_conversion_sql = N'UPDATE _values SET _Long = DATEDIFF_BIG(SECOND, ''1970-01-01'', _DateTimeOffset), _DateTimeOffset = NULL WHERE _id_structure = @sid AND _DateTimeOffset IS NOT NULL'; END -- GUID -> * ELSE IF @v_source_col = '_Guid' BEGIN IF @v_target_col = '_String' SET @v_conversion_sql = N'UPDATE _values SET _String = CAST(_Guid AS NVARCHAR(50)), _Guid = NULL WHERE _id_structure = @sid AND _Guid IS NOT NULL'; END; -- Conversion not supported IF @v_conversion_sql IS NULL BEGIN SELECT @v_affected_rows AS affected_rows, 0 AS success_count, @v_affected_rows AS error_count, N'Conversion ' + @p1 + N' -> ' + @p2 + N' not supported' AS errors; RETURN; END; -- Execute migration EXEC sp_executesql @v_conversion_sql, N'@sid BIGINT', @sid = @p0; SET @v_success_count = @@ROWCOUNT; -- V4 (P3): a SQL-side writer does not know the canonical form - the keys of the touched rows -- are released; scheme synchronisation recomputes them. NULL takes rows OUT of uniqueness. -- AFTER the @@ROWCOUNT capture: the migration's own success count must not measure this UPDATE. UPDATE _values SET _unique = NULL WHERE _id_structure = @p0 AND _unique IS NOT NULL; -- Return result SELECT @v_affected_rows AS affected_rows, @v_success_count AS success_count, @v_affected_rows - @v_success_count AS error_count, CAST(NULL AS NVARCHAR(MAX)) AS errors; END; GO PRINT 'migrate_structure_type procedure created!' PRINT '' PRINT 'Usage:' PRINT ' EXEC migrate_structure_type @p0, @p_old_type, @p_new_type, @p3' PRINT '' PRINT 'Examples:' PRINT ' EXEC migrate_structure_type 12345, ''String'', ''Long'', 1 -- dry run' PRINT ' EXEC migrate_structure_type 12345, ''String'', ''Long'', 0 -- execute' GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/28_migrate_dateonly_db_type.sql ---- -- ===================================================== -- MIGRATION: DateOnly gets db_type 'DateTimeOffset' (SQL Server) -- ===================================================== -- 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 -- redbMSSQL.sql. -- ===================================================== UPDATE [dbo].[_types] SET [_db_type] = 'DateTimeOffset' WHERE [_id] = -9223372036854775686 -- DateOnly AND [_db_type] <> 'DateTimeOffset' GO -- 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 parity with PostgreSQL): the cursor here only worked on a fresh database because it -- iterated zero rows; a dump-restored database WITH DateOnly schemes and WITHOUT the module would -- have hit the missing procedure the same way. Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/29_metadata_cache_sync.sql ---- -- ============================================================ -- METADATA CACHE SYNC — module-owned since V4 (MS SQL Server) -- ============================================================ -- 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 procedures ride the versioned bundle, exactly -- like dbo.get_object_json (09_core_object_json.sql). -- -- The cache TABLE, its indexes and the triggers stay in -- sql/redb_metadata_cache.sql: the triggers EXEC these procedures by name at -- run time. Column additions to the table itself go through the -- "0. Schema upgrades" block of 00_module_init.sql. -- ============================================================ IF OBJECT_ID('[dbo].[sync_metadata_cache_for_scheme]', 'P') IS NOT NULL DROP PROCEDURE [dbo].[sync_metadata_cache_for_scheme]; GO IF OBJECT_ID('[dbo].[warmup_all_metadata_caches]', 'P') IS NOT NULL DROP PROCEDURE [dbo].[warmup_all_metadata_caches]; GO CREATE PROCEDURE [dbo].[sync_metadata_cache_for_scheme] @target_scheme_id BIGINT AS BEGIN SET NOCOUNT ON; -- Delete old cache data for scheme DELETE FROM [dbo].[_scheme_metadata_cache] WHERE [_scheme_id] = @target_scheme_id; -- Insert current data (with collection types and scheme type support) INSERT INTO [dbo].[_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 [dbo].[_structures] s INNER JOIN [dbo].[_types] t ON t.[_id] = s.[_id_type] INNER JOIN [dbo].[_schemes] sch ON sch.[_id] = s.[_id_scheme] LEFT JOIN [dbo].[_types] scht ON scht.[_id] = sch.[_type] -- Scheme type LEFT JOIN [dbo].[_types] ct ON ct.[_id] = s.[_collection_type] -- Collection type LEFT JOIN [dbo].[_types] kt ON kt.[_id] = s.[_key_type] -- Key type WHERE s.[_id_scheme] = @target_scheme_id; END GO -- Warmup procedure (for app start or after crash) CREATE PROCEDURE [dbo].[warmup_all_metadata_caches] AS BEGIN SET NOCOUNT ON; TRUNCATE TABLE [dbo].[_scheme_metadata_cache]; -- Rebuild cache for ALL schemes DECLARE @scheme_id BIGINT; DECLARE cur CURSOR LOCAL FAST_FORWARD FOR SELECT [_id] FROM [dbo].[_schemes]; OPEN cur; FETCH NEXT FROM cur INTO @scheme_id; WHILE @@FETCH_STATUS = 0 BEGIN EXEC [dbo].[sync_metadata_cache_for_scheme] @scheme_id; FETCH NEXT FROM cur INTO @scheme_id; END CLOSE cur; DEALLOCATE cur; -- Return statistics SELECT s.[_id] AS scheme_id, COUNT(c.[_structure_id]) AS structures_count, s.[_name] AS scheme_name, s.[_structure_hash] AS structure_hash FROM [dbo].[_schemes] s LEFT JOIN [dbo].[_scheme_metadata_cache] c ON c.[_scheme_id] = s.[_id] GROUP BY s.[_id], s.[_name], s.[_structure_hash] ORDER BY s.[_id]; END GO -- ===================================================== -- Repair pass moved here from 28_migrate_dateonly_db_type.sql (BR-5 parity): the cache copies -- _db_type, so every scheme with a DateOnly field is resynced after the retype in 28 - and only -- here are the procedures above guaranteed to exist, whatever the database's history. -- Idempotent and cheap: only schemes that actually have a DateOnly structure. -- ===================================================== DECLARE @schemeId BIGINT DECLARE scheme_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT DISTINCT st.[_id_scheme] FROM [dbo].[_structures] st WHERE st.[_id_type] = -9223372036854775686 OPEN scheme_cursor FETCH NEXT FROM scheme_cursor INTO @schemeId WHILE @@FETCH_STATUS = 0 BEGIN EXEC [dbo].[sync_metadata_cache_for_scheme] @schemeId FETCH NEXT FROM scheme_cursor INTO @schemeId END CLOSE scheme_cursor DEALLOCATE scheme_cursor GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/30_soft_delete.sql ---- -- ===================================================== -- SOFT DELETE PROCEDURES FOR MSSQL - module-owned since V4 -- ===================================================== -- Moved from sql/redb_soft_delete.sql: that location lands only in -- redb_init.sql, i.e. fresh databases. sp_mark_for_deletion now also -- releases unique keys (_values._unique = NULL, UNIQUE plan decision 9), -- and that change must reach existing databases - so the procedures ride -- the versioned bundle. Part of Background Deletion System. -- -- Transactions (trash review, 2026-09-14): both procedures run with -- SET XACT_ABORT ON and open a transaction only when the caller has none. -- Without XACT_ABORT a command timeout or client cancel arrives as an -- attention that skips CATCH, and BEGIN TRANSACTION stayed open on the -- session: every later statement of the scope ran inside it and was rolled -- back with it when the pooled session was reset. With XACT_ABORT ON the -- server rolls the transaction back on any error or attention. Inside a -- caller's transaction the procedures neither commit nor roll back - the -- owner of the transaction does. -- ===================================================== -- Drop existing procedures if any IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'sp_mark_for_deletion') DROP PROCEDURE [dbo].[sp_mark_for_deletion] GO IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'sp_purge_trash') DROP PROCEDURE [dbo].[sp_purge_trash] GO -- ===================================================== -- PROCEDURE: sp_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) -- @trash_parent_id: optional parent for trash container (NULL = root level) -- ===================================================== CREATE PROCEDURE [dbo].[sp_mark_for_deletion] @object_ids NVARCHAR(MAX), -- Comma-separated list of object IDs @user_id BIGINT, @trash_parent_id BIGINT = NULL, -- Optional parent for trash container @trash_id BIGINT OUTPUT, @marked_count BIGINT OUTPUT AS BEGIN SET NOCOUNT ON; SET XACT_ABORT ON; DECLARE @own_transaction BIT = CASE WHEN @@TRANCOUNT = 0 THEN 1 ELSE 0 END; IF @own_transaction = 1 BEGIN TRANSACTION; BEGIN TRY -- 1. Create Trash container object with @@__deleted scheme -- Progress fields: _value_long=total, _key=deleted, _value_string=status SET @trash_id = NEXT VALUE FOR [dbo].[global_identity]; INSERT INTO [dbo].[_objects] ( [_id], [_id_scheme], [_id_parent], [_id_owner], [_id_who_change], [_name], [_date_create], [_date_modify], [_value_long], [_key], [_value_string] ) VALUES ( @trash_id, -10, -- @@__deleted scheme @trash_parent_id, -- user-specified parent or NULL @user_id, @user_id, '__TRASH__' + CAST(@user_id AS NVARCHAR(20)) + '_' + CAST(DATEDIFF(SECOND, '1970-01-01', GETUTCDATE()) AS NVARCHAR(20)), SYSDATETIMEOFFSET(), SYSDATETIMEOFFSET(), 0, -- _value_long = total (will be updated after count) 0, -- _key = deleted 'pending' -- _value_string = status ); -- 2. Create temp table for objects to process CREATE TABLE #objects_to_delete (_id BIGINT); -- 3. CTE: find all objects and their descendants recursively ;WITH all_descendants AS ( -- Start with requested objects SELECT o._id FROM [dbo].[_objects] o WHERE o._id IN (SELECT CAST(value AS BIGINT) FROM STRING_SPLIT(@object_ids, ',')) AND o._id_scheme != -10 -- skip already deleted UNION ALL -- Recursively find children SELECT o._id FROM [dbo].[_objects] o INNER JOIN all_descendants d ON o._id_parent = d._id WHERE o._id_scheme != -10 -- skip already deleted ) INSERT INTO #objects_to_delete SELECT _id FROM all_descendants; -- 4. UPDATE: move all found objects under Trash container and change scheme UPDATE [dbo].[_objects] SET [_id_parent] = @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] = SYSDATETIMEOFFSET() WHERE [_id] IN (SELECT _id FROM #objects_to_delete) -- Checked again here, after the row lock: a concurrent soft delete may have moved the object into its -- trash since the collection above. Without it the object moved into a second trash and was counted. AND [_id_scheme] <> -10; SET @marked_count = @@ROWCOUNT; -- V4 (UNIQUE, decision 9): a soft-deleted object releases its keys, whole and at once. -- Same transaction as the move above: no window where the object is in the trash but -- its key is still taken. UPDATE v SET v.[_unique] = NULL FROM [dbo].[_values] v INNER JOIN #objects_to_delete d ON v.[_id_object] = d.[_id] WHERE v.[_unique] IS NOT NULL; -- 5. Update trash container with total count UPDATE [dbo].[_objects] SET [_value_long] = @marked_count WHERE [_id] = @trash_id; DROP TABLE #objects_to_delete; IF @own_transaction = 1 COMMIT TRANSACTION; END TRY BEGIN CATCH IF @own_transaction = 1 AND @@TRANCOUNT > 0 ROLLBACK TRANSACTION; THROW; END CATCH END GO -- ===================================================== -- PROCEDURE: sp_purge_trash -- Physically deletes objects from a trash container in batches -- TR__objects__cascade_values trigger handles _values deletion -- 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 PROCEDURE [dbo].[sp_purge_trash] @trash_id BIGINT, @batch_size INT = 10, @deleted_count BIGINT OUTPUT, @remaining_count BIGINT OUTPUT AS BEGIN SET NOCOUNT ON; SET XACT_ABORT ON; DECLARE @own_transaction BIT = CASE WHEN @@TRANCOUNT = 0 THEN 1 ELSE 0 END; DECLARE @batch TABLE ([_id] BIGINT PRIMARY KEY); IF @own_transaction = 1 BEGIN TRANSACTION; BEGIN TRY -- Update status to 'running' if it was 'pending' UPDATE [dbo].[_objects] SET [_value_string] = 'running', [_date_modify] = SYSDATETIMEOFFSET() WHERE [_id] = @trash_id AND [_value_string] = 'pending'; -- The batch: objects of this container that no live object references INSERT INTO @batch ([_id]) SELECT TOP (@batch_size) o.[_id] FROM [dbo].[_objects] o WHERE o.[_id_parent] = @trash_id AND NOT EXISTS ( SELECT 1 FROM [dbo].[_values] v INNER JOIN [dbo].[_objects] r ON r.[_id] = v.[_id_object] WHERE v.[_Object] = o.[_id] AND r.[_id_scheme] <> -10); SET @deleted_count = @@ROWCOUNT; -- 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 v FROM [dbo].[_values] v INNER JOIN @batch b ON v.[_Object] = b.[_id] INNER JOIN [dbo].[_objects] r ON r.[_id] = v.[_id_object] WHERE r.[_id_scheme] = -10; -- Delete the batch (trigger handles its own _values). The count comes from the batch table: -- the INSTEAD OF trigger does the actual delete. DELETE o FROM [dbo].[_objects] o INNER JOIN @batch b ON o.[_id] = b.[_id]; -- Count remaining objects in this trash SELECT @remaining_count = COUNT(*) FROM [dbo].[_objects] WHERE [_id_parent] = @trash_id; -- Update progress in trash container. Nothing deletable while objects remain = every one of -- them is referenced by a live object: 'failed', no longer claimed by the background worker. UPDATE [dbo].[_objects] SET [_key] = [_key] + @deleted_count, [_value_string] = CASE WHEN @remaining_count = 0 THEN 'completed' WHEN @deleted_count = 0 THEN 'failed' ELSE 'running' END, [_date_modify] = SYSDATETIMEOFFSET() WHERE [_id] = @trash_id; -- If no more children, delete the trash container itself IF @remaining_count = 0 BEGIN DELETE FROM [dbo].[_objects] WHERE [_id] = @trash_id; END IF @own_transaction = 1 COMMIT TRANSACTION; END TRY BEGIN CATCH IF @own_transaction = 1 AND @@TRANCOUNT > 0 ROLLBACK TRANSACTION; THROW; END CATCH END GO Path: redb/redb.MSSql/sql/v2-pvt/31_node_permissions_trigger.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.MSSql/sql/v2-pvt/31_node_permissions_trigger.sql ---- -- ===================================================== -- tr_auto_create_node_permissions: disabled, as on PostgreSQL -- ===================================================== -- The trigger (sql/redb_permissions.sql, created at installation) copies an inherited permission onto the parent of a -- new child object. PostgreSQL creates it disabled (redbPostgre.sql: ALTER TABLE _objects DISABLE TRIGGER ...), and -- SQL Server never ran it either: the bulk copy of new objects did not fire triggers. From module 0.2.41 the bulk copy -- fires triggers and checks the foreign keys (FireTriggers | CheckConstraints), so the trigger is disabled here to keep -- the two providers saving the same rows. It rides the versioned bundle so existing databases get it on the next start. -- ===================================================== IF OBJECT_ID(N'dbo.tr_auto_create_node_permissions', N'TR') IS NOT NULL AND OBJECTPROPERTY(OBJECT_ID(N'dbo.tr_auto_create_node_permissions'), 'ExecIsTriggerDisabled') = 0 ALTER TABLE [dbo].[_objects] DISABLE TRIGGER [tr_auto_create_node_permissions]; GO Path: redb/redb.MSSql/sql/v2-pvt/32_delete_cascade.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.MSSql/sql/v2-pvt/32_delete_cascade.sql ---- -- ===================================================== -- delete_object_cascade / delete_objects_cascade: delete objects with their descendants -- ===================================================== -- The procedure's row count, which ExecuteAsync returns, is the number of REQUESTED objects this call deleted, as -- PostgreSQL and SQLite return it: descendants are not counted, and an object another session deletes concurrently is -- not counted either. -- -- In one transaction (its own when the caller has none): the requested rows are locked first (UPDLOCK, a seek on the -- primary key for each), then their descendants are collected by a plain read and everything is deleted bottom-up -- (_id_parent has no cascade on SQL Server; the INSTEAD OF trigger TR__objects__cascade_values removes the values of -- each object). A requested object that is locked here is deleted by this call, so the locked rows are the count. A -- concurrent delete of the same object waits at its own lock and, once this one commits, no longer finds it. -- Only the requested rows are locked, by key: a lock hint on the walk would hold every row it scans. -- -- The count used to be the number of ids collected by a plain read, descendants included: two concurrent deletes both -- collected the object, one deleted it, and both returned 1, so DeleteAsync answered true for an object another session -- had deleted. Counting the rows of the DELETE itself would not help: the INSTEAD OF trigger receives the rows the -- statement qualified, also when it then finds them gone. -- -- Part of the versioned bundle (from 0.2.43) so existing databases get it on the next start; the installation script -- no longer defines them. CREATE OR ALTER keeps one definition of each. -- ===================================================== CREATE OR ALTER PROCEDURE [dbo].[delete_object_cascade] @object_id BIGINT AS BEGIN SET NOCOUNT ON; SET XACT_ABORT ON; DECLARE @own_tran BIT = CASE WHEN @@TRANCOUNT = 0 THEN 1 ELSE 0 END; IF @own_tran = 1 BEGIN TRANSACTION; CREATE TABLE #locked (_id BIGINT PRIMARY KEY); CREATE TABLE #to_delete (_id BIGINT, depth INT); INSERT INTO #locked (_id) SELECT _id FROM _objects WITH (UPDLOCK, ROWLOCK) WHERE _id = @object_id; ;WITH Descendants AS ( SELECT _id, 0 AS depth FROM #locked UNION ALL SELECT o._id, d.depth + 1 FROM _objects o INNER JOIN Descendants d ON o._id_parent = d._id ) INSERT INTO #to_delete SELECT _id, depth FROM Descendants; -- Bottom-up: deepest children first. DECLARE @max_depth INT = (SELECT MAX(depth) FROM #to_delete); WHILE @max_depth >= 0 BEGIN DELETE FROM _objects WHERE _id IN (SELECT _id FROM #to_delete WHERE depth = @max_depth); SET @max_depth = @max_depth - 1; END IF @own_tran = 1 COMMIT TRANSACTION; -- The row count of this last statement is the result. SET NOCOUNT OFF; DELETE FROM #locked; END GO CREATE OR ALTER PROCEDURE [dbo].[delete_objects_cascade] @object_ids NVARCHAR(MAX) -- Comma-separated list of IDs AS BEGIN SET NOCOUNT ON; SET XACT_ABORT ON; DECLARE @own_tran BIT = CASE WHEN @@TRANCOUNT = 0 THEN 1 ELSE 0 END; IF @own_tran = 1 BEGIN TRANSACTION; CREATE TABLE #requested (_id BIGINT PRIMARY KEY); CREATE TABLE #locked (_id BIGINT PRIMARY KEY); CREATE TABLE #to_delete (_id BIGINT, depth INT); INSERT INTO #requested (_id) SELECT DISTINCT CAST(value AS BIGINT) FROM STRING_SPLIT(@object_ids, ',') WHERE LTRIM(value) <> N''; -- One key seek per requested id, in id order. INSERT INTO #locked (_id) SELECT o._id FROM #requested r INNER JOIN _objects o WITH (UPDLOCK, ROWLOCK, FORCESEEK) ON o._id = r._id; ;WITH Descendants AS ( SELECT _id, 0 AS depth FROM #locked UNION ALL SELECT o._id, d.depth + 1 FROM _objects o INNER JOIN Descendants d ON o._id_parent = d._id ) INSERT INTO #to_delete SELECT _id, depth FROM Descendants; DECLARE @max_depth INT = (SELECT MAX(depth) FROM #to_delete); WHILE @max_depth >= 0 BEGIN DELETE FROM _objects WHERE _id IN (SELECT _id FROM #to_delete WHERE depth = @max_depth); SET @max_depth = @max_depth - 1; END IF @own_tran = 1 COMMIT TRANSACTION; -- The requested objects this call locked and so deleted, each once (a requested object reached also as a -- descendant of another requested one is still one row here). SET NOCOUNT OFF; DELETE FROM #locked; END GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/99_module_version.sql ---- -- ===================================================================== -- v2-pvt module version (MSSql) -- ===================================================================== -- Applied LAST on purpose, see the PostgreSQL twin. The bundle runs as GO -- batches with autocommit, so a failure in the middle leaves the earlier -- batches applied; with the version created first (as until 0.1.9) such a -- failure left the NEW version next to the OLD functions and nothing ever -- retried. Step 2 of 00_module_init.sql drops dbo.pvt_module_version with -- the rest; it is recreated here only after everything else succeeded. -- ===================================================================== SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO -- ---------- 3. Module compatibility function --------------------------- -- What this module still serves, see the PostgreSQL twin: '|'. -- Raise the first part only when a change breaks the C# of older packages; -- never lower it. Created before the version function, so a module that -- reports a version always has this function too. CREATE FUNCTION dbo.pvt_module_compat() RETURNS nvarchar(50) WITH SCHEMABINDING AS BEGIN RETURN N'0.2.43|4.8.0'; END; GO -- ---------- 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 FUNCTION dbo.pvt_module_version() RETURNS nvarchar(50) WITH SCHEMABINDING AS BEGIN -- 0.1.2 - 13_pvt_condition.sql: pvt_build_field_condition dict_key -- branch now short-circuits to `_pvt_cte.[FieldName] OP val` -- when called in a post-pivot context (@base_prefix = 'o.' -- or '_pvt_cte.'). The nested-dict CTE already materializes -- the pivot column; emitting an independent EXISTS over -- dbo._values for the outer WHERE duplicated the lookup -- work. Symmetric with PG's pvt_build_field_condition. -- 0.1.1 - narrow-with-nested CTE shape + stable ORDER BY + -- Pro-parity nested-dict pushdown: -- * 12_pvt_cte_builder.sql: each LEFT JOIN nested derived -- table now folds `_id_scheme = X` (+ extra_where + -- tree_filter) into a dp._id_object IN (SELECT _id FROM -- _objects ...) subquery — mirrors PG PRO. -- * narrow-with-nested body skips INNER JOIN _values v -- when @sids = N'' (nested-only): no scalar pivot -- sids, no point in expanding+collapsing _values. -- * 20_pvt_build_query_sql.sql: narrow eligibility now -- allows nested groups; default ORDER BY @base_prefix -- + [_id] when paging is present without ORDER BY. -- 0.1.3 - fix: DISTINCT (@distinct=1) outer ORDER BY referenced the inner -- alias prefix (o./_pvt_cte.) outside the `_dist` wrapper -> "multi-part -- identifier 'o._id' could not be bound" with .Distinct().Take(). Outer -- order now uses the projected [_id] (@order_sql_dist) in all 3 branches. -- 0.1.4 - Soft-delete read-path fix + object-json materializer ownership: -- * The whole object->JSON materializer (dbo.get_object_json plus -- helpers build_properties / build_field_json / build_listitem_json -- / escape_json_string) moved from core (redb_json_objects.sql, -- now deleted) into the module (09_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). -- * dbo.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.2.10 - base64 через FOR XML PATH вместо XML-инстанса (.value): 111 -> 21 мс на мегабайте. -- В STRING_AGG подзапрос запрещён (Msg 130) - массив и словарь берут значение из OUTER APPLY. -- 0.2.9 - root value_bytes emitted (base64 via XML trick) - was absent entirely, read gave null -- (bug report BUG_BYTES �3.3 read side). -- 0.2.8 - техбамп-2: OUTER APPLY попал в соседние блоки (0.2.7 битый в тестовых базах). -- 0.2.7 - техбамп: T-SQL запрещает подзапрос в STRING_AGG, Р-1 переехал на OUTER APPLY -- (0.2.6 успел задеплоиться битым в тестовые базы). -- 0.2.6 - Р-1 (2026-09-03): legacy-толерантность «без _Guid И без детей» (оба места). -- 0.2.5 - В-1 «null должен быть null» (2026-09-03): null-элемент коллекции классов -- эмитится JSON-null (массив и словарь). -- 0.2.4 - BR-7 (2026-09-02): dbo.pvt_like_escape() - the operand of every LIKE sugar -- operator (field, dict, listitem, array, expression) is a LITERAL now, paired with -- ESCAPE; the raw $like/$arrayMatches operators keep the caller's pattern. -- 0.2.3 - the unread full-text index on _values._String is dropped (owner decision -- 2026-09-02): LIKE never used it, CONTAINS was never generated. -- 0.2.2 - V4 LAZY L2 (lazy references): -- * block 0: _structures._lazy and _scheme_metadata_cache._lazy (the virtual marker). -- * 29: the metadata cache carries the marker. -- * 09 build_field_json: @lazy parameter from the cache cursor; a lazy reference -- emits the base-fields stub (depth 0) when SESSION_CONTEXT(N'redb.lazy_refs') = 1. -- 0.1.12 - V4 byte[] scalar storage (B1): -- * build_field_json fetched _ByteArray but had no emit branch at all, so a -- ByteArray property always loaded as null. Base64 emit added to the three -- CASE paths (scalar, array element, dictionary value) via xs:base64Binary. -- 0.1.11 - V4 unique keys, stage 1 (UNIQUE_STRING_KEY_PLAN, Э1): -- * block "0. Schema upgrades": _objects._value_unique NVARCHAR(440) and the filtered -- unique index UIX__objects__scheme_unique (INCLUDE _id; 8+880 = 888 < 900). -- * get_object_json and the PVT base-field surface emit and filter the column -- (07/09/12/01), so the key behaves exactly like _value_string. -- * sp_mark_for_deletion (30_soft_delete.sql) also releases the object key on the -- way into the trash (decision 9). -- 0.1.10 - 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 UNIQUEIDENTIFIER, the filtered unique -- index UIX__values__structure_unique, and the same two columns on -- _scheme_metadata_cache (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. -- * 30_soft_delete.sql: sp_mark_for_deletion and sp_purge_trash move in from -- sql/redb_soft_delete.sql; sp_mark_for_deletion now releases unique keys -- (_values._unique = NULL) in the same transaction (decision 9). -- 0.1.8 - the DateOnly seed correction joins the module: -- * 28_migrate_dateonly_db_type.sql moved in from sql/. DateOnly was -- seeded with _db_type = 'DateTime', which no JSON projection -- branches on, so every DateOnly property materialised as -- 0001-01-01. The correction 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. -- * Idempotent by construction, as it must be: the bundle is -- reapplied on every version change. -- 0.1.7 - migrate_structure_type joins the module, and its String -> Boolean -- conversion is guarded: -- * 27_migrate_structure_type.sql moved in from sql/. It used to ship -- only in redb_init.sql, applied to fresh databases only, so a fix -- to it never reached an existing one. In the module, 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. It is now predicated on the accepted -- token list, like every other text conversion in that procedure, -- which already used TRY_CAST(...) IS NOT NULL. -- 0.1.6 - Scoped WhereLeaves()/WhereRoots() cross-tree leak fix: -- * 20_pvt_build_query_sql.sql tree_leaves/tree_roots fast-path now -- honours the seed: leaves = childless descendants of the seed root -- (via pvt_is_descendant_of), roots = the seed object itself — -- instead of a whole-scheme scan that ignored @tree_ids. So -- TreeQuery(rootObj).WhereLeaves() returns the leaves of that -- subtree, not every leaf in the scheme. -- * pvt_tree_leaves / pvt_tree_roots (08_pvt_tree_functions.sql) — -- the pvt_build_cte_sql (props-shape) path — seeded the same way. -- 0.2.26 - found by the module smoke runner once it ran in the gate (SQ-4, 2026-09-26), each a PostgreSQL -- parity gap that 1=0 had hidden: $arrayAt reads {"index":N,"value":V}; $arrayCountLte (was -- $arraycountle); $ilike on a field; ContainsKey with a bare string key. One typed element -- comparison (pvt_array_element_equals) instead of copies. -- 0.2.25 - SQ-5 (2026-09-26): dbo.pvt_fail refuses what the filter and aggregate builders cannot read -- (13, 14, 21). An unknown operator was 1=1 or 1=0, an unknown comparison '=', a value that -- was not a number 0, an aggregate it could not compile a NULL column. PostgreSQL raises there. -- 0.2.24 - pvt_build_query_sql, tree mode without props (2026-09-26): @distinct_on and @distinct were -- ignored - DistinctByRedb on a tree returned every node. Wrapped as in the flat Shape A. -- 0.2.23 - pvt_resolve_field_path (2026-09-26): T-SQL keeps a variable when SELECT @v = ... finds no -- row, so an unknown nested child resolved to its parent (Contacts[].NoSuchField became the -- Contacts array); the dictionary child and the 2b ListItem branch had the same trap. -- 0.2.22 - array GroupBy (2026-09-26): a key or aggregate field the array item does not have, or an -- unknown aggregate function, makes the result NULL. They were skipped - the grouping ran on -- the other keys, the aggregate vanished, and with no key left the flat item list came back. -- 0.2.21 - HAVING of the array GroupBy (2026-09-25): pvt_build_array_having_expr reads item fields -- through the joined columns (@cols) and returns NULL for any shape it does not know; the -- orchestrator joins a field only the HAVING aggregates and returns NULL on an unread -- HAVING. It returned 1=1 for an unknown node (the condition was dropped) and wrote an item -- field as [X], a column the query does not have. -- 0.2.20 - tech bump: 0.2.19 reached the test databases before the file-26 fix below. -- 0.2.19 - HAVING in GroupBy (2026-09-24): pvt_build_groupby_sql compiles @having through the -- new pvt_build_groupby_having_expr, aggregates via pvt_build_agg_expr as in the SELECT -- list; an unknown node makes the whole query NULL. @having was reserved and never -- emitted, and the provider passed NULL: GroupBy(...).Having(...) returned every group. -- 26: an array-item field aggregated twice (Min(Value) + Max(Value)) reuses the joined -- typed column; the second one named the field as an output alias and failed. -- 0.2.18 - Regex.IsMatch / Regex.Replace in filters (2026-09-16): $regex / $iregex compile to -- REGEXP_LIKE, $regexReplace to REGEXP_REPLACE (SQL Server 2025, compatibility level 170). -- The unsupported-top branch turned $regex into 1=1: the filter was dropped and every row -- came back. -- 0.2.17 - arrays and dictionaries of references keep a trashed target as null (2026-09-15): -- STRING_AGG skipped the NULL of the nested get_object_json and dropped the element / -- the key. PostgreSQL, SQLite and Pro already kept null. -- 0.2.16 - list item JSON in the model's shape (2026-09-15): dbo.build_listitem_json writes -- {id, id_list, value, alias, id_object}. It wrote {id, idList, value, alias}: the model -- reads id_list / id_object, so every load lost the list link and the object link. -- 0.2.15 - trash review (2026-09-14): sp_mark_for_deletion and sp_purge_trash run with -- SET XACT_ABORT ON and open their own transaction only when the caller has none - -- a command timeout or cancel inside BEGIN TRANSACTION used to leave it open on the -- session, and every later statement of the scope was rolled back with it. -- sp_purge_trash: a reference held by a trashed object is removed with the purge; 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.2.14 - 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.2.13 - block 0: S3 - _structures._unique_scope, _tags on schemes/structures/cache, -- IX__structures__tags; cache sync carries the two new columns. -- 0.2.12 - 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.2.11 - block 0: FK-column indexes IX__values__ListItem_not_null / -- IX__values__Object_not_null (filtered). Without them every DELETE of a -- referenced object or list item scanned the whole _values for the FK check -- (perf finding, 2026-09-10). -- 0.1.0 - skeleton: module bootstrap, drop-all, version function. -- Builder functions (pvt_build_query_sql etc.) not implemented yet. -- 0.2.27 - fail-closed on unescaped splices (SQLI-PoC): pvt_b2_expr_sql (:60 and :361 of -- 14_pvt_where.sql) and pvt_build_window_expr (23_pvt_window.sql) call -- dbo.pvt_fail instead of echoing a raw name inside a comment. -- 0.2.28 - the $case branch of pvt_extract_field_pairs (10_pvt_field_collection.sql) is -- reachable: the generic array descent swallowed $case first (its value is an -- array), so "when"/"then"/"else" were harvested as field paths and the $field -- references inside the arms were never collected. The expression builder then -- could not resolve the field (silently NULL before 0.2.27, an error after). -- 0.2.29 - block 0: the indexes another index of the same table fully replaces are dropped, -- the set PostgreSQL dropped in 0.7.13 (2026-10-14). The statements that bring them -- back are in the comment above the DROP block of 00_module_init.sql. -- 0.2.30 - block 0: value-leading indexes (_id_structure, , _id_object) INCLUDE (_array_index) for every -- value column but the string replace the eleven object-leading *_not_null / *_filter ones (2026-10-16). -- Restore statements: 00_module_init.sql. -- 0.2.31 - DistinctBy/DistinctRedb in tree queries: the row source ranks by the query order and by every key -- of @distinct_on, and the wrapper keeps _rn = 1 ordered by _ord. Until 0.2.30 the first key only was -- partitioned, ranked by (SELECT 1), with the ordering applied outside, where a Props column does not -- resolve: TreeQuery(...).DistinctBy(x => x.IsActive) failed with "Invalid column name 'IsActive'". -- 0.2.50 - IX__values__array_parent_id is dropped where another unfiltered index led by _array_parent_id remains -- (IX__values__array_parent_index; 00_module_init.sql). No function changed. -- 0.2.49 - _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.2.48 - TimeOnly and TimeSpan as Ticks in _Long: _types and the metadata cache say Long (00_module_init.sql), -- 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.2.47 - pvt_json_text: the pushed base condition ($.push of pvt_split_filter, read in 16, 20, 21, 22 and 23) -- and the search constant of $contains/$startsWith/$endsWith over an expression and of a window argument -- ($const, 14 and 23) are read through OPENJSON. JSON_VALUE returned NULL for a text over 4,000 characters -- and the condition was dropped: WhereRedb(ParentId in 400+ ids) with a props filter or a GroupBy returned -- every object of the scheme the props filter let through. -- 0.2.46 - _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.2.45 - pvt_build_query_sql returns [_ord] next to [_id], the position of the row in the order of the query, and -- the caller sorts by it: a number given outside (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) may run before -- the inner sort, and OrderByDescending(key).DistinctBy(key) came back ascending. pvt_build_hierarchical_conditions -- reads an exact $level with JSON_VALUE: JSON_QUERY returns NULL for a scalar, and {"$level": 1} was -- dropped from the filter (2026-11-14). -- 0.2.44 - pvt_build_query_sql: an order without paging is kept with OFFSET 0 ROWS; it was dropped, and OrderBy -- without Take came back in the order of the plan (2026-11-14). -- 0.2.43 - 32_delete_cascade.sql: delete_object_cascade and delete_objects_cascade move into the module, collect under update locks -- in a transaction of their own and return the number of requested objects this call deleted, as PostgreSQL -- and SQLite do; they returned the ids collected, descendants and objects another session had just deleted included. sp_mark_for_deletion checks again that -- the object is not in the trash yet when it moves it (2026-11-14). -- 0.2.42 - dbo.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.2.41 - 31_node_permissions_trigger.sql: tr_auto_create_node_permissions is disabled, as on PostgreSQL; the bulk -- copy of new rows now fires triggers and checks the foreign keys, and the two providers must keep -- saving the same rows (2026-11-13). -- 0.2.40 - pvt_build_window_sql: AVG casts its operand to NUMERIC(38, 10), as pvt_agg_expr does; over a bigint -- field the window average cut the fraction off (32 for 32.25) (2026-11-03). -- 0.2.39 - pvt_build_cte_sql, narrow shape over a tree source: the objects read their values through OUTER APPLY, -- so the walk (pvt_tree_descendants) runs once; joined to the pivot it ran on both sides, and a filter over -- a 100 thousand node subtree took 3.3 s instead of 1.8 s (2026-11-02). -- 0.2.38 - pvt_build_query_sql: WhereLevel of a tree query that starts from nodes counts from them (the walk depth -- of pvt_tree_descendants), as maxDepth and Pro do; it counted from the root of the whole tree (2026-11-02). -- 0.2.37 - tree_leaves with a depth (TreeQuery(root, maxDepth).WhereLeaves()): the leaves of the whole tree -- within the depth, in pvt_build_query_sql and pvt_build_cte_sql; the leaves below the depth were -- returned (2026-11-02). -- 0.2.36 - pvt_build_query_sql, tree without props: tree_descendants with a depth walks pvt_tree_descendants; -- the descendant check it used has no depth, and TreeQuery(root, maxDepth) returned the whole subtree -- (2026-11-02). -- 0.2.35 was a structure condition in the nested-dictionary join, withdrawn before release; some -- databases ran it, hence the next number. -- 0.2.34 - 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 (2026-11-02). -- 0.2.32 - dbo.pvt_build_array_groupby_sql (GroupByArray): array paths through classes and arrays, '$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 with -- _array_parent_id IS NOT NULL (the filtered covering index: 950 -> 160 ms on 200 thousand elements); -- what it cannot answer returns '--error: ' instead of NULL. The outer filter that fails to -- compile is refused; it used to be dropped (2026-11-02). RETURN N'0.2.50'; END; GO -- ---------- 4. Smoke ----------------------------------------------------- DECLARE @v nvarchar(50) = dbo.pvt_module_version(); PRINT N'v2-pvt module init OK, version: ' + @v; GO Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/99_smoke_auto.sql ---- -- ===================================================================== -- 99_smoke_auto.sql (MSSql v2-pvt) -- --------------------------------------------------------------------- -- Automated PVT smoke runner. Iterates a static table of filter cases, -- builds SQL via dbo.pvt_build_query_sql and counts rows. Reports -- OK/FAIL/SKIP per case through PRINT. Raises at the end when any -- case fails (via RAISERROR). -- -- Scope of this slice (files 00-22, MSSql free tier): -- * Filter operators: $eq $ne $gt $gte $lt $lte $in $nin $like -- $startsWith $endsWith $contains -- $startsWithIgnoreCase $endsWithIgnoreCase -- $containsIgnoreCase $null $isNull $notNull $exists -- * Boolean combinators: $and $or $not -- * Base-field pushdown: 0$: prefix, _id/_name/_date_* etc. -- * ORDER BY + paging (OFFSET/FETCH) -- * DistinctBy via ROW_NUMBER (DISTINCT ON emulation) -- * Terminal aggregation: pvt_build_aggregate_sql (file 21) -- * GROUP BY: pvt_build_groupby_sql (file 22) -- * Array operators: $arrayContains $arrayAny $arrayEmpty -- $arrayCount $arrayCountGt $arrayFirst $arrayLast -- * Property functions: .$length [].$count -- * Hierarchical: $isRoot (flat-data test) -- -- NOT in this slice (therefore not tested here): -- * $ilike / $regex / $fts (PG-specific or not yet ported) -- * $expr / B2 expression engine -- * Dictionary operators (ContainsKey etc.) -- * Window functions (file 23, PG-specific windowing) -- * Array GroupBy (file 26, not yet ported) -- * Full tree-mode tests (need tree-shaped data) -- -- Designed against the redb.Tests.Integration model corpus -- (Employee, Person, City, ProjectMetrics, Department). -- Schemes are looked up by suffix match on _schemes._name or _alias. -- Missing schemes are reported as SKIP and do not fail the run. -- -- Usage (from sqlcmd or SSMS): -- :r redb.MSSql/sql/v2-pvt/99_smoke_auto.sql -- -- or: -- sqlcmd -S ... -d -I -i redb.MSSql/sql/v2-pvt/99_smoke_auto.sql -- ===================================================================== SET NOCOUNT ON; SET QUOTED_IDENTIFIER ON; PRINT N'----------------------------------------------------------'; PRINT N'pvt smoke run starting, module version: ' + dbo.pvt_module_version(); PRINT N'----------------------------------------------------------'; -- ===================================================================== -- 1. FILTER CASES -- ===================================================================== CREATE TABLE #smoke_cases ( case_id INT IDENTITY(1,1) PRIMARY KEY, scheme_name NVARCHAR(256) NOT NULL, -- full CLR type name, as registered by C# InitializeAsync label NVARCHAR(200) NOT NULL, filter_json NVARCHAR(MAX) NULL, skip_reason NVARCHAR(200) NULL -- NULL = run; non-NULL = SKIP (not yet implemented) ); INSERT INTO #smoke_cases (scheme_name, label, filter_json) VALUES -- ----- Employee: comparison operators -------------------------------- ('redb.Tests.Integration.Models.EmployeeProps', 'eq string', '{"Department":{"$eq":"IT"}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'shorthand eq', '{"Department":"IT"}'), ('redb.Tests.Integration.Models.EmployeeProps', 'ne string', '{"Department":{"$ne":"Sales"}}'), ('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}}'), -- ----- Employee: null checks ----------------------------------------- ('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}}'), -- ----- Employee: string pattern operators ---------------------------- ('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%"}}'), -- ----- Employee: boolean combinators --------------------------------- ('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}}'), -- ----- Employee: date comparisons ------------------------------------ ('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"}}'), -- ----- Employee: base-field pushdown (0$: prefix + _col names) ------- ('redb.Tests.Integration.Models.EmployeeProps', 'base 0$:Id gt', '{"0$:Id":{"$gt":0}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'base 0$:Name startsWith', '{"0$:Name":{"$startsWith":"E"}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'base _id range', '{"_id":{"$gt":0}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'pushdown _date_create', '{"_date_create":{"$gte":"2000-01-01T00:00:00Z"}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'pushdown base+props AND', '{"_id":{"$gt":0},"Department":{"$ne":"X"}}'), ('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 $not base', '{"$not":{"_id":{"$lt":0}}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'pushdown nested $and+$or','{"$and":[{"_id":{"$gt":0}},{"$or":[{"Department":"IT"},{"Department":"HR"}]}]}'), -- ----- Employee: bool field ------------------------------------------- ('redb.Tests.Integration.Models.EmployeeProps', 'bool eq true', '{"IsRemote":{"$eq":true}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'bool eq false', '{"IsRemote":{"$eq":false}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'bool shorthand true', '{"IsRemote":true}'), -- ----- Person: basic -------------------------------------------------- ('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":"@"}}'), -- ListItem field by sub-property ('redb.Tests.Integration.Models.PersonProps', 'ListItem Status.Value', '{"Status.Value":{"$eq":"Active"}}'), ('redb.Tests.Integration.Models.PersonProps', 'ListItem Status.Id', '{"Status.Id":{"$gt":0}}'), -- ----- ProjectMetrics: basic ----------------------------------------- ('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', 'TeamSize range', '{"TeamSize":{"$gte":1,"$lte":1000}}'), ('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', 'population gt', '{"Population":{"$gt":1000}}'), ('redb.Tests.Integration.Models.CityProps', 'name in', '{"Name":{"$in":["Moscow","Paris"]}}'), ('redb.Tests.Integration.Models.CityProps', 'region startsWith', '{"Region":{"$startsWith":"M"}}'), -- ----- Department (auto-SKIP: DepartmentProps not in test DB) -------- ('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', 'budget range', '{"Budget":{"$gte":0}}'), -- ----- Employee: array operators ------------------------------------- ('redb.Tests.Integration.Models.EmployeeProps', '$arrayContains Skills C#', '{"Skills":{"$arrayContains":"C#"}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayAny Skills', '{"Skills":{"$arrayAny":true}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayEmpty Skills false', '{"Skills":{"$arrayEmpty":false}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayCount Skills eq 3', '{"Skills":{"$arrayCount":3}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayCountGt SkillLevels', '{"SkillLevels":{"$arrayCountGt":0}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayFirst Skills C#', '{"Skills":{"$arrayFirst":"C#"}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayLast SkillLevels', '{"SkillLevels":{"$arrayLast":3}}'), -- ----- Employee: property functions ---------------------------------- ('redb.Tests.Integration.Models.EmployeeProps', 'FirstName.$length gt 3', '{"FirstName.$length":{"$gt":3}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'Skills[].$count gte 2', '{"Skills[].$count":{"$gte":2}}'), -- ----- Employee: hierarchical (flat data; $isRoot = all rows) -------- ('redb.Tests.Integration.Models.EmployeeProps', '$isRoot true', '{"$isRoot":true}'), ('redb.Tests.Integration.Models.EmployeeProps', '$isRoot false', '{"$isRoot":false}'), -- ----- Employee: more array operators (already implemented) ---------- ('redb.Tests.Integration.Models.EmployeeProps', '$arrayCountGte SkillLevels', '{"SkillLevels":{"$arrayCountGte":1}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayCountLt Skills', '{"Skills":{"$arrayCountLt":10}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayCountLte Skills', '{"Skills":{"$arrayCountLte":5}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayAny false', '{"Skills":{"$arrayAny":false}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayEmpty true', '{"Skills":{"$arrayEmpty":true}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayAt index=0 C#', '{"Skills":{"$arrayAt":{"index":0,"value":"C#"}}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayAt index=1', '{"Skills":{"$arrayAt":{"index":1,"value":"SQL"}}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayStartsWith C', '{"Skills":{"$arrayStartsWith":"C"}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayEndsWith L', '{"Skills":{"$arrayEndsWith":"L"}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'Skills.$count gte 1', '{"Skills.$count":{"$gte":1}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'FirstName.$length eq 0', '{"FirstName.$length":{"$eq":0}}'), -- ----- Employee: PG-parity variants --------------------------------- ('redb.Tests.Integration.Models.EmployeeProps', 'ilike', '{"FirstName":{"$ilike":"a%"}}'), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayCount 0', '{"Skills":{"$arrayCount":0}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'Skills.$length gt', '{"Skills.$length":{"$gt":0}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'SkillLevels.$count gt', '{"SkillLevels.$count":{"$gt":0}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'pushdown $or mixed', '{"$or":[{"_id":{"$lt":10}},{"FirstName":"Ivan"}]}'), ('redb.Tests.Integration.Models.EmployeeProps', 'pushdown $not mixed', '{"$not":{"$and":[{"_id":{"$gt":0}},{"FirstName":"Ivan"}]}}'), ('redb.Tests.Integration.Models.EmployeeProps', 'pushdown 0$:Name+props', '{"0$:Name":{"$startsWith":"E"},"Age":{"$gt":0}}'), -- ----- ProjectMetrics: array + property ops ------------------------- ('redb.Tests.Integration.Models.ProjectMetricsProps', 'BugsFixed gte', '{"BugsFixed":{"$gte":0}}'), ('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 $arrayStartsWith', '{"Technologies":{"$arrayStartsWith":"P"}}'), ('redb.Tests.Integration.Models.ProjectMetricsProps', 'tech .$length gt', '{"Technologies.$length":{"$gt":0}}'), -- ----- City: float-array coords + range ----------------------------- ('redb.Tests.Integration.Models.CityProps', 'coords $arrayCount 2', '{"Coordinates":{"$arrayCount":2}}'), ('redb.Tests.Integration.Models.CityProps', 'coords $arrayAt index=0', '{"Coordinates":{"$arrayAt":{"index":0,"value":55.7558}}}'), ('redb.Tests.Integration.Models.CityProps', 'coords .$length eq 2', '{"Coordinates.$length":{"$eq":2}}'), ('redb.Tests.Integration.Models.CityProps', 'population range', '{"Population":{"$gte":0,"$lt":50000000}}'), -- ----- Department (auto-SKIP: DepartmentProps not in test DB) -------- ('redb.Tests.Integration.Models.DepartmentProps', 'code contains', '{"Code":{"$contains":"-"}}'), ('redb.Tests.Integration.Models.DepartmentProps', 'description notNull', '{"Description":{"$notNull":true}}'); -- ----- Not-yet-implemented: tracked as SKIP ------------------------- INSERT INTO #smoke_cases (scheme_name, label, filter_json, skip_reason) VALUES -- $array aggregates ('redb.Tests.Integration.Models.EmployeeProps', '$arrayMatches Skills', '{"Skills":{"$arrayMatches":"%QL%"}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', '$arraySum SkillLevels', '{"SkillLevels":{"$arraySum":10}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayMin SkillLevels', '{"SkillLevels":{"$arrayMin":1}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayMax SkillLevels', '{"SkillLevels":{"$arrayMax":5}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', '$arrayAvg SkillLevels', '{"SkillLevels":{"$arrayAvg":3}}', NULL), -- Dictionary operators ('redb.Tests.Integration.Models.EmployeeProps', 'dict ContainsKey work', '{"PhoneDirectory.ContainsKey":"work"}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'dict ContainsKey home', '{"PhoneDirectory.ContainsKey":"home"}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'dict indexer value', '{"PhoneDirectory[work]":{"$eq":"+7-000"}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'dict indexer notNull', '{"PhoneDirectory[work]":{"$notNull":true}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'dict nested .City', '{"OfficeLocations[Moscow].City":{"$eq":"Moscow"}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'dict nested .Street', '{"OfficeLocations[Moscow].Street":{"$notNull":true}}', NULL), -- ListItem accessors ('redb.Tests.Integration.Models.PersonProps', 'ListItem Status.Value', '{"Status.Value":{"$eq":"Active"}}', NULL), ('redb.Tests.Integration.Models.PersonProps', 'ListItem Status.Alias', '{"Status.Alias":{"$eq":"active"}}', NULL), ('redb.Tests.Integration.Models.PersonProps', 'ListItem Status.Id', '{"Status.Id":{"$gt":0}}', NULL), ('redb.Tests.Integration.Models.PersonProps', 'ListItem Roles[].Value in', '{"Roles[].Value":{"$in":["admin","user"]}}', NULL), ('redb.Tests.Integration.Models.PersonProps', 'ListItem Roles[].Value nin', '{"Roles[].Value":{"$nin":["guest"]}}', NULL), -- B2 expression engine ('redb.Tests.Integration.Models.EmployeeProps', 'expr $add gt', '{"$gt":[{"$add":[{"$field":"Age"},{"$const":1}]},{"$const":18}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $mul lt', '{"$lt":[{"$mul":[{"$field":"_id"},{"$const":2}]},{"$const":1000000}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $upper eq', '{"$eq":[{"$upper":[{"$field":"FirstName"}]},{"$const":"IVAN"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $concat ilike', '{"$ilike":[{"$concat":[{"$field":"FirstName"},{"$const":" "},{"$field":"LastName"}]},{"$const":"%van%"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $coalesce eq', '{"$eq":[{"$coalesce":[{"$field":"Department"},{"$const":"none"}]},{"$const":"IT"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $between', '{"$between":[{"$field":"_id"},{"$const":0},{"$const":1000000}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $in props', '{"$in":[{"$field":"Department"},["IT","HR","R&D"]]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $nin base', '{"$nin":[{"$field":"_id"},[-1,-2,-3]]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $length gt', '{"$gt":[{"$length":[{"$field":"FirstName"}]},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $abs sub', '{"$lt":[{"$abs":[{"$sub":[{"$field":"Age"},{"$const":30}]}]},{"$const":1000}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $null base push', '{"$null":{"$field":"_id_parent"}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $notNull props', '{"$notNull":{"$field":"FirstName"}}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $contains sugar', '{"$contains":[{"$field":"FirstName"},"a"]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $startsWith sugar', '{"$startsWith":[{"$field":"LastName"},"S"]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $endsWith sugar', '{"$endsWith":[{"$field":"LastName"},"ov"]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $min 2-arg', '{"$lt":[{"$min":[{"$field":"Age"},{"$const":100}]},{"$max":[{"$field":"Age"},{"$const":0}]}]}', NULL), -- B2-expr ORDER BY $expr: tested in dedicated block (section 2), not in the filter loop. -- B2-expr extended scalar functions in @filter ('redb.Tests.Integration.Models.EmployeeProps', 'expr $year EXTRACT', '{"$gte":[{"$year":{"$field":"HireDate"}},{"$const":2000}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $trimStart LTRIM', '{"$eq":[{"$trimStart":{"$field":"FirstName"}},{"$const":"Ivan"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $substring', '{"$eq":[{"$substring":[{"$field":"FirstName"},{"$const":1},{"$const":3}]},{"$const":"Iva"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $replace', '{"$eq":[{"$replace":[{"$field":"FirstName"},{"$const":"a"},{"$const":"A"}]},{"$const":"IvAn"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $power', '{"$lt":[{"$power":[{"$field":"Age"},{"$const":2}]},{"$const":1000000}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $dateAdd day', '{"$gt":[{"$dateAdd":["day",{"$field":"HireDate"},{"$const":30}]},{"$const":"2000-01-01T00:00:00Z"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $if conditional', '{"$eq":[{"$if":[{"$gte":[{"$field":"Salary"},{"$const":100000}]},{"$const":"High"},{"$const":"Normal"}]},{"$const":"Normal"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $case multi-arm', '{"$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"}]}', NULL), -- B2-expr: operators added in Pro parity sprint (floor/ceil/div/mod/neg/lower/trimEnd/ -- month/day/hour/minute/second/sqrt/sign/exp/ln/log10/round/log/dateSub/indexOf) ('redb.Tests.Integration.Models.EmployeeProps', 'expr $floor', '{"$gte":[{"$floor":{"$field":"Age"}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $ceil', '{"$gte":[{"$ceil":{"$field":"Age"}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $div', '{"$gte":[{"$div":[{"$field":"Age"},{"$const":1}]},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $mod', '{"$gte":[{"$mod":[{"$field":"Age"},{"$const":2}]},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $neg', '{"$lte":[{"$neg":{"$field":"Age"}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $lower', '{"$ne":[{"$lower":{"$field":"FirstName"}},{"$const":""}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $trimEnd', '{"$gte":[{"$length":{"$trimEnd":{"$field":"FirstName"}}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $month', '{"$gte":[{"$month":{"$field":"HireDate"}},{"$const":1}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $day', '{"$gte":[{"$day":{"$field":"HireDate"}},{"$const":1}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $hour', '{"$gte":[{"$hour":{"$field":"HireDate"}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $minute', '{"$gte":[{"$minute":{"$field":"HireDate"}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $second', '{"$gte":[{"$second":{"$field":"HireDate"}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $sqrt', '{"$gte":[{"$sqrt":{"$field":"Age"}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $sign', '{"$gt":[{"$sign":{"$field":"Age"}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $exp', '{"$gte":[{"$exp":{"$const":0}},{"$const":1}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $ln', '{"$gte":[{"$ln":{"$const":1}},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $log10', '{"$gte":[{"$log10":{"$const":100}},{"$const":1}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $round', '{"$gte":[{"$round":[{"$field":"Age"},{"$const":0}]},{"$const":0}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $log 2-arg', '{"$gte":[{"$log":[{"$const":100},{"$const":10}]},{"$const":1}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $dateSub day', '{"$gt":[{"$dateSub":["day",{"$field":"HireDate"},{"$const":30}]},{"$const":"1990-01-01T00:00:00Z"}]}', NULL), ('redb.Tests.Integration.Models.EmployeeProps', 'expr $indexOf', '{"$gte":[{"$indexOf":[{"$field":"FirstName"},{"$const":"a"}]},{"$const":0}]}', NULL); -- DISTINCT + DISTINCT ON guard: tested in dedicated block (section 3), not in the filter loop. -- ===================================================================== -- Run filter cases -- ===================================================================== DECLARE @i INT = 1, @max INT, @pass INT = 0, @fail INT = 0, @skip INT = 0; SELECT @max = MAX(case_id) FROM #smoke_cases; WHILE @i <= @max BEGIN DECLARE @scheme_name NVARCHAR(100), @label NVARCHAR(200), @filter_json NVARCHAR(MAX), @skip_reason NVARCHAR(200); SELECT @scheme_name = scheme_name, @label = label, @filter_json = filter_json, @skip_reason = skip_reason FROM #smoke_cases WHERE case_id = @i; IF @skip_reason IS NOT NULL BEGIN SET @skip += 1; PRINT N'SKIP [' + @scheme_name + N' / ' + @label + N'] ' + @skip_reason; SET @i += 1; CONTINUE; END; -- Scheme lookup: exact match on _name (full CLR type name, as stored by C# InitializeAsync). DECLARE @scheme_id BIGINT = NULL; SELECT TOP 1 @scheme_id = [_id] FROM dbo._schemes WHERE [_name] = @scheme_name; IF @scheme_id IS NULL BEGIN SET @skip += 1; PRINT N'SKIP [' + @scheme_name + N' / ' + @label + N'] scheme not found'; SET @i += 1; CONTINUE; END; BEGIN TRY DECLARE @sql NVARCHAR(MAX) = dbo.pvt_build_query_sql( @scheme_id, @filter_json, NULL, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); DECLARE @cnt_sql NVARCHAR(MAX) = N'SELECT @cnt = COUNT(*) FROM (' + @sql + N') _t'; DECLARE @cnt BIGINT; EXEC sp_executesql @cnt_sql, N'@cnt BIGINT OUTPUT', @cnt = @cnt OUTPUT; SET @pass += 1; PRINT N'OK [' + @scheme_name + N' / ' + @label + N'] rows=' + CAST(ISNULL(@cnt, 0) AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [' + @scheme_name + N' / ' + @label + N'] ' + ERROR_MESSAGE(); END CATCH; SET @i += 1; END; DROP TABLE #smoke_cases; -- ===================================================================== -- 2. ORDER BY + PAGING (Employee only) -- ===================================================================== DECLARE @emp_id BIGINT = NULL; SELECT TOP 1 @emp_id = [_id] FROM dbo._schemes WHERE [_name] = N'redb.Tests.Integration.Models.EmployeeProps'; IF @emp_id IS NOT NULL BEGIN -- order by props field desc + FETCH BEGIN TRY DECLARE @s1 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, NULL, 10, 0, N'[{"field":"Age","dir":"desc","nulls":"last"}]', NULL, NULL, N'flat', NULL, NULL, NULL, NULL); DECLARE @c1 BIGINT; DECLARE @x1 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @s1 + N') _t'; EXEC sp_executesql @x1, N'@c BIGINT OUTPUT', @c = @c1 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / order Age desc + FETCH 10] rows=' + CAST(@c1 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / order Age desc + FETCH 10] ' + ERROR_MESSAGE(); END CATCH; -- multi-column ORDER BY + offset BEGIN TRY DECLARE @s2 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, NULL, 25, 5, N'[{"field":"LastName","dir":"asc"},{"field":"FirstName","dir":"asc"}]', NULL, NULL, N'flat', NULL, NULL, NULL, NULL); DECLARE @c2 BIGINT; DECLARE @x2 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @s2 + N') _t'; EXEC sp_executesql @x2, N'@c BIGINT OUTPUT', @c = @c2 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / order multi + offset 5] rows=' + CAST(@c2 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / order multi + offset 5] ' + ERROR_MESSAGE(); END CATCH; -- order by base field 0$:Id desc + filter BEGIN TRY DECLARE @s3 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, N'{"Age":{"$gte":18}}', 5, 0, N'[{"field":"0$:Id","dir":"desc"}]', NULL, NULL, N'flat', NULL, NULL, NULL, NULL); DECLARE @c3 BIGINT; DECLARE @x3 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @s3 + N') _t'; EXEC sp_executesql @x3, N'@c BIGINT OUTPUT', @c = @c3 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / filter + order base Id desc] rows=' + CAST(@c3 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / filter + order base Id desc] ' + ERROR_MESSAGE(); END CATCH; -- ORDER BY $expr: arithmetic Age*2 DESC. -- NOTE: $expr ORDER BY currently emits ORDER BY (SELECT 1) — full expression -- evaluation in ORDER BY is not yet implemented; test guards against regression -- (ORDER BY clause must be present and query must execute without error). BEGIN TRY DECLARE @oe1 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, NULL, 5, 0, N'[{"$expr":{"$mul":[{"$field":"Age"},{"$const":2}]},"dir":"desc"}]', NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF @oe1 NOT LIKE N'%ORDER BY%' RAISERROR(N'expected ORDER BY in SQL, got: %.200s', 16, 1, @oe1); DECLARE @coe1 BIGINT; DECLARE @xoe1 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @oe1 + N') _t'; EXEC sp_executesql @xoe1, N'@c BIGINT OUTPUT', @c = @coe1 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / order $expr Age*2 desc] rows=' + CAST(@coe1 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / order $expr Age*2 desc] ' + ERROR_MESSAGE(); END CATCH; -- ORDER BY $expr: UPPER(FirstName) ASC. -- NOTE: same as above — placeholder ORDER BY (SELECT 1) until $expr ORDER BY is implemented. BEGIN TRY DECLARE @oe2 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, NULL, 5, 0, N'[{"$expr":{"$upper":{"$field":"FirstName"}},"dir":"asc"}]', NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF @oe2 NOT LIKE N'%ORDER BY%' RAISERROR(N'expected ORDER BY in SQL, got: %.200s', 16, 1, @oe2); DECLARE @coe2 BIGINT; DECLARE @xoe2 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @oe2 + N') _t'; EXEC sp_executesql @xoe2, N'@c BIGINT OUTPUT', @c = @coe2 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / order $expr UPPER(FirstName) asc] rows=' + CAST(@coe2 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / order $expr UPPER(FirstName) asc] ' + ERROR_MESSAGE(); END CATCH; -- ORDER BY $expr: LEN(_name)+1 DESC (base column in $expr). -- NOTE: same placeholder limitation — full $expr ORDER BY to be implemented later. BEGIN TRY DECLARE @oe3 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, NULL, 5, 0, N'[{"$expr":{"$add":[{"$length":{"$field":"_name"}},{"$const":1}]},"dir":"desc"}]', NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF @oe3 NOT LIKE N'%ORDER BY%' RAISERROR(N'expected ORDER BY in SQL, got: %.200s', 16, 1, @oe3); DECLARE @coe3 BIGINT; DECLARE @xoe3 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @oe3 + N') _t'; EXEC sp_executesql @xoe3, N'@c BIGINT OUTPUT', @c = @coe3 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / order $expr LEN(_name)+1 desc] rows=' + CAST(@coe3 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / order $expr LEN(_name)+1 desc] ' + ERROR_MESSAGE(); END CATCH; END ELSE PRINT N'SKIP [Employee / order+paging block] scheme not found'; -- ===================================================================== -- 2b. Phase 2: top-level $eq / $expr filter (base pushdown + residual) -- ===================================================================== IF @emp_id IS NOT NULL BEGIN -- Top-level $eq with base field -> pushed into Shape A. BEGIN TRY DECLARE @ex1 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, N'{"$eq":[{"$field":"_id"},{"$field":"_id"}]}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @ex1) > 0 RAISERROR(N'expected Shape A (no CTE) for top-level $eq base, got: %.200s', 16, 1, @ex1); DECLARE @cex1 BIGINT; DECLARE @xex1 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @ex1 + N') _t'; EXEC sp_executesql @xex1, N'@c BIGINT OUTPUT', @c = @cex1 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / filter top $eq base (Shape A)] rows=' + CAST(@cex1 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / filter top $eq base] ' + ERROR_MESSAGE(); END CATCH; -- Top-level $expr with base-only arithmetic -> pushed into Shape A. BEGIN TRY DECLARE @ex2 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, N'{"$expr":{"$gt":[{"$length":{"$field":"_name"}},{"$const":0}]}}', 10, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @ex2) > 0 RAISERROR(N'expected Shape A (no CTE) for $expr base-only, got: %.200s', 16, 1, @ex2); DECLARE @cex2 BIGINT; DECLARE @xex2 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @ex2 + N') _t'; EXEC sp_executesql @xex2, N'@c BIGINT OUTPUT', @c = @cex2 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / filter $expr base-only (Shape A)] rows=' + CAST(@cex2 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / filter $expr base-only] ' + ERROR_MESSAGE(); END CATCH; -- Top-level $expr referencing props -> Shape C, predicate runs over CTE. BEGIN TRY DECLARE @ex3 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, N'{"$expr":{"$gte":[{"$field":"Age"},{"$const":0}]}}', 10, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @ex3) = 0 RAISERROR(N'expected Shape C (CTE) for $expr props, got: %.200s', 16, 1, @ex3); DECLARE @cex3 BIGINT; DECLARE @xex3 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @ex3 + N') _t'; EXEC sp_executesql @xex3, N'@c BIGINT OUTPUT', @c = @cex3 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / filter $expr props (Shape C residual)] rows=' + CAST(@cex3 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / filter $expr props] ' + ERROR_MESSAGE(); END CATCH; -- Mixed: implicit $and of base $eq + props field -> Shape C with split. BEGIN TRY DECLARE @ex4 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, N'{"$gt":[{"$field":"_id"},{"$const":0}],"FirstName":{"$startsWith":"A"}}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @ex4) = 0 RAISERROR(N'expected Shape C (CTE) for mixed $gt+props, got: %.200s', 16, 1, @ex4); DECLARE @cex4 BIGINT; DECLARE @xex4 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @ex4 + N') _t'; EXEC sp_executesql @xex4, N'@c BIGINT OUTPUT', @c = @cex4 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / filter mixed $gt base + props residual] rows=' + CAST(@cex4 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / filter mixed $gt base + props residual] ' + ERROR_MESSAGE(); END CATCH; END ELSE PRINT N'SKIP [Employee / Phase 2 expr-filter block] scheme not found'; -- ===================================================================== -- 3. DISTINCT BY (ROW_NUMBER emulation) -- ===================================================================== IF @emp_id IS NOT NULL BEGIN -- DistinctBy props field (Department) BEGIN TRY DECLARE @sd1 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, NULL, NULL, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, N'[{"field":"Department"}]'); DECLARE @cd1 BIGINT; DECLARE @xd1 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @sd1 + N') _t'; EXEC sp_executesql @xd1, N'@c BIGINT OUTPUT', @c = @cd1 OUTPUT; -- Verify ROW_NUMBER pattern in generated SQL IF @sd1 NOT LIKE N'%ROW_NUMBER()%' BEGIN RAISERROR(N'expected ROW_NUMBER() in SQL for DistinctBy, got: %.200s', 16, 1, @sd1); END; SET @pass += 1; PRINT N'OK [Employee / DistinctBy Department (ROW_NUMBER)] rows=' + CAST(@cd1 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / DistinctBy Department (ROW_NUMBER)] ' + ERROR_MESSAGE(); END CATCH; -- DistinctBy base field (_id_owner) BEGIN TRY DECLARE @sd2 NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, NULL, NULL, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, N'[{"field":"0$:Id"}]'); DECLARE @cd2 BIGINT; DECLARE @xd2 NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @sd2 + N') _t'; EXEC sp_executesql @xd2, N'@c BIGINT OUTPUT', @c = @cd2 OUTPUT; SET @pass += 1; PRINT N'OK [Employee / DistinctBy base 0$:Id] rows=' + CAST(@cd2 AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / DistinctBy base 0$:Id] ' + ERROR_MESSAGE(); END CATCH; -- Plain SELECT DISTINCT BEGIN TRY DECLARE @sdis_build NVARCHAR(MAX) = dbo.pvt_build_query_sql( @emp_id, N'{"Age":{"$gte":18}}', 5, NULL, N'[{"field":"_id","dir":"asc"}]', NULL, 1, N'flat', NULL, NULL, NULL, NULL); IF @sdis_build NOT LIKE N'%DISTINCT%' RAISERROR(N'expected DISTINCT in SQL, got: %.200s', 16, 1, @sdis_build); DECLARE @sdis_cnt BIGINT; DECLARE @sdis_wrap NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM (' + @sdis_build + N') _t'; EXEC sp_executesql @sdis_wrap, N'@c BIGINT OUTPUT', @c = @sdis_cnt OUTPUT; SET @pass += 1; PRINT N'OK [Employee / DISTINCT filter Age>=18 limit 5] rows=' + CAST(ISNULL(@sdis_cnt, 0) AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / DISTINCT filter Age>=18 limit 5] ' + ERROR_MESSAGE(); END CATCH; -- DISTINCT + DISTINCT ON guard: both set must raise 'mutually exclusive'. -- Guard is implemented via CAST(text AS INT) in pvt_build_query_sql (file 20). BEGIN TRY DECLARE @guard_sql NVARCHAR(MAX); BEGIN TRY SET @guard_sql = dbo.pvt_build_query_sql( @emp_id, NULL, NULL, NULL, NULL, NULL, 1, N'flat', NULL, NULL, NULL, N'[{"field":"Department"}]'); -- @distinct=1 AND @distinct_on not null -- If no exception: fail SET @fail += 1; PRINT N'FAIL [Employee / DISTINCT + DISTINCT_ON guard] expected error, got SQL: ' + LEFT(ISNULL(@guard_sql, N'NULL'), 120); END TRY BEGIN CATCH IF ERROR_MESSAGE() LIKE N'%mutually exclusive%' BEGIN SET @pass += 1; PRINT N'OK [Employee / DISTINCT + DISTINCT_ON guard] raised: ' + ERROR_MESSAGE(); END ELSE BEGIN SET @fail += 1; PRINT N'FAIL [Employee / DISTINCT + DISTINCT_ON guard] wrong error: ' + ERROR_MESSAGE(); END END CATCH; END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / DISTINCT + DISTINCT_ON guard outer] ' + ERROR_MESSAGE(); END CATCH; END ELSE PRINT N'SKIP [Employee / DistinctBy block] scheme not found'; -- ===================================================================== -- 4. AGGREGATE (pvt_build_aggregate_sql, file 21) -- ===================================================================== IF @emp_id IS NOT NULL BEGIN -- COUNT(*) BEGIN TRY DECLARE @agg1_build NVARCHAR(MAX) = dbo.pvt_build_aggregate_sql( @emp_id, NULL, N'[{"alias":"total","$count":"*"}]', N'flat'); DECLARE @agg1_wrap NVARCHAR(MAX) = N'SELECT (SELECT * FROM (' + @agg1_build + N') _agg FOR JSON PATH, WITHOUT_ARRAY_WRAPPER, INCLUDE_NULL_VALUES)'; DECLARE @agg1_result NVARCHAR(MAX); EXEC sp_executesql @agg1_wrap, N'@r NVARCHAR(MAX) OUTPUT', @r = @agg1_result OUTPUT; SET @pass += 1; PRINT N'OK [Employee / agg COUNT(*)] json=' + ISNULL(@agg1_result, N'NULL'); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / agg COUNT(*)] ' + ERROR_MESSAGE(); END CATCH; -- SUM + AVG on Salary with filter BEGIN TRY DECLARE @agg2_build NVARCHAR(MAX) = dbo.pvt_build_aggregate_sql( @emp_id, N'{"IsRemote":{"$eq":true}}', N'[{"alias":"cnt","$count":"*"},{"alias":"avg_sal","$avg":{"$field":"Salary"}},{"alias":"sum_sal","$sum":{"$field":"Salary"}}]', N'flat'); DECLARE @agg2_wrap NVARCHAR(MAX) = N'SELECT (SELECT * FROM (' + @agg2_build + N') _agg FOR JSON PATH, WITHOUT_ARRAY_WRAPPER, INCLUDE_NULL_VALUES)'; DECLARE @agg2_result NVARCHAR(MAX); EXEC sp_executesql @agg2_wrap, N'@r NVARCHAR(MAX) OUTPUT', @r = @agg2_result OUTPUT; SET @pass += 1; PRINT N'OK [Employee / agg SUM+AVG+COUNT IsRemote=true] json=' + ISNULL(@agg2_result, N'NULL'); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / agg SUM+AVG+COUNT IsRemote=true] ' + ERROR_MESSAGE(); END CATCH; -- MIN + MAX on Age BEGIN TRY DECLARE @agg3_build NVARCHAR(MAX) = dbo.pvt_build_aggregate_sql( @emp_id, NULL, N'[{"alias":"min_age","$min":{"$field":"Age"}},{"alias":"max_age","$max":{"$field":"Age"}}]', N'flat'); DECLARE @agg3_wrap NVARCHAR(MAX) = N'SELECT (SELECT * FROM (' + @agg3_build + N') _agg FOR JSON PATH, WITHOUT_ARRAY_WRAPPER, INCLUDE_NULL_VALUES)'; DECLARE @agg3_result NVARCHAR(MAX); EXEC sp_executesql @agg3_wrap, N'@r NVARCHAR(MAX) OUTPUT', @r = @agg3_result OUTPUT; SET @pass += 1; PRINT N'OK [Employee / agg MIN+MAX Age] json=' + ISNULL(@agg3_result, N'NULL'); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / agg MIN+MAX Age] ' + ERROR_MESSAGE(); END CATCH; END ELSE PRINT N'SKIP [Employee / aggregate block] scheme not found'; -- ===================================================================== -- 5. GROUP BY (pvt_build_groupby_sql, file 22) -- ===================================================================== IF @emp_id IS NOT NULL BEGIN -- GroupBy Department + COUNT + SUM(Salary) BEGIN TRY DECLARE @grp1_build NVARCHAR(MAX) = dbo.pvt_build_groupby_sql( @emp_id, NULL, N'[{"field":"Department","alias":"Department"}]', N'[{"alias":"Count","$count":"*"},{"alias":"TotalSalary","$sum":{"$field":"Salary"}}]', NULL, NULL, NULL, 0, N'flat'); DECLARE @grp1_wrap NVARCHAR(MAX) = N'SELECT (SELECT * FROM (' + @grp1_build + N') _grp FOR JSON PATH, INCLUDE_NULL_VALUES)'; DECLARE @grp1_result NVARCHAR(MAX); EXEC sp_executesql @grp1_wrap, N'@r NVARCHAR(MAX) OUTPUT', @r = @grp1_result OUTPUT; SET @pass += 1; PRINT N'OK [Employee / groupby Department + COUNT + SUM] json_len=' + CAST(LEN(ISNULL(@grp1_result, N'')) AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / groupby Department + COUNT + SUM] ' + ERROR_MESSAGE(); END CATCH; -- GroupBy IsRemote (bool) + COUNT BEGIN TRY DECLARE @grp2_build NVARCHAR(MAX) = dbo.pvt_build_groupby_sql( @emp_id, NULL, N'[{"field":"IsRemote","alias":"IsRemote"}]', N'[{"alias":"Count","$count":"*"}]', NULL, NULL, NULL, 0, N'flat'); DECLARE @grp2_wrap NVARCHAR(MAX) = N'SELECT (SELECT * FROM (' + @grp2_build + N') _grp FOR JSON PATH, INCLUDE_NULL_VALUES)'; DECLARE @grp2_result NVARCHAR(MAX); EXEC sp_executesql @grp2_wrap, N'@r NVARCHAR(MAX) OUTPUT', @r = @grp2_result OUTPUT; SET @pass += 1; PRINT N'OK [Employee / groupby IsRemote + COUNT] json=' + ISNULL(@grp2_result, N'NULL'); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / groupby IsRemote + COUNT] ' + ERROR_MESSAGE(); END CATCH; -- GroupBy Department with filter (IsRemote=true) BEGIN TRY DECLARE @grp3_build NVARCHAR(MAX) = dbo.pvt_build_groupby_sql( @emp_id, N'{"IsRemote":{"$eq":true}}', N'[{"field":"Department","alias":"Department"}]', N'[{"alias":"Count","$count":"*"},{"alias":"AvgSalary","$avg":{"$field":"Salary"}}]', NULL, NULL, NULL, 0, N'flat'); DECLARE @grp3_wrap NVARCHAR(MAX) = N'SELECT (SELECT * FROM (' + @grp3_build + N') _grp FOR JSON PATH, INCLUDE_NULL_VALUES)'; DECLARE @grp3_result NVARCHAR(MAX); EXEC sp_executesql @grp3_wrap, N'@r NVARCHAR(MAX) OUTPUT', @r = @grp3_result OUTPUT; SET @pass += 1; PRINT N'OK [Employee / groupby Department + filter + AVG] json_len=' + CAST(LEN(ISNULL(@grp3_result, N'')) AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / groupby Department + filter + AVG] ' + ERROR_MESSAGE(); END CATCH; -- GroupBy + ORDER BY + LIMIT BEGIN TRY DECLARE @grp4_build NVARCHAR(MAX) = dbo.pvt_build_groupby_sql( @emp_id, NULL, N'[{"field":"Department","alias":"Department"}]', N'[{"alias":"Count","$count":"*"}]', NULL, N'[{"field":"Department","dir":"asc"}]', 3, 0, N'flat'); DECLARE @grp4_wrap NVARCHAR(MAX) = N'SELECT (SELECT * FROM (' + @grp4_build + N') _grp FOR JSON PATH, INCLUDE_NULL_VALUES)'; DECLARE @grp4_result NVARCHAR(MAX); EXEC sp_executesql @grp4_wrap, N'@r NVARCHAR(MAX) OUTPUT', @r = @grp4_result OUTPUT; SET @pass += 1; PRINT N'OK [Employee / groupby + ORDER + LIMIT 3] json=' + ISNULL(@grp4_result, N'NULL'); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / groupby + ORDER + LIMIT 3] ' + ERROR_MESSAGE(); END CATCH; END ELSE PRINT N'SKIP [Employee / groupby block] scheme not found'; -- ===================================================================== -- 5. ARRAY GROUPBY (file 26) -- ===================================================================== IF OBJECT_ID(N'dbo.pvt_build_array_groupby_sql') IS NOT NULL BEGIN IF @emp_id IS NOT NULL BEGIN BEGIN TRY DECLARE @ag_build NVARCHAR(MAX) = dbo.pvt_build_array_groupby_sql( @emp_id, N'Skills', NULL, N'[{"field":"$element","alias":"Skill"}]', N'[{"field":"*","func":"COUNT","alias":"Count"}]', NULL, N'flat'); IF @ag_build LIKE N'--error:%' THROW 50000, @ag_build, 1; DECLARE @ag_wrap NVARCHAR(MAX) = N'SELECT (SELECT * FROM (' + @ag_build + N') _ag FOR JSON PATH, INCLUDE_NULL_VALUES)'; DECLARE @ag_result NVARCHAR(MAX); EXEC sp_executesql @ag_wrap, N'@r NVARCHAR(MAX) OUTPUT', @r = @ag_result OUTPUT; SET @pass += 1; PRINT N'OK [Employee / array groupby Skills] json_len=' + CAST(LEN(ISNULL(@ag_result, N'')) AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / array groupby Skills] ' + ERROR_MESSAGE(); END CATCH; END; END ELSE BEGIN SET @skip += 1; PRINT N'SKIP [Employee / array groupby Skills] not-impl: pvt_build_array_groupby_sql missing'; END; -- ===================================================================== -- 6. PROJECTION (file 24 — not yet implemented) -- ===================================================================== IF OBJECT_ID(N'dbo.pvt_build_projection_sql') IS NOT NULL BEGIN IF @emp_id IS NOT NULL BEGIN BEGIN TRY DECLARE @pr_build NVARCHAR(MAX) = dbo.pvt_build_projection_sql( @emp_id, NULL, NULL, NULL, N'["FirstName","LastName","Department"]', N'flat'); DECLARE @pr_wrap NVARCHAR(MAX) = N'SELECT COUNT(*) FROM (' + @pr_build + N') _pr'; DECLARE @pr_cnt BIGINT; EXEC sp_executesql @pr_wrap, N'@c BIGINT OUTPUT', @c = @pr_cnt OUTPUT; SET @pass += 1; PRINT N'OK [Employee / projection 3 fields] rows=' + CAST(ISNULL(@pr_cnt, 0) AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [Employee / projection 3 fields] ' + ERROR_MESSAGE(); END CATCH; END; END ELSE BEGIN SET @skip += 1; PRINT N'SKIP [Employee / projection 3 fields] not-impl: pvt_build_projection_sql missing'; END; -- ===================================================================== -- 7. TREE-MODE (source_mode != flat; requires Department scheme) -- ===================================================================== DECLARE @dept_id BIGINT = NULL; SELECT TOP 1 @dept_id = [_id] FROM dbo._schemes WHERE [_name] = N'redb.Tests.Integration.Models.DepartmentProps'; IF @dept_id IS NOT NULL BEGIN DECLARE @dept_root_id BIGINT = NULL; DECLARE @dept_root NVARCHAR(MAX) = NULL; SELECT TOP 1 @dept_root_id = [_id] FROM dbo._objects WHERE [_id_scheme] = @dept_id AND [_id_parent] IS NULL; IF @dept_root_id IS NOT NULL SET @dept_root = N'[' + CAST(@dept_root_id AS NVARCHAR(40)) + N']'; DECLARE @tm_build NVARCHAR(MAX); DECLARE @tm_cnt BIGINT; DECLARE @tm_wrap NVARCHAR(MAX); -- Fallback seed list for tree_children/tree_descendants when no root object -- exists in the DB (Department has no rows). ID -1 never exists so result=0. DECLARE @tree_seed NVARCHAR(MAX) = COALESCE(@dept_root, N'[-1]'); -- tree_descendants SET @tm_build = dbo.pvt_build_query_sql(@dept_id, NULL, NULL, NULL, NULL, 5, NULL, N'tree_descendants', @tree_seed, 0, NULL, NULL); IF @tm_build IS NULL BEGIN SET @skip+=1; PRINT N'SKIP [Department / tree_descendants] not-impl: tree modes'; END ELSE BEGIN TRY SET @tm_wrap=N'SELECT @c=COUNT(*) FROM ('+@tm_build+N') _t'; EXEC sp_executesql @tm_wrap,N'@c BIGINT OUTPUT',@c=@tm_cnt OUTPUT; SET @pass+=1; PRINT N'OK [Department / tree_descendants] rows='+CAST(@tm_cnt AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail+=1; PRINT N'FAIL [Department / tree_descendants] '+ERROR_MESSAGE(); END CATCH; -- tree_children SET @tm_build = dbo.pvt_build_query_sql(@dept_id, NULL, NULL, NULL, NULL, 1, NULL, N'tree_children', @tree_seed, NULL, NULL, NULL); IF @tm_build IS NULL BEGIN SET @skip+=1; PRINT N'SKIP [Department / tree_children] not-impl: tree modes'; END ELSE BEGIN TRY SET @tm_wrap=N'SELECT @c=COUNT(*) FROM ('+@tm_build+N') _t'; EXEC sp_executesql @tm_wrap,N'@c BIGINT OUTPUT',@c=@tm_cnt OUTPUT; SET @pass+=1; PRINT N'OK [Department / tree_children] rows='+CAST(@tm_cnt AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail+=1; PRINT N'FAIL [Department / tree_children] '+ERROR_MESSAGE(); END CATCH; -- tree_roots SET @tm_build = dbo.pvt_build_query_sql(@dept_id, NULL, NULL, NULL, NULL, NULL, NULL, N'tree_roots', NULL, NULL, NULL, NULL); IF @tm_build IS NULL BEGIN SET @skip+=1; PRINT N'SKIP [Department / tree_roots] not-impl: tree modes'; END ELSE BEGIN TRY SET @tm_wrap=N'SELECT @c=COUNT(*) FROM ('+@tm_build+N') _t'; EXEC sp_executesql @tm_wrap,N'@c BIGINT OUTPUT',@c=@tm_cnt OUTPUT; SET @pass+=1; PRINT N'OK [Department / tree_roots] rows='+CAST(@tm_cnt AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail+=1; PRINT N'FAIL [Department / tree_roots] '+ERROR_MESSAGE(); END CATCH; -- tree_leaves SET @tm_build = dbo.pvt_build_query_sql(@dept_id, NULL, NULL, NULL, NULL, NULL, NULL, N'tree_leaves', NULL, NULL, NULL, NULL); IF @tm_build IS NULL BEGIN SET @skip+=1; PRINT N'SKIP [Department / tree_leaves] not-impl: tree modes'; END ELSE BEGIN TRY SET @tm_wrap=N'SELECT @c=COUNT(*) FROM ('+@tm_build+N') _t'; EXEC sp_executesql @tm_wrap,N'@c BIGINT OUTPUT',@c=@tm_cnt OUTPUT; SET @pass+=1; PRINT N'OK [Department / tree_leaves] rows='+CAST(@tm_cnt AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail+=1; PRINT N'FAIL [Department / tree_leaves] '+ERROR_MESSAGE(); END CATCH; -- $isRoot SET @tm_build = dbo.pvt_build_query_sql(@dept_id, N'{"$isRoot":true}', NULL, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF @tm_build IS NULL BEGIN SET @skip+=1; PRINT N'SKIP [Department / $isRoot] pvt returned NULL'; END ELSE BEGIN TRY SET @tm_wrap=N'SELECT @c=COUNT(*) FROM ('+@tm_build+N') _t'; EXEC sp_executesql @tm_wrap,N'@c BIGINT OUTPUT',@c=@tm_cnt OUTPUT; SET @pass+=1; PRINT N'OK [Department / $isRoot] rows='+CAST(@tm_cnt AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail+=1; PRINT N'FAIL [Department / $isRoot] '+ERROR_MESSAGE(); END CATCH; -- $isLeaf SET @tm_build = dbo.pvt_build_query_sql(@dept_id, N'{"$isLeaf":true}', NULL, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF @tm_build IS NULL BEGIN SET @skip+=1; PRINT N'SKIP [Department / $isLeaf] pvt returned NULL'; END ELSE BEGIN TRY SET @tm_wrap=N'SELECT @c=COUNT(*) FROM ('+@tm_build+N') _t'; EXEC sp_executesql @tm_wrap,N'@c BIGINT OUTPUT',@c=@tm_cnt OUTPUT; SET @pass+=1; PRINT N'OK [Department / $isLeaf] rows='+CAST(@tm_cnt AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail+=1; PRINT N'FAIL [Department / $isLeaf] '+ERROR_MESSAGE(); END CATCH; -- $level SET @tm_build = dbo.pvt_build_query_sql(@dept_id, N'{"$level":{"$gte":0}}', NULL, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF @tm_build IS NULL BEGIN SET @skip+=1; PRINT N'SKIP [Department / $level>=0] pvt returned NULL'; END ELSE BEGIN TRY SET @tm_wrap=N'SELECT @c=COUNT(*) FROM ('+@tm_build+N') _t'; EXEC sp_executesql @tm_wrap,N'@c BIGINT OUTPUT',@c=@tm_cnt OUTPUT; SET @pass+=1; PRINT N'OK [Department / $level>=0] rows='+CAST(@tm_cnt AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail+=1; PRINT N'FAIL [Department / $level>=0] '+ERROR_MESSAGE(); END CATCH; -- $childrenOf root IF @dept_root_id IS NOT NULL BEGIN DECLARE @cof_filter NVARCHAR(MAX) = N'{"$childrenOf":' + CAST(@dept_root_id AS NVARCHAR(40)) + N'}'; SET @tm_build = dbo.pvt_build_query_sql(@dept_id, @cof_filter, NULL, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF @tm_build IS NULL BEGIN SET @skip+=1; PRINT N'SKIP [Department / $childrenOf root] pvt returned NULL'; END ELSE BEGIN TRY SET @tm_wrap=N'SELECT @c=COUNT(*) FROM ('+@tm_build+N') _t'; EXEC sp_executesql @tm_wrap,N'@c BIGINT OUTPUT',@c=@tm_cnt OUTPUT; SET @pass+=1; PRINT N'OK [Department / $childrenOf root] rows='+CAST(@tm_cnt AS NVARCHAR(20)); END TRY BEGIN CATCH SET @fail+=1; PRINT N'FAIL [Department / $childrenOf root] '+ERROR_MESSAGE(); END CATCH; END ELSE BEGIN SET @skip+=1; PRINT N'SKIP [Department / $childrenOf root] no root object found'; END; END ELSE BEGIN SET @skip += 8; PRINT N'SKIP [Department / tree block (8 cases)] scheme not found'; END; -- ===================================================================== -- 8. HELPER FUNCTIONS DIRECT TESTS (files 05, 06, 06a, 07) -- ===================================================================== -- These functions return SQL fragments / JSON, not complete queries. -- Each test calls the function directly and validates the output. -- ---- 07: pvt_get_object_base_fields ---------------------------------- DECLARE @bf_obj_id BIGINT = NULL; IF @emp_id IS NOT NULL SELECT TOP 1 @bf_obj_id = [_id] FROM dbo._objects WHERE [_id_scheme] = @emp_id; IF @bf_obj_id IS NOT NULL BEGIN BEGIN TRY DECLARE @bf_json NVARCHAR(MAX) = dbo.pvt_get_object_base_fields(@bf_obj_id); IF @bf_json IS NOT NULL AND ISJSON(@bf_json) = 1 AND JSON_VALUE(@bf_json, N'$.id') IS NOT NULL BEGIN SET @pass += 1; PRINT N'OK [pvt_get_object_base_fields] id=' + JSON_VALUE(@bf_json, N'$.id'); END ELSE BEGIN SET @fail += 1; PRINT N'FAIL [pvt_get_object_base_fields] bad result: ' + ISNULL(@bf_json, N'NULL'); END END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [pvt_get_object_base_fields] ' + ERROR_MESSAGE(); END CATCH; END ELSE BEGIN SET @skip += 1; PRINT N'SKIP [pvt_get_object_base_fields] no Employee objects / scheme not found'; END; -- ---- 05: pvt_build_single_facet_condition ---------------------------- -- Use a base-field filter so the fragment is a simple WHERE predicate. IF @emp_id IS NOT NULL BEGIN BEGIN TRY DECLARE @sfc_cond NVARCHAR(MAX) = dbo.pvt_build_single_facet_condition( N'{"0$:Id":{"$gt":0}}', @emp_id, N'o', NULL); IF @sfc_cond IS NULL BEGIN SET @fail += 1; PRINT N'FAIL [pvt_build_single_facet_condition] returned NULL'; END ELSE BEGIN DECLARE @sfc_wrap NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM dbo._objects o' + N' WHERE o.[_id_scheme] = ' + CAST(@emp_id AS NVARCHAR(20)) + N' AND ' + @sfc_cond; DECLARE @sfc_cnt BIGINT; EXEC sp_executesql @sfc_wrap, N'@c BIGINT OUTPUT', @c = @sfc_cnt OUTPUT; SET @pass += 1; PRINT N'OK [pvt_build_single_facet_condition] rows=' + CAST(@sfc_cnt AS NVARCHAR(20)); END END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [pvt_build_single_facet_condition] ' + ERROR_MESSAGE(); END CATCH; END ELSE BEGIN SET @skip += 1; PRINT N'SKIP [pvt_build_single_facet_condition] Employee scheme not found'; END; -- ---- 06: pvt_build_hierarchical_conditions --------------------------- -- $isRoot:true -> ' AND o.[_id_parent] IS NULL' ; Employee is flat = 210 rows IF @emp_id IS NOT NULL BEGIN BEGIN TRY DECLARE @hc_result NVARCHAR(MAX) = dbo.pvt_build_hierarchical_conditions( N'{"$isRoot":true}', N'o'); IF @hc_result IS NULL OR @hc_result = N'' BEGIN SET @fail += 1; PRINT N'FAIL [pvt_build_hierarchical_conditions] returned empty for $isRoot:true'; END ELSE IF @hc_result NOT LIKE N'%_id_parent%' BEGIN SET @fail += 1; PRINT N'FAIL [pvt_build_hierarchical_conditions] unexpected output: ' + @hc_result; END ELSE BEGIN -- Strip leading ' AND ' (5 chars) to get bare WHERE predicate DECLARE @hc_bare NVARCHAR(MAX) = STUFF(@hc_result, 1, 5, N''); DECLARE @hc_wrap NVARCHAR(MAX) = N'SELECT @c = COUNT(*) FROM dbo._objects o' + N' WHERE o.[_id_scheme] = ' + CAST(@emp_id AS NVARCHAR(20)) + N' AND ' + @hc_bare; DECLARE @hc_cnt BIGINT; EXEC sp_executesql @hc_wrap, N'@c BIGINT OUTPUT', @c = @hc_cnt OUTPUT; SET @pass += 1; PRINT N'OK [pvt_build_hierarchical_conditions $isRoot:true] rows=' + CAST(@hc_cnt AS NVARCHAR(20)); END END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [pvt_build_hierarchical_conditions] ' + ERROR_MESSAGE(); END CATCH; END ELSE BEGIN SET @skip += 1; PRINT N'SKIP [pvt_build_hierarchical_conditions] Employee scheme not found'; END; -- ---- 06a: pvt_build_level_condition ---------------------------------- BEGIN TRY DECLARE @lc_result NVARCHAR(MAX) = dbo.pvt_build_level_condition(0, N'o'); IF @lc_result IS NULL OR @lc_result NOT LIKE N'%pvt_object_depth%' BEGIN SET @fail += 1; PRINT N'FAIL [pvt_build_level_condition] unexpected: ' + ISNULL(@lc_result, N'NULL'); END ELSE BEGIN SET @pass += 1; PRINT N'OK [pvt_build_level_condition(0)] sql=' + @lc_result; END END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [pvt_build_level_condition] ' + ERROR_MESSAGE(); END CATCH; -- ---- 06a: pvt_build_level_condition_with_operators ------------------- BEGIN TRY DECLARE @lco_result NVARCHAR(MAX) = dbo.pvt_build_level_condition_with_operators( N'{"$gte":0}', N'o'); IF @lco_result IS NULL OR @lco_result NOT LIKE N'%pvt_object_depth%' BEGIN SET @fail += 1; PRINT N'FAIL [pvt_build_level_condition_with_operators] unexpected: ' + ISNULL(@lco_result, N'NULL'); END ELSE BEGIN SET @pass += 1; PRINT N'OK [pvt_build_level_condition_with_operators {$gte:0}] sql=' + @lco_result; END END TRY BEGIN CATCH SET @fail += 1; PRINT N'FAIL [pvt_build_level_condition_with_operators] ' + ERROR_MESSAGE(); END CATCH; -- ===================================================================== -- SQL inspection: dump generated queries for shape verification. -- Shape A = no `_pvt_cte` alias; Shape C = subquery alias `_pvt_cte`. -- Shape assertions increment @fail so the final RAISERROR catches them. -- ===================================================================== DECLARE @insp_emp BIGINT; DECLARE @insp_sql NVARCHAR(MAX); DECLARE @insp_fail INT = 0; SELECT @insp_emp = _id FROM dbo._schemes WHERE _name = N'redb.Tests.Integration.Models.EmployeeProps'; IF @insp_emp IS NULL BEGIN PRINT N'inspect: Employee scheme not found, skipping SQL dump'; END ELSE BEGIN PRINT N''; PRINT N'===== INSPECT: SQL shape verification ====='; -- 1. Shape A: pure base _id>0 (expect no CTE) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"_id":{"$gt":0}}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) > 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_A: pure base _id>0] unexpected CTE'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_A: pure base _id>0 (expect no CTE)] -----'; PRINT N'FILTER: {"_id":{"$gt":0}}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_A: pure base _id>0]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 2. Shape A: empty filter (expect no CTE) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, NULL, 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) > 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_A: empty filter] unexpected CTE'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_A: empty filter (expect SELECT _id FROM [_objects] WHERE [_id_scheme]=X)] -----'; PRINT N'FILTER: (none)'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_A: empty filter]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 3. Shape A: $or all-base (no CTE expected) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"$or":[{"_id":{"$lt":10}},{"_id":{"$gt":100}}]}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) > 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_A: $or all-base] unexpected CTE'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_A: $or all-base (full pushdown, no CTE)] -----'; PRINT N'FILTER: {"$or":[{"_id":{"$lt":10}},{"_id":{"$gt":100}}]}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_A: $or all-base]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 4. Shape C: scalar prop eq (expect CTE) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"FirstName":"Ivan"}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) = 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_C: scalar prop eq] expected CTE, not found'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_C: scalar prop eq (FirstName=Ivan)] -----'; PRINT N'FILTER: {"FirstName":"Ivan"}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_C: scalar prop eq]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 5. Shape C: base+props AND (pushdown _id in subquery, residual FirstName) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"_id":{"$gt":0},"FirstName":{"$startsWith":"A"}}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) = 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_C: base+props AND] expected CTE, not found'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_C: base+props AND (pushdown _id, residual FirstName)] -----'; PRINT N'FILTER: {"_id":{"$gt":0},"FirstName":{"$startsWith":"A"}}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_C: base+props AND]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 6. Shape C: NULL check (expect CTE) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"EmployeeCode":{"$null":true}}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) = 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_C: $null:true] expected CTE, not found'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_C: $null:true (requires LEFT JOIN / wide CTE)] -----'; PRINT N'FILTER: {"EmployeeCode":{"$null":true}}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_C: $null:true]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 7. Shape C: NOT NULL props (expect CTE) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"EmployeeCode":{"$notNull":true}}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) = 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_C: $notNull:true] expected CTE, not found'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_C: $notNull:true (INNER JOIN, no NULL rows)] -----'; PRINT N'FILTER: {"EmployeeCode":{"$notNull":true}}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_C: $notNull:true]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 8. Shape C: dict ContainsKey (expect CTE) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"PhoneDirectory.ContainsKey":"work"}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) = 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_C: dict ContainsKey] expected CTE, not found'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_C: dict ContainsKey (PhoneDirectory[work])] -----'; PRINT N'FILTER: {"PhoneDirectory.ContainsKey":"work"}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_C: dict ContainsKey]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 9. Phase 2: top-level $eq with base field -> Shape A (no CTE) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"$eq":[{"$field":"_id"},{"$const":0}]}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) > 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_A: top-level $eq base] unexpected CTE'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_A: top-level $eq base (_id=0, expect pushdown)] -----'; PRINT N'FILTER: {"$eq":[{"$field":"_id"},{"$const":0}]}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_A: top-level $eq base]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 10. Phase 2: top-level $expr with base-only arithmetic -> Shape A BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"$expr":{"$gt":[{"$length":{"$field":"_name"}},{"$const":0}]}}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) > 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_A: $expr base-only] unexpected CTE'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_A: $expr base-only (LEN(_name) > 0, expect pushdown)] -----'; PRINT N'FILTER: {"$expr":{"$gt":[{"$length":{"$field":"_name"}},{"$const":0}]}}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_A: $expr base-only]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; -- 11. Phase 2: top-level $expr referencing props -> Shape C (residual) BEGIN TRY SET @insp_sql = dbo.pvt_build_query_sql(@insp_emp, N'{"$expr":{"$gt":[{"$field":"Age"},{"$const":30}]}}', 5, NULL, NULL, NULL, NULL, N'flat', NULL, NULL, NULL, NULL); IF CHARINDEX(N'_pvt_cte', @insp_sql) = 0 BEGIN PRINT N'SHAPE-FAIL [SHAPE_C: $expr props] expected CTE, not found'; SET @insp_fail += 1; END ELSE BEGIN PRINT N'----- INSPECT [SHAPE_C: $expr props (Age > 30, must stay in residual)] -----'; PRINT N'FILTER: {"$expr":{"$gt":[{"$field":"Age"},{"$const":30}]}}'; PRINT @insp_sql; END END TRY BEGIN CATCH PRINT N'INSPECT FAILED [SHAPE_C: $expr props]: ' + ERROR_MESSAGE(); SET @insp_fail += 1; END CATCH; IF @insp_fail > 0 BEGIN SET @fail += @insp_fail; PRINT N'INSPECT: ' + CAST(@insp_fail AS NVARCHAR(10)) + N' shape assertion(s) failed.'; END ELSE PRINT N'INSPECT: all shape assertions passed.'; PRINT N''; END -- ===================================================================== -- Summary -- ===================================================================== PRINT N'----------------------------------------------------------'; PRINT N'PASS: ' + CAST(@pass AS NVARCHAR(10)) + N' FAIL: ' + CAST(@fail AS NVARCHAR(10)) + N' SKIP: ' + CAST(@skip AS NVARCHAR(10)); PRINT N'----------------------------------------------------------'; IF @fail > 0 RAISERROR(N'pvt smoke FAILED: %d case(s) failed.', 16, 1, @fail); Path: redb/redb.MSSql/sql/v2-pvt/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.MSSql/sql/v2-pvt/README.md ---- # v2-pvt (MSSql) — PVT-based search engine Mirror of `redb.Postgres/sql/v2-pvt/`. Migration plan: see `docs/MsSqlPvtQuery/PLAN.md`. Delta register: `docs/MsSqlPvtQuery/MSSQL-FREE-GAPS.md`. ## File order Files are picked up alphabetically by numeric prefix and concatenated into `redb_init.sql` by `redb.MSSql.csproj` (`` ItemGroup). For standalone deploy use `_bundle.ps1` to produce `pvt_bundle.sql`. | Prefix | Purpose | |---|---| | `00_module_init.sql` | Precondition checks, `DROP` all `dbo.pvt_*`, `dbo.pvt_module_version()`. **MUST be first.** | | `01..07` | Forked helpers from `sql/deprecated/redb_facets_search.sql` / `redb_lazy_loading_search.sql` (TODO). | | `10..17` | PVT-specific helpers: field-path resolver, CTE builder, WHERE compiler, expression engine (TODO). | | `20_pvt_build_query_sql.sql` | Main orchestrator: builds the inner `_id`-list SQL for `Where + ToList / Count / Exists` (TODO). | | `21..26` | Projection / aggregate / groupby / array-groupby / window builders (TODO). | | `99_smoke_*.sql` | Smoke tests. **Excluded from the embedded bundle**; deploy manually. | ## Version policy `dbo.pvt_module_version()` returns semver. Major bumps require redeploy of the C# client (signature/result-shape break). Minor bumps are additive. The C# init-time check (`Query_PvtModuleVersionFunction()` in `MsSqlDialect.cs`) verifies the deployed module on `InitializeAsync()`. ## SQL-injection safety All `pvt_*` builders construct SQL via `QUOTENAME()` for identifiers and `'''' + REPLACE(@v, '''', '''''') + ''''` for literals. **No user value is ever concatenated raw.** See PLAN.md §7. ## Notes - Reference for T-SQL form/syntax: `redb.MSSql.Pro/Query/PivotSqlGenerator.cs` and `ProSqlBuilder.cs` (see `MSSQL-FREE-GAPS.md` §2.2). - Reference for algorithm: `redb.Postgres/sql/v2-pvt/*.sql` (PG v0.5.0). Path: redb/redb.MSSql/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.MSSql/sql/v2-pvt/_bundle.ps1 ---- # ===================================================================== # _bundle.ps1 (MSSql) # --------------------------------------------------------------------- # Concatenates all *.sql from this v2-pvt folder (by numeric prefix: # 00, 01, ..., 20, 99) into a single file pvt_bundle.sql. Convenient for # standalone deploy without rebuilding the C# package: # # sqlcmd -S , -U -P -d -b -i pvt_bundle.sql # # Ignores: # - subfolders (deprecated/); # - this script and any *.ps1; # - 99_smoke_tests.sql / 99_smoke_auto.sql (use -IncludeSmoke to add); # - pvt_bundle.sql itself (overwritten if exists). # # Usage: # ./_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 (MSSql) -- AUTO-GENERATED, DO NOT EDIT BY HAND -- --------------------------------------------------------------------- -- Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz') -- Generator: redb.MSSql/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 # without smoke -- pwsh ./_bundle.ps1 -IncludeSmoke # with smoke tests -- -- To deploy: -- sqlcmd -S , -U -P -d -b -i $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) }