Bundle: redb / redb.Export (redb.Export.txt), 35 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.Export/Flat/Dialects/IFlatDialect.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.Export/Flat/Dialects/IFlatDialect.cs
----
using System.Data;
namespace redb.Export.Flat.Dialects;
///
/// What differs between the three providers when flat tables are created and filled: identifier
/// quoting, column types, the value form the provider's bulk insert accepts, and how a consistent
/// read of the source is obtained.
///
internal interface IFlatDialect
{
/// Quotes an identifier, doubling the closing quote character inside it.
string Quote(string identifier);
/// Column type for .
string ColumnType(FlatStorageType type);
///
/// True when foreign keys can only be declared inside CREATE TABLE (SQLite). Otherwise
/// they are added after the data is loaded, so that load order does not matter.
///
bool InlineForeignKeys { get; }
/// Name of a column as the provider's BulkInsertAsync expects it in the .
string BulkColumnName(string column);
/// Converts a non-null CLR value of to the form the provider's bulk insert writes correctly.
object ToDbValue(object value, FlatStorageType type);
/// Isolation level under which a source of this provider is read as one snapshot.
IsolationLevel SnapshotIsolation { get; }
///
/// Statement that creates the key sequence, starting at 1; null when the provider has no sequences.
///
string? CreateSequence(string sequence);
/// Statement that makes the sequence hand out next; null without sequences.
string? RestartSequence(string sequence, long next);
///
/// DEFAULT clause of a key column that takes its value from the sequence when a writer leaves
/// it out; null when the provider generates such keys by itself.
///
string? KeyDefault(string sequence);
///
/// A statement whose only effect is that the provider's command-line client prints
/// : the last line of a script, so that a run that got that far says so.
///
string Report(string message);
///
/// False when the provider refuses a cascading foreign key from a table to itself (SQL Server: "may
/// cause cycles or multiple cascade paths"). Such a key is then declared without the cascade.
///
bool AllowsSelfCascade { get; }
}
/// Resolves the dialect of a provider by its IDataProvider.Name .
internal static class FlatDialects
{
public static IFlatDialect For(string providerName) => providerName switch
{
"postgres" => new PostgresFlatDialect(),
"mssql" => new MssqlFlatDialect(),
"sqlite" => new SqliteFlatDialect(),
_ => throw new NotSupportedException($"Flat export is not available for provider '{providerName}'.")
};
}
Path: redb/redb.Export/Flat/Dialects/MssqlFlatDialect.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.Export/Flat/Dialects/MssqlFlatDialect.cs
----
using System.Data;
namespace redb.Export.Flat.Dialects;
/// SQL Server: rows go through SqlBulkCopy .
internal sealed class MssqlFlatDialect : IFlatDialect
{
public string Quote(string identifier) => "[" + identifier.Replace("]", "]]") + "]";
public string ColumnType(FlatStorageType type) => type switch
{
FlatStorageType.Int64 => "bigint",
FlatStorageType.Int32 => "int",
FlatStorageType.Int16 => "smallint",
FlatStorageType.Byte => "tinyint",
FlatStorageType.Double => "float",
FlatStorageType.Single => "real",
FlatStorageType.Decimal => "decimal(38, 18)",
FlatStorageType.Boolean => "bit",
FlatStorageType.Text => "nvarchar(max)",
// Same bound redb keeps for _values._array_index: an index key cannot hold nvarchar(max).
FlatStorageType.KeyText => "nvarchar(430)",
FlatStorageType.Char => "nchar(1)",
FlatStorageType.Guid => "uniqueidentifier",
FlatStorageType.DateTime => "datetime2",
FlatStorageType.DateTimeOffset => "datetimeoffset",
FlatStorageType.Date => "date",
FlatStorageType.Time => "time",
// SQL Server has no interval type; time holds a span below 24 hours.
FlatStorageType.Duration => "time",
FlatStorageType.Bytes => "varbinary(max)",
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
public bool InlineForeignKeys => false;
// SqlBulkCopy column mappings take the plain column name.
public string BulkColumnName(string column) => column;
public object ToDbValue(object value, FlatStorageType type) => value switch
{
DateOnly date => date.ToDateTime(TimeOnly.MinValue),
TimeOnly time => time.ToTimeSpan(),
char character => character.ToString(),
_ => value
};
public IsolationLevel SnapshotIsolation => IsolationLevel.Snapshot;
public string? CreateSequence(string sequence) => $"CREATE SEQUENCE {Quote(sequence)} AS bigint START WITH 1";
public string? RestartSequence(string sequence, long next) =>
$"ALTER SEQUENCE {Quote(sequence)} RESTART WITH {next.ToString(System.Globalization.CultureInfo.InvariantCulture)}";
public string? KeyDefault(string sequence) => $"DEFAULT (NEXT VALUE FOR {Quote(sequence)})";
public string Report(string message) => $"PRINT N'{message.Replace("'", "''")}'";
// redb's own SQL Server schema declares FK__objects__objects with NO ACTION for the same reason.
public bool AllowsSelfCascade => false;
}
Path: redb/redb.Export/Flat/Dialects/PostgresFlatDialect.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.Export/Flat/Dialects/PostgresFlatDialect.cs
----
using System.Data;
using System.Globalization;
namespace redb.Export.Flat.Dialects;
/// PostgreSQL: rows go through COPY ... FROM STDIN in TEXT format.
internal sealed class PostgresFlatDialect : IFlatDialect
{
public string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\"";
public string ColumnType(FlatStorageType type) => type switch
{
FlatStorageType.Int64 => "bigint",
FlatStorageType.Int32 => "integer",
FlatStorageType.Int16 => "smallint",
FlatStorageType.Byte => "smallint",
FlatStorageType.Double => "double precision",
FlatStorageType.Single => "real",
FlatStorageType.Decimal => "numeric(38, 18)",
FlatStorageType.Boolean => "boolean",
FlatStorageType.Text => "text",
FlatStorageType.KeyText => "text",
FlatStorageType.Char => "character(1)",
FlatStorageType.Guid => "uuid",
FlatStorageType.DateTime => "timestamp with time zone",
FlatStorageType.DateTimeOffset => "timestamp with time zone",
FlatStorageType.Date => "date",
FlatStorageType.Time => "time",
FlatStorageType.Duration => "interval",
FlatStorageType.Bytes => "bytea",
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
public bool InlineForeignKeys => false;
// COPY takes the column list as SQL text.
public string BulkColumnName(string column) => Quote(column);
public object ToDbValue(object value, FlatStorageType type) => value switch
{
// A zone-less timestamp would be read in the session time zone; send the UTC offset with it.
DateTime dateTime => new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc)),
DateOnly date => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
TimeOnly time => time.ToString("HH:mm:ss.ffffff", CultureInfo.InvariantCulture),
// interval input does not read the .NET "d.hh:mm:ss" form; microseconds are exact and unambiguous.
TimeSpan span => (span.Ticks / 10).ToString(CultureInfo.InvariantCulture) + " microseconds",
char character => character.ToString(),
long or int or short or byte => Convert.ToInt64(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture),
_ => value
};
public IsolationLevel SnapshotIsolation => IsolationLevel.RepeatableRead;
public string? CreateSequence(string sequence) => $"CREATE SEQUENCE {Quote(sequence)} AS bigint START WITH 1";
public string? RestartSequence(string sequence, long next) =>
$"ALTER SEQUENCE {Quote(sequence)} RESTART WITH {next.ToString(CultureInfo.InvariantCulture)}";
// nextval takes the name as text; the quotes inside keep it exact.
public string? KeyDefault(string sequence) => $"DEFAULT nextval('{Quote(sequence).Replace("'", "''")}')";
public bool AllowsSelfCascade => true;
// psql prints a NOTICE as "NOTICE: ".
public string Report(string message) => $"DO $$ BEGIN RAISE NOTICE '{message.Replace("'", "''")}'; END $$";
}
Path: redb/redb.Export/Flat/Dialects/SqliteFlatDialect.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.Export/Flat/Dialects/SqliteFlatDialect.cs
----
using System.Data;
using System.Globalization;
namespace redb.Export.Flat.Dialects;
/// SQLite: rows go through a prepared parameterised INSERT .
internal sealed class SqliteFlatDialect : IFlatDialect
{
public string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\"";
public string ColumnType(FlatStorageType type) => type switch
{
FlatStorageType.Int64 or FlatStorageType.Int32 or FlatStorageType.Int16 or FlatStorageType.Byte => "INTEGER",
FlatStorageType.Boolean => "INTEGER",
FlatStorageType.Double or FlatStorageType.Single => "REAL",
FlatStorageType.Bytes => "BLOB",
// Decimals, GUIDs and every date and time form are kept as text: exact and readable.
_ => "TEXT"
};
// SQLite cannot add a foreign key to an existing table.
public bool InlineForeignKeys => true;
public string BulkColumnName(string column) => Quote(column);
public object ToDbValue(object value, FlatStorageType type) => value switch
{
bool flag => flag ? 1L : 0L,
decimal number => number.ToString(CultureInfo.InvariantCulture),
Guid guid => guid.ToString("D").ToUpperInvariant(),
DateTime dateTime => dateTime.ToString("yyyy-MM-dd HH:mm:ss.FFFFFFF", CultureInfo.InvariantCulture),
DateTimeOffset dateTimeOffset => dateTimeOffset.ToString("yyyy-MM-dd HH:mm:ss.FFFFFFFzzz", CultureInfo.InvariantCulture),
DateOnly date => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
TimeOnly time => time.ToString("HH:mm:ss.fffffff", CultureInfo.InvariantCulture),
TimeSpan span => span.ToString("c", CultureInfo.InvariantCulture),
char character => character.ToString(),
_ => value
};
// The only level SQLite has; a read transaction sees one snapshot of the file.
public IsolationLevel SnapshotIsolation => IsolationLevel.Serializable;
// SQLite has no sequences. An INTEGER PRIMARY KEY is the rowid, and a row inserted without it gets
// the next free one of its own table: keys are generated, though per table, not database-wide.
public string? CreateSequence(string sequence) => null;
public string? RestartSequence(string sequence, long next) => null;
public string? KeyDefault(string sequence) => null;
public bool AllowsSelfCascade => true;
// The sqlite3 shell prints the row.
public string Report(string message) => $"SELECT '{message.Replace("'", "''")}' AS result";
}
Path: redb/redb.Export/Flat/FlatDdlGenerator.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.Export/Flat/FlatDdlGenerator.cs
----
using System.Text;
using redb.Export.Flat.Dialects;
using redb.Export.Flat.Model;
namespace redb.Export.Flat;
///
/// Turns a into DDL for one provider.
///
/// Tables are created with plain CREATE TABLE - never IF NOT EXISTS - so a name that
/// is already taken fails loudly instead of two classes sharing one table. Where the provider
/// allows it, foreign keys are separate statements meant to run after the data is loaded.
///
///
public sealed class FlatDdlGenerator
{
private readonly IFlatDialect _dialect;
/// Creates a generator for a provider.
/// Provider name as reported by IDataProvider.Name : postgres , mssql or sqlite .
public FlatDdlGenerator(string providerName)
: this(FlatDialects.For(providerName))
{
}
internal FlatDdlGenerator(IFlatDialect dialect)
{
_dialect = dialect;
}
/// The CREATE TABLE statement of .
public string CreateTable(FlatTable table)
{
var lines = new List();
// Every key a writer may leave out comes from the one sequence. A scheme table is the exception:
// its key is the id of the header row in `objects`, set by whoever writes that row.
var keyDefault = table.Kind == FlatTableKind.Scheme ? null : _dialect.KeyDefault(FlatNaming.IdentitySequence);
foreach (var column in table.Columns)
{
var type = _dialect.ColumnType(FlatStorageTypes.Of(column));
var line = $"{_dialect.Quote(column.Name)} {type} {(column.IsNullable ? "NULL" : "NOT NULL")}";
if (keyDefault != null && column.Role == FlatColumnRole.PrimaryKey)
line += " " + keyDefault;
lines.Add(line);
}
lines.Add($"CONSTRAINT {_dialect.Quote(table.PrimaryKeyName)} PRIMARY KEY ({_dialect.Quote(table.PrimaryKey)})");
foreach (var unique in table.UniqueConstraints)
lines.Add($"CONSTRAINT {_dialect.Quote(unique.Name)} UNIQUE ({string.Join(", ", unique.Columns.Select(_dialect.Quote))})");
if (_dialect.InlineForeignKeys)
{
foreach (var foreignKey in table.ForeignKeys)
lines.Add($"CONSTRAINT {_dialect.Quote(foreignKey.Name)} {ForeignKeyClause(table, foreignKey)}");
}
var sql = new StringBuilder();
sql.Append("CREATE TABLE ").Append(_dialect.Quote(table.Name)).AppendLine(" (");
sql.AppendLine(" " + string.Join("," + Environment.NewLine + " ", lines));
sql.Append(')');
return sql.ToString();
}
///
/// The statements that create the plain indexes of (the foreign key indexes).
/// Meant to run after the data is loaded, on every provider.
///
public IReadOnlyList CreateIndexes(FlatTable table) => table.Indexes
.Select(index =>
$"CREATE INDEX {_dialect.Quote(index.Name)} ON {_dialect.Quote(table.Name)} ({string.Join(", ", index.Columns.Select(_dialect.Quote))})")
.ToList();
///
/// The statements that add the foreign keys of . Empty for a provider
/// that declares them inside CREATE TABLE .
///
public IReadOnlyList AddForeignKeys(FlatTable table)
{
if (_dialect.InlineForeignKeys)
return [];
return table.ForeignKeys
.Select(foreignKey =>
$"ALTER TABLE {_dialect.Quote(table.Name)} ADD CONSTRAINT {_dialect.Quote(foreignKey.Name)} {ForeignKeyClause(table, foreignKey)}")
.ToList();
}
///
/// The statement that creates the key sequence ( ), starting at 1.
/// Null for a provider without sequences, which generates such keys per table by itself.
///
public string? CreateSequence() => _dialect.CreateSequence(FlatNaming.IdentitySequence);
///
/// The statement that makes the key sequence hand out next: run after the
/// data is copied, with a value above every copied key. Null for a provider without sequences.
///
public string? RestartSequence(long next) => _dialect.RestartSequence(FlatNaming.IdentitySequence, next);
///
/// The whole model as one script: the key sequence, every table, then every foreign key. Run on an
/// empty database it gives the flat schema without data, with keys generated by the database. The
/// last statement makes the client print what was created, so a run that reached the end says so.
///
public string Script(FlatDatabaseModel model)
{
var sequence = CreateSequence();
var foreignKeys = model.Tables.Sum(table => table.ForeignKeys.Count);
var indexes = model.Tables.Sum(table => table.Indexes.Count);
var summary = $"redb flat schema created: {model.Tables.Count} tables, {foreignKeys} foreign keys, {indexes} indexes, " +
(sequence == null ? "keys generated per table" : $"key sequence {FlatNaming.IdentitySequence}");
var statements = (sequence == null ? Array.Empty() : new[] { sequence })
.Concat(model.Tables.Select(table => CreateTable(table)))
.Concat(model.Tables.SelectMany(table => AddForeignKeys(table)))
.Concat(model.Tables.SelectMany(table => CreateIndexes(table)))
.Append(_dialect.Report(summary));
var header = $"-- redb flat schema: {model.Tables.Count} tables, {foreignKeys} foreign keys, {indexes} indexes. Run on an empty database.";
return header + Environment.NewLine + Environment.NewLine +
string.Join(Environment.NewLine + Environment.NewLine, statements.Select(s => s + ";"));
}
private string ForeignKeyClause(FlatTable table, FlatForeignKey foreignKey)
{
var rule = foreignKey.OnDelete;
// A provider that refuses a cascade from a table to itself gets the key without it; deleting a
// parent object there means deleting its children first, as with redb on that provider.
if (rule == FlatDeleteRule.Cascade && foreignKey.TargetTable == table.Name && !_dialect.AllowsSelfCascade)
rule = FlatDeleteRule.NoAction;
var onDelete = rule switch
{
FlatDeleteRule.Cascade => " ON DELETE CASCADE",
FlatDeleteRule.SetNull => " ON DELETE SET NULL",
_ => ""
};
return $"FOREIGN KEY ({_dialect.Quote(foreignKey.Column)}) " +
$"REFERENCES {_dialect.Quote(foreignKey.TargetTable)} ({_dialect.Quote(foreignKey.TargetColumn)}){onDelete}";
}
}
Path: redb/redb.Export/Flat/FlatExportService.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.Export/Flat/FlatExportService.cs
----
using System.Reflection;
using redb.Core.Attributes;
using redb.Core.Models.Entities;
using redb.Export.Flat.Dialects;
using redb.Export.Flat.Model;
using redb.Export.Providers;
namespace redb.Export.Flat;
///
/// Unfolds redb objects into ordinary relational tables and copies the data into them.
///
/// Source and target are two independent connections, of the same provider or of different ones:
/// the source is read with its own dialect inside one snapshot transaction, the target receives DDL
/// and bulk inserts in its own dialect inside one transaction. Either everything lands in the target
/// or nothing does. The transfer is one-way and expects a target without the flat tables.
///
///
public sealed class FlatExportService
{
// Objects of a scheme read by one statement.
private const int ObjectsPerRead = 1000;
// Largest key copied so far, in any table.
private long _maxKey;
private readonly IDataProvider _source;
private readonly IDataProvider _target;
private readonly bool _verbose;
private readonly int _batchSize;
///
/// Initializes a new instance of .
///
/// An opened provider over the redb database to read.
/// An opened provider over the database that receives the flat tables.
/// When true , progress is written to .
/// Rows buffered per table before a bulk insert.
public FlatExportService(IDataProvider source, IDataProvider target, bool verbose, int batchSize)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(batchSize);
_source = source;
_target = target;
_verbose = verbose;
_batchSize = batchSize;
}
///
/// Name of the scheme a Props type is stored under: the explicit name of
/// when set, otherwise the full type name. Same rule as scheme synchronisation.
///
public static string SchemeNameOf(Type propsType) =>
propsType.GetCustomAttribute()?.GetSchemeName(propsType)
?? propsType.FullName
?? propsType.Name;
///
/// Exports the given Props types.
///
///
/// Props types to unfold. A type referenced through RedbObject<T> must be in the set:
/// the reference becomes a foreign key to its table.
///
/// Cancellation token.
public async Task ExportAsync(IReadOnlyCollection propsTypes, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(propsTypes);
var sourceDialect = FlatDialects.For(_source.Name);
var targetDialect = FlatDialects.For(_target.Name);
await using var snapshot = await _source.Connection.BeginTransactionAsync(sourceDialect.SnapshotIsolation, ct);
var reader = new FlatSourceReader(_source, snapshot);
// Bind every type to its scheme and structure tree before anything is written.
var schemeIds = new Dictionary();
var trees = new Dictionary>();
foreach (var propsType in propsTypes)
{
var schemeName = SchemeNameOf(propsType);
var schemeId = await reader.FindSchemeIdAsync(schemeName, ct)
?? throw new InvalidOperationException(
$"Scheme '{schemeName}' of type '{propsType.FullName}' is not in the source database.");
schemeIds[propsType] = schemeId;
trees[propsType] = StructureTreeBuilder.BuildFromFlat(await reader.ReadStructuresAsync(schemeId, ct));
}
var model = new FlatModelBuilder().Build(propsTypes, trees);
Validate(model);
var ddl = new FlatDdlGenerator(targetDialect);
var buffers = model.Tables.ToDictionary(t => t.Name, t => new FlatTableBuffer(t, targetDialect));
await _target.BeginImportAsync(ct);
try
{
var createSequence = ddl.CreateSequence();
if (createSequence != null)
await _target.ExecuteAsync(createSequence, ct);
Log($"Creating {model.Tables.Count} tables...");
foreach (var table in model.Tables)
await _target.ExecuteAsync(ddl.CreateTable(table), ct);
await CopyServiceTableAsync(reader, "_objects", Single(model, FlatTableKind.Objects), buffers, targetDialect, ct);
await CopyServiceTableAsync(reader, "_lists", Single(model, FlatTableKind.Lists), buffers, targetDialect, ct);
await CopyServiceTableAsync(reader, "_list_items", Single(model, FlatTableKind.ListItems), buffers, targetDialect, ct);
foreach (var propsType in propsTypes)
{
var schemeTables = model.Tables.Where(t => t.PropsType == propsType).ToList();
await CopySchemeAsync(reader, schemeIds[propsType], schemeTables, buffers, targetDialect, ct);
}
// New rows written later, by EF or by hand, take their keys from the sequence: it has to
// start above every key copied from redb.
var restartSequence = ddl.RestartSequence(_maxKey + 1);
if (restartSequence != null)
await _target.ExecuteAsync(restartSequence, ct);
Log("Adding foreign keys...");
foreach (var statement in model.Tables.SelectMany(table => ddl.AddForeignKeys(table)))
await _target.ExecuteAsync(statement, ct);
Log("Creating foreign key indexes...");
foreach (var statement in model.Tables.SelectMany(table => ddl.CreateIndexes(table)))
await _target.ExecuteAsync(statement, ct);
await _target.CommitImportAsync(ct);
}
catch
{
await _target.AbortImportAsync();
throw;
}
Log("Flat export completed.");
}
private async Task CopyServiceTableAsync(
FlatSourceReader reader,
string sourceTable,
FlatTable table,
IReadOnlyDictionary buffers,
IFlatDialect dialect,
CancellationToken ct)
{
Log($"Copying {sourceTable} -> {table.Name}...");
var buffer = buffers[table.Name];
long count = 0;
await foreach (var values in reader.ReadServiceRowsAsync(sourceTable, table, ct))
{
// The first column of a service table is its key.
if (values[0] is long key && key > _maxKey)
_maxKey = key;
var row = buffer.Data.NewRow();
for (var i = 0; i < values.Length; i++)
row[i] = values[i] == null ? DBNull.Value : dialect.ToDbValue(values[i]!, buffer.StorageTypes[i]);
buffer.Data.Rows.Add(row);
count++;
if (buffer.Data.Rows.Count >= _batchSize)
await FlushAsync(buffer, dialect, ct);
}
await FlushAsync(buffer, dialect, ct);
LogCount(table.Name, count);
}
private async Task CopySchemeAsync(
FlatSourceReader reader,
long schemeId,
IReadOnlyList schemeTables,
IReadOnlyDictionary buffers,
IFlatDialect dialect,
CancellationToken ct)
{
var schemeTable = schemeTables.Single(t => t.Kind == FlatTableKind.Scheme);
Log($"Unfolding {schemeTable.FullName} ({schemeTables.Count} tables)...");
var assembler = new FlatRowAssembler(schemeTables, buffers, dialect);
var objectIds = await reader.ReadSchemeObjectIdsAsync(schemeId, ct);
var started = DateTime.UtcNow;
long count = 0;
// The scheme is read in slices of ObjectsPerRead objects, so the first rows arrive at once
// and progress is visible from the start.
for (var offset = 0; offset < objectIds.Count; offset += ObjectsPerRead)
{
var fromId = objectIds[offset];
var toId = objectIds[Math.Min(offset + ObjectsPerRead, objectIds.Count) - 1];
await foreach (var (objectId, values) in reader.ReadSchemeObjectsAsync(schemeId, fromId, toId, ct))
{
assembler.Append(schemeTable, objectId, values);
count++;
// Owners are flushed before the tables they own: the list is in creation order.
if (schemeTables.Any(t => buffers[t.Name].Data.Rows.Count >= _batchSize))
{
foreach (var table in schemeTables)
await FlushAsync(buffers[table.Name], dialect, ct);
}
}
if (_verbose)
Console.Write($"\r {schemeTable.FullName}: {count:N0} / {objectIds.Count:N0}, {DateTime.UtcNow - started:hh\\:mm\\:ss}");
}
foreach (var table in schemeTables)
await FlushAsync(buffers[table.Name], dialect, ct);
_maxKey = Math.Max(_maxKey, assembler.MaxRowId);
LogCount(schemeTable.FullName, count);
}
private async Task FlushAsync(FlatTableBuffer buffer, IFlatDialect dialect, CancellationToken ct)
{
if (buffer.Data.Rows.Count == 0)
return;
await _target.BulkInsertAsync(dialect.Quote(buffer.Table.Name), buffer.Data, ct);
buffer.Data.Clear();
}
///
/// Refuses a model that cannot be filled: a field with no structure in the source (the scheme
/// was not synchronised with this version of the class) or a reference to a Props type that is
/// not exported.
///
private static void Validate(FlatDatabaseModel model)
{
var tableNames = model.Tables.Select(t => t.Name).ToHashSet();
foreach (var table in model.Tables)
{
foreach (var foreignKey in table.ForeignKeys)
{
if (!tableNames.Contains(foreignKey.TargetTable))
throw new InvalidOperationException(
$"Column '{foreignKey.Column}' of table '{table.FullName}' references " +
$"'{foreignKey.TargetPropsType?.FullName ?? foreignKey.TargetTable}', which is not in the " +
"export set. Add that Props type to the exported types.");
}
if (table.PropsType == null)
continue;
if (table.Kind != FlatTableKind.Scheme && table.StructureId == null)
throw MissingStructure(table, table.PropertyPath!);
foreach (var column in table.Columns)
{
if (column.ValueSource != FlatValueSource.None && column.StructureId == null)
throw MissingStructure(table, table.PropertyPath == null ? column.Name : $"{table.PropertyPath}.{column.Name}");
}
}
}
private static InvalidOperationException MissingStructure(FlatTable table, string path) => new(
$"Property '{table.PropsType!.Name}.{path}' has no structure in the source database. " +
"Synchronise the scheme with this version of the class before exporting.");
private static FlatTable Single(FlatDatabaseModel model, FlatTableKind kind) =>
model.Tables.Single(t => t.Kind == kind);
private void Log(string message)
{
if (_verbose)
Console.WriteLine(message);
}
private void LogCount(string entity, long count)
{
if (_verbose)
// Padded so that it wipes the longer progress line it overwrites.
Console.WriteLine($"\r {entity}: {count:N0}".PadRight(79));
}
}
Path: redb/redb.Export/Flat/FlatModelBuilder.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.Export/Flat/FlatModelBuilder.cs
----
using redb.Core.Models.Entities;
using redb.Core.Utils;
using redb.Export.Flat.Model;
namespace redb.Export.Flat;
///
/// Builds the flat model of a set of Props types: the shared header table, the two list tables and,
/// for every Props type, its scheme table with the nested-class and collection tables below it.
///
/// The walk follows scheme synchronisation property by property, so the tables line up with the
/// structure tree: pass the tree of each scheme and every table and column is bound to its
/// _structures._id . Without the trees the model is complete except for those ids - enough to
/// review the shape of the tables.
///
///
public sealed class FlatModelBuilder
{
///
/// Builds the model.
///
/// Props types to flatten, each becoming one scheme table.
///
/// Root nodes of the structure tree of each Props type (see
/// ). Optional; a type without a tree is built
/// with no structure ids.
///
public FlatDatabaseModel Build(
IEnumerable propsTypes,
IReadOnlyDictionary>? structureTrees = null)
{
ArgumentNullException.ThrowIfNull(propsTypes);
var tables = new List
{
BuildObjectsTable(),
BuildListsTable(),
BuildListItemsTable()
};
foreach (var propsType in propsTypes)
{
IReadOnlyList? roots = null;
if (structureTrees != null)
structureTrees.TryGetValue(propsType, out roots);
BuildSchemeTable(propsType, roots, tables);
}
foreach (var table in tables)
AddForeignKeyIndexes(table);
return new FlatDatabaseModel(tables);
}
// ---------------------------------------------------------------------------------------
// Service tables: column for column the redb tables, minus the hashes.
// ---------------------------------------------------------------------------------------
private static FlatTable BuildObjectsTable()
{
var table = new FlatTable(FlatNaming.ObjectsTable) { Kind = FlatTableKind.Objects };
table.Add(Header("_id", typeof(long), nullable: false, FlatColumnRole.PrimaryKey));
table.Add(Header("_id_parent", typeof(long), nullable: true));
table.Add(Header("_id_scheme", typeof(long), nullable: false));
table.Add(Header("_id_owner", typeof(long), nullable: false));
table.Add(Header("_id_who_change", typeof(long), nullable: false));
table.Add(Header("_date_create", typeof(DateTimeOffset), nullable: false));
table.Add(Header("_date_modify", typeof(DateTimeOffset), nullable: false));
table.Add(Header("_date_begin", typeof(DateTimeOffset), nullable: true));
table.Add(Header("_date_complete", typeof(DateTimeOffset), nullable: true));
table.Add(Header("_key", typeof(long), nullable: true));
table.Add(Header("_name", typeof(string), nullable: true));
table.Add(Header("_note", typeof(string), nullable: true));
table.Add(Header("_value_long", typeof(long), nullable: true));
table.Add(Header("_value_string", typeof(string), nullable: true));
table.Add(Header("_value_guid", typeof(Guid), nullable: true));
table.Add(Header("_value_bool", typeof(bool), nullable: true));
table.Add(Header("_value_double", typeof(double), nullable: true));
table.Add(Header("_value_numeric", typeof(decimal), nullable: true));
table.Add(Header("_value_datetime", typeof(DateTimeOffset), nullable: true));
table.Add(Header("_value_bytes", typeof(byte[]), nullable: true));
// The parent of an object may be of any scheme; the header table holds them all.
// redb deletes the children of an object with it (FK__objects__objects).
table.Add(ForeignKey(table, "_id_parent", FlatNaming.ObjectsTable, FlatDeleteRule.Cascade));
return table;
}
private static FlatTable BuildListsTable()
{
var table = new FlatTable(FlatNaming.ListsTable) { Kind = FlatTableKind.Lists };
table.Add(Header("_id", typeof(long), nullable: false, FlatColumnRole.PrimaryKey));
table.Add(Header("_name", typeof(string), nullable: false));
table.Add(Header("_alias", typeof(string), nullable: true));
return table;
}
private static FlatTable BuildListItemsTable()
{
var table = new FlatTable(FlatNaming.ListItemsTable) { Kind = FlatTableKind.ListItems };
table.Add(Header("_id", typeof(long), nullable: false, FlatColumnRole.PrimaryKey));
table.Add(Header("_id_list", typeof(long), nullable: false));
table.Add(Header("_value", typeof(string), nullable: true));
table.Add(Header("_alias", typeof(string), nullable: true));
table.Add(Header("_id_object", typeof(long), nullable: true));
table.Add(ForeignKey(table, "_id_list", FlatNaming.ListsTable, FlatDeleteRule.Cascade));
table.Add(ForeignKey(table, "_id_object", FlatNaming.ObjectsTable, FlatDeleteRule.SetNull));
return table;
}
// ---------------------------------------------------------------------------------------
// Scheme tables
// ---------------------------------------------------------------------------------------
private static void BuildSchemeTable(Type propsType, IReadOnlyList? roots, List tables)
{
var table = new FlatTable(propsType.Name)
{
Kind = FlatTableKind.Scheme,
PropsType = propsType,
ClassType = propsType
};
// The key of a scheme row is the object id, and the header of that object lives in `objects`.
table.Add(Service(FlatNaming.IdColumn, FlatColumnRole.PrimaryKey, typeof(long)));
// The Props of an object go with its header, as its _values rows go with it in redb.
table.Add(ForeignKey(table, FlatNaming.IdColumn, FlatNaming.ObjectsTable, FlatDeleteRule.Cascade));
tables.Add(table);
AddMembers(table, propsType, roots, propsType, path: null, [], tables);
}
///
/// Adds the properties of to : scalars and single
/// references as columns, nested classes and collections as tables of their own.
///
private static void AddMembers(
FlatTable table,
Type type,
IReadOnlyList? nodes,
Type propsType,
string? path,
HashSet typesOnPath,
List tables)
{
// Scheme sync does not descend into a type already on the path; the structure of the
// property exists, its children do not.
if (!typesOnPath.Add(type))
return;
foreach (var property in FlatTypeClassifier.StoredProperties(type))
{
var node = nodes?.FirstOrDefault(n => n.Structure.Name == property.Name);
var structureId = node?.Structure.Id;
var children = node?.Children;
var memberPath = path == null ? property.Name : $"{path}.{property.Name}";
var description = $"Property '{propsType.Name}.{memberPath}'";
var propertyType = property.PropertyType;
if (FlatTypeClassifier.IsDictionary(propertyType))
{
var (keyType, valueType) = FlatTypeClassifier.DictionaryTypes(propertyType);
BuildCollectionTable(table, property.Name, memberPath, description, valueType, keyType,
structureId, children, propsType, typesOnPath, tables);
}
else if (FlatTypeClassifier.IsArray(propertyType))
{
BuildCollectionTable(table, property.Name, memberPath, description,
FlatTypeClassifier.ArrayElementType(propertyType), keyType: null,
structureId, children, propsType, typesOnPath, tables);
}
else if (FlatTypeClassifier.IsObjectReference(propertyType, description))
{
var target = propertyType.GetGenericArguments()[0];
table.Add(Payload(property.Name, FlatColumnRole.ObjectReference, typeof(long), FlatValueSource.Object, structureId));
table.Add(ForeignKey(table, property.Name, target.Name, FlatDeleteRule.NoAction, target));
}
else if (FlatTypeClassifier.IsListItem(propertyType))
{
table.Add(Payload(property.Name, FlatColumnRole.ListItemReference, typeof(long), FlatValueSource.ListItem, structureId));
table.Add(ForeignKey(table, property.Name, FlatNaming.ListItemsTable, FlatDeleteRule.NoAction));
}
else if (FlatTypeClassifier.IsBusinessClass(propertyType))
{
var nested = new FlatTable(FlatNaming.ChildTable(table.FullName, property.Name))
{
Kind = FlatTableKind.NestedClass,
PropsType = propsType,
ClassType = propertyType,
PropertyPath = memberPath,
OwnerTable = table.Name,
StructureId = structureId
};
AddKeyAndOwner(nested, table);
// One nested instance per owner row.
nested.Add(Unique(nested, FlatNaming.OwnerColumn));
tables.Add(nested);
AddMembers(nested, propertyType, children, propsType, memberPath, typesOnPath, tables);
}
else
{
table.Add(Payload(property.Name, FlatColumnRole.Scalar, propertyType,
FlatTypeClassifier.ScalarSource(propertyType), structureId));
}
}
typesOnPath.Remove(type);
}
private static void BuildCollectionTable(
FlatTable owner,
string propertyName,
string memberPath,
string description,
Type elementType,
Type? keyType,
long? structureId,
IReadOnlyList? children,
Type propsType,
HashSet typesOnPath,
List tables)
{
FlatElementKind elementKind;
if (FlatTypeClassifier.IsObjectReference(elementType, description))
elementKind = FlatElementKind.ObjectReference;
else if (FlatTypeClassifier.IsListItem(elementType))
elementKind = FlatElementKind.ListItemReference;
else if (FlatTypeClassifier.IsBusinessClass(elementType))
elementKind = FlatElementKind.Class;
else
elementKind = FlatElementKind.Scalar;
var keyKind = keyType == null ? FlatKeyKind.None : ClassifyKey(keyType);
var table = new FlatTable(FlatNaming.ChildTable(owner.FullName, propertyName))
{
Kind = FlatTableKind.Collection,
PropsType = propsType,
ClassType = elementKind == FlatElementKind.Class ? elementType : null,
PropertyPath = memberPath,
OwnerTable = owner.Name,
StructureId = structureId,
CollectionKind = keyType == null ? FlatCollectionKind.Array : FlatCollectionKind.Dictionary,
ElementKind = elementKind,
ElementType = elementType,
KeyType = keyType,
KeyKind = keyKind
};
AddKeyAndOwner(table, owner);
// Position or key: what tells the elements of one owner apart.
var identity = new List { FlatNaming.OwnerColumn };
switch (keyKind)
{
case FlatKeyKind.None:
table.Add(Service(FlatNaming.IndexColumn, FlatColumnRole.ArrayIndex, typeof(int)));
identity.Add(FlatNaming.IndexColumn);
break;
case FlatKeyKind.Simple:
table.Add(Service(FlatNaming.KeyColumn, FlatColumnRole.DictionaryKey, keyType!));
identity.Add(FlatNaming.KeyColumn);
break;
case FlatKeyKind.Tuple:
foreach (var field in keyType!.GetFields())
{
var name = FlatNaming.Shorten($"{FlatNaming.KeyColumn}_{field.Name}");
table.Add(new FlatColumn
{
Name = name,
Role = FlatColumnRole.DictionaryKey,
ClrType = field.FieldType,
IsNullable = false,
KeyComponent = field.Name
});
identity.Add(name);
}
break;
default:
table.Add(Service(FlatNaming.KeyColumn, FlatColumnRole.DictionaryKey, typeof(string)));
identity.Add(FlatNaming.KeyColumn);
break;
}
table.Add(Unique(table, [.. identity]));
tables.Add(table);
switch (elementKind)
{
case FlatElementKind.ObjectReference:
var target = elementType.GetGenericArguments()[0];
table.Add(Payload(FlatNaming.ValueColumn, FlatColumnRole.ObjectReference, typeof(long), FlatValueSource.Object, structureId));
table.Add(ForeignKey(table, FlatNaming.ValueColumn, target.Name, FlatDeleteRule.NoAction, target));
break;
case FlatElementKind.ListItemReference:
table.Add(Payload(FlatNaming.ValueColumn, FlatColumnRole.ListItemReference, typeof(long), FlatValueSource.ListItem, structureId));
table.Add(ForeignKey(table, FlatNaming.ValueColumn, FlatNaming.ListItemsTable, FlatDeleteRule.NoAction));
break;
case FlatElementKind.Class:
// The element row is the class instance: its properties are columns of this table.
AddMembers(table, elementType, children, propsType, memberPath, typesOnPath, tables);
break;
default:
table.Add(Payload(FlatNaming.ValueColumn, FlatColumnRole.Scalar, elementType,
FlatTypeClassifier.ScalarSource(elementType), structureId));
break;
}
}
///
/// A simple key is stored as plain text and gets one typed column. A ValueTuple of simple
/// components is stored as JSON keyed by Item1 , Item2 , ... and gets one column per
/// component. Everything else stays one text column.
///
private static FlatKeyKind ClassifyKey(Type keyType)
{
if (!RedbKeySerializer.IsComplexKey(keyType))
return FlatKeyKind.Simple;
if (FlatTypeClassifier.IsValueTuple(keyType) &&
keyType.GetFields().All(f => !RedbKeySerializer.IsComplexKey(f.FieldType)))
return FlatKeyKind.Tuple;
return FlatKeyKind.Json;
}
// ---------------------------------------------------------------------------------------
// Pieces
// ---------------------------------------------------------------------------------------
///
/// An index for every foreign key column that no key already leads with, as EF Core creates by
/// convention. The primary key covers a scheme table's link to objects ; the unique constraints
/// of nested and collection tables lead with _owner_id and cover the owner link.
///
private static void AddForeignKeyIndexes(FlatTable table)
{
foreach (var column in table.ForeignKeys.Select(f => f.Column).Distinct())
{
var covered = column == table.PrimaryKey
|| table.UniqueConstraints.Any(u => u.Columns.Count > 0 && u.Columns[0] == column);
if (covered)
continue;
table.Add(new FlatIndex
{
Name = FlatNaming.Shorten($"IX_{table.FullName}_{column}"),
Columns = [column]
});
}
}
private static void AddKeyAndOwner(FlatTable table, FlatTable owner)
{
table.Add(Service(FlatNaming.IdColumn, FlatColumnRole.PrimaryKey, typeof(long)));
table.Add(Service(FlatNaming.OwnerColumn, FlatColumnRole.Owner, typeof(long)));
table.Add(ForeignKey(table, FlatNaming.OwnerColumn, owner.FullName, FlatDeleteRule.Cascade));
}
private static FlatColumn Header(string name, Type clrType, bool nullable, FlatColumnRole role = FlatColumnRole.Header) => new()
{
Name = name,
Role = role,
ClrType = clrType,
IsNullable = nullable,
SourceColumn = name
};
private static FlatColumn Service(string name, FlatColumnRole role, Type clrType) => new()
{
Name = name,
Role = role,
ClrType = clrType,
IsNullable = false
};
private static FlatColumn Payload(string propertyName, FlatColumnRole role, Type clrType, FlatValueSource source, long? structureId) => new()
{
Name = FlatNaming.Shorten(propertyName),
Role = role,
ClrType = clrType,
IsNullable = true,
ValueSource = source,
StructureId = structureId
};
private static FlatForeignKey ForeignKey(FlatTable table, string column, string targetFullName, FlatDeleteRule onDelete, Type? targetPropsType = null) => new()
{
Name = FlatNaming.Shorten($"FK_{table.FullName}_{column}"),
Column = FlatNaming.Shorten(column),
TargetTable = FlatNaming.Shorten(targetFullName),
TargetColumn = FlatNaming.IdColumn,
TargetPropsType = targetPropsType,
OnDelete = onDelete
};
private static FlatUniqueConstraint Unique(FlatTable table, params string[] columns) => new()
{
Name = FlatNaming.Shorten($"UQ_{table.FullName}"),
Columns = columns
};
}
Path: redb/redb.Export/Flat/FlatNaming.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.Export/Flat/FlatNaming.cs
----
using System.Security.Cryptography;
using System.Text;
namespace redb.Export.Flat;
///
/// Names of the flat tables and columns, and the rule that keeps every identifier within the
/// strictest provider limit.
///
/// Table names come from the code as they are: the Props class name for a scheme table and the
/// property path (EmployeeProps.HomeAddress.Building ) for every table below it. Service
/// tables and service columns keep the redb spelling so they cannot be mistaken for user members.
///
///
public static class FlatNaming
{
///
/// Identifier limit applied on every provider: the 63 bytes of PostgreSQL, the strictest of the
/// three, so that a table carries the same name in any target database.
///
public const int MaxIdentifierBytes = 63;
/// Shared header table: one row per object, the flat copy of _objects .
public const string ObjectsTable = "objects";
/// Flat copy of _lists .
public const string ListsTable = "lists";
/// Flat copy of _list_items .
public const string ListItemsTable = "list_items";
/// Primary key column of every flat table.
public const string IdColumn = "_id";
///
/// The one sequence of the flat database, the counterpart of redb's global_identity . Every key
/// a writer leaves out is taken from it, so new rows of any table never collide.
///
public const string IdentitySequence = "flat_identity";
/// Reference from a nested or collection table to the row that owns it.
public const string OwnerColumn = "_owner_id";
/// Position of an array element.
public const string IndexColumn = "_idx";
/// Dictionary key; the prefix of the per-component columns of a tuple key.
public const string KeyColumn = "_key";
/// Payload of a collection whose elements are not classes.
public const string ValueColumn = "_value";
// "~" plus eight hex digits.
private const int HashSuffixBytes = 9;
///
/// Returns unchanged when it fits ;
/// otherwise cuts it on a character boundary and appends ~ with eight hex digits of the
/// SHA-256 of the full name. The result is stable across runs and providers.
///
public static string Shorten(string fullName)
{
ArgumentException.ThrowIfNullOrEmpty(fullName);
var bytes = Encoding.UTF8.GetBytes(fullName);
if (bytes.Length <= MaxIdentifierBytes)
return fullName;
var budget = MaxIdentifierBytes - HashSuffixBytes;
var kept = new StringBuilder();
var used = 0;
foreach (var rune in fullName.EnumerateRunes())
{
if (used + rune.Utf8SequenceLength > budget)
break;
kept.Append(rune.ToString());
used += rune.Utf8SequenceLength;
}
var hash = Convert.ToHexString(SHA256.HashData(bytes), 0, 4).ToLowerInvariant();
return $"{kept}~{hash}";
}
/// Full (unshortened) name of the table that holds of .
public static string ChildTable(string ownerFullName, string propertyName) => $"{ownerFullName}.{propertyName}";
}
Path: redb/redb.Export/Flat/FlatRowAssembler.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.Export/Flat/FlatRowAssembler.cs
----
using System.Data;
using System.Text;
using redb.Core.Utils;
using redb.Export.Flat.Dialects;
using redb.Export.Flat.Model;
namespace redb.Export.Flat;
/// Rows of one flat table waiting for the next bulk insert.
internal sealed class FlatTableBuffer
{
public FlatTableBuffer(FlatTable table, IFlatDialect dialect)
{
Table = table;
StorageTypes = table.Columns.Select(FlatStorageTypes.Of).ToArray();
Data = new DataTable();
foreach (var column in table.Columns)
Data.Columns.Add(dialect.BulkColumnName(column.Name), typeof(object));
}
public FlatTable Table { get; }
public FlatStorageType[] StorageTypes { get; }
public DataTable Data { get; }
}
///
/// Turns the _values rows of one object into rows of the scheme table and of every table
/// below it.
///
/// The layout it reads is the one ObjectStorageProviderBase.SaveAsync writes: a field outside
/// a collection is one row found by its structure under the row of its parent; a class has a base
/// row its fields hang from; a collection has a base row and, under it, one row per element with
/// the position or the key in _array_index ; an element that is a class is itself the parent
/// of the rows of its fields.
///
///
internal sealed class FlatRowAssembler
{
// Parent of the rows that hang directly from the object.
private const long RootParent = 0;
private readonly IFlatDialect _dialect;
private readonly IReadOnlyDictionary _buffers;
private readonly ILookup _tablesByOwner;
public FlatRowAssembler(
IReadOnlyList schemeTables,
IReadOnlyDictionary buffers,
IFlatDialect dialect)
{
_dialect = dialect;
_buffers = buffers;
_tablesByOwner = schemeTables.ToLookup(t => t.OwnerTable);
}
/// Largest row key appended so far, in any table.
public long MaxRowId { get; private set; }
/// Appends the rows of one object to the buffers.
public void Append(FlatTable schemeTable, long objectId, List values)
{
var index = values.ToLookup(v => (v.ArrayParentId ?? RootParent, v.StructureId));
EmitRow(schemeTable, objectId, ownerRowId: null, RootParent, element: null, index);
}
private void EmitRow(
FlatTable table,
long rowId,
long? ownerRowId,
long parentValueId,
FlatSourceValue? element,
ILookup<(long Parent, long Structure), FlatSourceValue> index)
{
if (rowId > MaxRowId)
MaxRowId = rowId;
var buffer = _buffers[table.Name];
var row = buffer.Data.NewRow();
object? key = null;
for (var i = 0; i < table.Columns.Count; i++)
{
var column = table.Columns[i];
var storageType = buffer.StorageTypes[i];
object? value;
switch (column.Role)
{
case FlatColumnRole.PrimaryKey:
value = rowId;
break;
case FlatColumnRole.Owner:
value = ownerRowId;
break;
case FlatColumnRole.ArrayIndex:
value = int.Parse(element!.ArrayIndex!, System.Globalization.CultureInfo.InvariantCulture);
break;
case FlatColumnRole.DictionaryKey:
key ??= DecodeKey(table, element!.ArrayIndex!);
value = KeyColumnValue(table, column, key, storageType);
break;
default:
// The payload of a collection of scalars or references sits on the element row
// itself; everything else is a row of its own under the parent.
var source = table.Kind == FlatTableKind.Collection && table.ElementKind != FlatElementKind.Class
? element
: index[(parentValueId, column.StructureId!.Value)].FirstOrDefault();
value = source == null ? null : FlatValueConverter.Read(source, column, storageType);
break;
}
row[i] = value == null ? DBNull.Value : _dialect.ToDbValue(value, storageType);
}
buffer.Data.Rows.Add(row);
foreach (var child in _tablesByOwner[table.Name])
{
var baseRow = index[(parentValueId, child.StructureId!.Value)].FirstOrDefault();
if (baseRow == null)
continue;
if (child.Kind == FlatTableKind.NestedClass)
{
EmitRow(child, baseRow.Id, rowId, baseRow.Id, element: null, index);
continue;
}
foreach (var item in index[(baseRow.Id, child.StructureId.Value)])
EmitRow(child, item.Id, rowId, item.Id, item, index);
}
}
private static object DecodeKey(FlatTable table, string arrayIndex) => table.KeyKind switch
{
// A complex key is stored as Base64 of its JSON.
FlatKeyKind.Json => Encoding.UTF8.GetString(Convert.FromBase64String(arrayIndex)),
_ => RedbKeySerializer.DeserializeObject(arrayIndex, table.KeyType!)
?? throw new InvalidOperationException(
$"Dictionary key '{arrayIndex}' of table '{table.FullName}' cannot be read as {table.KeyType!.Name}.")
};
private static object KeyColumnValue(FlatTable table, FlatColumn column, object key, FlatStorageType storageType)
{
var value = column.KeyComponent == null
? key
: table.KeyType!.GetField(column.KeyComponent)!.GetValue(key)!;
// Enum keys are stored, and exported, by name.
return storageType is FlatStorageType.Text or FlatStorageType.KeyText ? value.ToString()! : value;
}
}
/// Reads the typed value of a column out of a _values row.
internal static class FlatValueConverter
{
public static object? Read(FlatSourceValue source, FlatColumn column, FlatStorageType storageType)
{
switch (column.ValueSource)
{
case FlatValueSource.Long:
if (source.Long is not { } number) return null;
return storageType switch
{
FlatStorageType.Int32 => (object)checked((int)number),
FlatStorageType.Int16 => checked((short)number),
FlatStorageType.Byte => checked((byte)number),
// TimeOnly and TimeSpan are stored as their Ticks.
FlatStorageType.Time => new TimeOnly(number),
FlatStorageType.Duration => TimeSpan.FromTicks(number),
_ => number
};
case FlatValueSource.Double:
if (source.Double is not { } real) return null;
return storageType == FlatStorageType.Single ? (object)(float)real : real;
case FlatValueSource.Numeric:
return source.Numeric;
case FlatValueSource.Boolean:
return source.Boolean;
case FlatValueSource.Guid:
return source.Guid;
case FlatValueSource.ByteArray:
return source.ByteArray;
case FlatValueSource.Object:
return source.Object;
case FlatValueSource.ListItem:
return source.ListItem;
case FlatValueSource.DateTimeOffset:
if (source.DateTimeOffset is not { } moment) return null;
return storageType switch
{
// DateTime and DateOnly are stored as a UTC clock reading (DateTimeConverter.NormalizeForStorage).
FlatStorageType.DateTime => (object)moment.UtcDateTime,
FlatStorageType.Date => DateOnly.FromDateTime(moment.UtcDateTime),
_ => moment
};
case FlatValueSource.String:
return source.String;
default:
throw new InvalidOperationException($"Column '{column.Name}' has no value source.");
}
}
}
Path: redb/redb.Export/Flat/FlatSourceReader.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.Export/Flat/FlatSourceReader.cs
----
using System.Data.Common;
using System.Runtime.CompilerServices;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Export.Flat.Model;
using redb.Export.Providers;
namespace redb.Export.Flat;
/// One row of _values as the flat export reads it (hashes and unique keys left out).
internal sealed class FlatSourceValue
{
public long Id { get; init; }
public long StructureId { get; init; }
public long? ArrayParentId { get; init; }
public string? ArrayIndex { get; init; }
public string? String { get; init; }
public long? Long { get; init; }
public Guid? Guid { get; init; }
public double? Double { get; init; }
public DateTimeOffset? DateTimeOffset { get; init; }
public bool? Boolean { get; init; }
public byte[]? ByteArray { get; init; }
public decimal? Numeric { get; init; }
public long? ListItem { get; init; }
public long? Object { get; init; }
}
///
/// Reads the redb tables of the source database. Every command runs inside the one transaction the
/// reader was given, so the whole export sees a single snapshot. Readers are consumed one at a
/// time: a connection carries one open reader.
///
internal sealed class FlatSourceReader
{
private readonly IDataProvider _provider;
private readonly DbTransaction _transaction;
public FlatSourceReader(IDataProvider provider, DbTransaction transaction)
{
_provider = provider;
_transaction = transaction;
}
/// Id of the scheme stored under , or null when there is none.
public async Task FindSchemeIdAsync(string schemeName, CancellationToken ct)
{
await using var command = Command("SELECT _id FROM _schemes WHERE _name = @name");
AddParameter(command, "@name", schemeName);
var result = await command.ExecuteScalarAsync(ct);
return result is null or DBNull ? null : Convert.ToInt64(result);
}
/// The structures of a scheme, with the columns the structure tree is built from.
public async Task> ReadStructuresAsync(long schemeId, CancellationToken ct)
{
await using var command = Command(
"SELECT _id, _id_parent, _name, _id_type, _collection_type, _key_type, _order " +
"FROM _structures WHERE _id_scheme = @scheme");
AddParameter(command, "@scheme", schemeId);
var structures = new List();
await using var reader = await command.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
structures.Add(new RedbStructure
{
Id = reader.GetInt64(0),
IdParent = reader.IsDBNull(1) ? null : reader.GetInt64(1),
IdScheme = schemeId,
Name = reader.GetString(2),
IdType = reader.GetInt64(3),
CollectionType = reader.IsDBNull(4) ? null : reader.GetInt64(4),
KeyType = reader.IsDBNull(5) ? null : reader.GetInt64(5),
Order = reader.IsDBNull(6) ? null : reader.GetInt64(6)
});
}
return structures;
}
///
/// Streams a redb table into the shape of its flat copy: one array per row, a value per column of
/// , read from the redb column named by .
///
public async IAsyncEnumerable ReadServiceRowsAsync(
string sourceTable,
FlatTable table,
[EnumeratorCancellation] CancellationToken ct)
{
var columns = table.Columns;
var list = string.Join(", ", columns.Select(c => c.SourceColumn));
await using var command = Command($"SELECT {list} FROM {sourceTable} ORDER BY _id");
await using var reader = await command.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var row = new object?[columns.Count];
for (var i = 0; i < columns.Count; i++)
row[i] = ReadTyped(reader, i, columns[i].ClrType);
yield return row;
}
}
/// Ids of every object of a scheme, ascending.
public async Task> ReadSchemeObjectIdsAsync(long schemeId, CancellationToken ct)
{
await using var command = Command("SELECT _id FROM _objects WHERE _id_scheme = @scheme ORDER BY _id");
AddParameter(command, "@scheme", schemeId);
var ids = new List();
await using var reader = await command.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
ids.Add(reader.GetInt64(0));
return ids;
}
///
/// Streams the objects of a scheme whose id lies in [fromId, toId] , in id order, each with
/// all of its _values rows. An object without rows is still returned: it has a row in the
/// scheme table.
///
/// The range keeps each read small. One statement over the whole scheme makes the server join and
/// sort every _values row of the scheme before it returns the first one: minutes of
/// silence on a few million rows, and a command timeout beyond that.
///
///
public async IAsyncEnumerable<(long ObjectId, List Values)> ReadSchemeObjectsAsync(
long schemeId,
long fromId,
long toId,
[EnumeratorCancellation] CancellationToken ct)
{
// The range is stated on both sides of the join so that _values is reached through its
// _id_object index instead of being scanned.
await using var command = Command(
"SELECT o._id, v._id, v._id_structure, v._array_parent_id, v._array_index, " +
"v._String, v._Long, v._Guid, v._Double, v._DateTimeOffset, v._Boolean, v._ByteArray, " +
"v._Numeric, v._ListItem, v._Object " +
"FROM _objects o LEFT JOIN _values v ON v._id_object = o._id " +
"AND v._id_object >= @fromId AND v._id_object <= @toId " +
"WHERE o._id_scheme = @scheme AND o._id >= @fromId AND o._id <= @toId ORDER BY o._id");
AddParameter(command, "@scheme", schemeId);
AddParameter(command, "@fromId", fromId);
AddParameter(command, "@toId", toId);
long? currentId = null;
var values = new List();
await using var reader = await command.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var objectId = reader.GetInt64(0);
if (currentId != objectId)
{
if (currentId.HasValue)
yield return (currentId.Value, values);
currentId = objectId;
values = [];
}
if (reader.IsDBNull(1))
continue;
// Same typed reads as ExportService.ExportValuesAsync.
values.Add(new FlatSourceValue
{
Id = reader.GetInt64(1),
StructureId = reader.GetInt64(2),
ArrayParentId = reader.IsDBNull(3) ? null : reader.GetInt64(3),
ArrayIndex = reader.IsDBNull(4) ? null : reader.GetString(4),
String = reader.IsDBNull(5) ? null : reader.GetString(5),
Long = reader.IsDBNull(6) ? null : reader.GetInt64(6),
Guid = reader.IsDBNull(7) ? null : reader.GetGuid(7),
Double = reader.IsDBNull(8) ? null : reader.GetDouble(8),
DateTimeOffset = reader.IsDBNull(9) ? null : _provider.ReadDateTimeOffset(reader, 9),
Boolean = reader.IsDBNull(10) ? null : reader.GetBoolean(10),
ByteArray = reader.IsDBNull(11) ? null : (byte[])reader.GetValue(11),
Numeric = reader.IsDBNull(12) ? null : reader.GetDecimal(12),
ListItem = reader.IsDBNull(13) ? null : reader.GetInt64(13),
Object = reader.IsDBNull(14) ? null : reader.GetInt64(14)
});
}
if (currentId.HasValue)
yield return (currentId.Value, values);
}
private object? ReadTyped(DbDataReader reader, int ordinal, Type type)
{
if (reader.IsDBNull(ordinal))
return null;
if (type == typeof(long)) return reader.GetInt64(ordinal);
if (type == typeof(string)) return reader.GetString(ordinal);
if (type == typeof(Guid)) return reader.GetGuid(ordinal);
if (type == typeof(bool)) return reader.GetBoolean(ordinal);
if (type == typeof(double)) return reader.GetDouble(ordinal);
if (type == typeof(decimal)) return reader.GetDecimal(ordinal);
if (type == typeof(DateTimeOffset)) return _provider.ReadDateTimeOffset(reader, ordinal);
if (type == typeof(byte[])) return (byte[])reader.GetValue(ordinal);
throw new NotSupportedException($"A service column of type '{type.Name}' cannot be read.");
}
private DbCommand Command(string sql)
{
var command = _provider.Connection.CreateCommand();
command.Transaction = _transaction;
command.CommandText = sql;
return command;
}
private static void AddParameter(DbCommand command, string name, object value)
{
var parameter = command.CreateParameter();
parameter.ParameterName = name;
parameter.Value = value;
command.Parameters.Add(parameter);
}
}
Path: redb/redb.Export/Flat/FlatStorageType.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.Export/Flat/FlatStorageType.cs
----
using redb.Export.Flat.Model;
namespace redb.Export.Flat;
///
/// Dialect-independent type of a flat column. Each dialect maps it to a column type and to the form
/// its bulk insert accepts.
///
public enum FlatStorageType
{
/// .
Int64,
/// .
Int32,
/// .
Int16,
/// .
Byte,
/// .
Double,
/// .
Single,
/// .
Decimal,
/// .
Boolean,
/// Unbounded text: strings, enum names and every type scheme sync stores as text.
Text,
/// Text that takes part in a unique constraint (a dictionary key).
KeyText,
/// .
Char,
/// .
Guid,
/// , a UTC reading.
DateTime,
/// .
DateTimeOffset,
/// .
Date,
/// .
Time,
/// .
Duration,
/// byte[] .
Bytes
}
/// Chooses the of a column from its CLR type.
public static class FlatStorageTypes
{
/// Storage type of .
public static FlatStorageType Of(FlatColumn column)
{
var type = Nullable.GetUnderlyingType(column.ClrType) ?? column.ClrType;
if (type == typeof(long)) return FlatStorageType.Int64;
if (type == typeof(int)) return FlatStorageType.Int32;
if (type == typeof(short)) return FlatStorageType.Int16;
if (type == typeof(byte)) return FlatStorageType.Byte;
if (type == typeof(double)) return FlatStorageType.Double;
if (type == typeof(float)) return FlatStorageType.Single;
if (type == typeof(decimal)) return FlatStorageType.Decimal;
if (type == typeof(bool)) return FlatStorageType.Boolean;
if (type == typeof(char)) return FlatStorageType.Char;
if (type == typeof(Guid)) return FlatStorageType.Guid;
if (type == typeof(DateTime)) return FlatStorageType.DateTime;
if (type == typeof(DateTimeOffset)) return FlatStorageType.DateTimeOffset;
if (type == typeof(DateOnly)) return FlatStorageType.Date;
if (type == typeof(TimeOnly)) return FlatStorageType.Time;
if (type == typeof(TimeSpan)) return FlatStorageType.Duration;
if (type == typeof(byte[])) return FlatStorageType.Bytes;
return column.Role == FlatColumnRole.DictionaryKey ? FlatStorageType.KeyText : FlatStorageType.Text;
}
}
Path: redb/redb.Export/Flat/FlatTypeClassifier.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.Export/Flat/FlatTypeClassifier.cs
----
using System.Reflection;
using redb.Core.Attributes;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Export.Flat.Model;
namespace redb.Export.Flat;
///
/// Classifies Props members the way scheme synchronisation does. The rules are a copy of the private
/// helpers of redb.Core/Providers/Base/SchemeSyncProviderBase.cs (IsArrayType ,
/// IsDictionaryType , IsBusinessClass , MapCSharpTypeToRedbTypeAsync ) and of the
/// value writer ObjectStorageProviderBase.SetSimpleValueByType : the flat model has to see a
/// field exactly as the structure tree and the stored rows do. When those rules change, this class
/// changes with them.
///
internal static class FlatTypeClassifier
{
/// Properties scheme sync turns into structures, in declaration order.
public static IEnumerable StoredProperties(Type type) =>
type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
// Save skips indexers (it looks properties up by name and rejects index parameters),
// so an indexer never has rows.
.Where(p => p.GetIndexParameters().Length == 0)
.Where(p => p.GetCustomAttribute() == null);
public static bool IsDictionary(Type type)
{
if (!type.IsGenericType)
return false;
var definition = type.GetGenericTypeDefinition();
return definition == typeof(Dictionary<,>) || definition == typeof(IDictionary<,>);
}
/// Array in the scheme-sync sense. byte[] is a scalar.
public static bool IsArray(Type type)
{
if (type == typeof(byte[]) || IsDictionary(type))
return false;
return IsArrayShape(type);
}
public static Type ArrayElementType(Type type) =>
type.IsArray ? type.GetElementType()! : type.GetGenericArguments()[0];
public static (Type Key, Type Value) DictionaryTypes(Type type)
{
var arguments = type.GetGenericArguments();
return (arguments[0], arguments[1]);
}
public static bool IsListItem(Type type) =>
type == typeof(IRedbListItem) || type == typeof(RedbListItem);
///
/// True for RedbObject<T> . Any other object-shaped type is refused: scheme sync
/// rejects the bare shapes itself and would reflect a derived generic one as a plain class.
///
public static bool IsObjectReference(Type type, string memberDescription)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(RedbObject<>))
return true;
if (typeof(IRedbObject).IsAssignableFrom(type))
throw new NotSupportedException(
$"{memberDescription} has type '{type.Name}'. A reference in a flat model must be " +
"declared as RedbObject.");
return false;
}
public static bool IsBusinessClass(Type type)
{
if (type.IsPrimitive || type == typeof(string) || type == typeof(decimal))
return false;
if (type == typeof(DateTime) || type == typeof(DateTimeOffset) ||
type == typeof(DateOnly) || type == typeof(TimeOnly) ||
type == typeof(Guid) || type == typeof(TimeSpan) || type == typeof(byte[]))
return false;
if (Nullable.GetUnderlyingType(type) != null)
return false;
if (type.IsArray || IsArrayShape(type) || IsDictionary(type))
return false;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(RedbObject<>))
return false;
if (IsListItem(type) || type.IsEnum)
return false;
if (type.Namespace?.StartsWith("System") == true)
return false;
return type.IsClass;
}
///
/// The _values column a scalar of is written to. A type scheme
/// sync has no mapping for (an enum included) is stored as text.
///
public static FlatValueSource ScalarSource(Type type)
{
var underlying = Nullable.GetUnderlyingType(type) ?? type;
// TimeSpan and TimeOnly are stored as their Ticks.
if (underlying == typeof(long) || underlying == typeof(int) ||
underlying == typeof(short) || underlying == typeof(byte) ||
underlying == typeof(TimeSpan) || underlying == typeof(TimeOnly))
return FlatValueSource.Long;
if (underlying == typeof(double) || underlying == typeof(float))
return FlatValueSource.Double;
if (underlying == typeof(decimal))
return FlatValueSource.Numeric;
if (underlying == typeof(bool))
return FlatValueSource.Boolean;
if (underlying == typeof(Guid))
return FlatValueSource.Guid;
if (underlying == typeof(DateTime) || underlying == typeof(DateTimeOffset) || underlying == typeof(DateOnly))
return FlatValueSource.DateTimeOffset;
if (underlying == typeof(byte[]))
return FlatValueSource.ByteArray;
return FlatValueSource.String;
}
public static bool IsValueTuple(Type type) =>
type.IsValueType && type.IsGenericType &&
type.GetGenericTypeDefinition().FullName?.StartsWith("System.ValueTuple`", StringComparison.Ordinal) == true;
private static bool IsArrayShape(Type type)
{
if (type.IsArray)
return true;
if (!type.IsGenericType)
return false;
var definition = type.GetGenericTypeDefinition();
return definition == typeof(List<>) || definition == typeof(IList<>) ||
definition == typeof(ICollection<>) || definition == typeof(IEnumerable<>);
}
}
Path: redb/redb.Export/Flat/Model/FlatColumn.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.Export/Flat/Model/FlatColumn.cs
----
namespace redb.Export.Flat.Model;
///
/// One column of a flat table, described independently of any SQL dialect: the target column type
/// is chosen later from .
///
public sealed class FlatColumn
{
/// Column name as it goes into DDL (already within the identifier limit).
public string Name { get; init; } = "";
/// The part the column plays in its table.
public FlatColumnRole Role { get; init; }
///
/// CLR type the column carries: the property type for Props values (nullable wrappers kept),
/// for keys and references.
///
public Type ClrType { get; init; } = typeof(object);
/// Whether the column accepts NULL. Every Props column does: an object saved before a field existed has no row for it.
public bool IsNullable { get; init; }
/// The _values column the value is read from; for service columns.
public FlatValueSource ValueSource { get; init; }
///
/// _structures._id of the field. Null for service columns, and for every column when the
/// model was built without a structure tree.
///
public long? StructureId { get; init; }
/// For a column: the redb column it is copied from.
public string? SourceColumn { get; init; }
/// For one component of a tuple key: the field of the tuple (Item1 , Item2 , ...), as stored in the key JSON.
public string? KeyComponent { get; init; }
}
Path: redb/redb.Export/Flat/Model/FlatConstraints.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.Export/Flat/Model/FlatConstraints.cs
----
namespace redb.Export.Flat.Model;
/// A single-column foreign key of a flat table.
public sealed class FlatForeignKey
{
/// Constraint name (already within the identifier limit).
public string Name { get; init; } = "";
/// Referencing column.
public string Column { get; init; } = "";
/// Referenced table. It may be created later than the referencing one, or be absent when its Props type is not part of the model.
public string TargetTable { get; init; } = "";
/// Referenced column.
public string TargetColumn { get; init; } = "";
/// For a RedbObject<T> reference: the Props type T the target table belongs to.
public Type? TargetPropsType { get; init; }
/// What happens to the referencing row when the referenced one is deleted.
public FlatDeleteRule OnDelete { get; init; }
}
///
/// A plain index of a flat table. The export creates one for every foreign key column that no key already
/// leads with, as EF Core does by convention: lookups by owner, parent or reference, and the checks a
/// cascading delete makes, then find the rows without reading the whole table.
///
public sealed class FlatIndex
{
/// Index name (already within the identifier limit).
public string Name { get; init; } = "";
/// Columns of the index, in order.
public IReadOnlyList Columns { get; init; } = [];
}
/// A unique constraint of a flat table.
public sealed class FlatUniqueConstraint
{
/// Constraint name (already within the identifier limit).
public string Name { get; init; } = "";
/// Columns of the constraint, in order.
public IReadOnlyList Columns { get; init; } = [];
}
Path: redb/redb.Export/Flat/Model/FlatModelEnums.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.Export/Flat/Model/FlatModelEnums.cs
----
namespace redb.Export.Flat.Model;
/// What a flat table holds.
public enum FlatTableKind
{
/// The shared header table (objects ).
Objects,
/// The flat copy of _lists .
Lists,
/// The flat copy of _list_items .
ListItems,
/// Props of one scheme; one row per object, keyed by the object id.
Scheme,
/// A nested class outside a collection; one-to-one with its owner row.
NestedClass,
/// Elements of an array or a dictionary; many rows per owner row.
Collection
}
/// Kind of the collection a table stores.
public enum FlatCollectionKind
{
/// Not a collection table.
None,
/// Array, List<T> and the other shapes scheme sync treats as an array.
Array,
/// Dictionary<TKey, TValue> or IDictionary<TKey, TValue> .
Dictionary
}
/// What one element of a collection is.
public enum FlatElementKind
{
/// Not a collection table.
None,
/// A scalar stored in the _value column.
Scalar,
/// A class; its properties are the columns of the collection table.
Class,
/// A RedbObject<T> ; _value holds the target object id.
ObjectReference,
/// A RedbListItem ; _value holds the list item id.
ListItemReference
}
/// How a dictionary key is laid out in the flat table.
public enum FlatKeyKind
{
/// Not a dictionary table.
None,
/// A simple key in one typed _key column.
Simple,
/// A ValueTuple of simple components, one _key_ItemN column per component.
Tuple,
/// Any other key; one text _key column with the JSON the key is stored as.
Json
}
/// The part a column plays in its table.
public enum FlatColumnRole
{
/// Primary key: the object id in a scheme table, the _values._id of the row elsewhere.
PrimaryKey,
/// Reference to the owner row.
Owner,
/// Position of an array element, read from _array_index .
ArrayIndex,
/// Dictionary key or one component of it, read from _array_index .
DictionaryKey,
/// A column of a service table, copied from the redb column of the same name.
Header,
/// A scalar Props value.
Scalar,
/// The id of the object a RedbObject<T> points to.
ObjectReference,
/// The id of the list item a RedbListItem points to.
ListItemReference
}
/// The _values column a payload value is read from.
public enum FlatValueSource
{
/// Not read from a typed _values column.
None,
/// _String .
String,
/// _Long .
Long,
/// _Guid .
Guid,
/// _Double .
Double,
/// _DateTimeOffset .
DateTimeOffset,
/// _Boolean .
Boolean,
/// _ByteArray .
ByteArray,
/// _Numeric .
Numeric,
/// _ListItem .
ListItem,
/// _Object .
Object
}
///
/// Delete rule of a flat foreign key. The rules mirror redb's own schema: what redb removes together
/// with an object, the flat database removes together with its row.
///
public enum FlatDeleteRule
{
/// The referenced row cannot be deleted while it is referenced: references between objects.
NoAction,
///
/// Deleted together with the referenced row: the Props of an object, the elements of a collection,
/// the fields of a nested class, the children in a tree, the items of a list.
///
Cascade,
/// Kept, with the reference cleared: a list item that points to a deleted object.
SetNull
}
Path: redb/redb.Export/Flat/Model/FlatTable.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.Export/Flat/Model/FlatTable.cs
----
namespace redb.Export.Flat.Model;
///
/// One flat table: its columns and constraints, plus where its rows come from in redb.
///
public sealed class FlatTable
{
private readonly List _columns = [];
private readonly List _foreignKeys = [];
private readonly List _uniqueConstraints = [];
private readonly List _indexes = [];
/// Creates a table; is shortened to the identifier limit when needed.
public FlatTable(string fullName)
{
FullName = fullName;
Name = FlatNaming.Shorten(fullName);
PrimaryKeyName = FlatNaming.Shorten($"PK_{fullName}");
}
/// Table name as it goes into DDL.
public string Name { get; }
/// Name before shortening: the class name or the full property path.
public string FullName { get; }
/// What the table holds.
public FlatTableKind Kind { get; init; }
/// The Props type of the scheme the table belongs to; null for service tables.
public Type? PropsType { get; init; }
/// The class whose properties are the columns: the Props type, a nested class, or the element class of a collection.
public Type? ClassType { get; init; }
/// Property path from the Props type (HomeAddress.Building ); null for scheme and service tables.
public string? PropertyPath { get; init; }
/// Name of the table whose rows own the rows of this one; null for scheme and service tables.
public string? OwnerTable { get; init; }
///
/// _structures._id of the field the table is built from: the class field of a nested
/// table, the collection field of a collection table. Null for scheme and service tables, and
/// when the model was built without a structure tree.
///
public long? StructureId { get; init; }
/// Array or dictionary, for a collection table.
public FlatCollectionKind CollectionKind { get; init; }
/// What one element is, for a collection table.
public FlatElementKind ElementKind { get; init; }
/// CLR type of one element (the value type of a dictionary), for a collection table.
public Type? ElementType { get; init; }
/// CLR type of the key, for a dictionary table.
public Type? KeyType { get; init; }
/// How the key is laid out, for a dictionary table.
public FlatKeyKind KeyKind { get; init; }
/// Name of the primary key column.
public string PrimaryKey { get; init; } = FlatNaming.IdColumn;
/// Name of the primary key constraint.
public string PrimaryKeyName { get; }
/// Columns in declaration order.
public IReadOnlyList Columns => _columns;
/// Foreign keys. They are meant to be created after every table exists: a reference may point to a table that comes later.
public IReadOnlyList ForeignKeys => _foreignKeys;
/// Unique constraints.
public IReadOnlyList UniqueConstraints => _uniqueConstraints;
internal void Add(FlatColumn column) => _columns.Add(column);
internal void Add(FlatForeignKey foreignKey) => _foreignKeys.Add(foreignKey);
/// Plain indexes. Like foreign keys, they are meant to be created after the data is loaded.
public IReadOnlyList Indexes => _indexes;
internal void Add(FlatUniqueConstraint uniqueConstraint) => _uniqueConstraints.Add(uniqueConstraint);
internal void Add(FlatIndex index) => _indexes.Add(index);
}
///
/// The whole flat model: the three service tables followed by the tables of every scheme, each
/// owner before the tables it owns.
///
public sealed class FlatDatabaseModel
{
/// Creates the model over an ordered list of tables.
public FlatDatabaseModel(IReadOnlyList tables)
{
Tables = tables;
}
/// Tables in creation order.
public IReadOnlyList Tables { get; }
}
Path: redb/redb.Export/Models/ExportFooter.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.Export/Models/ExportFooter.cs
----
namespace redb.Export.Models;
///
/// Represents the footer (trailer) record of a .redb export file.
/// The footer is always the last line written to the JSONL stream
/// and contains aggregate statistics and the global-identity sequence value
/// required for a consistent restore.
///
public sealed class ExportFooter
{
/// Record type discriminator. Always "footer" .
public string Type => "footer";
/// Value of the global_identity sequence at the time of export.
public long SequenceValue { get; init; }
/// Total number of type definition records exported.
public long TotalTypes { get; init; }
/// Total number of role records exported.
public long TotalRoles { get; init; }
/// Total number of user records exported.
public long TotalUsers { get; init; }
/// Total number of user-role junction records exported.
public long TotalUserRoles { get; init; }
/// Total number of list definition records exported.
public long TotalLists { get; init; }
/// Total number of list item records exported.
public long TotalListItems { get; init; }
/// Total number of scheme definition records exported.
public long TotalSchemes { get; init; }
/// Total number of structure (field) definition records exported.
public long TotalStructures { get; init; }
///
/// Total number of migration history records exported. null in a file written by an earlier version, which
/// did not carry the migration history; the import checks the total only when it is present.
///
public long? TotalMigrations { get; init; }
/// Total number of object instance records exported.
public long TotalObjects { get; init; }
/// Total number of permission records exported.
public long TotalPermissions { get; init; }
/// Total number of property-value records exported.
public long TotalValues { get; init; }
/// SHA-256 checksum of the export file (hex-encoded, lowercase).
public string Checksum { get; init; } = "";
/// Wall-clock duration of the export operation.
public TimeSpan Duration { get; init; }
}
Path: redb/redb.Export/Models/ExportHeader.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.Export/Models/ExportHeader.cs
----
namespace redb.Export.Models;
///
/// Represents the header record of a .redb export file.
/// The header is always the first line written to the JSONL stream
/// and carries metadata about the export (provider, timestamp, filters).
///
public sealed class ExportHeader
{
/// Record type discriminator. Always "header" .
public string Type => "header";
/// Format version of the export file (currently "1.0" ).
public string Version { get; init; } = "1.0";
/// Database provider name that produced the export (e.g. "postgres" , "mssql" ).
public string Provider { get; init; } = "";
/// UTC timestamp when the export was started.
public DateTime ExportedAt { get; init; } = DateTime.UtcNow;
///
/// Schema version of the source database the export checked before reading it: the redb module version on
/// PostgreSQL and SQL Server (e.g. "0.7.33" ), the file schema version on SQLite (e.g. "17" ).
/// null in a file written by an earlier version, which did not record it; the import does not require it.
///
public string? SourceSchema { get; init; }
///
/// Scheme identifiers that were exported.
/// An empty array means all schemes were included.
///
public long[] SchemeIds { get; init; } = [];
/// Optional human-readable description of the export.
public string? Description { get; init; }
}
Path: redb/redb.Export/Models/ExportRecord.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.Export/Models/ExportRecord.cs
----
using System.Text.Json.Serialization;
namespace redb.Export.Models;
///
/// Abstract base class for all data records in a .redb JSONL stream.
/// Each concrete subclass maps to one REDB database table.
/// JSON polymorphism is handled via the "type" discriminator property.
///
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(TypeRecord), "type")]
[JsonDerivedType(typeof(RoleRecord), "role")]
[JsonDerivedType(typeof(UserRecord), "user")]
[JsonDerivedType(typeof(UserRoleRecord), "user_role")]
[JsonDerivedType(typeof(ListRecord), "list")]
[JsonDerivedType(typeof(ListItemRecord), "list_item")]
[JsonDerivedType(typeof(SchemeRecord), "scheme")]
[JsonDerivedType(typeof(StructureRecord), "structure")]
[JsonDerivedType(typeof(MigrationRecord), "migration")]
[JsonDerivedType(typeof(ObjectRecord), "object")]
[JsonDerivedType(typeof(PermissionRecord), "permission")]
[JsonDerivedType(typeof(ValueRecord), "value")]
public abstract class ExportRecord
{
}
///
/// Represents a row from the _types table (REDB type definition).
///
public sealed class TypeRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Type name.
public string Name { get; init; } = "";
/// Database-specific type name (e.g. "bigint" ).
public string? DbType { get; init; }
/// .NET CLR type name (e.g. "System.Int64" ).
public string? DotnetType { get; init; }
}
///
/// Represents a row from the _roles table.
///
public sealed class RoleRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Role name.
public string Name { get; init; } = "";
/// Optional configuration object reference.
public long? IdConfiguration { get; init; }
}
///
/// Represents a row from the _users table.
///
public sealed class UserRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Login (username).
public string Login { get; init; } = "";
/// Password hash.
public string Password { get; init; } = "";
/// Display name.
public string Name { get; init; } = "";
/// Phone number.
public string? Phone { get; init; }
/// E-mail address.
public string? Email { get; init; }
/// Registration timestamp.
public DateTimeOffset DateRegister { get; init; }
/// Dismissal timestamp (null if user is active).
public DateTimeOffset? DateDismiss { get; init; }
/// Whether the user account is enabled.
public bool Enabled { get; init; }
/// Optional numeric key.
public long? Key { get; init; }
/// Optional integer code.
public long? CodeInt { get; init; }
/// Optional string code.
public string? CodeString { get; init; }
/// Optional GUID code.
public Guid? CodeGuid { get; init; }
/// Free-text note.
public string? Note { get; init; }
/// Row hash for change tracking.
public Guid? Hash { get; init; }
/// Optional configuration object reference.
public long? IdConfiguration { get; init; }
}
///
/// Represents a row from the _users_roles junction table.
///
public sealed class UserRoleRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Foreign key to _roles .
public long IdRole { get; init; }
/// Foreign key to _users .
public long IdUser { get; init; }
}
///
/// Represents a row from the _lists table (enumeration/lookup list).
///
public sealed class ListRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// List display name.
public string Name { get; init; } = "";
/// Machine-friendly alias.
public string? Alias { get; init; }
}
///
/// Represents a row from the _list_items table.
///
public sealed class ListItemRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Foreign key to the parent _lists row.
public long IdList { get; init; }
/// Display value of the list item.
public string? Value { get; init; }
/// Machine-friendly alias.
public string? Alias { get; init; }
/// Optional object reference.
public long? IdObject { get; init; }
}
///
/// Represents a row from the _schemes table (schema/class definition).
///
public sealed class SchemeRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Parent scheme identifier (for inheritance).
public long? IdParent { get; init; }
/// Scheme name.
public string Name { get; init; } = "";
/// Machine-friendly alias.
public string? Alias { get; init; }
/// Namespace for code generation.
public string? NameSpace { get; init; }
/// Hash of the scheme structure for change detection.
public Guid? StructureHash { get; init; }
/// Scheme type discriminator (0 = normal, 1 = primitive, etc.).
public long SchemeType { get; init; }
/// Free-form marker of the scheme ([RedbTags] or written by an extension); null when unset.
public string? Tags { get; init; }
///
/// Previous names of the scheme, oldest first, as the JSON array text of _schemes._renamed_from ; null when
/// the scheme was never renamed, and in files written before the column existed.
///
public string? RenamedFrom { get; init; }
}
///
/// Represents a row from the _structures table (field/property definition).
///
public sealed class StructureRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Parent structure identifier (for nested fields).
public long? IdParent { get; init; }
/// Foreign key to the owning scheme.
public long IdScheme { get; init; }
/// Override reference for inherited fields.
public long? IdOverride { get; init; }
/// Foreign key to _types .
public long IdType { get; init; }
/// Foreign key to _lists (for enumeration-typed fields).
public long? IdList { get; init; }
/// Field name.
public string Name { get; init; } = "";
/// Machine-friendly alias.
public string? Alias { get; init; }
/// Display order within the scheme.
public long? Order { get; init; }
/// Whether the field is read-only.
public bool? Readonly { get; init; }
/// Whether the field requires a non-null value.
public bool? AllowNotNull { get; init; }
/// Collection type (0 = none, 1 = list, 2 = dictionary, etc.).
public long? CollectionType { get; init; }
/// Key type for dictionary-typed fields.
public long? KeyType { get; init; }
/// Whether the value is stored compressed.
public bool? IsCompress { get; init; }
/// Whether explicit NULLs are persisted.
public bool? StoreNull { get; init; }
/// Whether the field is a unique key within its scheme ([RedbUnique]).
public bool? Unique { get; init; }
/// Encoder version the stored keys were computed with.
public long? UniqueVersion { get; init; }
/// Whether the reference is lazy (`virtual` in the CLR model, V4).
public bool? Lazy { get; init; }
/// Element-key scope of a collection key (null = default, 1 = scheme elements, 2 = collection elements).
public long? UniqueScope { get; init; }
/// Free-form marker of the field ([RedbTags] or written by an extension); null when unset.
public string? Tags { get; init; }
///
/// Previous names of the field, oldest first, as the JSON array text of _structures._renamed_from ; null
/// when the field was never renamed, and in files written before the column existed.
///
public string? RenamedFrom { get; init; }
/// Serialized default value.
public byte[]? DefaultValue { get; init; }
/// Editor hint for UI generation.
public string? DefaultEditor { get; init; }
}
///
/// Represents a row from the _migrations table: one data migration applied to a scheme (redb Pro). The rows
/// tell a later migration run what the data already has, so an imported database does not get a migration twice.
/// Written after the structures; a database that never ran a migration writes none.
///
public sealed class MigrationRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Identifier of the migration within its scheme (e.g. "OrderProps_TotalPrice_v1" ).
public string MigrationId { get; init; } = "";
/// Scheme the migration was applied to.
public long SchemeId { get; init; }
/// Structure the migration changed; null for the whole scheme.
public long? StructureId { get; init; }
/// Name of the property the migration changed.
public string? PropertyName { get; init; }
/// Hash of the migration's expression, used to detect a changed migration.
public string? ExpressionHash { get; init; }
/// Kind of migration (e.g. "ComputedFrom" , "Transform" ).
public string MigrationType { get; init; } = "";
/// When the migration was applied.
public DateTimeOffset AppliedAt { get; init; }
/// Who applied the migration.
public string? AppliedBy { get; init; }
/// The statement the migration ran, kept for audit.
public string? SqlExecuted { get; init; }
/// Rows the migration changed.
public long? AffectedRows { get; init; }
/// How long the migration ran, in milliseconds.
public long? DurationMs { get; init; }
/// Whether the row records a dry run, which changed nothing.
public bool DryRun { get; init; }
}
///
/// Represents a row from the _objects table (entity instance).
///
public sealed class ObjectRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Parent object identifier (for tree structures).
public long? IdParent { get; init; }
/// Foreign key to the defining scheme.
public long IdScheme { get; init; }
/// Owner user identifier.
public long IdOwner { get; init; }
/// User who last modified the object.
public long IdWhoChange { get; init; }
/// Creation timestamp.
public DateTimeOffset DateCreate { get; init; }
/// Last modification timestamp.
public DateTimeOffset DateModify { get; init; }
/// Optional workflow start date.
public DateTimeOffset? DateBegin { get; init; }
/// Optional workflow completion date.
public DateTimeOffset? DateComplete { get; init; }
/// Optional numeric key.
public long? Key { get; init; }
/// Display name.
public string? Name { get; init; }
/// Free-text note.
public string? Note { get; init; }
/// Row hash for change tracking.
public Guid? Hash { get; init; }
// --- Primitive value columns for RedbPrimitive ---
/// Inline value (for primitive schemes).
public long? ValueLong { get; init; }
/// Inline value (for primitive schemes).
public string? ValueString { get; init; }
/// Inline value (for primitive schemes).
public Guid? ValueGuid { get; init; }
/// Inline value (for primitive schemes).
public bool? ValueBool { get; init; }
/// Inline value (for primitive schemes).
public double? ValueDouble { get; init; }
/// Inline value (for primitive schemes).
public decimal? ValueNumeric { get; init; }
/// Inline value (for primitive schemes).
public DateTimeOffset? ValueDatetime { get; init; }
/// Inline binary value (for primitive schemes).
public byte[]? ValueBytes { get; init; }
/// Unique key within the scheme (V4, UNIQUE stage 1).
public string? ValueUnique { get; init; }
}
///
/// Represents a row from the _permissions table.
///
public sealed class PermissionRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Role to which the permission applies (mutually exclusive with ).
public long? IdRole { get; init; }
/// User to which the permission applies (mutually exclusive with ).
public long? IdUser { get; init; }
/// Reference identifier (scheme or object) the permission targets.
public long IdRef { get; init; }
/// SELECT permission flag.
public bool? Select { get; init; }
/// INSERT permission flag.
public bool? Insert { get; init; }
/// UPDATE permission flag.
public bool? Update { get; init; }
/// DELETE permission flag.
public bool? Delete { get; init; }
}
///
/// Represents a row from the _values table (EAV property value).
/// Exactly one of the typed value columns is populated per row.
///
public sealed class ValueRecord : ExportRecord
{
/// Primary key.
public long Id { get; init; }
/// Foreign key to _structures .
public long IdStructure { get; init; }
/// Foreign key to _objects .
public long IdObject { get; init; }
/// String value.
public string? String { get; init; }
/// Integer value.
public long? Long { get; init; }
/// GUID value.
public Guid? Guid { get; init; }
/// Double-precision floating-point value.
public double? Double { get; init; }
/// Date/time value with timezone offset.
public DateTimeOffset? DateTimeOffset { get; init; }
/// Boolean value.
public bool? Boolean { get; init; }
/// Binary (byte array) value.
public byte[]? ByteArray { get; init; }
/// Decimal (numeric) value.
public decimal? Numeric { get; init; }
/// Foreign key to _list_items .
public long? ListItem { get; init; }
/// Foreign key to another _objects row (object reference).
public long? Object { get; init; }
/// Parent row identifier for array/collection elements.
public long? ArrayParentId { get; init; }
/// Index or key within an array/dictionary.
public string? ArrayIndex { get; init; }
///
/// Unique-key hash of a [RedbUnique] field (V4). Absent in pre-V4 exports: the
/// import then leaves _values._unique NULL, and the next scheme synchronisation
/// recomputes the keys from the stored values (rows with a value but no key are a
/// standing recompute trigger).
///
public Guid? Unique { get; init; }
}
Path: redb/redb.Export/Providers/ForeignKeyRefusal.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.Export/Providers/ForeignKeyRefusal.cs
----
namespace redb.Export.Providers;
///
/// The wording an import uses to refuse a file whose rows point at rows it does not hold, shared by the providers
/// that check the foreign keys themselves at the end of an import, so the same file is described the same way.
///
internal static class ForeignKeyRefusal
{
/// One line for one broken key.
/// The key: its name, or the referencing column where the database keeps no name.
/// The table whose rows point nowhere.
/// How many of its rows do.
/// The table the key points at.
/// The columns of that table the key points at.
/// One of the rows, as column = value pairs.
public static string Describe(string key, string table, long rows, string referencedTable,
IEnumerable referencedColumns, string example) =>
$"{key}: {rows} row(s) of {table} point at a missing row of {referencedTable} " +
$"({string.Join(", ", referencedColumns)}), for example {example}";
/// The exception that refuses the import.
/// The lines from .
/// What the refusal leaves in the database.
public static InvalidOperationException Exception(IReadOnlyCollection broken, string outcome) =>
new("The file holds references to rows it does not contain, and the database refuses them " +
"(a file exported with --schemes whose rows point into schemes left out is one way to get one):" +
Environment.NewLine + string.Join(Environment.NewLine, broken.Select(b => " " + b)) +
Environment.NewLine + outcome);
}
Path: redb/redb.Export/Providers/IDataProvider.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.Export/Providers/IDataProvider.cs
----
using System.Data.Common;
namespace redb.Export.Providers;
///
/// Abstracts database-specific operations required by the export/import pipeline.
///
/// Each implementation handles connection management, bulk-insert strategy,
/// constraint toggling, and sequence manipulation for its target RDBMS.
///
///
public interface IDataProvider : IAsyncDisposable
{
///
/// Short provider identifier (e.g. "postgres" , "mssql" ).
///
string Name { get; }
///
/// Opens a connection to the database using the supplied connection string.
///
/// ADO.NET connection string.
/// Cancellation token.
Task OpenAsync(string connectionString, CancellationToken ct = default);
///
/// Returns the underlying instance.
/// Must be called after .
///
DbConnection Connection { get; }
///
/// Truncates all REDB tables in the correct foreign-key order, leaving the schema intact.
///
/// Cancellation token.
Task CleanDatabaseAsync(CancellationToken ct = default);
///
/// Returns the current value of the global_identity sequence.
///
/// Cancellation token.
Task GetSequenceValueAsync(CancellationToken ct = default);
///
/// Resets the global_identity sequence to the specified value
/// (typically the value stored in the export footer).
///
/// New sequence value.
/// Cancellation token.
Task SetSequenceValueAsync(long value, CancellationToken ct = default);
// Contract of the pair: GetSequenceValueAsync returns the LAST id handed out, and SetSequenceValueAsync(v) makes
// the NEXT id handed out v + 1. SQL Server's RESTART WITH names the next value itself, so it restarts at v + 1
// (review 2026-09-24: it restarted at v, and the first object saved after an import took an id already in use).
///
/// Starts the import transaction. Everything the import writes from here on - cleaning, rows, the
/// sequence, the constraint mode - commits or rolls back as one: an import that fails half-way (a broken
/// file, a cancelled run, a server error) leaves the database as it was, cleaning included.
///
/// Cancellation token.
Task BeginImportAsync(CancellationToken ct = default);
/// Commits the import transaction and restores the session state the import changed.
/// Cancellation token.
Task CommitImportAsync(CancellationToken ct = default);
///
/// Rolls back whatever the import wrote and restores the session state it changed. Called on every path
/// that did not commit; does nothing after a commit.
///
Task AbortImportAsync();
///
/// Disables foreign-key constraints and triggers so that rows can be
/// bulk-inserted in arbitrary order.
///
/// Cancellation token.
Task DisableConstraintsAsync(CancellationToken ct = default);
///
/// Re-enables foreign-key constraints and triggers after bulk import.
///
/// Cancellation token.
Task EnableConstraintsAsync(CancellationToken ct = default);
///
/// Performs a bulk insert of the supplied
/// into the specified database table using the most efficient provider-specific mechanism
/// (e.g. COPY FROM STDIN for PostgreSQL, SqlBulkCopy for SQL Server).
///
/// Target table name (e.g. "_objects" ).
/// Data to insert.
/// Cancellation token.
Task BulkInsertAsync(string tableName, System.Data.DataTable data, CancellationToken ct = default);
///
/// Executes a statement that returns no rows (DDL included). Inside an import it runs in the
/// import transaction, so it commits or rolls back with everything else the import wrote.
///
/// Statement text in the provider's dialect.
/// Cancellation token.
Task ExecuteAsync(string sql, CancellationToken ct = default);
///
/// Reads a date column of a redb table into its portable form.
/// PostgreSQL and SQL Server store these columns natively. SQLite stores them as a UTC Julian
/// day (REAL), and the number has to be decoded the way the redb SQLite provider decodes it.
/// The write side of the same seam is , which stores a
/// in the form the provider reads.
///
/// Reader positioned on a row.
/// Ordinal of a non-null date column.
DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal);
///
/// Reads a uuid-semantic column value into its portable form.
/// PostgreSQL/MSSQL store these columns natively; SQLite stores them as a 16-byte BLOB in
/// RFC 4122 (text) order - _users._hash , _schemes._structure_hash ,
/// _objects._hash , _values._unique . Reading such a BLOB through the driver's
/// GetGuid would byte-swap the first three groups; this seam keeps the JSONL canonical.
/// Genuine binary columns (_value_bytes , _values._ByteArray ) are NOT uuids and
/// never go through this conversion.
///
Guid GuidFromDb(object raw);
///
/// Converts a portable into the value this provider stores in a
/// uuid-semantic column (see ): the itself for
/// PostgreSQL/MSSQL, the RFC 4122-ordered 16-byte BLOB for SQLite.
///
object GuidToDb(Guid value);
}
Path: redb/redb.Export/Providers/IParallelImportProvider.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.Export/Providers/IParallelImportProvider.cs
----
namespace redb.Export.Providers;
///
/// What a provider needs to offer for an import that writes over several connections at once.
///
/// The ordinary import is one connection and one transaction: it either lands whole or leaves the
/// database as it was. The parallel import trades that guarantee for speed. Rows go in over N
/// connections that commit on their own, and the secondary indexes of the large tables are dropped
/// before the load and built again after it, because maintaining them row by row is what makes a
/// large import slow. A parallel import that stops half-way leaves a partly loaded database; the
/// definitions of the dropped indexes are kept in the database itself so that the next run, or the
/// operator, can put them back.
///
public interface IParallelImportProvider
{
///
/// Opens one more connection to the same database, set up for loading: no transaction, and
/// foreign key checks off for the whole session, since parents and children arrive in any order.
///
Task OpenWorkerAsync(CancellationToken ct = default);
///
/// Drops the secondary indexes of the large tables and returns the statements that create them
/// again. The statements are stored in the database first, so a run that dies after this call
/// loses no index definition; a later call returns the stored ones together with whatever it
/// drops itself. Indexes that back a constraint (primary keys, UNIQUE) are left in place.
///
Task> DropLoadIndexesAsync(CancellationToken ct = default);
/// Creates one index from the statement returned.
Task CreateIndexAsync(DroppedIndex index, CancellationToken ct = default);
/// Removes the stored definitions once every index is back.
Task ForgetDroppedIndexesAsync(CancellationToken ct = default);
///
/// Switches off foreign key checks and triggers for the load where that is a setting of the
/// database and not of a session. A provider whose workers do it for themselves in
/// has nothing to do here.
///
Task RelaxConstraintsForLoadAsync(CancellationToken ct = default);
///
/// Undoes once the rows and the indexes are in, and
/// has the database check the loaded rows against the foreign keys again.
///
Task RestoreConstraintsAfterLoadAsync(CancellationToken ct = default);
///
/// False when two index builds on the same table must not run side by side; the indexes of a
/// table are then built one after another, and only different tables in parallel.
///
bool BuildsIndexesOfOneTableConcurrently { get; }
}
/// An index dropped for the duration of a load, with the statement that creates it again.
/// Index name.
/// Table it belongs to.
/// Complete CREATE INDEX statement.
public sealed record DroppedIndex(string Name, string Table, string Definition);
Path: redb/redb.Export/Providers/MssqlProvider.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.Export/Providers/MssqlProvider.cs
----
using System.Data.Common;
using Microsoft.Data.SqlClient;
namespace redb.Export.Providers;
///
/// implementation for Microsoft SQL Server.
///
/// Uses for high-throughput inserts and
/// sp_MSforeachtable to toggle constraints and triggers during import.
///
///
public sealed class MssqlProvider : IDataProvider, IParallelImportProvider
{
private SqlConnection? _connection;
private string? _connectionString;
private SqlTransaction? _transaction;
///
public async Task BeginImportAsync(CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
if (_transaction is not null) throw new InvalidOperationException("An import transaction is already open.");
// NOCHECK / DISABLE TRIGGER, TRUNCATE, SqlBulkCopy and ALTER SEQUENCE all take part in a SQL Server
// transaction: a rollback also re-enables what the import disabled.
_transaction = (SqlTransaction)await _connection.BeginTransactionAsync(ct);
}
///
public async Task CommitImportAsync(CancellationToken ct = default)
{
if (_transaction is null) throw new InvalidOperationException("No import transaction is open.");
await _transaction.CommitAsync(ct);
await _transaction.DisposeAsync();
_transaction = null;
}
///
public async Task AbortImportAsync()
{
if (_transaction is null) return;
// A severe server error may already have rolled the transaction back; its connection then reports none.
if (_transaction.Connection is not null)
await _transaction.RollbackAsync();
await _transaction.DisposeAsync();
_transaction = null;
}
///
public string Name => "mssql";
///
public DbConnection Connection => _connection
?? throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
///
public async Task OpenAsync(string connectionString, CancellationToken ct = default)
{
_connectionString = connectionString;
_connection = new SqlConnection(connectionString);
await _connection.OpenAsync(ct);
}
///
public async Task CleanDatabaseAsync(CancellationToken ct = default)
{
if (_connection is null) return;
var tables = new[]
{
"_values",
"_list_items",
"_objects",
"_permissions",
"_functions",
"_dependencies",
"_migrations",
"_structures",
"_schemes",
"_users_roles",
"_users",
"_roles",
"_lists",
"_links"
// _types is kept: the built-in types of this build; ImportService adds only the file's types the target lacks.
};
// Disable triggers and FK checks before truncation. Only the triggers that are on, and only those back on after:
// the schema keeps some off (tr_auto_create_node_permissions), and ENABLE TRIGGER ALL switched them on.
await using (var cmd = new SqlCommand(
"EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'", _connection, _transaction))
{
await cmd.ExecuteNonQueryAsync(ct);
}
var enabledTriggers = await ReadEnabledTriggersAsync(ct);
await SetTriggersAsync(enabledTriggers, enable: false, ct);
foreach (var table in tables)
{
// TRUNCATE is refused for a table any foreign key points at, disabled or not, so those are emptied
// with DELETE - decided from the catalog, not by trying and swallowing the error: the old empty
// catch also swallowed a lock timeout or a missing permission, the table stayed full, and the import
// went on to mix old and new rows (review 2026-09-24). Any failure now fails the import, and the
// import transaction undoes the cleaning.
await using var referenced = new SqlCommand(
"SELECT CASE WHEN EXISTS (SELECT 1 FROM sys.foreign_keys WHERE referenced_object_id = OBJECT_ID(@table)) THEN 1 ELSE 0 END",
_connection, _transaction);
referenced.Parameters.AddWithValue("@table", "dbo." + table);
var isReferenced = Convert.ToInt32(await referenced.ExecuteScalarAsync(ct)) == 1;
await using var cmd = new SqlCommand(
isReferenced ? $"DELETE FROM {table}" : $"TRUNCATE TABLE {table}", _connection, _transaction);
await cmd.ExecuteNonQueryAsync(ct);
}
// Re-enable the triggers that were on, and the FK checks.
await SetTriggersAsync(enabledTriggers, enable: true, ct);
await using (var cmd = new SqlCommand(
"EXEC sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL'", _connection, _transaction))
{
await cmd.ExecuteNonQueryAsync(ct);
}
}
///
public async Task GetSequenceValueAsync(CancellationToken ct = default)
{
if (_connection is null) return 0;
const string sql = "SELECT CAST(current_value AS BIGINT) FROM sys.sequences WHERE name = 'global_identity'";
await using var cmd = new SqlCommand(sql, _connection, _transaction);
var result = await cmd.ExecuteScalarAsync(ct);
return result is null ? 0 : Convert.ToInt64(result);
}
///
public async Task SetSequenceValueAsync(long value, CancellationToken ct = default)
{
if (_connection is null) return;
await using var cmd = new SqlCommand($"ALTER SEQUENCE global_identity RESTART WITH {value + 1}", _connection, _transaction);
await cmd.ExecuteNonQueryAsync(ct);
}
///
public async Task DisableConstraintsAsync(CancellationToken ct = default)
{
if (_connection is null) return;
await using var cmd1 = new SqlCommand(
"EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'", _connection, _transaction) { CommandTimeout = 0 };
await cmd1.ExecuteNonQueryAsync(ct);
// The triggers that are on are written down before they go off, in a table of the database: a parallel load
// that dies half-way leaves them off, and the next run must still know which to turn on again. A trigger the
// schema keeps off is not on the list and stays off.
await using (var remember = new SqlCommand($"""
IF OBJECT_ID(N'dbo.{DisabledTriggersTable}', N'U') IS NULL
CREATE TABLE dbo.{DisabledTriggersTable} (table_name sysname NOT NULL, trigger_name sysname NOT NULL,
CONSTRAINT PK_{DisabledTriggersTable} PRIMARY KEY (table_name, trigger_name));
""", _connection, _transaction))
{
await remember.ExecuteNonQueryAsync(ct);
}
var enabled = await ReadEnabledTriggersAsync(ct);
foreach (var (table, trigger) in enabled)
{
await using var insert = new SqlCommand($"""
IF NOT EXISTS (SELECT 1 FROM dbo.{DisabledTriggersTable} WHERE table_name = @table AND trigger_name = @trigger)
INSERT INTO dbo.{DisabledTriggersTable} (table_name, trigger_name) VALUES (@table, @trigger)
""", _connection, _transaction);
insert.Parameters.AddWithValue("@table", table);
insert.Parameters.AddWithValue("@trigger", trigger);
await insert.ExecuteNonQueryAsync(ct);
}
await SetTriggersAsync(enabled, enable: false, ct);
}
///
public async Task EnableConstraintsAsync(CancellationToken ct = default)
{
if (_connection is null) return;
// Exactly the triggers DisableConstraintsAsync turned off, this run's or a dead run's.
var disabled = new List<(string Table, string Trigger)>();
await using (var read = new SqlCommand($"""
IF OBJECT_ID(N'dbo.{DisabledTriggersTable}', N'U') IS NOT NULL
SELECT table_name, trigger_name FROM dbo.{DisabledTriggersTable}
""", _connection, _transaction))
await using (var reader = await read.ExecuteReaderAsync(ct))
{
while (await reader.ReadAsync(ct))
disabled.Add((reader.GetString(0), reader.GetString(1)));
}
await SetTriggersAsync(disabled, enable: true, ct);
await using (var drop = new SqlCommand(
$"IF OBJECT_ID(N'dbo.{DisabledTriggersTable}', N'U') IS NOT NULL DROP TABLE dbo.{DisabledTriggersTable}",
_connection, _transaction))
{
await drop.ExecuteNonQueryAsync(ct);
}
await using var cmd2 = new SqlCommand(
"EXEC sp_MSforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'", _connection, _transaction) { CommandTimeout = 0 };
await cmd2.ExecuteNonQueryAsync(ct);
}
///
/// Options of every bulk load: the rows land exactly as the writer gives them. KeepIdentity keeps a written key
/// in an IDENTITY column instead of a generated one, KeepNulls keeps a written null instead of the column's
/// default. Constraint checks and triggers stay off on purpose: an import turns both off for the load and checks
/// every constraint in one pass afterwards ( ), and a flat export adds its
/// foreign keys after the rows. No table lock: parallel workers load the same table at once.
///
private const SqlBulkCopyOptions BulkCopyOptions = SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.KeepNulls;
///
public async Task BulkInsertAsync(string tableName, System.Data.DataTable data, CancellationToken ct = default)
{
if (_connection is null || data.Rows.Count == 0) return;
using var bulkCopy = new SqlBulkCopy(_connection, BulkCopyOptions, _transaction)
{
DestinationTableName = tableName,
BatchSize = 5000,
BulkCopyTimeout = 600
};
foreach (System.Data.DataColumn col in data.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
await bulkCopy.WriteToServerAsync(data, ct);
}
///
public async Task ExecuteAsync(string sql, CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
await using var cmd = new SqlCommand(sql, _connection, _transaction);
await cmd.ExecuteNonQueryAsync(ct);
}
// ===== Parallel import =====
/// Tables large enough for their secondary indexes to dominate the load.
private static readonly string[] LoadTables = ["_values", "_objects"];
///
public async Task OpenWorkerAsync(CancellationToken ct = default)
{
if (_connectionString is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
// Nothing to set on the session: SqlBulkCopy neither checks foreign keys nor fires triggers
// unless asked to, and what it skipped is checked once at the end by
// RestoreConstraintsAfterLoadAsync.
var worker = new MssqlProvider();
await worker.OpenAsync(_connectionString, ct);
return worker;
}
///
/// Disables the secondary indexes of the large tables and returns the statements that rebuild them.
/// A disabled index keeps its definition in the catalog, so nothing has to be stored elsewhere and
/// a run that died half-way loses nothing: the next call finds the indexes still disabled and
/// returns them with the rest. Left alone: the clustered index (disabling it takes the table
/// offline), indexes that back a PRIMARY KEY or UNIQUE constraint, and any index a foreign key
/// resolves through (disabling it would disable that foreign key).
///
public async Task> DropLoadIndexesAsync(CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
var indexes = new List<(string Name, string Table, bool Disabled)>();
await using (var read = new SqlCommand($"""
SELECT i.name, t.name, i.is_disabled
FROM sys.indexes i
JOIN sys.tables t ON t.object_id = i.object_id
WHERE SCHEMA_NAME(t.schema_id) = 'dbo'
AND t.name IN ({string.Join(", ", LoadTables.Select(n => "'" + n + "'"))})
AND i.type = 2
AND i.is_primary_key = 0
AND i.is_unique_constraint = 0
AND NOT EXISTS (SELECT 1 FROM sys.foreign_keys f
WHERE f.referenced_object_id = i.object_id AND f.key_index_id = i.index_id)
ORDER BY t.name, i.name
""", _connection))
await using (var reader = await read.ExecuteReaderAsync(ct))
{
while (await reader.ReadAsync(ct))
indexes.Add((reader.GetString(0), reader.GetString(1), reader.GetBoolean(2)));
}
var disabled = new List();
foreach (var (name, table, alreadyDisabled) in indexes)
{
var target = $"{QuoteIdentifier(name)} ON [dbo].{QuoteIdentifier(table)}";
if (!alreadyDisabled)
{
await using var disable = new SqlCommand($"ALTER INDEX {target} DISABLE", _connection) { CommandTimeout = 0 };
await disable.ExecuteNonQueryAsync(ct);
}
disabled.Add(new DroppedIndex(name, table, $"ALTER INDEX {target} REBUILD"));
}
return disabled;
}
///
public async Task CreateIndexAsync(DroppedIndex index, CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
// A rebuild over tens of millions of rows outlives any ordinary command timeout.
await using var cmd = new SqlCommand(index.Definition, _connection) { CommandTimeout = 0 };
await cmd.ExecuteNonQueryAsync(ct);
}
///
// The catalog itself says which indexes are still disabled; there is nothing kept to forget.
public Task ForgetDroppedIndexesAsync(CancellationToken ct = default) => Task.CompletedTask;
///
public Task RelaxConstraintsForLoadAsync(CancellationToken ct = default) => DisableConstraintsAsync(ct);
///
// WITH CHECK CHECK CONSTRAINT reads every loaded row against its foreign keys; on a large
// database that is minutes, and it is what makes the constraints trusted again.
public Task RestoreConstraintsAfterLoadAsync(CancellationToken ct = default) => EnableConstraintsAsync(ct);
///
// An offline index rebuild ends by taking a schema-modification lock on the table; two of them
// on one table wait for each other.
public bool BuildsIndexesOfOneTableConcurrently => false;
private static string QuoteIdentifier(string identifier) => "[" + identifier.Replace("]", "]]") + "]";
/// The triggers an import turned off, kept until it turns them on again (see ).
private const string DisabledTriggersTable = "_import_disabled_triggers";
/// The table triggers of dbo that are on, as (table, trigger).
private async Task> ReadEnabledTriggersAsync(CancellationToken ct)
{
var triggers = new List<(string Table, string Trigger)>();
await using var read = new SqlCommand("""
SELECT OBJECT_NAME(parent_id), name FROM sys.triggers
WHERE parent_class = 1 AND is_disabled = 0 AND OBJECT_SCHEMA_NAME(parent_id) = 'dbo'
ORDER BY 1, 2
""", _connection, _transaction);
await using var reader = await read.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
triggers.Add((reader.GetString(0), reader.GetString(1)));
return triggers;
}
private async Task SetTriggersAsync(IEnumerable<(string Table, string Trigger)> triggers, bool enable, CancellationToken ct)
{
foreach (var (table, trigger) in triggers)
{
await using var cmd = new SqlCommand(
$"ALTER TABLE [dbo].{QuoteIdentifier(table)} {(enable ? "ENABLE" : "DISABLE")} TRIGGER {QuoteIdentifier(trigger)}",
_connection, _transaction) { CommandTimeout = 0 };
await cmd.ExecuteNonQueryAsync(ct);
}
}
///
public async ValueTask DisposeAsync()
{
if (_connection is not null)
{
await _connection.DisposeAsync();
}
}
///
public DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal) =>
reader.GetFieldValue(ordinal);
///
public Guid GuidFromDb(object raw) => (Guid)raw;
///
public object GuidToDb(Guid value) => value;
}
Path: redb/redb.Export/Providers/PostgresProvider.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.Export/Providers/PostgresProvider.cs
----
using System.Data.Common;
using Npgsql;
namespace redb.Export.Providers;
///
/// implementation for PostgreSQL.
///
/// Uses COPY FROM STDIN (TEXT format) for bulk inserts and
/// session_replication_role = 'replica' to bypass foreign-key triggers
/// during import.
///
///
public sealed class PostgresProvider : IDataProvider, IParallelImportProvider
{
private NpgsqlConnection? _connection;
private string? _connectionString;
private NpgsqlTransaction? _transaction;
/// The redb tables an import writes, dependents before parents (the order cleaning needs).
private static readonly string[] RedbTables =
[
"_values",
"_list_items",
"_objects",
"_permissions",
"_functions",
"_dependencies",
"_migrations",
"_structures",
"_schemes",
"_users_roles",
"_users",
"_roles",
"_lists",
"_links",
"_types"
];
///
public async Task BeginImportAsync(CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
if (_transaction is not null) throw new InvalidOperationException("An import transaction is already open.");
// DDL, TRUNCATE and COPY are all transactional on PostgreSQL, and the constraint mode is SET LOCAL:
// a rollback leaves nothing behind, not even the relaxed constraints.
_transaction = await _connection.BeginTransactionAsync(ct);
}
///
public async Task CommitImportAsync(CancellationToken ct = default)
{
if (_transaction is null) throw new InvalidOperationException("No import transaction is open.");
await _transaction.CommitAsync(ct);
await _transaction.DisposeAsync();
_transaction = null;
}
///
/// The planner statistics of the redb tables an import wrote, and of no other table of the database: COPY leaves
/// them without statistics until autoanalyze reaches them (see ImportFinishing.AnalyzeAsync).
///
public async Task AnalyzeRedbTablesAsync(CancellationToken ct = default)
{
await using var command = Connection.CreateCommand();
command.CommandText = "ANALYZE " + string.Join(", ", RedbTables);
command.CommandTimeout = 0;
await command.ExecuteNonQueryAsync(ct);
}
///
public async Task AbortImportAsync()
{
if (_transaction is null) return;
await _transaction.RollbackAsync();
await _transaction.DisposeAsync();
_transaction = null;
}
///
public string Name => "postgres";
///
public DbConnection Connection => _connection
?? throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
///
public async Task OpenAsync(string connectionString, CancellationToken ct = default)
{
_connectionString = connectionString;
_connection = new NpgsqlConnection(connectionString);
await _connection.OpenAsync(ct);
}
///
public async Task CleanDatabaseAsync(CancellationToken ct = default)
{
if (_connection is null) return;
// The target keeps its own _types rows: they are the built-in types of this build (the file may carry those of an
// older one), and ImportService adds only the file's types the target lacks.
foreach (var table in RedbTables.Where(t => t != "_types"))
{
await using var cmd = new NpgsqlCommand($"TRUNCATE TABLE {table} CASCADE", _connection, _transaction);
await cmd.ExecuteNonQueryAsync(ct);
}
}
///
public async Task GetSequenceValueAsync(CancellationToken ct = default)
{
if (_connection is null) return 0;
await using var cmd = new NpgsqlCommand("SELECT last_value FROM global_identity", _connection, _transaction);
var result = await cmd.ExecuteScalarAsync(ct);
return Convert.ToInt64(result);
}
///
public async Task SetSequenceValueAsync(long value, CancellationToken ct = default)
{
if (_connection is null) return;
await using var cmd = new NpgsqlCommand($"SELECT setval('global_identity', {value})", _connection, _transaction);
await cmd.ExecuteNonQueryAsync(ct);
}
///
public async Task DisableConstraintsAsync(CancellationToken ct = default)
{
if (_connection is null) return;
await using var cmd = new NpgsqlCommand(
"SET LOCAL session_replication_role = 'replica'", _connection, _transaction);
await cmd.ExecuteNonQueryAsync(ct);
}
///
public async Task EnableConstraintsAsync(CancellationToken ct = default)
{
if (_connection is null) return;
await using var cmd = new NpgsqlCommand(
"SET LOCAL session_replication_role = 'origin'", _connection, _transaction);
await cmd.ExecuteNonQueryAsync(ct);
// The rows went in with the foreign key triggers off, and switching them back on checks nothing that is
// already there. SQL Server re-checks every key at this point; the same file must not load with broken
// references here and be refused there. Inside the import transaction, so a refusal rolls everything back.
await CheckForeignKeysAsync(_transaction, "Nothing was imported; the database is unchanged.", ct);
}
///
public async Task BulkInsertAsync(string tableName, System.Data.DataTable data, CancellationToken ct = default)
{
if (_connection is null || data.Rows.Count == 0) return;
var columns = string.Join(", ", data.Columns.Cast().Select(c => c.ColumnName));
var copyCommand = $"COPY {tableName} ({columns}) FROM STDIN (FORMAT TEXT, NULL '\\N')";
await using var writer = await _connection.BeginTextImportAsync(copyCommand, ct);
foreach (System.Data.DataRow row in data.Rows)
{
var values = new List();
for (int i = 0; i < data.Columns.Count; i++)
{
values.Add(FormatValueForCopy(row[i]));
}
await writer.WriteLineAsync(string.Join("\t", values));
}
}
///
public async Task ExecuteAsync(string sql, CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
await using var cmd = new NpgsqlCommand(sql, _connection, _transaction);
await cmd.ExecuteNonQueryAsync(ct);
}
// ===== Parallel import =====
/// Tables large enough for their secondary indexes to dominate the load.
private static readonly string[] LoadTables = ["_values", "_objects"];
/// Where the definitions of the dropped indexes live until every index is back.
private const string DroppedIndexesTable = "_import_dropped_indexes";
///
public async Task OpenWorkerAsync(CancellationToken ct = default)
{
if (_connectionString is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
var worker = new PostgresProvider();
await worker.OpenAsync(_connectionString, ct);
// Session-wide, not SET LOCAL: a worker has no transaction of its own to scope it to.
await worker.ExecuteAsync("SET session_replication_role = 'replica'", ct);
return worker;
}
///
public async Task> DropLoadIndexesAsync(CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
// One transaction: the definitions are written and the indexes dropped together, so there is
// no moment at which an index is gone and its definition is nowhere.
await using var transaction = await _connection.BeginTransactionAsync(ct);
await using (var create = new NpgsqlCommand(
$"CREATE TABLE IF NOT EXISTS {DroppedIndexesTable} (name text PRIMARY KEY, table_name text NOT NULL, definition text NOT NULL)",
_connection, transaction))
{
await create.ExecuteNonQueryAsync(ct);
}
// Every index of the load tables that no constraint stands on. A unique index without a
// constraint is dropped too: building it again checks the uniqueness of everything loaded.
await using (var remember = new NpgsqlCommand($"""
INSERT INTO {DroppedIndexesTable} (name, table_name, definition)
SELECT i.relname, t.relname, pg_get_indexdef(x.indexrelid)
FROM pg_index x
JOIN pg_class i ON i.oid = x.indexrelid
JOIN pg_class t ON t.oid = x.indrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE n.nspname = current_schema()
AND t.relname = ANY(@tables)
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = x.indexrelid)
ON CONFLICT (name) DO NOTHING
""", _connection, transaction))
{
remember.Parameters.AddWithValue("tables", LoadTables);
await remember.ExecuteNonQueryAsync(ct);
}
var dropped = new List();
await using (var read = new NpgsqlCommand(
$"SELECT name, table_name, definition FROM {DroppedIndexesTable} ORDER BY table_name, name", _connection, transaction))
await using (var reader = await read.ExecuteReaderAsync(ct))
{
while (await reader.ReadAsync(ct))
dropped.Add(new DroppedIndex(reader.GetString(0), reader.GetString(1), reader.GetString(2)));
}
foreach (var index in dropped)
{
await using var drop = new NpgsqlCommand(
$"DROP INDEX IF EXISTS {QuoteIdentifier(index.Name)}", _connection, transaction);
await drop.ExecuteNonQueryAsync(ct);
}
await transaction.CommitAsync(ct);
return dropped;
}
///
public async Task CreateIndexAsync(DroppedIndex index, CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
// pg_get_indexdef returns a plain CREATE INDEX. IF NOT EXISTS makes a repeated run harmless.
var statement = index.Definition.StartsWith("CREATE UNIQUE INDEX ", StringComparison.Ordinal)
? "CREATE UNIQUE INDEX IF NOT EXISTS " + index.Definition["CREATE UNIQUE INDEX ".Length..]
: "CREATE INDEX IF NOT EXISTS " + index.Definition["CREATE INDEX ".Length..];
// An index build over tens of millions of rows outlives any ordinary command timeout.
await using var cmd = new NpgsqlCommand(statement, _connection) { CommandTimeout = 0 };
await cmd.ExecuteNonQueryAsync(ct);
}
///
public async Task ForgetDroppedIndexesAsync(CancellationToken ct = default)
{
if (_connection is null) return;
await using var cmd = new NpgsqlCommand($"DROP TABLE IF EXISTS {DroppedIndexesTable}", _connection);
await cmd.ExecuteNonQueryAsync(ct);
}
///
// Each worker relaxes its own session in OpenWorkerAsync; nothing is switched off for the database.
public Task RelaxConstraintsForLoadAsync(CancellationToken ct = default) => Task.CompletedTask;
///
// The workers' sessions are closed, so nothing is to be switched back on; what remains is to check the loaded
// rows against the foreign keys, as the serial import does. The rows are committed by now and stay.
public Task RestoreConstraintsAfterLoadAsync(CancellationToken ct = default) =>
CheckForeignKeysAsync(null,
"The parallel import has already written its rows, these references included: fix the file and run it again with --clean.",
ct);
///
/// Checks the rows of the redb tables against every foreign key they carry, one anti-join per key read from
/// pg_constraint , and refuses the import when a row points at a row that is not there. The message names
/// each broken key, how many rows break it and one of them.
///
private async Task CheckForeignKeysAsync(NpgsqlTransaction? transaction, string outcome, CancellationToken ct)
{
if (_connection is null) return;
var keys = new List();
await using (var read = new NpgsqlCommand("""
SELECT c.conname::text, t.relname::text, p.relname::text,
ARRAY(SELECT a.attname::text FROM unnest(c.conkey) WITH ORDINALITY k(n, i)
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.n ORDER BY k.i),
ARRAY(SELECT a.attname::text FROM unnest(c.confkey) WITH ORDINALITY k(n, i)
JOIN pg_attribute a ON a.attrelid = c.confrelid AND a.attnum = k.n ORDER BY k.i),
EXISTS (SELECT 1 FROM pg_attribute a
WHERE a.attrelid = c.conrelid AND a.attname = '_id' AND NOT a.attisdropped)
FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
JOIN pg_class p ON p.oid = c.confrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE c.contype = 'f'
AND n.nspname = current_schema()
AND t.relname = ANY(@tables)
ORDER BY t.relname, c.conname
""", _connection, transaction))
{
read.Parameters.AddWithValue("tables", RedbTables);
await using var reader = await read.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
keys.Add(new ForeignKey(reader.GetString(0), reader.GetString(1), reader.GetString(2),
reader.GetFieldValue(3), reader.GetFieldValue(4), reader.GetBoolean(5)));
}
var broken = new List();
foreach (var key in keys)
{
// MATCH SIMPLE, as the key itself: a row with a null in any of its columns is not checked.
var notNull = string.Join(" AND ", key.Columns.Select(c => $"c.{QuoteIdentifier(c)} IS NOT NULL"));
var match = string.Join(" AND ", key.Columns.Zip(key.ReferencedColumns,
(c, r) => $"p.{QuoteIdentifier(r)} = c.{QuoteIdentifier(c)}"));
var sample = string.Join(" || ', ' || ",
key.Columns.Select(c => $"'{c} = ' || c.{QuoteIdentifier(c)}::text"));
if (key.ChildHasId)
sample = "'_id = ' || c._id::text || ', ' || " + sample;
// An anti-join over a large table outlives any ordinary command timeout, like an index build.
await using var check = new NpgsqlCommand($"""
SELECT count(*) OVER (), {sample}
FROM {QuoteIdentifier(key.Table)} c
WHERE {notNull}
AND NOT EXISTS (SELECT 1 FROM {QuoteIdentifier(key.ReferencedTable)} p WHERE {match})
LIMIT 1
""", _connection, transaction) { CommandTimeout = 0 };
await using var reader = await check.ExecuteReaderAsync(ct);
if (await reader.ReadAsync(ct))
broken.Add(ForeignKeyRefusal.Describe(key.Name, key.Table, reader.GetInt64(0),
key.ReferencedTable, key.ReferencedColumns, reader.GetString(1)));
}
if (broken.Count > 0)
throw ForeignKeyRefusal.Exception(broken, outcome);
}
/// A foreign key of a redb table, as pg_constraint describes it.
private sealed record ForeignKey(
string Name, string Table, string ReferencedTable, string[] Columns, string[] ReferencedColumns, bool ChildHasId);
///
// CREATE INDEX takes a lock that lets other index builds on the same table run.
public bool BuildsIndexesOfOneTableConcurrently => true;
private static string QuoteIdentifier(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\"";
///
/// Formats a CLR value for the PostgreSQL TEXT COPY protocol.
///
private static string FormatValueForCopy(object? value)
{
if (value is null or DBNull)
return "\\N";
return value switch
{
bool b => b ? "t" : "f",
DateTime dt => dt.ToString("yyyy-MM-dd HH:mm:ss.ffffff"),
DateTimeOffset dto => dto.ToString("yyyy-MM-dd HH:mm:ss.ffffffzzz"),
Guid g => g.ToString(),
byte[] bytes => "\\\\x" + Convert.ToHexString(bytes),
string s => EscapeCopyString(s),
decimal d => d.ToString(System.Globalization.CultureInfo.InvariantCulture),
double d => d.ToString(System.Globalization.CultureInfo.InvariantCulture),
float f => f.ToString(System.Globalization.CultureInfo.InvariantCulture),
_ => value.ToString() ?? "\\N"
};
}
///
/// Escapes special characters for the PostgreSQL TEXT COPY format.
///
private static string EscapeCopyString(string s)
{
return s
.Replace("\\", "\\\\")
.Replace("\t", "\\t")
.Replace("\n", "\\n")
.Replace("\r", "\\r");
}
///
public async ValueTask DisposeAsync()
{
if (_connection is not null)
{
await _connection.DisposeAsync();
}
}
///
public DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal) =>
reader.GetFieldValue(ordinal);
///
public Guid GuidFromDb(object raw) => (Guid)raw;
///
public object GuidToDb(Guid value) => value;
}
Path: redb/redb.Export/Providers/ProviderFactory.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.Export/Providers/ProviderFactory.cs
----
namespace redb.Export.Providers;
///
/// Factory that creates instances by provider name.
///
public static class ProviderFactory
{
///
/// Creates a new for the given provider name.
///
///
/// Case-insensitive provider name. Accepted values:
/// postgres , postgresql , pgsql ,
/// mssql , sqlserver , sqlite
/// (oracle is recognized but not implemented).
///
/// A new, unopened instance.
/// The provider is recognized but not yet implemented.
/// Unknown provider name.
public static IDataProvider Create(string providerName)
{
return providerName.ToLowerInvariant() switch
{
"postgres" or "postgresql" or "pgsql" => new PostgresProvider(),
"mssql" or "sqlserver" => new MssqlProvider(),
"oracle" => throw new NotSupportedException("Oracle provider is not implemented yet."),
"sqlite" => new SqliteProvider(),
_ => throw new ArgumentException($"Unknown provider: {providerName}", nameof(providerName))
};
}
///
/// Returns the list of all recognized provider names (including not-yet-implemented ones).
///
public static string[] SupportedProviders => ["postgres", "mssql", "oracle", "sqlite"];
}
Path: redb/redb.Export/Providers/SqliteJulianDay.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.Export/Providers/SqliteJulianDay.cs
----
namespace redb.Export.Providers;
///
/// The stored form of a date in a redb SQLite database: a UTC Julian day number (REAL), in
/// _objects._date_* , _objects._value_datetime , _users._date_* and
/// _values._DateTimeOffset .
///
/// A copy of redb.SQLite/Data/SqliteJulian.cs - same epoch, same millisecond rounding - because
/// this package does not reference the provider. The two must stay identical: the provider binds
/// every date parameter of a query as this number, and in SQLite a REAL never equals, and always
/// sorts before, a TEXT. A date written in any other form is invisible to every date filter.
///
///
internal static class SqliteJulianDay
{
// 1899-12-30 00:00 UTC.
private const double EpochJulianDay = 2415018.5;
private const long EpochMillis = 599264352000000000L / TimeSpan.TicksPerMillisecond;
private const double MillisPerDay = 86_400_000.0;
/// The UTC instant of as a Julian day.
public static double ToJulian(DateTimeOffset value)
{
var millis = value.UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond - EpochMillis;
return millis / MillisPerDay + EpochJulianDay;
}
/// A Julian day as a at +00:00, to the millisecond.
public static DateTimeOffset FromJulian(double julian)
{
var millis = (long)Math.Round((julian - EpochJulianDay) * MillisPerDay, MidpointRounding.AwayFromZero);
var ticks = (millis + EpochMillis) * TimeSpan.TicksPerMillisecond;
return new DateTimeOffset(new DateTime(ticks, DateTimeKind.Utc), TimeSpan.Zero);
}
}
Path: redb/redb.Export/Providers/SqliteProvider.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.Export/Providers/SqliteProvider.cs
----
using System.Data.Common;
using Microsoft.Data.Sqlite;
namespace redb.Export.Providers;
///
/// implementation for SQLite (via Microsoft.Data.Sqlite ).
///
/// SQLite has no TRUNCATE , no server-side sequences, and no bulk-copy protocol,
/// so this provider uses DELETE FROM for cleaning, the AUTOINCREMENT high-water
/// mark in sqlite_sequence (row _global_identity ) for the identity counter,
/// and batched parameterized INSERT s inside a single transaction for bulk import.
/// Foreign keys are toggled per-connection via PRAGMA foreign_keys (they default to
/// OFF in Microsoft.Data.Sqlite and must be enabled per connection, never inside a transaction).
///
///
public sealed class SqliteProvider : IDataProvider
{
///
/// Name of the AUTOINCREMENT table whose sqlite_sequence row holds the
/// global identity high-water mark. Must match the schema in redbSqlite.sql .
///
private const string SequenceName = "_global_identity";
///
/// The redb tables an import writes, dependents before parents. _scheme_metadata_cache is a derived cache
/// (no foreign keys); clearing it is safe, the runtime rebuilds it on the next scheme sync.
///
private static readonly string[] RedbTables =
[
"_values",
"_list_items",
"_objects",
"_permissions",
"_functions",
"_dependencies",
"_migrations",
"_structures",
"_schemes",
"_users_roles",
"_users",
"_roles",
"_lists",
"_links",
"_types",
"_scheme_metadata_cache"
];
private SqliteConnection? _connection;
private SqliteTransaction? _transaction;
///
public async Task BeginImportAsync(CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
if (_transaction is not null) throw new InvalidOperationException("An import transaction is already open.");
// Foreign keys can only be switched outside a transaction, so they go off before it begins and come back
// after it ends, whichever way it ends.
await ExecuteAsync("PRAGMA foreign_keys = OFF", ct);
_transaction = (SqliteTransaction)await _connection.BeginTransactionAsync(ct);
}
///
public async Task CommitImportAsync(CancellationToken ct = default)
{
if (_transaction is null) throw new InvalidOperationException("No import transaction is open.");
await _transaction.CommitAsync(ct);
await _transaction.DisposeAsync();
_transaction = null;
await ExecuteAsync("PRAGMA foreign_keys = ON", ct);
}
///
public async Task AbortImportAsync()
{
if (_transaction is null) return;
await _transaction.RollbackAsync();
await _transaction.DisposeAsync();
_transaction = null;
await ExecuteAsync("PRAGMA foreign_keys = ON", CancellationToken.None);
}
///
public string Name => "sqlite";
///
public DbConnection Connection => _connection
?? throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
///
public async Task OpenAsync(string connectionString, CancellationToken ct = default)
{
_connection = new SqliteConnection(connectionString);
await _connection.OpenAsync(ct);
}
///
public async Task CleanDatabaseAsync(CancellationToken ct = default)
{
if (_connection is null) return;
// SQLite has no TRUNCATE, so we DELETE. We deliberately do NOT touch sqlite_sequence: the
// _global_identity high-water mark must survive.
// Foreign keys are off for the whole import transaction (BeginImportAsync), so the order of the deletes
// does not matter. A table the schema does not have is skipped by the catalog, not by swallowing an
// error: the old catch also hid a locked database, and the import went on over a half-cleaned one.
// The target keeps its own _types rows: the built-in types of this build; ImportService adds only the file's types
// the target lacks.
foreach (var table in RedbTables.Where(t => t != "_types"))
{
if (!await TableExistsAsync(table, ct))
continue;
await ExecuteAsync($"DELETE FROM {table}", ct);
}
}
///
public async Task GetSequenceValueAsync(CancellationToken ct = default)
{
if (_connection is null) return 0;
await using var cmd = _connection.CreateCommand();
cmd.Transaction = _transaction;
cmd.CommandText = "SELECT seq FROM sqlite_sequence WHERE name = @name";
cmd.Parameters.AddWithValue("@name", SequenceName);
var result = await cmd.ExecuteScalarAsync(ct);
return result is null or DBNull ? 0 : Convert.ToInt64(result);
}
///
public async Task SetSequenceValueAsync(long value, CancellationToken ct = default)
{
if (_connection is null) return;
await using (var update = _connection.CreateCommand())
{
update.Transaction = _transaction;
update.CommandText = "UPDATE sqlite_sequence SET seq = @value WHERE name = @name";
update.Parameters.AddWithValue("@value", value);
update.Parameters.AddWithValue("@name", SequenceName);
var affected = await update.ExecuteNonQueryAsync(ct);
if (affected > 0) return;
}
// No sqlite_sequence row yet (DB created without materializing it): create it.
await using var insert = _connection.CreateCommand();
insert.Transaction = _transaction;
insert.CommandText = "INSERT INTO sqlite_sequence (name, seq) VALUES (@name, @value)";
insert.Parameters.AddWithValue("@name", SequenceName);
insert.Parameters.AddWithValue("@value", value);
await insert.ExecuteNonQueryAsync(ct);
}
///
public Task DisableConstraintsAsync(CancellationToken ct = default)
// PRAGMA foreign_keys is a no-op inside a transaction. Within an import it was switched off before the
// transaction began and comes back on after it ends (BeginImportAsync / CommitImportAsync / AbortImportAsync).
=> _transaction is not null ? Task.CompletedTask : ExecuteAsync("PRAGMA foreign_keys = OFF", ct);
///
// Inside an import the keys come back on only after the commit, and switching them on checks nothing that is
// already there: the loaded rows are checked here, still inside the transaction, so a refusal rolls back.
public Task EnableConstraintsAsync(CancellationToken ct = default)
=> _transaction is not null
? CheckForeignKeysAsync("Nothing was imported; the database is unchanged.", ct)
: ExecuteAsync("PRAGMA foreign_keys = ON", ct);
///
/// Checks the rows of the redb tables against their foreign keys with PRAGMA foreign_key_check , which
/// works whatever PRAGMA foreign_keys says, and refuses the import when a row points at a row that is not
/// there. SQLite keeps no name for a key, so a key is named by its table and column.
///
private async Task CheckForeignKeysAsync(string outcome, CancellationToken ct)
{
if (_connection is null) return;
var broken = new List();
foreach (var table in RedbTables)
{
if (!await TableExistsAsync(table, ct)) continue;
// One row per violating row: rowid and the id of the key (its position in foreign_key_list).
var violations = new Dictionary();
await using (var check = _connection.CreateCommand())
{
check.Transaction = _transaction;
check.CommandText = $"PRAGMA foreign_key_check({table})";
await using var reader = await check.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var keyId = reader.GetInt64(3);
var rowId = reader.GetInt64(1);
violations[keyId] = violations.TryGetValue(keyId, out var seen)
? (seen.Rows + 1, seen.ExampleRowId)
: (1, rowId);
}
}
if (violations.Count == 0) continue;
var keys = new List<(long Id, string Parent, string From, string? To)>();
await using (var list = _connection.CreateCommand())
{
list.Transaction = _transaction;
list.CommandText = $"SELECT id, \"table\", \"from\", \"to\" FROM pragma_foreign_key_list('{table}') ORDER BY id, seq";
await using var reader = await list.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
keys.Add((reader.GetInt64(0), reader.GetString(1), reader.GetString(2), reader.IsDBNull(3) ? null : reader.GetString(3)));
}
foreach (var (keyId, (rows, exampleRowId)) in violations.OrderBy(v => v.Key))
{
var columns = keys.Where(k => k.Id == keyId).ToList();
var from = columns.Select(k => k.From).ToList();
var example = await DescribeRowAsync(table, exampleRowId, from, ct);
broken.Add(ForeignKeyRefusal.Describe(
$"{table}.{string.Join(",", from)}", table, rows, columns[0].Parent,
columns.Select(k => k.To ?? "primary key"), example));
}
}
if (broken.Count > 0)
throw ForeignKeyRefusal.Exception(broken, outcome);
}
/// The id and the key columns of one row, as column = value pairs.
private async Task DescribeRowAsync(string table, long rowId, IReadOnlyList columns, CancellationToken ct)
{
await using var read = _connection!.CreateCommand();
read.Transaction = _transaction;
read.CommandText = $"SELECT _id, {string.Join(", ", columns.Select(c => $"\"{c}\""))} FROM {table} WHERE rowid = @rowid";
read.Parameters.AddWithValue("@rowid", rowId);
await using var reader = await read.ExecuteReaderAsync(ct);
if (!await reader.ReadAsync(ct)) return $"rowid = {rowId}";
return string.Join(", ", Enumerable.Range(0, columns.Count + 1)
.Select(i => $"{(i == 0 ? "_id" : columns[i - 1])} = {reader.GetValue(i)}"));
}
private async Task TableExistsAsync(string table, CancellationToken ct)
{
await using var exists = _connection!.CreateCommand();
exists.Transaction = _transaction;
exists.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = @name";
exists.Parameters.AddWithValue("@name", table);
return Convert.ToInt64(await exists.ExecuteScalarAsync(ct)) > 0;
}
///
public async Task BulkInsertAsync(string tableName, System.Data.DataTable data, CancellationToken ct = default)
{
if (_connection is null || data.Rows.Count == 0) return;
var columns = data.Columns.Cast().ToArray();
var columnList = string.Join(", ", columns.Select(c => c.ColumnName));
var paramList = string.Join(", ", columns.Select((_, i) => $"@p{i}"));
// Inside the import transaction every batch joins it; outside one (a caller of its own) a batch is atomic alone.
var ownTransaction = _transaction is null
? (SqliteTransaction)await _connection.BeginTransactionAsync(ct)
: null;
await using var cmd = _connection.CreateCommand();
cmd.Transaction = _transaction ?? ownTransaction;
cmd.CommandText = $"INSERT INTO {tableName} ({columnList}) VALUES ({paramList})";
// Create the parameter set once and reuse it across every row (prepared once).
var parameters = new SqliteParameter[columns.Length];
for (int i = 0; i < columns.Length; i++)
{
parameters[i] = cmd.CreateParameter();
parameters[i].ParameterName = $"@p{i}";
cmd.Parameters.Add(parameters[i]);
}
cmd.Prepare();
foreach (System.Data.DataRow row in data.Rows)
{
for (int i = 0; i < columns.Length; i++)
{
parameters[i].Value = row[i] switch
{
null or DBNull => DBNull.Value,
// The driver would bind a date as TEXT. redb's SQLite schema keeps dates as a
// UTC Julian day (REAL) and the provider compares them as numbers, so a TEXT
// date matches no date filter and sorts as a string.
DateTimeOffset moment => SqliteJulianDay.ToJulian(moment),
DateTime moment => SqliteJulianDay.ToJulian(new DateTimeOffset(DateTime.SpecifyKind(moment, DateTimeKind.Utc))),
// Same reason, same cure as the redb SQLite provider: the driver binds a decimal
// as TEXT, _Numeric and _value_numeric are REAL, and a REAL never compares equal
// to, and always sorts before, a TEXT.
decimal number => (double)number,
var value => value
};
}
await cmd.ExecuteNonQueryAsync(ct);
}
if (ownTransaction is not null)
{
await ownTransaction.CommitAsync(ct);
await ownTransaction.DisposeAsync();
}
}
///
public async Task ExecuteAsync(string sql, CancellationToken ct = default)
{
if (_connection is null) throw new InvalidOperationException("Connection not opened. Call OpenAsync first.");
await using var cmd = _connection.CreateCommand();
cmd.Transaction = _transaction;
cmd.CommandText = sql;
await cmd.ExecuteNonQueryAsync(ct);
}
///
public async ValueTask DisposeAsync()
{
if (_connection is not null)
{
await _connection.DisposeAsync();
}
}
///
///
/// Decoded here, not by the driver: the driver's own Julian conversion returns a date of
/// unspecified kind and keeps sub-millisecond noise of the REAL, while the redb SQLite provider
/// reads the number as UTC rounded to the millisecond. A database filled by an earlier import
/// holds these columns as TEXT; that form is read too.
///
public DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal) => reader.GetValue(ordinal) switch
{
double julian => SqliteJulianDay.FromJulian(julian),
long julian => SqliteJulianDay.FromJulian(julian),
string text => DateTimeOffset.Parse(text, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal),
var other => throw new InvalidOperationException(
$"Unexpected date column representation: {other.GetType().Name}")
};
///
///
/// redb's SQLite schema stores uuid-semantic columns as a 16-byte BLOB in RFC 4122 (text)
/// order (see SqliteHash in redb.SQLite); the driver's GetGuid would byte-swap the
/// first three groups. Legacy pre-V4 databases may still hold the TEXT form.
///
public Guid GuidFromDb(object raw) => raw switch
{
byte[] blob => Guid.ParseExact(Convert.ToHexString(blob), "N"),
string text => Guid.Parse(text),
Guid guid => guid,
_ => throw new InvalidOperationException(
$"Unexpected uuid column representation: {raw.GetType().Name}")
};
///
public object GuidToDb(Guid value) => Convert.FromHexString(value.ToString("N"));
}
Path: redb/redb.Export/Services/ExportService.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.Export/Services/ExportService.cs
----
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using redb.Export.Models;
using redb.Export.Providers;
namespace redb.Export.Services;
///
/// Exports an entire REDB database (or a filtered subset of schemes) to a .redb file.
///
/// The output is a JSONL (line-delimited JSON) stream, optionally wrapped in a ZIP archive.
/// Records are written in foreign-key-safe order so the file can be imported with a single pass.
///
///
public sealed class ExportService
{
private readonly IDataProvider _provider;
private readonly bool _verbose;
private readonly int _batchSize;
private long _typesCount;
private long _rolesCount;
private long _usersCount;
private long _userRolesCount;
private long _listsCount;
private long _listItemsCount;
private long _schemesCount;
private long _structuresCount;
private long _migrationsCount;
private long _objectsCount;
private long _permissionsCount;
private long _valuesCount;
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
///
/// Initializes a new instance of .
///
/// An opened .
/// When true , progress is written to .
/// Number of records per batch (affects memory usage).
public ExportService(IDataProvider provider, bool verbose, int batchSize)
{
_provider = provider;
_verbose = verbose;
_batchSize = batchSize;
}
///
/// Exports the database to the specified file path.
///
///
/// Destination file path. The .redb extension is appended automatically if missing.
///
///
/// Optional array of scheme identifiers to export.
/// When null or empty, all schemes are included.
///
/// When true , the JSONL stream is wrapped in a ZIP archive.
/// When true , only prints statistics without writing a file.
/// Cancellation token.
public async Task ExportAsync(
string outputPath,
long[]? schemeIds,
bool compress,
bool dryRun,
CancellationToken ct = default)
{
var startTime = DateTime.UtcNow;
// Before anything is read: a source of another schema than this build's stops here with the exceptions of a
// service start, a newer one always (the file would leave out what this build does not know).
var sourceSchema = await SchemaGate.CheckSourceAsync(_provider, ct);
if (dryRun)
{
await PrintDryRunInfoAsync(schemeIds, ct);
return;
}
var actualPath = outputPath;
if (!actualPath.EndsWith(".redb", StringComparison.OrdinalIgnoreCase))
{
actualPath += ".redb";
}
Log($"Exporting to: {actualPath}");
long sequenceValue;
TimeSpan duration;
FileStream? fileStream = null;
ZipArchive? archive = null;
Stream writeStream;
try
{
fileStream = File.Create(actualPath);
if (compress)
{
archive = new ZipArchive(fileStream, ZipArchiveMode.Create, leaveOpen: false);
var entry = archive.CreateEntry("data.jsonl", CompressionLevel.Optimal);
writeStream = entry.Open();
}
else
{
writeStream = fileStream;
}
await using (var writer = new StreamWriter(writeStream, Encoding.UTF8, leaveOpen: false))
{
// Header
var header = new ExportHeader
{
Provider = _provider.Name,
ExportedAt = startTime,
SourceSchema = sourceSchema,
SchemeIds = schemeIds ?? []
};
await writer.WriteLineAsync(JsonSerializer.Serialize(header, JsonOptions));
// Data in FK-safe order
await ExportTypesAsync(writer, ct);
await ExportListsAsync(writer, ct);
await ExportSchemesAsync(writer, schemeIds, ct);
await ExportStructuresAsync(writer, schemeIds, ct);
await ExportMigrationsAsync(writer, schemeIds, ct);
await ExportRolesAsync(writer, ct);
await ExportUsersAsync(writer, ct);
await ExportUserRolesAsync(writer, ct);
await ExportObjectsAsync(writer, schemeIds, ct);
await ExportListItemsAsync(writer, ct);
await ExportPermissionsAsync(writer, ct);
await ExportValuesAsync(writer, schemeIds, ct);
// Footer
sequenceValue = await _provider.GetSequenceValueAsync(ct);
Log($"Sequence value: {sequenceValue}");
duration = DateTime.UtcNow - startTime;
var footer = new ExportFooter
{
SequenceValue = sequenceValue,
TotalTypes = _typesCount,
TotalRoles = _rolesCount,
TotalUsers = _usersCount,
TotalUserRoles = _userRolesCount,
TotalLists = _listsCount,
TotalListItems = _listItemsCount,
TotalSchemes = _schemesCount,
TotalStructures = _structuresCount,
TotalMigrations = _migrationsCount,
TotalObjects = _objectsCount,
TotalPermissions = _permissionsCount,
TotalValues = _valuesCount,
Duration = duration
};
await writer.WriteLineAsync(JsonSerializer.Serialize(footer, JsonOptions));
await writer.FlushAsync(ct);
}
archive?.Dispose();
archive = null;
fileStream = null;
var checksum = await ComputeChecksumAsync(actualPath, ct);
var fileSize = new FileInfo(actualPath).Length;
Console.WriteLine();
Console.WriteLine("Export completed successfully!");
Console.WriteLine($" File: {actualPath}");
Console.WriteLine($" Size: {FormatSize(fileSize)}{(compress ? " (compressed)" : "")}");
Console.WriteLine($" Duration: {duration:hh\\:mm\\:ss}");
Console.WriteLine($" Checksum: SHA256:{checksum[..16]}...");
Console.WriteLine();
Console.WriteLine("Statistics:");
Console.WriteLine($" Types: {_typesCount:N0}");
Console.WriteLine($" Roles: {_rolesCount:N0}");
Console.WriteLine($" Users: {_usersCount:N0}");
Console.WriteLine($" UserRoles: {_userRolesCount:N0}");
Console.WriteLine($" Lists: {_listsCount:N0}");
Console.WriteLine($" ListItems: {_listItemsCount:N0}");
Console.WriteLine($" Schemes: {_schemesCount:N0}");
Console.WriteLine($" Structures: {_structuresCount:N0}");
Console.WriteLine($" Migrations: {_migrationsCount:N0}");
Console.WriteLine($" Objects: {_objectsCount:N0}");
Console.WriteLine($" Permissions: {_permissionsCount:N0}");
Console.WriteLine($" Values: {_valuesCount:N0}");
}
finally
{
archive?.Dispose();
fileStream?.Dispose();
}
}
private async Task PrintDryRunInfoAsync(long[]? schemeIds, CancellationToken ct)
{
Console.WriteLine("DRY RUN - No changes will be made");
Console.WriteLine();
var counts = await GetCountsAsync(schemeIds, ct);
Console.WriteLine("Would export:");
Console.WriteLine($" Types: {counts.Types:N0}");
Console.WriteLine($" Lists: {counts.Lists:N0}");
Console.WriteLine($" ListItems: {counts.ListItems:N0}");
Console.WriteLine($" Schemes: {counts.Schemes:N0}");
Console.WriteLine($" Structures: {counts.Structures:N0}");
Console.WriteLine($" Objects: {counts.Objects:N0}");
Console.WriteLine($" Values: {counts.Values:N0}");
if (schemeIds?.Length > 0)
{
Console.WriteLine();
Console.WriteLine($"Filtered by schemes: {string.Join(", ", schemeIds)}");
}
}
private async Task<(long Types, long Lists, long ListItems, long Schemes, long Structures, long Objects, long Values)>
GetCountsAsync(long[]? schemeIds, CancellationToken ct)
{
var conn = _provider.Connection;
async Task CountAsync(string sql)
{
await using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
var result = await cmd.ExecuteScalarAsync(ct);
return Convert.ToInt64(result);
}
var schemeFilter = schemeIds?.Length > 0
? $"WHERE _id_scheme IN ({string.Join(",", schemeIds)})"
: "";
var schemeFilter2 = schemeIds?.Length > 0
? $"WHERE _id IN ({string.Join(",", schemeIds)})"
: "";
return (
await CountAsync("SELECT COUNT(*) FROM _types"),
await CountAsync("SELECT COUNT(*) FROM _lists"),
await CountAsync("SELECT COUNT(*) FROM _list_items"),
await CountAsync($"SELECT COUNT(*) FROM _schemes {schemeFilter2}"),
await CountAsync($"SELECT COUNT(*) FROM _structures {schemeFilter}"),
await CountAsync($"SELECT COUNT(*) FROM _objects {schemeFilter}"),
await CountAsync($"SELECT COUNT(*) FROM _values WHERE _id_object IN (SELECT _id FROM _objects {schemeFilter})")
);
}
private async Task ExportTypesAsync(StreamWriter writer, CancellationToken ct)
{
Log("Exporting types...");
await using var cmd = _provider.Connection.CreateCommand();
cmd.CommandText = "SELECT _id, _name, _db_type, _type FROM _types ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new TypeRecord
{
Id = reader.GetInt64(0),
Name = reader.GetString(1),
DbType = reader.IsDBNull(2) ? null : reader.GetString(2),
DotnetType = reader.IsDBNull(3) ? null : reader.GetString(3)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_typesCount++;
}
LogCount("Types", _typesCount);
}
private async Task ExportUsersAsync(StreamWriter writer, CancellationToken ct)
{
Log("Exporting users...");
await using var cmd = _provider.Connection.CreateCommand();
cmd.CommandText = @"
SELECT _id, _login, _password, _name, _phone, _email,
_date_register, _date_dismiss, _enabled, _key,
_code_int, _code_string, _code_guid, _note, _hash, _id_configuration
FROM _users ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new UserRecord
{
Id = reader.GetInt64(0),
Login = reader.GetString(1),
Password = reader.GetString(2),
Name = reader.GetString(3),
Phone = reader.IsDBNull(4) ? null : reader.GetString(4),
Email = reader.IsDBNull(5) ? null : reader.GetString(5),
DateRegister = _provider.ReadDateTimeOffset(reader, 6),
DateDismiss = reader.IsDBNull(7) ? null : _provider.ReadDateTimeOffset(reader, 7),
Enabled = reader.GetBoolean(8),
Key = reader.IsDBNull(9) ? null : reader.GetInt64(9),
CodeInt = reader.IsDBNull(10) ? null : reader.GetInt64(10),
CodeString = reader.IsDBNull(11) ? null : reader.GetString(11),
CodeGuid = reader.IsDBNull(12) ? null : reader.GetGuid(12),
Note = reader.IsDBNull(13) ? null : reader.GetString(13),
Hash = reader.IsDBNull(14) ? null : _provider.GuidFromDb(reader.GetValue(14)),
IdConfiguration = reader.IsDBNull(15) ? null : reader.GetInt64(15)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_usersCount++;
}
LogCount("Users", _usersCount);
}
private async Task ExportRolesAsync(StreamWriter writer, CancellationToken ct)
{
Log("Exporting roles...");
await using var cmd = _provider.Connection.CreateCommand();
cmd.CommandText = "SELECT _id, _name, _id_configuration FROM _roles ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new RoleRecord
{
Id = reader.GetInt64(0),
Name = reader.GetString(1),
IdConfiguration = reader.IsDBNull(2) ? null : reader.GetInt64(2)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_rolesCount++;
}
LogCount("Roles", _rolesCount);
}
private async Task ExportUserRolesAsync(StreamWriter writer, CancellationToken ct)
{
Log("Exporting user-roles...");
await using var cmd = _provider.Connection.CreateCommand();
cmd.CommandText = "SELECT _id, _id_role, _id_user FROM _users_roles ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new UserRoleRecord
{
Id = reader.GetInt64(0),
IdRole = reader.GetInt64(1),
IdUser = reader.GetInt64(2)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_userRolesCount++;
}
LogCount("UserRoles", _userRolesCount);
}
private async Task ExportPermissionsAsync(StreamWriter writer, CancellationToken ct)
{
Log("Exporting permissions...");
await using var cmd = _provider.Connection.CreateCommand();
cmd.CommandText = @"
SELECT _id, _id_role, _id_user, _id_ref, _select, _insert, _update, _delete
FROM _permissions ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new PermissionRecord
{
Id = reader.GetInt64(0),
IdRole = reader.IsDBNull(1) ? null : reader.GetInt64(1),
IdUser = reader.IsDBNull(2) ? null : reader.GetInt64(2),
IdRef = reader.GetInt64(3),
Select = reader.IsDBNull(4) ? null : reader.GetBoolean(4),
Insert = reader.IsDBNull(5) ? null : reader.GetBoolean(5),
Update = reader.IsDBNull(6) ? null : reader.GetBoolean(6),
Delete = reader.IsDBNull(7) ? null : reader.GetBoolean(7)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_permissionsCount++;
}
LogCount("Permissions", _permissionsCount);
}
private async Task ExportListsAsync(StreamWriter writer, CancellationToken ct)
{
Log("Exporting lists...");
await using var cmd = _provider.Connection.CreateCommand();
cmd.CommandText = "SELECT _id, _name, _alias FROM _lists ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new ListRecord
{
Id = reader.GetInt64(0),
Name = reader.GetString(1),
Alias = reader.IsDBNull(2) ? null : reader.GetString(2)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_listsCount++;
}
LogCount("Lists", _listsCount);
}
private async Task ExportListItemsAsync(StreamWriter writer, CancellationToken ct)
{
Log("Exporting list items...");
await using var cmd = _provider.Connection.CreateCommand();
cmd.CommandText = "SELECT _id, _id_list, _value, _alias, _id_object FROM _list_items ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new ListItemRecord
{
Id = reader.GetInt64(0),
IdList = reader.GetInt64(1),
Value = reader.IsDBNull(2) ? null : reader.GetString(2),
Alias = reader.IsDBNull(3) ? null : reader.GetString(3),
IdObject = reader.IsDBNull(4) ? null : reader.GetInt64(4)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_listItemsCount++;
}
LogCount("ListItems", _listItemsCount);
}
private async Task ExportSchemesAsync(StreamWriter writer, long[]? schemeIds, CancellationToken ct)
{
Log("Exporting schemes...");
await using var cmd = _provider.Connection.CreateCommand();
var filter = schemeIds?.Length > 0
? $"WHERE _id IN ({string.Join(",", schemeIds)})"
: "";
cmd.CommandText = $"SELECT _id, _id_parent, _name, _alias, _name_space, _structure_hash, _type, _tags, _renamed_from FROM _schemes {filter} ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new SchemeRecord
{
Id = reader.GetInt64(0),
IdParent = reader.IsDBNull(1) ? null : reader.GetInt64(1),
Name = reader.GetString(2),
Alias = reader.IsDBNull(3) ? null : reader.GetString(3),
NameSpace = reader.IsDBNull(4) ? null : reader.GetString(4),
StructureHash = reader.IsDBNull(5) ? null : _provider.GuidFromDb(reader.GetValue(5)),
SchemeType = reader.GetInt64(6),
Tags = reader.IsDBNull(7) ? null : reader.GetString(7),
RenamedFrom = reader.IsDBNull(8) ? null : reader.GetString(8)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_schemesCount++;
}
LogCount("Schemes", _schemesCount);
}
private async Task ExportStructuresAsync(StreamWriter writer, long[]? schemeIds, CancellationToken ct)
{
Log("Exporting structures...");
await using var cmd = _provider.Connection.CreateCommand();
var filter = schemeIds?.Length > 0
? $"WHERE _id_scheme IN ({string.Join(",", schemeIds)})"
: "";
cmd.CommandText = $@"
SELECT _id, _id_parent, _id_scheme, _id_override, _id_type, _id_list,
_name, _alias, _order, _readonly, _allow_not_null,
_collection_type, _key_type, _is_compress, _store_null,
_default_value, _default_editor,
_unique, _unique_version, _lazy, _unique_scope, _tags, _renamed_from
FROM _structures {filter} ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new StructureRecord
{
Id = reader.GetInt64(0),
IdParent = reader.IsDBNull(1) ? null : reader.GetInt64(1),
IdScheme = reader.GetInt64(2),
IdOverride = reader.IsDBNull(3) ? null : reader.GetInt64(3),
IdType = reader.GetInt64(4),
IdList = reader.IsDBNull(5) ? null : reader.GetInt64(5),
Name = reader.GetString(6),
Alias = reader.IsDBNull(7) ? null : reader.GetString(7),
Order = reader.IsDBNull(8) ? null : reader.GetInt64(8),
Readonly = reader.IsDBNull(9) ? null : reader.GetBoolean(9),
AllowNotNull = reader.IsDBNull(10) ? null : reader.GetBoolean(10),
CollectionType = reader.IsDBNull(11) ? null : reader.GetInt64(11),
KeyType = reader.IsDBNull(12) ? null : reader.GetInt64(12),
IsCompress = reader.IsDBNull(13) ? null : reader.GetBoolean(13),
StoreNull = reader.IsDBNull(14) ? null : reader.GetBoolean(14),
DefaultValue = reader.IsDBNull(15) ? null : (byte[])reader.GetValue(15),
DefaultEditor = reader.IsDBNull(16) ? null : reader.GetString(16),
Unique = reader.IsDBNull(17) ? null : reader.GetBoolean(17),
UniqueVersion = reader.IsDBNull(18) ? null : reader.GetInt64(18),
Lazy = reader.IsDBNull(19) ? null : reader.GetBoolean(19),
UniqueScope = reader.IsDBNull(20) ? null : reader.GetInt64(20),
Tags = reader.IsDBNull(21) ? null : reader.GetString(21),
RenamedFrom = reader.IsDBNull(22) ? null : reader.GetString(22)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_structuresCount++;
}
LogCount("Structures", _structuresCount);
}
///
/// The history of the data migrations applied to the exported schemes. Without it an application that runs its
/// migrations at start applied every one of them again to the imported values, which already had them.
///
private async Task ExportMigrationsAsync(StreamWriter writer, long[]? schemeIds, CancellationToken ct)
{
Log("Exporting migration history...");
await using var cmd = _provider.Connection.CreateCommand();
var filter = schemeIds?.Length > 0
? $"WHERE _scheme_id IN ({string.Join(",", schemeIds)})"
: "";
cmd.CommandText = $@"
SELECT _id, _migration_id, _scheme_id, _structure_id, _property_name, _expression_hash,
_migration_type, _applied_at, _applied_by, _sql_executed, _affected_rows, _duration_ms, _dry_run
FROM _migrations {filter} ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new MigrationRecord
{
Id = reader.GetInt64(0),
MigrationId = reader.GetString(1),
SchemeId = reader.GetInt64(2),
StructureId = reader.IsDBNull(3) ? null : reader.GetInt64(3),
PropertyName = reader.IsDBNull(4) ? null : reader.GetString(4),
ExpressionHash = reader.IsDBNull(5) ? null : reader.GetString(5),
MigrationType = reader.GetString(6),
AppliedAt = _provider.ReadDateTimeOffset(reader, 7),
AppliedBy = reader.IsDBNull(8) ? null : reader.GetString(8),
SqlExecuted = reader.IsDBNull(9) ? null : reader.GetString(9),
// INT on PostgreSQL and SQL Server, INTEGER on SQLite.
AffectedRows = reader.IsDBNull(10) ? null : Convert.ToInt64(reader.GetValue(10), System.Globalization.CultureInfo.InvariantCulture),
DurationMs = reader.IsDBNull(11) ? null : Convert.ToInt64(reader.GetValue(11), System.Globalization.CultureInfo.InvariantCulture),
DryRun = reader.GetBoolean(12)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_migrationsCount++;
}
LogCount("Migrations", _migrationsCount);
}
private async Task ExportObjectsAsync(StreamWriter writer, long[]? schemeIds, CancellationToken ct)
{
Log("Exporting objects...");
await using var cmd = _provider.Connection.CreateCommand();
var filter = schemeIds?.Length > 0
? $"WHERE _id_scheme IN ({string.Join(",", schemeIds)})"
: "";
cmd.CommandText = $@"
SELECT _id, _id_parent, _id_scheme, _id_owner, _id_who_change,
_date_create, _date_modify, _date_begin, _date_complete,
_key, _name, _note, _hash,
_value_long, _value_string, _value_guid, _value_bool,
_value_double, _value_numeric, _value_datetime, _value_bytes, _value_unique
FROM _objects {filter} ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new ObjectRecord
{
Id = reader.GetInt64(0),
IdParent = reader.IsDBNull(1) ? null : reader.GetInt64(1),
IdScheme = reader.GetInt64(2),
IdOwner = reader.GetInt64(3),
IdWhoChange = reader.GetInt64(4),
DateCreate = _provider.ReadDateTimeOffset(reader, 5),
DateModify = _provider.ReadDateTimeOffset(reader, 6),
DateBegin = reader.IsDBNull(7) ? null : _provider.ReadDateTimeOffset(reader, 7),
DateComplete = reader.IsDBNull(8) ? null : _provider.ReadDateTimeOffset(reader, 8),
Key = reader.IsDBNull(9) ? null : reader.GetInt64(9),
Name = reader.IsDBNull(10) ? null : reader.GetString(10),
Note = reader.IsDBNull(11) ? null : reader.GetString(11),
Hash = reader.IsDBNull(12) ? null : _provider.GuidFromDb(reader.GetValue(12)),
ValueLong = reader.IsDBNull(13) ? null : reader.GetInt64(13),
ValueString = reader.IsDBNull(14) ? null : reader.GetString(14),
ValueGuid = reader.IsDBNull(15) ? null : reader.GetGuid(15),
ValueBool = reader.IsDBNull(16) ? null : reader.GetBoolean(16),
ValueDouble = reader.IsDBNull(17) ? null : reader.GetDouble(17),
ValueNumeric = reader.IsDBNull(18) ? null : reader.GetDecimal(18),
ValueDatetime = reader.IsDBNull(19) ? null : _provider.ReadDateTimeOffset(reader, 19),
ValueBytes = reader.IsDBNull(20) ? null : (byte[])reader.GetValue(20),
ValueUnique = reader.IsDBNull(21) ? null : reader.GetString(21)
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_objectsCount++;
if (_verbose && _objectsCount % 10000 == 0)
{
Console.Write($"\r Objects: {_objectsCount:N0}");
}
}
LogCount("Objects", _objectsCount);
}
private async Task ExportValuesAsync(StreamWriter writer, long[]? schemeIds, CancellationToken ct)
{
Log("Exporting values...");
await using var cmd = _provider.Connection.CreateCommand();
var filter = schemeIds?.Length > 0
? $"WHERE _id_object IN (SELECT _id FROM _objects WHERE _id_scheme IN ({string.Join(",", schemeIds)}))"
: "";
cmd.CommandText = $@"
SELECT _id, _id_structure, _id_object,
_String, _Long, _Guid, _Double, _DateTimeOffset,
_Boolean, _ByteArray, _Numeric, _ListItem, _Object,
_array_parent_id, _array_index, _unique
FROM _values {filter} ORDER BY _id";
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
var record = new ValueRecord
{
Id = reader.GetInt64(0),
IdStructure = reader.GetInt64(1),
IdObject = reader.GetInt64(2),
String = reader.IsDBNull(3) ? null : reader.GetString(3),
Long = reader.IsDBNull(4) ? null : reader.GetInt64(4),
Guid = reader.IsDBNull(5) ? null : reader.GetGuid(5),
Double = reader.IsDBNull(6) ? null : reader.GetDouble(6),
DateTimeOffset = reader.IsDBNull(7) ? null : _provider.ReadDateTimeOffset(reader, 7),
Boolean = reader.IsDBNull(8) ? null : reader.GetBoolean(8),
ByteArray = reader.IsDBNull(9) ? null : (byte[])reader.GetValue(9),
Numeric = reader.IsDBNull(10) ? null : reader.GetDecimal(10),
ListItem = reader.IsDBNull(11) ? null : reader.GetInt64(11),
Object = reader.IsDBNull(12) ? null : reader.GetInt64(12),
ArrayParentId = reader.IsDBNull(13) ? null : reader.GetInt64(13),
ArrayIndex = reader.IsDBNull(14) ? null : reader.GetString(14),
Unique = reader.IsDBNull(15) ? null : _provider.GuidFromDb(reader.GetValue(15))
};
await writer.WriteLineAsync(JsonSerializer.Serialize(record, JsonOptions));
_valuesCount++;
if (_verbose && _valuesCount % 50000 == 0)
{
Console.Write($"\r Values: {_valuesCount:N0}");
}
}
LogCount("Values", _valuesCount);
}
private static async Task ComputeChecksumAsync(string filePath, CancellationToken ct)
{
await using var stream = File.OpenRead(filePath);
var hash = await SHA256.HashDataAsync(stream, ct);
return Convert.ToHexString(hash).ToLowerInvariant();
}
private static string FormatSize(long bytes)
{
string[] sizes = ["B", "KB", "MB", "GB", "TB"];
int order = 0;
double size = bytes;
while (size >= 1024 && order < sizes.Length - 1)
{
order++;
size /= 1024;
}
return $"{size:0.##} {sizes[order]}";
}
private void Log(string message)
{
if (_verbose)
{
Console.WriteLine(message);
}
}
private void LogCount(string entity, long count)
{
if (_verbose)
{
Console.WriteLine($"\r {entity}: {count:N0} ");
}
}
}
Path: redb/redb.Export/Services/ImportFinishing.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.Export/Services/ImportFinishing.cs
----
using System.Data;
using System.Data.Common;
using redb.Core.Query;
using redb.Export.Providers;
namespace redb.Export.Services;
///
/// What an import does around its load, outside the load's transaction: which type rows the target already holds,
/// and after the load the scheme metadata cache and the note about time values stored as text by an older version.
///
internal static class ImportFinishing
{
/// _types ids of TimeOnly and TimeSpan, the same on every provider (RedbTypeIds).
private const long TimeOnlyTypeId = -9223372036854775685;
private const long TimeSpanTypeId = -9223372036854775684;
/// The _types ids the target holds: its built-in types, kept by the import whatever the file says.
public static async Task> TargetTypeIdsAsync(IDataProvider provider, CancellationToken ct)
{
var ids = new HashSet();
await using var command = provider.Connection.CreateCommand();
command.CommandText = "SELECT _id FROM _types";
await using var reader = await command.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
ids.Add(reader.GetInt64(0));
return ids;
}
///
/// Builds the scheme metadata cache of every imported scheme through the dialect's per-scheme statement, as the
/// scheme sync of a service does. Without it the first query of a Pro application rebuilt it, which is slow on a
/// large database and needs write rights.
///
public static async Task SyncMetadataCacheAsync(IDataProvider provider, CancellationToken ct)
{
var schemes = new List();
await using (var read = provider.Connection.CreateCommand())
{
read.CommandText = "SELECT _id FROM _schemes";
await using var reader = await read.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
schemes.Add(reader.GetInt64(0));
}
var (dialect, parameter) = provider.Name switch
{
"postgres" => ((ISqlDialect)new global::redb.Postgres.Sql.PostgreSqlDialect(), ""),
"mssql" => (new global::redb.MSSql.Sql.MsSqlDialect(), "@p0"),
"sqlite" => (new global::redb.SQLite.Sql.SqliteDialect(), "$1"),
_ => throw new ArgumentException($"Unknown provider: {provider.Name}", nameof(provider)),
};
foreach (var scheme in schemes)
{
await using var sync = provider.Connection.CreateCommand();
sync.CommandText = dialect.Schemes_SyncMetadataCache();
sync.CommandTimeout = 0;
var value = sync.CreateParameter();
value.ParameterName = parameter;
value.DbType = DbType.Int64;
value.Value = scheme;
sync.Parameters.Add(value);
await sync.ExecuteNonQueryAsync(ct);
}
return schemes.Count;
}
///
/// PostgreSQL: the planner statistics of the loaded tables, before an application queries them. COPY leaves a
/// table without statistics until autoanalyze reaches it, and a query planned meanwhile takes every table for
/// one row: on a new database of a few hundred objects a grouping ran for minutes. The other providers keep
/// their own (SQL Server creates them on the first query, SQLite plans without them). False when nothing ran.
///
public static async Task AnalyzeAsync(IDataProvider provider, CancellationToken ct)
{
if (provider is not PostgresProvider postgres)
return false;
// Only the redb tables: the database may hold tables of others, and analyzing them is not the import's business.
await postgres.AnalyzeRedbTablesAsync(ct);
return true;
}
///
/// How many imported values of TimeSpan and TimeOnly fields are stored as text: a file of a version before they
/// were stored as ticks. The import leaves them as the file has them; the upgrade notes convert them.
///
public static async Task TimeValuesAsTextAsync(IDataProvider provider, CancellationToken ct)
{
await using var command = provider.Connection.CreateCommand();
command.CommandText =
"SELECT COUNT(*) FROM _values v JOIN _structures s ON s._id = v._id_structure " +
$"WHERE s._id_type IN ({TimeOnlyTypeId}, {TimeSpanTypeId}) AND v._String IS NOT NULL";
command.CommandTimeout = 0;
return Convert.ToInt64(await command.ExecuteScalarAsync(ct));
}
}
Path: redb/redb.Export/Services/ImportService.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.Export/Services/ImportService.cs
----
using System.Data;
using System.IO.Compression;
using System.Text;
using System.Text.Json;
using redb.Export.Models;
using redb.Export.Providers;
namespace redb.Export.Services;
///
/// Imports data from a .redb file into a REDB database.
///
/// Uses a streaming approach: records are read line-by-line, accumulated into
/// batches, and bulk-inserted via .
/// The file may be plain JSONL or ZIP-compressed (auto-detected).
///
///
public sealed class ImportService
{
private readonly IDataProvider _provider;
private readonly bool _verbose;
private readonly int _batchSize;
private long _typesCount;
private long _rolesCount;
private long _usersCount;
private long _userRolesCount;
private long _listsCount;
private long _listItemsCount;
private long _schemesCount;
private long _structuresCount;
private long _migrationsCount;
private bool _fileCarriesMigrationHistory;
private long _objectsCount;
private long _permissionsCount;
private long _valuesCount;
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
};
private readonly int _parallelism;
private ParallelImportWriter? _writer;
private CountingStream? _progress;
private long _totalBytes;
private DateTime _loadStarted;
///
/// Initializes a new instance of .
///
/// Connection the import runs on.
/// Print progress.
/// Rows per bulk insert.
///
/// 1 (the default) keeps the whole import in one transaction on one connection. More than 1 writes
/// over that many connections and rebuilds the secondary indexes of the large tables afterwards;
/// see for what is given up in exchange.
///
public ImportService(IDataProvider provider, bool verbose, int batchSize, int parallelism = 1)
{
if (parallelism < 1)
throw new ArgumentOutOfRangeException(nameof(parallelism), "Parallelism must be at least 1.");
if (parallelism > 1 && provider is not IParallelImportProvider)
throw new NotSupportedException($"Parallel import is not available for the '{provider.Name}' provider.");
_provider = provider;
_verbose = verbose;
_batchSize = batchSize;
_parallelism = parallelism;
}
///
/// Imports data from the specified .redb file.
///
/// Path to the .redb file (JSONL or ZIP).
///
/// When true , all existing data is truncated before import
/// via .
///
/// When true , only prints statistics without writing to the database.
/// Cancellation token.
public async Task ImportAsync(
string inputPath,
bool clean,
bool dryRun,
CancellationToken ct = default)
{
var startTime = DateTime.UtcNow;
// Before anything is cleaned or written: a target of another schema than this build's stops here with the
// exceptions of a service start. Without it a parallel import committed its cleaning, then failed on the
// first batch naming a column the target does not have, and left an emptied database behind.
await SchemaGate.CheckTargetAsync(_provider, ct);
Log($"Importing from: {inputPath}");
var isZip = await IsZipFileAsync(inputPath);
Log($"Detected: {(isZip ? "ZIP compressed" : "Plain JSONL")}");
Stream dataStream;
ZipArchive? archive = null;
if (isZip)
{
archive = ZipFile.OpenRead(inputPath);
var entry = archive.Entries.FirstOrDefault(e => e.Name.EndsWith(".jsonl"))
?? throw new InvalidOperationException("No .jsonl file found in archive");
dataStream = entry.Open();
_totalBytes = entry.Length;
}
else
{
dataStream = File.OpenRead(inputPath);
_totalBytes = new FileInfo(inputPath).Length;
}
// Progress and the time estimate are told from how far into the file the reader is.
_progress = new CountingStream(dataStream);
dataStream = _progress;
try
{
using var reader = new StreamReader(dataStream, Encoding.UTF8);
var headerLine = await reader.ReadLineAsync(ct)
?? throw new InvalidOperationException("Empty file");
var headerDoc = JsonDocument.Parse(headerLine);
var provider = headerDoc.RootElement.TryGetProperty("provider", out var p) ? p.GetString() : "unknown";
var exportedAt = headerDoc.RootElement.TryGetProperty("exported_at", out var e)
? e.GetDateTime() : DateTime.MinValue;
Log($"Source: {provider}");
Log($"Exported: {exportedAt:yyyy-MM-dd HH:mm:ss} UTC");
Console.WriteLine();
if (dryRun)
{
await PrintDryRunInfoAsync(reader, ct);
return;
}
// One transaction for the whole import, cleaning included: a run that stops half-way - a broken or
// truncated file, a cancellation, a server error - leaves the database exactly as it found it, with
// its constraints on. Before, rows went in batch by batch as read, the constraints came back only on
// success, and an import with cleaning that failed left an emptied, half-filled database with its
// integrity switched off (review 2026-09-24).
// The target's own _types rows stay, the cleaning keeps them: they are the built-in types of this build, and
// a file of an older version carries its own (TimeSpan and TimeOnly as text before they were ticks). Only the
// file's types the target lacks are added.
var targetTypeIds = await ImportFinishing.TargetTypeIdsAsync(_provider, ct);
await _provider.BeginImportAsync(ct);
var committed = false;
var parallelFinished = false;
try
{
if (clean)
{
Log("Cleaning database...");
await _provider.CleanDatabaseAsync(ct);
Log("Database cleaned.");
}
IReadOnlyList droppedIndexes = [];
if (_parallelism > 1)
{
// From here on several connections write and commit on their own, so the cleaning is
// committed first: there is no single transaction to roll back any more.
var parallel = (IParallelImportProvider)_provider;
await _provider.CommitImportAsync(ct);
committed = true;
droppedIndexes = await parallel.DropLoadIndexesAsync(ct);
Log($"Took {droppedIndexes.Count} secondary indexes out for the load; they are rebuilt at the end.");
await parallel.RelaxConstraintsForLoadAsync(ct);
_writer = await ParallelImportWriter.StartAsync(parallel, _parallelism, ct);
Log($"Writing over {_parallelism} connections.");
}
else
{
await _provider.DisableConstraintsAsync(ct);
}
_loadStarted = DateTime.UtcNow;
var tables = CreateDataTables();
long sequenceValue = 0;
ExportFooter? footer = null;
Log("Importing data (streaming)...");
string? line;
while ((line = await reader.ReadLineAsync(ct)) != null)
{
var doc = JsonDocument.Parse(line);
if (!doc.RootElement.TryGetProperty("type", out var typeProp))
{
if (doc.RootElement.TryGetProperty("sequence_value", out var seqProp))
{
sequenceValue = seqProp.GetInt64();
}
continue;
}
var type = typeProp.GetString();
if (_currentRecordType != null && _currentRecordType != type)
{
await FlushCurrentTableAsync(tables, ct);
}
_currentRecordType = type;
switch (type)
{
case "type":
var typeRecord = JsonSerializer.Deserialize(line, JsonOptions)!;
if (!targetTypeIds.Contains(typeRecord.Id))
AddTypeRow(tables.Types, typeRecord);
tables.TypesTotal++;
if (tables.Types.Rows.Count >= _batchSize)
await FlushTableAsync("_types", tables.Types, ct);
break;
case "list":
AddListRow(tables.Lists, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.ListsTotal++;
if (tables.Lists.Rows.Count >= _batchSize)
await FlushTableAsync("_lists", tables.Lists, ct);
break;
case "scheme":
AddSchemeRow(tables.Schemes, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.SchemesTotal++;
if (tables.Schemes.Rows.Count >= _batchSize)
await FlushTableAsync("_schemes", tables.Schemes, ct);
break;
case "structure":
AddStructureRow(tables.Structures, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.StructuresTotal++;
if (tables.Structures.Rows.Count >= _batchSize)
await FlushTableAsync("_structures", tables.Structures, ct);
break;
case "migration":
AddMigrationRow(tables.Migrations, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.MigrationsTotal++;
if (tables.Migrations.Rows.Count >= _batchSize)
await FlushTableAsync("_migrations", tables.Migrations, ct);
break;
case "role":
AddRoleRow(tables.Roles, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.RolesTotal++;
if (tables.Roles.Rows.Count >= _batchSize)
await FlushTableAsync("_roles", tables.Roles, ct);
break;
case "user":
AddUserRow(tables.Users, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.UsersTotal++;
if (tables.Users.Rows.Count >= _batchSize)
await FlushTableAsync("_users", tables.Users, ct);
break;
case "user_role":
AddUserRoleRow(tables.UserRoles, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.UserRolesTotal++;
if (tables.UserRoles.Rows.Count >= _batchSize)
await FlushTableAsync("_users_roles", tables.UserRoles, ct);
break;
case "object":
AddObjectRow(tables.Objects, JsonSerializer.Deserialize(line, JsonOptions)!);
_objectsCount++;
if (tables.Objects.Rows.Count >= _batchSize)
await FlushTableAsync("_objects", tables.Objects, ct);
break;
case "list_item":
AddListItemRow(tables.ListItems, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.ListItemsTotal++;
if (tables.ListItems.Rows.Count >= _batchSize)
await FlushTableAsync("_list_items", tables.ListItems, ct);
break;
case "permission":
AddPermissionRow(tables.Permissions, JsonSerializer.Deserialize(line, JsonOptions)!);
tables.PermissionsTotal++;
if (tables.Permissions.Rows.Count >= _batchSize)
await FlushTableAsync("_permissions", tables.Permissions, ct);
break;
case "value":
AddValueRow(tables.Values, JsonSerializer.Deserialize(line, JsonOptions)!);
_valuesCount++;
if (tables.Values.Rows.Count >= _batchSize)
await FlushTableAsync("_values", tables.Values, ct);
break;
case "footer":
footer = JsonSerializer.Deserialize(line, JsonOptions);
_fileCarriesMigrationHistory = footer?.TotalMigrations is not null;
if (footer?.SequenceValue > 0)
{
sequenceValue = footer.SequenceValue;
}
break;
}
}
await FlushCurrentTableAsync(tables, ct);
if (_verbose && _lastTable != null)
{
_tableRowCounts.TryGetValue(_lastTable, out var lastCount);
WriteProgressLine($" {_lastTable}: {lastCount:N0} rows", final: true);
}
if (_writer != null)
Console.WriteLine($"Data read in {(DateTime.UtcNow - _loadStarted):hh\\:mm\\:ss}; waiting for the writers, then the indexes are rebuilt.");
if (_writer != null)
{
await _writer.CompleteAsync();
// Every row is written; what is left puts the database back in shape. Each step is attempted
// whatever the one before it did, and the failures are reported together: one failing step (the
// id sequence of a database that had lost it) used to leave every index disabled and every
// constraint and trigger off.
var failures = await FinishParallelLoadAsync(footer, tables, sequenceValue, droppedIndexes, ct);
parallelFinished = true;
if (failures.Count > 0)
{
throw new InvalidOperationException(
$"The parallel import has written its rows, and {failures.Count} of its finishing steps " +
"failed; every step was attempted:" +
string.Concat(failures.Select(f => $"{Environment.NewLine} - {f.Step}: {f.Error.Message}")) +
$"{Environment.NewLine}Run the import again with --clean and --parallel: it reloads the data " +
"and repeats every step.",
new AggregateException(failures.Select(f => f.Error)));
}
}
else
{
// The footer is the last line of every export: without it the file was cut short, and with it every
// table must have arrived in full. Checked before the commit, so a short file changes nothing.
VerifyAgainstFooter(footer, tables);
await _provider.EnableConstraintsAsync(ct);
if (sequenceValue > 0)
{
Log($"Setting sequence to: {sequenceValue}");
await _provider.SetSequenceValueAsync(sequenceValue, ct);
}
await _provider.CommitImportAsync(ct);
committed = true;
}
_typesCount = tables.TypesTotal;
_listsCount = tables.ListsTotal;
_schemesCount = tables.SchemesTotal;
_structuresCount = tables.StructuresTotal;
_migrationsCount = tables.MigrationsTotal;
_rolesCount = tables.RolesTotal;
_usersCount = tables.UsersTotal;
_userRolesCount = tables.UserRolesTotal;
_listItemsCount = tables.ListItemsTotal;
_permissionsCount = tables.PermissionsTotal;
}
finally
{
if (!committed)
await _provider.AbortImportAsync();
if (_writer != null)
{
await _writer.DisposeAsync();
_writer = null;
if (!parallelFinished)
{
Console.WriteLine();
Console.WriteLine("The parallel import did not finish. The database holds part of the data, the secondary indexes");
Console.WriteLine("of the large tables are out (dropped with their definitions kept in _import_dropped_indexes, or");
Console.WriteLine("disabled, depending on the database), and foreign key checks may still be off.");
Console.WriteLine("Run the import again with --clean and --parallel: it reloads the data and puts all of that back.");
}
}
}
// The rows are committed: the scheme metadata cache is built now, not by the first query of an application.
var cached = await ImportFinishing.SyncMetadataCacheAsync(_provider, ct);
Log($"Scheme metadata cache built for {cached} scheme(s).");
if (await ImportFinishing.AnalyzeAsync(_provider, ct))
Log("Planner statistics refreshed (ANALYZE).");
var timeAsText = await ImportFinishing.TimeValuesAsTextAsync(_provider, ct);
// A file of an earlier version does not carry the history of the data migrations its database had; the
// values arrive with every applied migration in them, and the target cannot tell which those were.
var historyMissing = !_fileCarriesMigrationHistory && await HasSchemesAsync(ct);
var duration = DateTime.UtcNow - startTime;
Console.WriteLine();
Console.WriteLine("Import completed successfully!");
if (timeAsText > 0)
{
Console.WriteLine(
$" Note: {timeAsText:N0} imported TimeSpan or TimeOnly value(s) are stored as text by an older version. " +
"Convert them with the statement of the redb upgrade notes (\"TimeSpan and TimeOnly are stored as ticks\") " +
"before an application reads them.");
}
if (historyMissing)
{
Console.WriteLine(
" Warning: the file was written by an earlier version and does not carry the history of the data " +
"migrations (redb Pro) applied to its database. Do not run data migrations on this database before " +
"checking which of them the data already has: a migration that is not idempotent would be applied " +
"a second time. Exporting the source again with this version carries the history.");
}
Console.WriteLine($" Duration: {duration:hh\\:mm\\:ss}");
Console.WriteLine();
Console.WriteLine("Statistics:");
Console.WriteLine($" Types: {_typesCount:N0}");
Console.WriteLine($" Roles: {_rolesCount:N0}");
Console.WriteLine($" Users: {_usersCount:N0}");
Console.WriteLine($" UserRoles: {_userRolesCount:N0}");
Console.WriteLine($" Lists: {_listsCount:N0}");
Console.WriteLine($" ListItems: {_listItemsCount:N0}");
Console.WriteLine($" Schemes: {_schemesCount:N0}");
Console.WriteLine($" Structures: {_structuresCount:N0}");
Console.WriteLine($" Migrations: {_migrationsCount:N0}");
Console.WriteLine($" Objects: {_objectsCount:N0}");
Console.WriteLine($" Permissions: {_permissionsCount:N0}");
Console.WriteLine($" Values: {_valuesCount:N0}");
}
finally
{
await dataStream.DisposeAsync();
archive?.Dispose();
}
}
///
/// Refuses an import whose file ended before its footer, or whose tables did not all arrive in full. The
/// counts in the footer are written by the exporter as it goes; a mismatch means a cut or damaged file.
///
private void VerifyAgainstFooter(ExportFooter? footer, ImportTables tables)
{
if (footer is null)
throw new InvalidOperationException(
"The file ends before its footer: it was cut short, or it is not a complete redb export. " +
"Nothing was imported; the database is unchanged.");
var mismatches = new List();
void Check(string table, long expected, long actual)
{
if (expected != actual)
mismatches.Add($"{table}: expected {expected:N0}, read {actual:N0}");
}
Check("types", footer.TotalTypes, tables.TypesTotal);
Check("roles", footer.TotalRoles, tables.RolesTotal);
Check("users", footer.TotalUsers, tables.UsersTotal);
Check("user roles", footer.TotalUserRoles, tables.UserRolesTotal);
Check("lists", footer.TotalLists, tables.ListsTotal);
Check("list items", footer.TotalListItems, tables.ListItemsTotal);
Check("schemes", footer.TotalSchemes, tables.SchemesTotal);
Check("structures", footer.TotalStructures, tables.StructuresTotal);
// A file of an earlier version has no such total and no migration records.
if (footer.TotalMigrations is { } migrations)
Check("migrations", migrations, tables.MigrationsTotal);
Check("objects", footer.TotalObjects, _objectsCount);
Check("permissions", footer.TotalPermissions, tables.PermissionsTotal);
Check("values", footer.TotalValues, _valuesCount);
if (mismatches.Count > 0)
throw new InvalidOperationException(
"The file does not hold what its footer lists (" + string.Join("; ", mismatches) + "). " +
"Nothing was imported; the database is unchanged.");
}
/// Whether the database holds any scheme after the import.
private async Task HasSchemesAsync(CancellationToken ct)
{
await using var cmd = _provider.Connection.CreateCommand();
cmd.CommandText = "SELECT COUNT(*) FROM _schemes";
return Convert.ToInt64(await cmd.ExecuteScalarAsync(ct), System.Globalization.CultureInfo.InvariantCulture) > 0;
}
private readonly Dictionary _tableRowCounts = new();
private string? _lastTable;
private string? _currentRecordType;
private async Task FlushTableAsync(string tableName, DataTable table, CancellationToken ct)
{
if (table.Rows.Count == 0) return;
_tableRowCounts.TryGetValue(tableName, out var currentCount);
currentCount += table.Rows.Count;
_tableRowCounts[tableName] = currentCount;
if (_verbose)
{
if (_lastTable != null && _lastTable != tableName)
{
_tableRowCounts.TryGetValue(_lastTable, out var prevCount);
WriteProgressLine($" {_lastTable}: {prevCount:N0} rows", final: true);
}
_lastTable = tableName;
WriteProgressLine($" {tableName}: {currentCount:N0} rows... {ProgressText()}", final: false);
}
if (_writer != null)
{
// The batch is handed over as a copy: the reader keeps filling this table while a worker sends that one.
await _writer.EnqueueAsync(tableName, table.Copy());
}
else
{
await _provider.BulkInsertAsync(tableName, table, ct);
}
table.Clear();
}
private async Task FlushCurrentTableAsync(ImportTables tables, CancellationToken ct)
{
switch (_currentRecordType)
{
case "type": await FlushTableAsync("_types", tables.Types, ct); break;
case "list": await FlushTableAsync("_lists", tables.Lists, ct); break;
case "scheme": await FlushTableAsync("_schemes", tables.Schemes, ct); break;
case "structure": await FlushTableAsync("_structures", tables.Structures, ct); break;
case "migration": await FlushTableAsync("_migrations", tables.Migrations, ct); break;
case "role": await FlushTableAsync("_roles", tables.Roles, ct); break;
case "user": await FlushTableAsync("_users", tables.Users, ct); break;
case "user_role": await FlushTableAsync("_users_roles", tables.UserRoles, ct); break;
case "object": await FlushTableAsync("_objects", tables.Objects, ct); break;
case "list_item": await FlushTableAsync("_list_items", tables.ListItems, ct); break;
case "permission": await FlushTableAsync("_permissions", tables.Permissions, ct); break;
case "value": await FlushTableAsync("_values", tables.Values, ct); break;
}
}
private async Task PrintDryRunInfoAsync(StreamReader reader, CancellationToken ct)
{
Console.WriteLine("DRY RUN - No changes will be made");
Console.WriteLine();
long types = 0, lists = 0, schemes = 0, structures = 0, migrations = 0;
long roles = 0, users = 0, userRoles = 0;
long objects = 0, listItems = 0, permissions = 0, values = 0;
string? line;
while ((line = await reader.ReadLineAsync(ct)) != null)
{
var doc = JsonDocument.Parse(line);
if (!doc.RootElement.TryGetProperty("type", out var typeProp)) continue;
switch (typeProp.GetString())
{
case "type": types++; break;
case "list": lists++; break;
case "scheme": schemes++; break;
case "structure": structures++; break;
case "migration": migrations++; break;
case "role": roles++; break;
case "user": users++; break;
case "user_role": userRoles++; break;
case "object": objects++; break;
case "list_item": listItems++; break;
case "permission": permissions++; break;
case "value": values++; break;
}
}
Console.WriteLine("Would import:");
Console.WriteLine($" Types: {types:N0}");
Console.WriteLine($" Roles: {roles:N0}");
Console.WriteLine($" Users: {users:N0}");
Console.WriteLine($" UserRoles: {userRoles:N0}");
Console.WriteLine($" Lists: {lists:N0}");
Console.WriteLine($" ListItems: {listItems:N0}");
Console.WriteLine($" Schemes: {schemes:N0}");
Console.WriteLine($" Structures: {structures:N0}");
Console.WriteLine($" Migrations: {migrations:N0}");
Console.WriteLine($" Objects: {objects:N0}");
Console.WriteLine($" Permissions: {permissions:N0}");
Console.WriteLine($" Values: {values:N0}");
}
///
/// Index builds running at the same time, whatever the number of writer connections. Each build
/// sorts the whole table; more of them at once compete for the same disk and memory and finish
/// no sooner.
///
private const int MaxConcurrentIndexBuilds = 5;
private int _progressLineLength;
///
/// Writes the progress line over the previous one and blanks whatever the previous one left
/// beyond it. A final line ends with a newline; a running one is overwritten by the next.
///
private void WriteProgressLine(string text, bool final)
{
var padding = Math.Max(0, _progressLineLength - text.Length);
Console.Write("\r" + text + new string(' ', padding));
if (final)
{
Console.WriteLine();
_progressLineLength = 0;
}
else
{
_progressLineLength = text.Length;
}
}
///
/// How far into the file the reader is and how long the rest should take, from the bytes read so
/// far. It measures reading; in a parallel import the index rebuild comes on top and is timed
/// separately.
///
private string ProgressText()
{
if (_progress == null || _totalBytes <= 0) return "";
var fraction = Math.Clamp((double)_progress.BytesRead / _totalBytes, 0d, 1d);
var elapsed = DateTime.UtcNow - _loadStarted;
if (fraction < 0.005 || elapsed.TotalSeconds < 2)
return $"data {fraction:P0}";
var remaining = TimeSpan.FromSeconds(elapsed.TotalSeconds * (1 - fraction) / fraction);
var indexes = _parallelism > 1 ? "; indexes follow" : "";
return $"data {fraction:P0}, {elapsed:hh\\:mm\\:ss} elapsed, about {remaining:hh\\:mm\\:ss} left{indexes}";
}
///
/// Builds the indexes again, several at a time: one statement per connection. Where the
/// database lets index builds on one table run side by side, any free connection takes the next
/// index; where it does not, each table gets one connection and its indexes go in turn.
///
///
/// The finishing steps of a parallel load, each attempted whatever the others did: the file against its footer,
/// the id sequence, the index rebuild, then the constraints (after the indexes: checking foreign keys over the
/// loaded rows wants them in place). Returns the steps that failed.
///
private async Task> FinishParallelLoadAsync(
ExportFooter? footer, ImportTables tables, long sequenceValue, IReadOnlyList droppedIndexes,
CancellationToken ct)
{
var failures = new List<(string Step, Exception Error)>();
async Task StepAsync(string step, Func run)
{
try
{
await run();
}
catch (Exception ex)
{
failures.Add((step, ex));
}
}
// The footer is the last line of every export: without it the file was cut short, and with it every table
// must have arrived in full. The serial import says "nothing was imported" there; a parallel one has written.
await StepAsync("file check", () =>
{
try
{
VerifyAgainstFooter(footer, tables);
}
catch (InvalidOperationException ex)
{
throw new InvalidOperationException(ex.Message.Replace(" Nothing was imported; the database is unchanged.", ""), ex);
}
return Task.CompletedTask;
});
if (sequenceValue > 0)
{
await StepAsync("id sequence", () =>
{
Log($"Setting sequence to: {sequenceValue}");
return _provider.SetSequenceValueAsync(sequenceValue, ct);
});
}
await StepAsync("index rebuild", () => RebuildIndexesAsync(droppedIndexes, ct));
await StepAsync("constraints", async () =>
{
var constraintsStarted = DateTime.UtcNow;
await ((IParallelImportProvider)_provider).RestoreConstraintsAfterLoadAsync(ct);
Log($"Constraints restored in {(DateTime.UtcNow - constraintsStarted):hh\\:mm\\:ss}.");
});
return failures;
}
private async Task RebuildIndexesAsync(IReadOnlyList indexes, CancellationToken ct)
{
var parallel = (IParallelImportProvider)_provider;
if (indexes.Count == 0)
{
await parallel.ForgetDroppedIndexesAsync(ct);
return;
}
Console.WriteLine();
// One queue for everything, or one queue per table.
List> queues = parallel.BuildsIndexesOfOneTableConcurrently
? [new System.Collections.Concurrent.ConcurrentQueue(indexes)]
: indexes.GroupBy(i => i.Table)
.Select(g => new System.Collections.Concurrent.ConcurrentQueue(g))
.ToList();
var connections = _writer!.Connections.Take(MaxConcurrentIndexBuilds).ToList();
var builders = parallel.BuildsIndexesOfOneTableConcurrently
? connections.Select(c => (Connection: c, Queue: queues[0])).ToList()
: connections.Zip(queues, (c, q) => (Connection: c, Queue: q)).ToList();
if (builders.Count < queues.Count)
throw new InvalidOperationException(
$"{queues.Count} tables have indexes to rebuild and only {builders.Count} connections are open; raise --parallel.");
Console.WriteLine($"Rebuilding {indexes.Count} indexes, {builders.Count} at a time...");
var started = DateTime.UtcNow;
var done = 0;
async Task BuildAsync((IDataProvider Connection, System.Collections.Concurrent.ConcurrentQueue Queue) work)
{
var builder = (IParallelImportProvider)work.Connection;
var pending = work.Queue;
while (pending.TryDequeue(out var index))
{
var indexStarted = DateTime.UtcNow;
await builder.CreateIndexAsync(index, ct);
var finished = Interlocked.Increment(ref done);
Console.WriteLine(
$" [{finished}/{indexes.Count}] {index.Table}.{index.Name} {(DateTime.UtcNow - indexStarted):hh\\:mm\\:ss}");
}
}
await Task.WhenAll(builders.Select(BuildAsync));
await parallel.ForgetDroppedIndexesAsync(ct);
Console.WriteLine($"Indexes rebuilt in {(DateTime.UtcNow - started):hh\\:mm\\:ss}.");
}
private void Log(string message)
{
if (_verbose) Console.WriteLine(message);
}
#region DataTable Creation and Row Mapping
private sealed class ImportTables
{
public DataTable Types { get; } = CreateTypesTable();
public DataTable Lists { get; } = CreateListsTable();
public DataTable Schemes { get; } = CreateSchemesTable();
public DataTable Structures { get; } = CreateStructuresTable();
public DataTable Migrations { get; } = CreateMigrationsTable();
public DataTable Roles { get; } = CreateRolesTable();
public DataTable Users { get; } = CreateUsersTable();
public DataTable UserRoles { get; } = CreateUserRolesTable();
public DataTable Objects { get; } = CreateObjectsTable();
public DataTable ListItems { get; } = CreateListItemsTable();
public DataTable Permissions { get; } = CreatePermissionsTable();
public DataTable Values { get; } = CreateValuesTable();
public long TypesTotal { get; set; }
public long ListsTotal { get; set; }
public long SchemesTotal { get; set; }
public long StructuresTotal { get; set; }
public long MigrationsTotal { get; set; }
public long RolesTotal { get; set; }
public long UsersTotal { get; set; }
public long UserRolesTotal { get; set; }
public long ListItemsTotal { get; set; }
public long PermissionsTotal { get; set; }
}
private static ImportTables CreateDataTables() => new();
private static DataTable CreateTypesTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_name", typeof(string));
dt.Columns.Add("_db_type", typeof(string));
dt.Columns.Add("_type", typeof(string));
return dt;
}
private static void AddTypeRow(DataTable dt, TypeRecord r)
{
dt.Rows.Add(r.Id, r.Name, r.DbType ?? (object)DBNull.Value, r.DotnetType ?? (object)DBNull.Value);
}
private static DataTable CreateListsTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_name", typeof(string));
dt.Columns.Add("_alias", typeof(string));
return dt;
}
private static void AddListRow(DataTable dt, ListRecord r)
{
dt.Rows.Add(r.Id, r.Name, r.Alias ?? (object)DBNull.Value);
}
private static DataTable CreateSchemesTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_id_parent", typeof(long));
dt.Columns.Add("_name", typeof(string));
dt.Columns.Add("_alias", typeof(string));
dt.Columns.Add("_name_space", typeof(string));
// uuid-semantic: object, not Guid - SQLite stores it as an RFC-ordered BLOB (GuidToDb).
dt.Columns.Add("_structure_hash", typeof(object));
dt.Columns.Add("_type", typeof(long));
dt.Columns.Add("_tags", typeof(string));
dt.Columns.Add("_renamed_from", typeof(string));
return dt;
}
private void AddSchemeRow(DataTable dt, SchemeRecord r)
{
dt.Rows.Add(
r.Id,
r.IdParent ?? (object)DBNull.Value,
r.Name,
r.Alias ?? (object)DBNull.Value,
r.NameSpace ?? (object)DBNull.Value,
GuidDb(r.StructureHash),
r.SchemeType,
r.Tags ?? (object)DBNull.Value,
r.RenamedFrom ?? (object)DBNull.Value
);
}
private static DataTable CreateStructuresTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_id_parent", typeof(long));
dt.Columns.Add("_id_scheme", typeof(long));
dt.Columns.Add("_id_override", typeof(long));
dt.Columns.Add("_id_type", typeof(long));
dt.Columns.Add("_id_list", typeof(long));
dt.Columns.Add("_name", typeof(string));
dt.Columns.Add("_alias", typeof(string));
dt.Columns.Add("_order", typeof(int));
dt.Columns.Add("_readonly", typeof(bool));
dt.Columns.Add("_allow_not_null", typeof(bool));
dt.Columns.Add("_collection_type", typeof(long));
dt.Columns.Add("_key_type", typeof(long));
dt.Columns.Add("_is_compress", typeof(bool));
dt.Columns.Add("_store_null", typeof(bool));
dt.Columns.Add("_default_value", typeof(byte[]));
dt.Columns.Add("_default_editor", typeof(string));
dt.Columns.Add("_unique", typeof(bool));
dt.Columns.Add("_unique_version", typeof(long));
dt.Columns.Add("_lazy", typeof(bool));
dt.Columns.Add("_unique_scope", typeof(long));
dt.Columns.Add("_tags", typeof(string));
dt.Columns.Add("_renamed_from", typeof(string));
return dt;
}
private static void AddStructureRow(DataTable dt, StructureRecord r)
{
dt.Rows.Add(
r.Id,
r.IdParent ?? (object)DBNull.Value,
r.IdScheme,
r.IdOverride ?? (object)DBNull.Value,
r.IdType,
r.IdList ?? (object)DBNull.Value,
r.Name,
r.Alias ?? (object)DBNull.Value,
r.Order ?? (object)DBNull.Value,
r.Readonly ?? (object)DBNull.Value,
r.AllowNotNull ?? (object)DBNull.Value,
r.CollectionType ?? (object)DBNull.Value,
r.KeyType ?? (object)DBNull.Value,
r.IsCompress ?? (object)DBNull.Value,
r.StoreNull ?? (object)DBNull.Value,
r.DefaultValue ?? (object)DBNull.Value,
r.DefaultEditor ?? (object)DBNull.Value,
r.Unique ?? (object)DBNull.Value,
r.UniqueVersion ?? (object)DBNull.Value,
r.Lazy ?? (object)DBNull.Value,
r.UniqueScope ?? (object)DBNull.Value,
r.Tags ?? (object)DBNull.Value,
r.RenamedFrom ?? (object)DBNull.Value
);
}
private static DataTable CreateRolesTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_name", typeof(string));
dt.Columns.Add("_id_configuration", typeof(long));
return dt;
}
private static void AddRoleRow(DataTable dt, RoleRecord r)
{
dt.Rows.Add(r.Id, r.Name, r.IdConfiguration ?? (object)DBNull.Value);
}
private static DataTable CreateUsersTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_login", typeof(string));
dt.Columns.Add("_password", typeof(string));
dt.Columns.Add("_name", typeof(string));
dt.Columns.Add("_phone", typeof(string));
dt.Columns.Add("_email", typeof(string));
dt.Columns.Add("_date_register", typeof(DateTimeOffset));
dt.Columns.Add("_date_dismiss", typeof(DateTimeOffset));
dt.Columns.Add("_enabled", typeof(bool));
dt.Columns.Add("_key", typeof(long));
dt.Columns.Add("_code_int", typeof(long));
dt.Columns.Add("_code_string", typeof(string));
dt.Columns.Add("_code_guid", typeof(Guid));
dt.Columns.Add("_note", typeof(string));
// uuid-semantic: object, not Guid - SQLite stores it as an RFC-ordered BLOB (GuidToDb).
dt.Columns.Add("_hash", typeof(object));
dt.Columns.Add("_id_configuration", typeof(long));
return dt;
}
private void AddUserRow(DataTable dt, UserRecord r)
{
dt.Rows.Add(
r.Id,
r.Login,
r.Password,
r.Name,
r.Phone ?? (object)DBNull.Value,
r.Email ?? (object)DBNull.Value,
(object)r.DateRegister,
r.DateDismiss.HasValue ? (object)r.DateDismiss.Value : DBNull.Value,
(object)r.Enabled,
r.Key ?? (object)DBNull.Value,
r.CodeInt ?? (object)DBNull.Value,
r.CodeString ?? (object)DBNull.Value,
r.CodeGuid ?? (object)DBNull.Value,
r.Note ?? (object)DBNull.Value,
GuidDb(r.Hash),
r.IdConfiguration ?? (object)DBNull.Value
);
}
private static DataTable CreateUserRolesTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_id_role", typeof(long));
dt.Columns.Add("_id_user", typeof(long));
return dt;
}
private static void AddUserRoleRow(DataTable dt, UserRoleRecord r)
{
dt.Rows.Add(r.Id, r.IdRole, r.IdUser);
}
private static DataTable CreateObjectsTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_id_parent", typeof(long));
dt.Columns.Add("_id_scheme", typeof(long));
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("_name", typeof(string));
dt.Columns.Add("_note", typeof(string));
// uuid-semantic: object, not Guid - SQLite stores it as an RFC-ordered BLOB (GuidToDb).
dt.Columns.Add("_hash", typeof(object));
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("_value_unique", typeof(string));
return dt;
}
private void AddObjectRow(DataTable dt, ObjectRecord r)
{
dt.Rows.Add(
r.Id,
r.IdParent ?? (object)DBNull.Value,
r.IdScheme,
(object)r.IdOwner,
(object)r.IdWhoChange,
(object)r.DateCreate,
(object)r.DateModify,
r.DateBegin.HasValue ? (object)r.DateBegin.Value : DBNull.Value,
r.DateComplete.HasValue ? (object)r.DateComplete.Value : DBNull.Value,
r.Key ?? (object)DBNull.Value,
r.Name ?? (object)DBNull.Value,
r.Note ?? (object)DBNull.Value,
GuidDb(r.Hash),
r.ValueLong ?? (object)DBNull.Value,
r.ValueString ?? (object)DBNull.Value,
r.ValueGuid ?? (object)DBNull.Value,
r.ValueBool ?? (object)DBNull.Value,
r.ValueDouble ?? (object)DBNull.Value,
r.ValueNumeric ?? (object)DBNull.Value,
r.ValueDatetime.HasValue ? (object)r.ValueDatetime.Value : DBNull.Value,
r.ValueBytes ?? (object)DBNull.Value,
r.ValueUnique ?? (object)DBNull.Value
);
}
private static DataTable CreateListItemsTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_id_list", typeof(long));
dt.Columns.Add("_value", typeof(string));
dt.Columns.Add("_alias", typeof(string));
dt.Columns.Add("_id_object", typeof(long));
return dt;
}
private static void AddListItemRow(DataTable dt, ListItemRecord r)
{
dt.Rows.Add(
r.Id,
r.IdList,
r.Value ?? (object)DBNull.Value,
r.Alias ?? (object)DBNull.Value,
r.IdObject ?? (object)DBNull.Value
);
}
private static DataTable CreatePermissionsTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_id_role", typeof(long));
dt.Columns.Add("_id_user", typeof(long));
dt.Columns.Add("_id_ref", typeof(long));
dt.Columns.Add("_select", typeof(bool));
dt.Columns.Add("_insert", typeof(bool));
dt.Columns.Add("_update", typeof(bool));
dt.Columns.Add("_delete", typeof(bool));
return dt;
}
private static void AddPermissionRow(DataTable dt, PermissionRecord r)
{
dt.Rows.Add(
r.Id,
r.IdRole ?? (object)DBNull.Value,
r.IdUser ?? (object)DBNull.Value,
(object)r.IdRef,
r.Select ?? (object)DBNull.Value,
r.Insert ?? (object)DBNull.Value,
r.Update ?? (object)DBNull.Value,
r.Delete ?? (object)DBNull.Value
);
}
private static DataTable CreateMigrationsTable()
{
var dt = new DataTable();
dt.Columns.Add("_id", typeof(long));
dt.Columns.Add("_migration_id", typeof(string));
dt.Columns.Add("_scheme_id", typeof(long));
dt.Columns.Add("_structure_id", typeof(long));
dt.Columns.Add("_property_name", typeof(string));
dt.Columns.Add("_expression_hash", typeof(string));
dt.Columns.Add("_migration_type", typeof(string));
dt.Columns.Add("_applied_at", typeof(DateTimeOffset));
dt.Columns.Add("_applied_by", typeof(string));
dt.Columns.Add("_sql_executed", typeof(string));
// INT on PostgreSQL and SQL Server.
dt.Columns.Add("_affected_rows", typeof(int));
dt.Columns.Add("_duration_ms", typeof(int));
dt.Columns.Add("_dry_run", typeof(bool));
return dt;
}
private static void AddMigrationRow(DataTable dt, MigrationRecord r)
{
dt.Rows.Add(
r.Id,
r.MigrationId,
r.SchemeId,
r.StructureId ?? (object)DBNull.Value,
r.PropertyName ?? (object)DBNull.Value,
r.ExpressionHash ?? (object)DBNull.Value,
r.MigrationType,
(object)r.AppliedAt,
r.AppliedBy ?? (object)DBNull.Value,
r.SqlExecuted ?? (object)DBNull.Value,
r.AffectedRows.HasValue ? checked((int)r.AffectedRows.Value) : DBNull.Value,
r.DurationMs.HasValue ? checked((int)r.DurationMs.Value) : DBNull.Value,
(object)r.DryRun
);
}
private static DataTable CreateValuesTable()
{
var dt = new DataTable();
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("_array_parent_id", typeof(long));
dt.Columns.Add("_array_index", typeof(string));
// uuid-semantic: object, not Guid - SQLite stores it as an RFC-ordered BLOB (GuidToDb).
dt.Columns.Add("_unique", typeof(object));
return dt;
}
private void AddValueRow(DataTable dt, ValueRecord r)
{
dt.Rows.Add(
r.Id,
r.IdStructure,
r.IdObject,
r.String ?? (object)DBNull.Value,
r.Long ?? (object)DBNull.Value,
r.Guid ?? (object)DBNull.Value,
r.Double ?? (object)DBNull.Value,
r.DateTimeOffset ?? (object)DBNull.Value,
r.Boolean ?? (object)DBNull.Value,
r.ByteArray ?? (object)DBNull.Value,
r.Numeric ?? (object)DBNull.Value,
r.ListItem ?? (object)DBNull.Value,
r.Object ?? (object)DBNull.Value,
r.ArrayParentId ?? (object)DBNull.Value,
r.ArrayIndex ?? (object)DBNull.Value,
GuidDb(r.Unique)
);
}
///
/// Provider form of a uuid-semantic column value (_hash , _structure_hash ,
/// _values._unique ): the Guid itself for PostgreSQL/MSSQL, an RFC 4122-ordered
/// BLOB for SQLite. Genuine binary columns never go through this.
///
private object GuidDb(Guid? value) => value is { } v ? _provider.GuidToDb(v) : DBNull.Value;
#endregion
private static async Task IsZipFileAsync(string filePath)
{
await using var stream = File.OpenRead(filePath);
var buffer = new byte[4];
var read = await stream.ReadAsync(buffer);
// ZIP magic number: PK\x03\x04
return read >= 4 && buffer[0] == 0x50 && buffer[1] == 0x4B &&
buffer[2] == 0x03 && buffer[3] == 0x04;
}
}
Path: redb/redb.Export/Services/ParallelImportWriter.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.Export/Services/ParallelImportWriter.cs
----
using System.Data;
using System.Threading.Channels;
using redb.Export.Providers;
namespace redb.Export.Services;
///
/// Writes batches of rows over several connections at once.
///
/// The reader hands each full batch over and goes on reading; a fixed number of workers, one
/// connection each, send the batches to the database. The queue between them is bounded, so a
/// reader that outruns the database waits instead of filling memory with rows.
///
internal sealed class ParallelImportWriter : IAsyncDisposable
{
private readonly Channel<(string Table, DataTable Rows)> _queue;
private readonly List _connections = new();
private readonly List _workers = new();
private readonly CancellationTokenSource _stop;
private ParallelImportWriter(int degree, CancellationToken ct)
{
_stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
_queue = Channel.CreateBounded<(string, DataTable)>(new BoundedChannelOptions(degree * 2)
{
SingleWriter = true,
FullMode = BoundedChannelFullMode.Wait
});
}
/// Connections the workers hold; reused afterwards to build indexes.
public IReadOnlyList Connections => _connections;
public static async Task StartAsync(
IParallelImportProvider provider, int degree, CancellationToken ct)
{
var writer = new ParallelImportWriter(degree, ct);
try
{
for (var i = 0; i < degree; i++)
writer._connections.Add(await provider.OpenWorkerAsync(ct));
}
catch
{
await writer.DisposeAsync();
throw;
}
foreach (var connection in writer._connections)
writer._workers.Add(Task.Run(() => writer.RunAsync(connection)));
return writer;
}
///
/// Queues a batch. Waits while the queue is full; fails at once if a worker has already failed,
/// so the reader does not go on parsing a file whose rows nobody will write.
///
public async ValueTask EnqueueAsync(string table, DataTable rows)
{
try
{
await _queue.Writer.WriteAsync((table, rows), _stop.Token);
}
catch (OperationCanceledException) when (FirstFailure() is { } failure)
{
throw new InvalidOperationException("A writer connection failed: " + failure.Message, failure);
}
}
/// Waits until every queued batch is written. Rethrows the first worker failure.
public async Task CompleteAsync()
{
_queue.Writer.TryComplete();
await Task.WhenAll(_workers);
}
private async Task RunAsync(IDataProvider connection)
{
try
{
await foreach (var (table, rows) in _queue.Reader.ReadAllAsync(_stop.Token))
{
await connection.BulkInsertAsync(table, rows, _stop.Token);
rows.Dispose();
}
}
catch (OperationCanceledException) when (_stop.IsCancellationRequested)
{
// Another worker failed or the caller cancelled; that one carries the reason.
}
catch
{
await _stop.CancelAsync();
throw;
}
}
private Exception? FirstFailure()
=> _workers.Where(w => w.IsFaulted).Select(w => w.Exception?.GetBaseException()).FirstOrDefault(e => e != null);
public async ValueTask DisposeAsync()
{
_queue.Writer.TryComplete();
await _stop.CancelAsync();
try
{
await Task.WhenAll(_workers);
}
catch
{
// Already reported through CompleteAsync or EnqueueAsync.
}
foreach (var connection in _connections)
await connection.DisposeAsync();
_stop.Dispose();
}
}
///
/// Read-only stream wrapper that counts the bytes read, so progress through a compressed file can
/// be told from the uncompressed length even though the underlying stream cannot report a position.
///
internal sealed class CountingStream(Stream inner) : Stream
{
private long _read;
public long BytesRead => Interlocked.Read(ref _read);
public override int Read(byte[] buffer, int offset, int count)
{
var n = inner.Read(buffer, offset, count);
Interlocked.Add(ref _read, n);
return n;
}
public override int Read(Span buffer)
{
var n = inner.Read(buffer);
Interlocked.Add(ref _read, n);
return n;
}
public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
{
var n = await inner.ReadAsync(buffer, cancellationToken);
Interlocked.Add(ref _read, n);
return n;
}
public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var n = await inner.ReadAsync(buffer.AsMemory(offset, count), cancellationToken);
Interlocked.Add(ref _read, n);
return n;
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => BytesRead; set => throw new NotSupportedException(); }
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing) inner.Dispose();
base.Dispose(disposing);
}
public override async ValueTask DisposeAsync()
{
await inner.DisposeAsync();
await base.DisposeAsync();
}
}
Path: redb/redb.Export/Services/RedbSchemaProbe.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.Export/Services/RedbSchemaProbe.cs
----
using System.Data;
using System.Data.Common;
using redb.Core.Query;
using redb.Export.Providers;
namespace redb.Export.Services;
/// Whether a database holds the redb schema at all: its core table _schemes , as a service start asks.
internal static class RedbSchemaProbe
{
public static async Task ExistsAsync(IDataProvider provider, CancellationToken ct)
{
var (dialect, table, schema) = provider.Name switch
{
"postgres" => ((ISqlDialect)new global::redb.Postgres.Sql.PostgreSqlDialect(), "", ""),
"mssql" => (new global::redb.MSSql.Sql.MsSqlDialect(), "@p0", "@p1"),
"sqlite" => (new global::redb.SQLite.Sql.SqliteDialect(), "$1", "$2"),
_ => throw new ArgumentException($"Unknown provider: {provider.Name}", nameof(provider)),
};
await using var command = provider.Connection.CreateCommand();
command.CommandText = dialect.Maintenance_SelectTableExists();
command.Parameters.Add(Parameter(command, table, "_schemes"));
command.Parameters.Add(Parameter(command, schema, null));
return Convert.ToInt64(await command.ExecuteScalarAsync(ct)) > 0;
}
/// A parameter by the name the dialect's statement uses; an empty name is a positional one (PostgreSQL).
private static DbParameter Parameter(DbCommand command, string name, string? value)
{
var parameter = command.CreateParameter();
parameter.ParameterName = name;
parameter.DbType = DbType.String;
parameter.Value = (object?)value ?? DBNull.Value;
return parameter;
}
}
Path: redb/redb.Export/Services/SchemaGate.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.Export/Services/SchemaGate.cs
----
using System.Data.Common;
using System.Globalization;
using redb.Core.Data;
using redb.Core.Exceptions;
using redb.Export.Providers;
namespace redb.Export.Services;
///
/// The schema an export or import needs from its database: what a redb service of this build requires at start.
/// PostgreSQL and SQL Server state it through their module functions, SQLite through PRAGMA user_version .
///
/// Provider name as the services report it (PostgreSQL, MSSql, SQLite).
/// Module version (SQLite: file schema version) this build requires.
/// Module version function; null on SQLite.
/// Module compatibility function; null on SQLite.
internal sealed record ExpectedSchema(string Provider, string RequiredVersion, string? VersionFunction, string? CompatFunction)
{
internal bool IsSqlite => VersionFunction is null;
/// The schema the provider build referenced by redb.Export requires, for an export provider.
public static ExpectedSchema For(IDataProvider provider) => provider.Name switch
{
"postgres" => FromDialect("PostgreSQL", new global::redb.Postgres.Sql.PostgreSqlDialect()),
"mssql" => FromDialect("MSSql", new global::redb.MSSql.Sql.MsSqlDialect()),
"sqlite" => new ExpectedSchema("SQLite",
global::redb.SQLite.RedbService.SchemaVersion.ToString(CultureInfo.InvariantCulture), null, null),
_ => throw new ArgumentException($"Unknown provider: {provider.Name}", nameof(provider)),
};
private static ExpectedSchema FromDialect(string name, global::redb.Core.Query.ISqlDialect dialect) =>
new(name, dialect.Query_PvtRequiredVersion()!, dialect.Query_PvtModuleVersionFunction()!, dialect.Query_PvtModuleCompatFunction());
}
///
/// Stops an export from or an import into a database whose schema this build does not match, before anything is read
/// for the file or written to the database, with the exceptions a redb service throws at start:
///
/// - the same version passes;
/// - an older one stops with
: the tool upgrades nothing;
/// - a newer database is refused for an export whatever it serves (the file would miss what this build does not
/// know), and passes for an import only when it says it still serves this build, as a service start does;
/// otherwise
.
///
/// Without it the first statement naming a column the database does not have failed with a driver error, and a
/// parallel import had already committed its cleaning by then.
///
internal static class SchemaGate
{
private const string Reason = "the redb CLI does not upgrade a database";
///
/// Checks the source of an export and returns its schema version as read: the module version on PostgreSQL and
/// SQL Server, PRAGMA user_version on SQLite.
///
public static Task CheckSourceAsync(IDataProvider provider, CancellationToken ct) =>
CheckAsync(provider, ExpectedSchema.For(provider), export: true, ct);
/// Checks the target of an import.
public static Task CheckTargetAsync(IDataProvider provider, CancellationToken ct) =>
CheckAsync(provider, ExpectedSchema.For(provider), export: false, ct);
/// Checks the database and returns the schema version it states.
private static async Task CheckAsync(IDataProvider provider, ExpectedSchema expected, bool export, CancellationToken ct)
{
var connection = provider.Connection;
// A database without the redb schema is not an older one: it needs `redb init`, not an upgrade.
if (!await RedbSchemaProbe.ExistsAsync(provider, ct))
{
throw new InvalidOperationException(export
? $"The {expected.Provider} database holds no redb schema (table _schemes not found): there is nothing " +
"to export, and nothing was read. Check that the connection string names the database you meant."
: $"The {expected.Provider} database holds no redb schema (table _schemes not found), and nothing was " +
$"changed. Create it with `redb init --provider {provider.Name}`, then import again.");
}
var (deployed, newer) = expected.IsSqlite
? await ReadSqliteAsync(connection, expected, ct)
: await ReadModuleAsync(connection, expected, ct);
if (deployed == expected.RequiredVersion)
return expected.RequiredVersion;
var what = export ? "export from it" : "import into it";
if (!newer)
{
// No version number: a build between releases carries the last released one, and naming it would send
// the reader to the wrong packages. `redb --version` prints this CLI's own.
var remedy = expected.IsSqlite
? $"Upgrade the file with `redb init --provider sqlite` of this CLI, or open it once with a redb " +
$"application of the same redb version as this CLI (`redb --version`), then {what} again."
: $"Bring the database to the module this build requires: have the schema owner run the script of " +
$"`redb schema --upgrade --provider {CliProviderName(expected)}` with psql / sqlcmd, or start a redb " +
$"application of the same redb version as this CLI (`redb --version`) on it, then {what} again.";
throw new RedbSchemaOutdatedException(expected.Provider, deployed, expected.RequiredVersion, Reason, remedy);
}
var (serves, fromPackage) = await ReadCompatAsync(connection, expected, ct);
if (export)
{
throw new RedbSchemaNewerException(expected.Provider, deployed!, expected.RequiredVersion, fromPackage,
"An export by this redb CLI would leave out what its build does not know of the newer schema: export " +
"with a redb CLI of the version whose packages run on this database.");
}
if (!serves)
{
throw new RedbSchemaNewerException(expected.Provider, deployed!, expected.RequiredVersion, fromPackage,
"Import with a redb CLI of the version whose packages run on this database.");
}
return deployed!;
}
/// The module version and whether it is newer than the required one; a missing module reads as null.
private static async Task<(string? Deployed, bool Newer)> ReadModuleAsync(
DbConnection connection, ExpectedSchema expected, CancellationToken ct)
{
var deployed = await TryScalarFunctionAsync(connection, expected.VersionFunction!, ct);
return (deployed, ModuleCompatibility.IsNewer(deployed, expected.RequiredVersion));
}
/// The file schema version and whether it is newer than the one this build writes.
private static async Task<(string? Deployed, bool Newer)> ReadSqliteAsync(
DbConnection connection, ExpectedSchema expected, CancellationToken ct)
{
await using var command = connection.CreateCommand();
command.CommandText = "PRAGMA user_version";
var version = Convert.ToInt64(await command.ExecuteScalarAsync(ct), CultureInfo.InvariantCulture);
var required = long.Parse(expected.RequiredVersion, CultureInfo.InvariantCulture);
return (version.ToString(CultureInfo.InvariantCulture), version > required);
}
///
/// Whether the newer database serves this build, and the package version it names. PostgreSQL and SQL Server ask
/// the module's compatibility function ( ); SQLite reads the
/// _schema_compat row as the SQLite service does, and a file without it serves nothing.
///
private static async Task<(bool Serves, string? FromPackage)> ReadCompatAsync(
DbConnection connection, ExpectedSchema expected, CancellationToken ct)
{
if (!expected.IsSqlite)
{
var compat = expected.CompatFunction is null ? null : await TryScalarFunctionAsync(connection, expected.CompatFunction, ct);
var serves = ModuleCompatibility.Serves(compat, expected.RequiredVersion, out var fromPackage);
return (serves, fromPackage);
}
await using (var exists = connection.CreateCommand())
{
exists.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '_schema_compat'";
if (Convert.ToInt64(await exists.ExecuteScalarAsync(ct), CultureInfo.InvariantCulture) == 0)
return (false, null);
}
await using var command = connection.CreateCommand();
command.CommandText = "SELECT _min_reader, _package FROM _schema_compat LIMIT 1";
await using var reader = await command.ExecuteReaderAsync(ct);
if (!await reader.ReadAsync(ct))
return (false, null);
var minReader = reader.IsDBNull(0) ? (long?)null : reader.GetInt64(0);
var package = reader.IsDBNull(1) ? null : reader.GetString(1);
var own = long.Parse(expected.RequiredVersion, CultureInfo.InvariantCulture);
return (minReader is not null && minReader <= own, package);
}
private static async Task TryScalarFunctionAsync(DbConnection connection, string function, CancellationToken ct)
{
await using var command = connection.CreateCommand();
command.CommandText = $"SELECT {function}()";
try
{
var value = await command.ExecuteScalarAsync(ct);
return value is null or DBNull ? null : Convert.ToString(value, CultureInfo.InvariantCulture);
}
catch (Exception ex) when (DbErrorClassifier.IsUndefinedFunction(ex))
{
return null;
}
}
private static string CliProviderName(ExpectedSchema expected) =>
expected.Provider == "PostgreSQL" ? "postgres" : "mssql";
}
Path: redb/redb.Export/Services/SchemaInitService.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.Export/Services/SchemaInitService.cs
----
using System.Text.RegularExpressions;
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Core.Extensions;
using redb.Export.Providers;
using redb.SQLite.Extensions;
namespace redb.Export.Services;
///
/// Creates the redb schema in a database, as redb init does: the schema an export can be imported into.
///
public static class SchemaInitService
{
///
/// Creates the schema. PostgreSQL and SQL Server run the provider's initialization script, which deploys the module
/// too, into a database without the redb schema only: one that holds it is refused before anything runs. SQLite goes through the SQLite service's : the schema script
/// and then the file stamp (PRAGMA user_version and the _schema_compat row) that the service and the
/// export schema check read. The script alone left the file unstamped, and an import into it was refused as into
/// an older file.
///
/// postgres, mssql or sqlite (the names redb init takes).
/// The database.
/// Progress lines, or null.
/// Cancellation token.
public static async Task InitializeAsync(string provider, string connectionString, Action? log = null,
CancellationToken ct = default)
{
if (IsSqlite(provider))
{
var services = new ServiceCollection();
services.AddRedb(options => options.UseSqlite(connectionString));
await using var serviceProvider = services.BuildServiceProvider();
log?.Invoke("Creating the schema through the SQLite service...");
await serviceProvider.GetRequiredService().EnsureDatabaseAsync();
return;
}
await using var dataProvider = ProviderFactory.Create(provider);
await dataProvider.OpenAsync(connectionString, ct);
// The scripts create a schema in an empty database. Over an existing one both stop at their guard on _types
// before any statement changes it, with a message of their own; refused here first, with the same advice,
// before anything is sent.
// SQL Server runs its script batch by batch, each committed on its own, so a run that stopped half-way leaves
// part of the schema behind; an upgrade cannot finish it. Told apart from a complete schema before the general
// refusal, whose first advice is the upgrade.
if (IsMssql(provider) && await ReadMssqlSchemaStateAsync(dataProvider, ct) == MssqlSchemaState.Incomplete)
throw HalfCreatedMssql(changedNothing: true, cause: null);
if (await RedbSchemaProbe.ExistsAsync(dataProvider, ct))
{
throw new InvalidOperationException(
"The database already holds the redb schema; `redb init` creates it in an empty database only and has " +
$"changed nothing. Upgrade an existing schema with `redb schema --upgrade --provider {dataProvider.Name}` " +
"or by starting the service; to start over, drop and create the database first.");
}
// PostgreSQL older than 15 fails in the middle of the script on NULLS NOT DISTINCT: refused first, by name.
if (IsPostgres(provider))
{
await using var versionCommand = dataProvider.Connection.CreateCommand();
versionCommand.CommandText = redb.Postgres.Data.PostgresServerVersion.Query;
redb.Postgres.Data.PostgresServerVersion.EnsureSupported(
Convert.ToString(await versionCommand.ExecuteScalarAsync(ct), System.Globalization.CultureInfo.InvariantCulture));
}
var sql = GetSchemaScript(provider);
log?.Invoke($"Schema script: {sql.Length:N0} characters.");
if (IsMssql(provider))
{
var executed = 0;
try
{
foreach (var batch in Regex.Split(sql, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase))
{
var trimmed = batch.Trim();
if (string.IsNullOrEmpty(trimmed)) continue;
await using var command = dataProvider.Connection.CreateCommand();
command.CommandText = trimmed;
command.CommandTimeout = 300;
await command.ExecuteNonQueryAsync(ct);
executed++;
}
}
catch (Exception ex)
{
// The batches before the failure are committed. Whether they left any of the schema is read from the
// catalog: a failure before the first table (the database option batch) leaves an empty database, and
// its own error says more.
MssqlSchemaState state;
try
{
state = await ReadMssqlSchemaStateAsync(dataProvider, CancellationToken.None);
}
catch (Exception readError)
{
throw new InvalidOperationException(
$"The creation script failed after {executed} batch(es) ({ex.Message}), and the database could " +
"not be read afterwards: it may hold part of the redb schema. `redb init` cannot complete it and " +
"an upgrade cannot either: drop and create the database, then run `redb init` again.",
new AggregateException(ex, readError));
}
if (state == MssqlSchemaState.Empty)
throw;
throw HalfCreatedMssql(changedNothing: false, cause: ex);
}
log?.Invoke($"Executed {executed} SQL batches.");
}
else
{
await using var command = dataProvider.Connection.CreateCommand();
command.CommandText = sql;
command.CommandTimeout = 300;
await command.ExecuteNonQueryAsync(ct);
}
}
/// The full schema initialization script of a provider, embedded in its assembly.
/// postgres, mssql or sqlite.
public static string GetSchemaScript(string provider)
{
var (assembly, resourceName) = provider.ToLowerInvariant() switch
{
"postgres" or "postgresql" or "pgsql" =>
(typeof(redb.Postgres.RedbService).Assembly, "redb.Postgres.sql.redb_init.sql"),
"mssql" or "sqlserver" =>
(typeof(redb.MSSql.RedbService).Assembly, "redb.MSSql.sql.redb_init.sql"),
"sqlite" =>
(typeof(redb.SQLite.RedbService).Assembly, "redb.SQLite.sql.redbSqlite.sql"),
_ => throw new ArgumentException($"Unknown provider: {provider}", nameof(provider))
};
using var stream = assembly.GetManifestResourceStream(resourceName)
?? throw new InvalidOperationException(
$"Embedded resource '{resourceName}' not found in {assembly.GetName().Name}.");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
private enum MssqlSchemaState { Empty, Incomplete, Complete }
///
/// Whether a SQL Server database holds none of the redb schema, part of it, or all of it. The creation script
/// creates _types first and deploys dbo.pvt_module_version last (99_module_version.sql; the module init
/// drops it before it redeploys the module), so a redb table without that function is a schema the script did not
/// finish.
///
private static async Task ReadMssqlSchemaStateAsync(IDataProvider provider, CancellationToken ct)
{
await using var command = provider.Connection.CreateCommand();
command.CommandText =
"SELECT CASE WHEN OBJECT_ID(N'dbo._types', N'U') IS NULL AND OBJECT_ID(N'dbo._schemes', N'U') IS NULL THEN 0 " +
"WHEN OBJECT_ID(N'dbo.pvt_module_version', N'FN') IS NULL THEN 1 ELSE 2 END";
return (MssqlSchemaState)Convert.ToInt32(await command.ExecuteScalarAsync(ct), System.Globalization.CultureInfo.InvariantCulture);
}
private static InvalidOperationException HalfCreatedMssql(bool changedNothing, Exception? cause) => new(
(cause is null
? "The database holds part of the redb schema: its tables are there, but not dbo.pvt_module_version, which " +
"the creation script deploys last. An earlier `redb init` or run of the creation script stopped half-way; " +
"an upgrade cannot complete it. "
: $"The creation script failed in the middle ({cause.Message}). The database now holds part of the redb " +
"schema: SQL Server commits the script batch by batch, and those before the failure stay. An upgrade " +
"cannot complete it. ") +
(changedNothing ? "`redb init` has changed nothing. " : "") +
"To create the schema, drop and create the database first, then run `redb init` again. If it is a database of " +
"an old redb version that holds data, start a redb application of this version on it instead.",
cause);
private static bool IsPostgres(string provider) => provider.ToLowerInvariant() is "postgres" or "postgresql" or "pgsql";
private static bool IsMssql(string provider) => provider.ToLowerInvariant() is "mssql" or "sqlserver";
private static bool IsSqlite(string provider) => provider.ToLowerInvariant() is "sqlite";
}
Path: redb/redb.Export/redb.Export.csproj
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Export/redb.Export.csproj
----
net10.0;net11.0
enable
enable
true
redb.Export
REDB - Entity Database for .NET
Database export/import library for REDB. Supports PostgreSQL and MS SQL Server. Streams schema and data as JSONL (optionally compressed) for backup, migration, and replication scenarios.
https://github.com/redbase-app/redb
README.md
redb;export;import;database;postgres;mssql;migration;backup