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