Bundle: redb / redb.CLI (redb.CLI.txt), 3 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.CLI/Program.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.CLI/Program.cs
----
using System.CommandLine;
using System.Data.Common;
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.Extensions.DependencyInjection;
using redb.Core.Attributes;
using redb.Export.Flat;
using redb.Export.Providers;
using redb.Export.Services;
namespace redb.CLI;
///
/// REDB CLI - Command line tool for database export/import operations.
///
/// === PostgreSQL ===
///
/// Export (with compression):
/// dotnet run -- export -p postgres -c "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true;Include Error Detail=true;Timeout=600;Command Timeout=600" -o data.redb --compress --batch-size 100000 -v
///
/// Import (with clean):
/// dotnet run -- import -p postgres -c "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true;Include Error Detail=true;Timeout=600;Command Timeout=600" -i data.redb --clean -v --batch-size 100000
///
/// === MS SQL Server ===
///
/// Export (with compression):
/// dotnet run -- export -p mssql -c "Server=localhost;Database=redb;User Id=sa;Password=1;TrustServerCertificate=True;Command Timeout=600" -o data.redb --compress --batch-size 100000 -v
///
/// Import (with clean):
/// dotnet run -- import -p mssql -c "Server=localhost;Database=redb;User Id=sa;Password=1;TrustServerCertificate=True;Command Timeout=600" -i data.redb --clean -v --batch-size 100000
///
/// === Flat export (redb objects -> ordinary relational tables) ===
///
/// Print the DDL of the flat tables, no database opened:
/// dotnet run -- flat -a MyApp.Models.dll -tp postgres --ddl-only
///
/// Unfold and copy (source and target are independent connections, of any two providers):
/// dotnet run -- flat -a MyApp.Models.dll -sp postgres -sc "Host=localhost;Database=redb;..." -tp mssql -tc "Server=localhost;Database=flat;..." --batch-size 10000 -v
///
/// --types - Props classes to unfold (name or full name, comma-separated);
/// default: every class marked with [RedbScheme] in the assembly
///
/// === Options ===
/// --compress - compress exported file with ZIP (export only)
/// --clean - clean database before import (import only)
/// --schemes - export only specified scheme IDs: --schemes 100,200
/// --dry-run - show what would be done without execution
/// --batch-size - batch size for operations (default: 1000)
/// -v, --verbose - enable verbose output
///
public static class Program
{
public static async Task Main(string[] args)
{
// The texts of System.CommandLine itself (help headings, parse errors) follow the UI culture; keep them in
// English like the rest of the tool, whatever the language of the operating system.
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
var rootCommand = new RootCommand("REDB CLI - Database export/import tool");
// Common options
var connectionOption = new Option("--connection", "-c")
{
Description = "Database connection string",
Required = true
};
var providerOption = new Option("--provider", "-p")
{
Description = "Database provider: postgres | mssql | oracle | sqlite",
Required = true
};
var verboseOption = new Option("--verbose", "-v")
{
Description = "Enable verbose output"
};
var batchSizeOption = new Option("--batch-size")
{
Description = "Batch size for operations (default: 1000)",
DefaultValueFactory = _ => 1000
};
var dryRunOption = new Option("--dry-run")
{
Description = "Show what would be done without making changes"
};
// Export command
var exportCommand = new Command("export", "Export database to .redb file");
var outputOption = new Option("--output", "-o")
{
Description = "Output file path (.redb)",
Required = true
};
var compressOption = new Option("--compress")
{
Description = "Compress output file with ZIP"
};
var schemesOption = new Option("--schemes")
{
Description = "Export only specified scheme IDs (comma-separated): --schemes 100,200,300"
};
exportCommand.Options.Add(connectionOption);
exportCommand.Options.Add(providerOption);
exportCommand.Options.Add(outputOption);
exportCommand.Options.Add(compressOption);
exportCommand.Options.Add(schemesOption);
exportCommand.Options.Add(verboseOption);
exportCommand.Options.Add(batchSizeOption);
exportCommand.Options.Add(dryRunOption);
exportCommand.SetAction(async (parseResult, ct) =>
{
var connection = parseResult.GetValue(connectionOption)!;
var provider = parseResult.GetValue(providerOption)!;
var output = parseResult.GetValue(outputOption)!;
var compress = parseResult.GetValue(compressOption);
var schemesStr = parseResult.GetValue(schemesOption);
var verbose = parseResult.GetValue(verboseOption);
var batchSize = parseResult.GetValue(batchSizeOption);
var dryRun = parseResult.GetValue(dryRunOption);
long[]? schemeIds = null;
if (!string.IsNullOrWhiteSpace(schemesStr))
{
schemeIds = schemesStr.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(s => long.Parse(s.Trim()))
.ToArray();
}
return await ExportAsync(connection, provider, output, compress, schemeIds,
verbose, batchSize, dryRun, ct);
});
// Import command
var importCommand = new Command("import",
"Import database from .redb file. Restart every application that uses the target database afterwards: " +
"the ids it reserved before the import can belong to imported rows.");
var inputOption = new Option("--input", "-i")
{
Description = "Input file path (.redb)",
Required = true
};
var cleanOption = new Option("--clean")
{
Description = "Clean database before import"
};
importCommand.Options.Add(connectionOption);
importCommand.Options.Add(providerOption);
importCommand.Options.Add(inputOption);
var parallelOption = new Option("--parallel", "-j")
{
Description = "Number of connections to load over (postgres). 1 keeps the whole import in one " +
"transaction. More than 1 loads in parallel and rebuilds the secondary indexes of the " +
"large tables afterwards: much faster on a large file, but not atomic - a run that " +
"fails leaves a partly loaded database to be imported again with --clean.",
DefaultValueFactory = _ => 1
};
importCommand.Options.Add(cleanOption);
importCommand.Options.Add(parallelOption);
importCommand.Options.Add(verboseOption);
importCommand.Options.Add(batchSizeOption);
importCommand.Options.Add(dryRunOption);
importCommand.SetAction(async (parseResult, ct) =>
{
var connection = parseResult.GetValue(connectionOption)!;
var provider = parseResult.GetValue(providerOption)!;
var input = parseResult.GetValue(inputOption)!;
var clean = parseResult.GetValue(cleanOption);
var verbose = parseResult.GetValue(verboseOption);
var batchSize = parseResult.GetValue(batchSizeOption);
var dryRun = parseResult.GetValue(dryRunOption);
var parallel = parseResult.GetValue(parallelOption);
return await ImportAsync(connection, provider, input, clean,
verbose, batchSize, dryRun, parallel, ct);
});
rootCommand.Subcommands.Add(exportCommand);
rootCommand.Subcommands.Add(importCommand);
// Init command — create REDB schema in a database
var initCommand = new Command("init", "Create REDB schema in an existing database");
initCommand.Options.Add(connectionOption);
initCommand.Options.Add(providerOption);
initCommand.Options.Add(verboseOption);
initCommand.SetAction(async (parseResult, ct) =>
{
var connection = parseResult.GetValue(connectionOption)!;
var provider = parseResult.GetValue(providerOption)!;
var verbose = parseResult.GetValue(verboseOption);
return await InitSchemaAsync(connection, provider, verbose, ct);
});
// Schema command — export REDB schema SQL to stdout or file
var schemaCommand = new Command("schema", "Export REDB schema SQL script");
schemaCommand.Options.Add(providerOption);
var schemaOutputOption = new Option("--output", "-o")
{
Description = "Output file path. If omitted, writes to stdout."
};
schemaCommand.Options.Add(schemaOutputOption);
var schemaUpgradeOption = new Option("--upgrade")
{
Description = "Export the upgrade script for an EXISTING database (the versioned SQL module) " +
"instead of the full schema. Hand it to the schema owner when the application " +
"is not allowed to apply it itself. Idempotent, safe to re-run. " +
"Not available for sqlite (the database file upgrades itself)."
};
schemaCommand.Options.Add(schemaUpgradeOption);
schemaCommand.SetAction(parseResult =>
{
var provider = parseResult.GetValue(providerOption)!;
var output = parseResult.GetValue(schemaOutputOption);
var upgrade = parseResult.GetValue(schemaUpgradeOption);
ExportSchemaScript(provider, output, upgrade);
});
rootCommand.Subcommands.Add(initCommand);
rootCommand.Subcommands.Add(schemaCommand);
// Indexes command — compare the indexes of a database with those of the base schema, build the missing ones
var indexesCommand = new Command("indexes",
"Check the indexes of a database against the base schema of this build, or build the missing ones");
var indexesCheck = new Command("check",
"Report every base index that is missing, INVALID or defined otherwise (exit code 2 when there is one). " +
"Read only. The indexes of Pro modules are checked by the application (CheckBaseIndexesAsync).");
indexesCheck.Options.Add(connectionOption);
indexesCheck.Options.Add(providerOption);
var indexesRepair = new Command("repair",
"Build the missing base indexes, and again those left INVALID: PostgreSQL CONCURRENTLY, SQL Server ONLINE " +
"where the edition has it, SQLite plainly. An index defined otherwise is reported, never changed.");
indexesRepair.Options.Add(connectionOption);
indexesRepair.Options.Add(providerOption);
var indexNameOption = new Option("--name", "-n")
{
Description = "Build only these indexes (repeatable). Default: every missing one.",
AllowMultipleArgumentsPerToken = true
};
var offlineOption = new Option("--offline")
{
Description = "SQL Server editions without ONLINE index operations: build anyway, which blocks writes to " +
"the table while each index builds. Without it the statements are printed instead."
};
indexesRepair.Options.Add(indexNameOption);
indexesRepair.Options.Add(offlineOption);
indexesCheck.SetAction(async (parseResult, ct) =>
await IndexesAsync(parseResult.GetValue(providerOption)!, parseResult.GetValue(connectionOption)!,
repair: false, names: null, offline: false, ct));
indexesRepair.SetAction(async (parseResult, ct) =>
await IndexesAsync(parseResult.GetValue(providerOption)!, parseResult.GetValue(connectionOption)!,
repair: true, names: parseResult.GetValue(indexNameOption), offline: parseResult.GetValue(offlineOption), ct));
indexesCommand.Subcommands.Add(indexesCheck);
indexesCommand.Subcommands.Add(indexesRepair);
rootCommand.Subcommands.Add(indexesCommand);
// Flat command — unfold redb objects into ordinary relational tables
var flatCommand = new Command("flat",
"Unfold redb objects into flat relational tables and copy the data into them");
var sourceConnectionOption = new Option("--source-connection", "-sc")
{
Description = "Connection string of the redb database to read"
};
var sourceProviderOption = new Option("--source-provider", "-sp")
{
Description = "Provider of the source database: postgres | mssql | sqlite"
};
var targetConnectionOption = new Option("--target-connection", "-tc")
{
Description = "Connection string of the database that receives the flat tables " +
"(may be the source database itself; the tables must not exist yet)"
};
var targetProviderOption = new Option("--target-provider", "-tp")
{
Description = "Provider of the target database: postgres | mssql | sqlite",
Required = true
};
var assemblyOption = new Option("--assembly", "-a")
{
Description = "Path to an assembly that declares Props classes. Give several paths, or repeat " +
"the option, when the classes live in more than one project. The dependencies of " +
"each assembly are resolved from the folder it lies in.",
Required = true,
AllowMultipleArgumentsPerToken = true
};
var typesOption = new Option("--types")
{
Description = "Props classes to unfold, by name or full name (comma-separated). " +
"When omitted, every class marked with [RedbScheme] in the given assemblies is taken."
};
var ddlOnlyOption = new Option("--ddl-only")
{
Description = "Print the DDL of the flat tables for the target provider and exit. " +
"No database is opened; only --assembly and --target-provider are needed."
};
flatCommand.Options.Add(sourceConnectionOption);
flatCommand.Options.Add(sourceProviderOption);
flatCommand.Options.Add(targetConnectionOption);
flatCommand.Options.Add(targetProviderOption);
flatCommand.Options.Add(assemblyOption);
flatCommand.Options.Add(typesOption);
flatCommand.Options.Add(ddlOnlyOption);
flatCommand.Options.Add(verboseOption);
flatCommand.Options.Add(batchSizeOption);
flatCommand.SetAction(async (parseResult, ct) =>
{
var sourceConnection = parseResult.GetValue(sourceConnectionOption);
var sourceProvider = parseResult.GetValue(sourceProviderOption);
var targetConnection = parseResult.GetValue(targetConnectionOption);
var targetProvider = parseResult.GetValue(targetProviderOption)!;
var assemblyPaths = parseResult.GetValue(assemblyOption)!;
var typesStr = parseResult.GetValue(typesOption);
var ddlOnly = parseResult.GetValue(ddlOnlyOption);
var verbose = parseResult.GetValue(verboseOption);
var batchSize = parseResult.GetValue(batchSizeOption);
return await FlatAsync(sourceConnection, sourceProvider, targetConnection, targetProvider,
assemblyPaths, typesStr, ddlOnly, verbose, batchSize, ct);
});
rootCommand.Subcommands.Add(flatCommand);
return await rootCommand.Parse(args).InvokeAsync();
}
// === Flat Export ===
private static async Task FlatAsync(
string? sourceConnection,
string? sourceProvider,
string? targetConnection,
string targetProvider,
string[] assemblyPaths,
string? typesStr,
bool ddlOnly,
bool verbose,
int batchSize,
CancellationToken ct)
{
try
{
var propsTypes = LoadPropsTypes(assemblyPaths, typesStr);
await using var target = ProviderFactory.Create(targetProvider);
if (ddlOnly)
{
// Built without the source, so without structure ids: the shape of the tables does
// not depend on them. Nothing but the script goes to stdout.
var model = new FlatModelBuilder().Build(propsTypes);
Console.WriteLine(new FlatDdlGenerator(target.Name).Script(model));
return 0;
}
if (string.IsNullOrWhiteSpace(sourceConnection) ||
string.IsNullOrWhiteSpace(sourceProvider) ||
string.IsNullOrWhiteSpace(targetConnection))
{
throw new ArgumentException(
"--source-connection, --source-provider and --target-connection are required unless --ddl-only is given.");
}
Console.WriteLine("REDB Flat Export");
Console.WriteLine("================");
Console.WriteLine();
await using var source = ProviderFactory.Create(sourceProvider);
if (verbose)
{
Console.WriteLine($"Props types ({propsTypes.Count}): {string.Join(", ", propsTypes.Select(t => t.Name))}");
Console.WriteLine($"Connecting to source ({sourceProvider}) and target ({targetProvider})...");
}
await source.OpenAsync(sourceConnection, ct);
await target.OpenAsync(targetConnection, ct);
if (verbose)
{
Console.WriteLine("Connected.");
Console.WriteLine();
}
var flatExportService = new FlatExportService(source, target, verbose, batchSize);
await flatExportService.ExportAsync(propsTypes, ct);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Flat export completed successfully.");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error: {ex.Message}");
Console.ResetColor();
if (verbose)
{
Console.WriteLine();
Console.WriteLine(ex.StackTrace);
}
return 1;
}
return 0;
}
///
/// Loads the Props classes to unfold from the user assemblies: the ones named in
/// (by name or full name), or every class marked with
/// when none is named. The classes are looked up across all
/// the given assemblies, so a scheme and the scheme it references may live in different projects.
///
private static IReadOnlyList LoadPropsTypes(string[] assemblyPaths, string? typesStr)
{
var classes = new List();
foreach (var assemblyPath in assemblyPaths)
{
var fullPath = Path.GetFullPath(assemblyPath);
if (!File.Exists(fullPath))
throw new FileNotFoundException($"Assembly not found: {fullPath}");
// LoadFrom resolves the assembly's own dependencies from the folder it lies in.
classes.AddRange(Assembly.LoadFrom(fullPath).GetTypes().Where(t => t.IsClass && !t.IsAbstract));
}
var where = string.Join(", ", assemblyPaths.Select(Path.GetFileName));
if (string.IsNullOrWhiteSpace(typesStr))
{
var marked = classes
.Where(t => t.GetCustomAttribute() != null)
.OrderBy(t => t.FullName, StringComparer.Ordinal)
.ToList();
if (marked.Count == 0)
throw new InvalidOperationException(
$"No class marked with [RedbScheme] in {where}. Name the Props classes with --types.");
return marked;
}
var selected = new List();
foreach (var name in typesStr.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var matches = classes.Where(t => t.FullName == name || t.Name == name).ToList();
if (matches.Count == 0)
throw new InvalidOperationException($"Class '{name}' not found in {where}.");
if (matches.Count > 1)
throw new InvalidOperationException(
$"Class name '{name}' is ambiguous in {where}: {string.Join(", ", matches.Select(t => t.AssemblyQualifiedName))}. Use the full name.");
selected.Add(matches[0]);
}
return selected;
}
private static async Task ExportAsync(
string connection,
string provider,
string output,
bool compress,
long[]? schemeIds,
bool verbose,
int batchSize,
bool dryRun,
CancellationToken ct)
{
Console.WriteLine("REDB Export");
Console.WriteLine("===========");
Console.WriteLine();
await using var dataProvider = ProviderFactory.Create(provider);
try
{
if (verbose)
{
Console.WriteLine($"Connecting to {provider}...");
}
await dataProvider.OpenAsync(connection, ct);
if (verbose)
{
Console.WriteLine("Connected.");
Console.WriteLine();
}
var exportService = new ExportService(dataProvider, verbose, batchSize);
await exportService.ExportAsync(output, schemeIds, compress, dryRun, ct);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error: {ex.Message}");
Console.ResetColor();
if (verbose)
{
Console.WriteLine();
Console.WriteLine(ex.StackTrace);
}
return 1;
}
return 0;
}
private static async Task ImportAsync(
string connection,
string provider,
string input,
bool clean,
bool verbose,
int batchSize,
bool dryRun,
int parallel,
CancellationToken ct)
{
Console.WriteLine("REDB Import");
Console.WriteLine("===========");
Console.WriteLine();
await using var dataProvider = ProviderFactory.Create(provider);
try
{
if (verbose)
{
Console.WriteLine($"Connecting to {provider}...");
}
await dataProvider.OpenAsync(connection, ct);
if (verbose)
{
Console.WriteLine("Connected.");
Console.WriteLine();
}
var importService = new ImportService(dataProvider, verbose, batchSize, parallel);
await importService.ImportAsync(input, clean, dryRun, ct);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error: {ex.Message}");
Console.ResetColor();
if (verbose)
{
Console.WriteLine();
Console.WriteLine(ex.StackTrace);
}
return 1;
}
return 0;
}
// === Schema Management Commands ===
private static string GetEmbeddedSql(string providerName) => SchemaInitService.GetSchemaScript(providerName);
private static async Task InitSchemaAsync(
string connection, string provider, bool verbose, CancellationToken ct)
{
Console.WriteLine("REDB Schema Init");
Console.WriteLine("=================");
Console.WriteLine();
try
{
Console.WriteLine("Executing schema script...");
await SchemaInitService.InitializeAsync(provider, connection, verbose ? Console.WriteLine : null, ct);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("REDB schema created successfully.");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error: {ex.Message}");
Console.ResetColor();
if (verbose)
{
Console.WriteLine();
Console.WriteLine(ex.StackTrace);
}
return 1;
}
return 0;
}
///
/// redb indexes check|repair: the base indexes of the database against those of this build. Exit code 0 when
/// nothing is left to report, 2 when an index is missing, INVALID or defined otherwise after the command, 1 on error.
///
private static async Task IndexesAsync(string provider, string connection, bool repair, string[]? names,
bool offline, CancellationToken ct)
{
var services = new ServiceCollection();
redb.Core.Extensions.RedbServiceCollectionExtensions.AddRedb(services, o =>
{
_ = provider.ToLowerInvariant() switch
{
"postgres" or "postgresql" or "pgsql" => redb.Postgres.Extensions.PostgresOptionsExtensions.UsePostgres(o, connection),
"mssql" or "sqlserver" => redb.MSSql.Extensions.MsSqlOptionsExtensions.UseMsSql(o, connection),
"sqlite" => redb.SQLite.Extensions.SqliteOptionsExtensions.UseSqlite(o, connection),
_ => throw new ArgumentException($"Unknown provider: {provider}")
};
o.Configure(c => c.CheckBaseIndexesOnStart = false);
});
try
{
await using var sp = services.BuildServiceProvider();
var service = sp
.GetRequiredService();
if (repair)
{
var result = await service.RepairBaseIndexesAsync(names is { Length: > 0 } ? names : null, offline, ct);
foreach (var built in result.Built)
Console.WriteLine($"built {built}");
if (result.Reason != null)
{
Console.WriteLine($"not built: {result.Reason}");
foreach (var statement in result.Statements)
Console.WriteLine($" {statement};");
foreach (var duplicate in result.Duplicates)
Console.WriteLine($" {duplicate}");
}
foreach (var finding in result.NotBuilt.Where(f => f.State == redb.Core.Models.RedbIndexState.Differs))
Console.WriteLine($"left as is {finding}");
}
var report = await service.CheckBaseIndexesAsync(ct);
if (report.IsClean)
{
Console.WriteLine($"All {report.ExpectedCount} expected indexes are there as expected.");
return 0;
}
Console.WriteLine($"{report.Findings.Count} of {report.ExpectedCount} expected indexes are missing, INVALID or defined otherwise:");
foreach (var finding in report.Findings)
Console.WriteLine($" {finding}");
if (!repair && report.Repairable.Any())
Console.WriteLine("'redb indexes repair' builds the missing and INVALID ones; one defined otherwise is left to you.");
return 2;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error: {ex.Message}");
Console.ResetColor();
return 1;
}
}
private static void ExportSchemaScript(string provider, string? outputPath, bool upgrade = false)
{
var sql = upgrade ? GetEmbeddedUpgradeSql(provider) : GetEmbeddedSql(provider);
var kind = upgrade ? "Upgrade" : "Schema";
if (string.IsNullOrEmpty(outputPath))
{
Console.Write(sql);
}
else
{
File.WriteAllText(outputPath, sql);
Console.WriteLine($"{kind} script written to {outputPath} ({sql.Length:N0} characters).");
}
}
///
/// The versioned SQL module bundle — what start-up applies automatically when the connected role
/// may, and what the DBA applies by hand when it may not (RedbSchemaOutdatedException names this
/// command). Same embedded resource the provider's RedbService reads, so the two texts cannot
/// drift.
///
private static string GetEmbeddedUpgradeSql(string providerName)
{
var (assembly, resourceName) = providerName.ToLowerInvariant() switch
{
"postgres" or "postgresql" or "pgsql" =>
(typeof(redb.Postgres.RedbService).Assembly, "redb.Postgres.sql.v2-pvt.pvt_bundle.sql"),
"mssql" or "sqlserver" =>
(typeof(redb.MSSql.RedbService).Assembly, "redb.MSSql.sql.v2-pvt.pvt_bundle.sql"),
"sqlite" =>
throw new ArgumentException(
"SQLite has no upgrade script: the database file belongs to the process and is upgraded on open."),
_ => throw new ArgumentException($"Unknown provider: {providerName}")
};
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();
}
}
Path: redb/redb.CLI/README.md
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.CLI/README.md
----
# REDB CLI
Command-line tool for REDB database management: schema creation, data export and import, and
unfolding redb objects into ordinary relational tables.
## Installation
Two ways: a standalone executable that needs no .NET on the machine, or a .NET tool.
### Standalone executable
Every release of [redbase-app/redb](https://github.com/redbase-app/redb/releases) carries the CLI as one
self-contained file for `win-x64`, `linux-x64` and `linux-arm64`, signed with cosign:
```bash
VER=4.4.1
BASE=https://github.com/redbase-app/redb/releases/download/v$VER
curl -LO $BASE/redb-cli-$VER-linux-x64.tar.gz
curl -LO $BASE/redb-cli-$VER-linux-x64.tar.gz.bundle
curl -LO $BASE/cosign.pub
# Check the signature (https://docs.sigstore.dev/cosign/system_config/installation/)
cosign verify-blob --key cosign.pub --bundle redb-cli-$VER-linux-x64.tar.gz.bundle redb-cli-$VER-linux-x64.tar.gz
tar -xzf redb-cli-$VER-linux-x64.tar.gz
sudo install -m 755 redb /usr/local/bin/redb
redb --version
```
On Windows take `redb-cli--win-x64.zip` and its `.bundle`, check it the same way, unpack it and put the
folder with `redb.exe` on `PATH`. `checksums.txt` of the release lists the SHA-256 of every archive.
The CLI works on the schema and the data directly, so it does not need the native SQLite extension that
applications on `redb.SQLite` load.
### .NET tool
**Requires the .NET 10 runtime.** From 3.7.1 the tool targets `net10.0`; earlier versions targeted
`net8.0` and installed on any .NET 8 or newer runtime. Roll-forward only moves up, never down, so a
machine carrying only .NET 8 or .NET 9 cannot install this version — install .NET 10 there.
Older versions are not a workaround: 3.7.0 and earlier are unlisted and carry a known high-severity
advisory in a transitive dependency ([GHSA-2m69-gcr7-jv3q](https://github.com/advisories/GHSA-2m69-gcr7-jv3q)),
fixed in 3.7.1. Both .NET 8 and .NET 9 reach end of support on 10 November 2026 anyway; .NET 10 is
supported until 14 November 2028.
```bash
# Install as a global .NET tool
dotnet tool install --global redb.CLI
# Or run directly from the project
dotnet run --project redb.CLI -- [options]
```
## Commands
### `init` — Create Database Schema
Creates all REDB tables, sequences, functions and views in an existing empty database.
```bash
redb init -p postgres -c "Host=localhost;Database=mydb;Username=postgres;Password=pass"
redb init -p mssql -c "Server=localhost;Database=mydb;User Id=sa;Password=pass;TrustServerCertificate=True"
redb init -p sqlite -c "Data Source=app.db"
```
| Option | Alias | Required | Description |
|--------|-------|----------|-------------|
| `--provider` | `-p` | Yes | Database provider: `postgres`, `mssql`, `sqlite` |
| `--connection` | `-c` | Yes | ADO.NET connection string |
| `--verbose` | `-v` | No | Show detailed output |
On SQL Server the script runs batch by batch, each committed on its own. When it fails in the middle, the database keeps
part of the schema; `redb init` says so, and the remedy is to drop and create the database, then run `redb init` again.
An upgrade cannot complete such a schema.
### `schema` — Export Schema Script
Outputs the full SQL initialization script to a file or stdout. Useful for DBA review or CI/CD pipelines.
```bash
# Write to file
redb schema -p postgres -o redb_schema.sql
# Output to stdout
redb schema -p postgres
# Pipe to psql
redb schema -p postgres | psql -d mydb
```
| Option | Alias | Required | Description |
|--------|-------|----------|-------------|
| `--provider` | `-p` | Yes | Database provider: `postgres`, `mssql`, `sqlite` |
| `--output` | `-o` | No | Output file path. If omitted, writes to stdout |
### `export` — Export Data
Exports the entire database (or specific schemes) to a `.redb` file (JSONL format, optionally compressed).
```bash
# Full export with compression
redb export -p postgres -c "Host=localhost;Database=redb;Username=postgres;Password=pass" \
-o backup.redb --compress --batch-size 100000 -v
# Export specific schemes only
redb export -p postgres -c "..." -o partial.redb --schemes 100,200,300
# Dry run — show what would be exported
redb export -p postgres -c "..." -o test.redb --dry-run
```
| Option | Alias | Required | Description |
|--------|-------|----------|-------------|
| `--provider` | `-p` | Yes | Database provider: `postgres`, `mssql`, `sqlite` |
| `--connection` | `-c` | Yes | Connection string |
| `--output` | `-o` | Yes | Output file path (`.redb`) |
| `--compress` | | No | Compress with ZIP |
| `--schemes` | | No | Export only specified scheme IDs (comma-separated) |
| `--batch-size` | | No | Batch size for read operations (default: 1000) |
| `--dry-run` | | No | Show what would be done without execution |
| `--verbose` | `-v` | No | Enable verbose output |
The file carries the previous names of renamed schemes and properties (`[RedbRename]`, `RedbScheme.RenamedFrom`), with
`--schemes` those of the exported schemes. A file written before this history existed imports with none.
The file also carries the history of the data migrations applied to the database (redb Pro, `_migrations`), with
`--schemes` that of the exported schemes, so a migration run after the import does not apply them a second time. A file
written by an earlier version carries no such history: it imports as before, and the import warns that the migrations
already in the data are unknown to the target. Export the source again, or check which migrations the data has, before
running migrations on it. `import --clean` also clears the target's own history, so none of it outlives its data.
Before it reads anything, the export checks that the source database has the schema of this CLI's redb version. An
older one stops with `RedbSchemaOutdatedException`: upgrade it with `redb schema --upgrade` (SQLite: `redb init -p
sqlite` upgrades an existing file) and export again. A newer one stops with `RedbSchemaNewerException`: export with the
CLI of the version the database runs, since this one would leave out what it does not know. A database without the
redb schema has nothing to export and says so.
### `import` — Import Data
Imports data from a `.redb` file into the database.
```bash
# Import with clean (drops existing data first)
redb import -p postgres -c "Host=localhost;Database=redb;Username=postgres;Password=pass" \
-i backup.redb --clean -v --batch-size 100000
# Dry run
redb import -p mssql -c "..." -i backup.redb --dry-run
```
| Option | Alias | Required | Description |
|--------|-------|----------|-------------|
| `--provider` | `-p` | Yes | Database provider: `postgres`, `mssql`, `sqlite` |
| `--connection` | `-c` | Yes | Connection string |
| `--input` | `-i` | Yes | Input file path (`.redb`) |
| `--clean` | | No | Truncate all REDB tables before import |
| `--batch-size` | | No | Batch size for bulk insert (default: 1000) |
| `--dry-run` | | No | Show what would be done without execution |
| `--verbose` | `-v` | No | Enable verbose output |
Rows are loaded with the foreign key checks off, since a file may hold a child before its parent. On every provider
each key is checked once the rows are in, and a file with a reference to a row it does not hold is refused; the error
names each broken key, the number of rows and an example. A file exported with `--schemes` whose objects
point into a scheme left out is such a file: export the referenced schemes too.
Stop every application that uses the target database before the import and start it again afterwards. A running redb
service keeps handing out the ids it reserved before the import, and those ids collide with the imported rows.
Before it cleans or writes anything, the import checks the target's schema the way a redb application does at start:
an older one stops with `RedbSchemaOutdatedException` (upgrade it as above, then import again), a newer one goes on
when it states that it serves this version and stops with `RedbSchemaNewerException` otherwise. A database without the
redb schema is told to get one with `redb init` first.
With `--parallel` the rows are committed as they are loaded. The steps after the load (the id sequence, the index
rebuild, the constraints) are each attempted; if any of them fails, the import exits with a non-zero code and its
message lists every failed step. A script that runs the CLI must check the exit code, then run the import again with
`--clean`.
### `indexes` — Check and Repair the Base Indexes
Compares the indexes of a database with those of the base schema of this version: every index that is missing, INVALID
(PostgreSQL, an interrupted concurrent build) or defined otherwise is listed with what it serves.
```bash
redb indexes check -p postgres -c "Host=localhost;Database=mydb;Username=postgres;Password=secret"
redb indexes repair -p postgres -c "..." # every missing or INVALID one
redb indexes repair -p mssql -c "..." -n IX__values__array_key
redb indexes repair -p mssql -c "..." --offline # SQL Server Standard/Express: build anyway
```
`check` only reads. `repair` builds with `CREATE INDEX CONCURRENTLY` on PostgreSQL, `WITH (ONLINE = ON)` on SQL Server
editions that have it, plainly on SQLite. On SQL Server editions without ONLINE index operations it prints the
statements and builds nothing unless `--offline` is given (an offline build blocks writes to the table). An index
defined otherwise is reported and never changed. Both exit with code 2 while an index is still reported. The indexes of
Pro modules are checked by the application (`CheckBaseIndexesAsync`).
### `flat` — Unfold Objects into Relational Tables
Builds ordinary relational tables from your `*Props` classes and copies the data of a redb database
into them. Use it to hand data to reporting and BI tools, to another system, or to read it with plain
SQL or any ORM. The transfer is one-way: the flat tables are a copy, changes made to them do not go
back to redb.
Source and target are two independent connections. They may be the same provider or different ones,
and the target may be the source database itself.
```bash
# Print the DDL of the flat tables. No database is opened.
redb flat -a MyApp/bin/Release/net10.0/MyApp.Models.dll -tp postgres --ddl-only
# Unfold and copy, PostgreSQL -> PostgreSQL
redb flat -a MyApp/bin/Release/net10.0/MyApp.Models.dll \
-sp postgres -sc "Host=localhost;Database=redb;Username=postgres;Password=pass" \
-tp postgres -tc "Host=localhost;Database=redb_flat;Username=postgres;Password=pass" \
--batch-size 10000 -v
# Props classes spread over several projects, target on another provider
redb flat -a App.Orders.dll App.Catalog.dll --types OrderProps,ProductProps \
-sp postgres -sc "..." -tp mssql -tc "..."
```
| Option | Alias | Required | Description |
|--------|-------|----------|-------------|
| `--assembly` | `-a` | Yes | Path to an assembly that declares Props classes. Several paths may be given, or the option repeated |
| `--target-provider` | `-tp` | Yes | Provider of the target database: `postgres`, `mssql`, `sqlite` |
| `--target-connection` | `-tc` | Unless `--ddl-only` | Connection string of the database that receives the flat tables |
| `--source-provider` | `-sp` | Unless `--ddl-only` | Provider of the redb database to read |
| `--source-connection` | `-sc` | Unless `--ddl-only` | Connection string of the redb database to read |
| `--types` | | No | Props classes to unfold, by name or full name (comma-separated). Default: every class marked with `[RedbScheme]` in the given assemblies |
| `--ddl-only` | | No | Print the DDL for the target provider and exit |
| `--batch-size` | | No | Rows buffered per table before a bulk insert (default: 1000) |
| `--verbose` | `-v` | No | Enable verbose output |
#### Before you run it
- **The target database must exist and must not contain the flat tables.** The tool creates tables,
it does not create the database, and it never uses `IF NOT EXISTS`: a name that is already taken
stops the run.
- **Point `-a` at the build output of your application** (`bin/...`), where all its assemblies lie
together. The dependencies of each assembly are resolved from the folder it lies in.
- **A class without `[RedbScheme]` has to be named in `--types`.**
- **A type referenced through `RedbObject` must be part of the run.** The reference becomes a
foreign key to the table of `T`; if `T` is not exported the tool refuses before writing anything.
- **The scheme must match the class.** A property with no structure in the source database stops the
run: synchronise the scheme with the current version of the class first.
- Everything is written in one transaction of the target. After an error the target is left as it was.
#### What you get
| In your Props | In the target database |
|---|---|
| Every object of the source | A row in `objects`: id, parent, owner, dates, name, note and the `_value_*` columns |
| A Props class | A table named after the class (`EmployeeProps`), one row per object, keyed by the object id |
| A scalar property | A column named after the property |
| A nested class | A table named by the property path (`EmployeeProps.HomeAddress`), one-to-one with its owner |
| An array or list | A table (`EmployeeProps.Skills`) with `_idx` and either `_value` or the columns of the element class |
| A dictionary | A table with `_key` and either `_value` or the columns of the value class |
| A dictionary with a tuple key | The same, with one column per component: `_key_Item1`, `_key_Item2`, ... |
| `RedbObject` | A column holding the id of the target object, with a foreign key to the table of `T` |
| `RedbListItem` | A column holding the list item id; the lists themselves are copied to `lists` and `list_items` |
| A tree | `objects._id_parent`, a foreign key to `objects`; parents and children of different schemes are supported |
Rules that apply everywhere:
- Names are taken from the code as they are and are always quoted, so in PostgreSQL they are
case-sensitive: `SELECT "FirstName" FROM "EmployeeProps"`.
- Service columns start with an underscore: `_id`, `_owner_id`, `_idx`, `_key`, `_value`.
- A name longer than 63 bytes is cut and gets `~` plus eight hex digits of a hash, the same on every
provider.
- Ids are kept: a row in a scheme table has the id of its object.
- Hashes and unique-key columns of redb are not copied.
- Users, roles and permissions are not copied.
#### Limitations
- An empty collection and a missing one look the same in the flat tables: neither has rows.
- SQL Server: a `TimeSpan` is stored as `time` and cannot hold 24 hours or more; a text dictionary
key is limited to 430 characters.
- SQL Server as a source is read under `SNAPSHOT` isolation, which has to be allowed in that database.
- SQLite as both source and target in one file needs the file in WAL mode.
- Soft-deleted objects are present in `objects`. A `RedbObject` reference that still points to one
cannot get its foreign key, and the run is rolled back.
## Supported Providers
| Provider | Aliases | Connection String Example |
|----------|---------|--------------------------|
| PostgreSQL | `postgres`, `postgresql`, `pgsql` | `Host=localhost;Port=5432;Database=redb;Username=postgres;Password=pass;Timeout=600` |
| SQL Server | `mssql`, `sqlserver` | `Server=localhost;Database=redb;User Id=sa;Password=pass;TrustServerCertificate=True;Command Timeout=600` |
| SQLite | `sqlite` | `Data Source=app.db` |
## Typical Workflows
### New Project Setup
```bash
# 1. Create database (psql / SSMS)
createdb myapp
# 2. Initialize REDB schema
redb init -p postgres -c "Host=localhost;Database=myapp;Username=postgres;Password=pass" -v
# 3. Run your application
dotnet run --project MyApp
```
### Database Migration (Postgres → MSSQL)
```bash
# 1. Export from Postgres
redb export -p postgres -c "Host=src;Database=redb;..." -o data.redb --compress -v
# 2. Init schema in MSSQL
redb init -p mssql -c "Server=dst;Database=redb;..." -v
# 3. Import into MSSQL
redb import -p mssql -c "Server=dst;Database=redb;..." -i data.redb --clean -v
```
### Backup & Restore
```bash
# Backup
redb export -p postgres -c "..." -o "backup_$(date +%Y%m%d).redb" --compress
# Restore (clean + import)
redb import -p postgres -c "..." -i backup_20260213.redb --clean -v
```
### Flat Tables for Reporting
```bash
# 1. Create an empty target database
createdb myapp_flat
# 2. Review the tables that will be created
redb flat -a MyApp/bin/Release/net10.0/MyApp.Models.dll -tp postgres --ddl-only
# 3. Unfold and copy
redb flat -a MyApp/bin/Release/net10.0/MyApp.Models.dll \
-sp postgres -sc "Host=localhost;Database=myapp;..." \
-tp postgres -tc "Host=localhost;Database=myapp_flat;..." -v
```
## Exit Codes
| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | Error (connection failed, invalid options, SQL error) |
| 2 | `indexes`: an index is still missing, INVALID or defined otherwise |
## License
Apache License 2.0 — same as redb.Core.
## Links
- Documentation (EN): [redbase.app](https://redbase.app)
- Documentation (RU): [redb.ru](https://redb.ru)
- API Reference: [redbase-app.github.io/redb](https://redbase-app.github.io/redb/)
- NuGet: [nuget.org/packages/redb.CLI](https://www.nuget.org/packages/redb.CLI)
- GitHub: [github.com/redbase-app/redb](https://github.com/redbase-app/redb)
Path: redb/redb.CLI/redb.CLI.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.CLI/redb.CLI.csproj
----
Exe
net10.0
LatestMajor
enable
enable
redb
redb.CLI
true
redb
redb.CLI
REDB - Entity Database for .NET
CLI tool for REDB database management: export, import, schema init.
https://github.com/redbase-app/redb
redb;cli;database;tool
README.md
<_CliKeepRids>;win-x64;win-arm64;linux-x64;linux-arm64;linux-musl-x64;linux-musl-arm64;osx-x64;osx-arm64;