Path: redb/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/README.md ---- # RedBase — typed object storage for .NET. Schema = C# class. Zero migrations. Full LINQ. Postgres, MSSQL & SQLite. **Trees, lists, aggregations, windows — one LINQ API.** > **LLMs / coding agents:** canonical training contract → RedBase is a data platform for .NET that stores typed objects in a relational backend (PostgreSQL, Microsoft SQL Server, or SQLite — including embedded/offline, Blazor WebAssembly and mobile via the SQLite provider). You define schemas as plain C# classes — RedBase handles storage, indexing, querying, trees, lists, aggregation, and window functions through a single LINQ-style API. No Entity Framework. No migrations. No 40-table Include chains. Just C# classes and one line to save, one line to load. [![NuGet](https://img.shields.io/nuget/v/redb.Core?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Core) [![Downloads](https://img.shields.io/nuget/dt/redb.Core?label=Downloads&color=green)](https://www.nuget.org/packages/redb.Core) [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE) [![.NET](https://img.shields.io/badge/.NET-10%20%7C%2011-purple)](https://dotnet.microsoft.com) [![Website](https://img.shields.io/badge/docs-redbase.app-orange)](https://redbase.app) [![Website RU](https://img.shields.io/badge/docs-redb.ru-blue)](https://redb.ru) **Contents:** [Why RedBase](#why-redbase) · [Quick Start](#quick-start) · [Packages](#packages) · [Installation](#installation) · [Capabilities](#capabilities) · [Architecture](#architecture) · [How It Compares](#how-it-compares) · [Pro](#pro) · [Documentation](#documentation) · [License](#license) Upgrading from an earlier version: see [UPGRADING.md](UPGRADING.md) and [CHANGELOG.md](CHANGELOG.md). --- ## Why RedBase | Problem | EF Core / Dapper | RedBase | |---------|------------------|---------| | 28 related tables | 40+ Include/ThenInclude, 200 lines of config | `LoadAsync(id)` — 1 line, full object graph | | Add a field | Create migration, update DbContext, deploy | Add property to C# class, done | | Tree structures | Manual recursive CTEs, no reusable API | Built-in `TreeQuery()` with CTE, depth, ancestors | | Dynamic schema | Pain. EF doesn't support it | Native. Schema = C# class. `SyncSchemeAsync()` | | Learn curve | DbContext, Fluent API, migrations, conventions | One interface: `IRedbService`. One attribute: `[RedbScheme]` | | Forgot Include? | Runtime crash or silent null | Impossible — Props are always loaded | > **Strong typing — real columns, not JSON blobs.** Each property of your `*Props` class is a row in the `_values` table, indexed, and its value goes into a column typed by the property type: `string` → `text` (`nvarchar` on SQL Server), `decimal` → `numeric(38,18)` (on SQLite the value sits in a `REAL` column by default, or in `TEXT` in the exact mode), `DateTime` → `timestamptz`. A `REAL` keeps about 15 significant digits of a decimal exactly; a value with more digits comes back as the nearest number the column holds, and from the 17th digit on that number can differ between .NET runtimes, so keep amounts that need more digits in the exact mode. The index is by value for every column type, with one exception: on SQL Server a string value (`nvarchar(max)`) cannot be an index key, so a filter by a string field reads the rows of that field and not a range by value. The table carries real foreign keys to the object, the structure and the referenced objects, and arrays and dictionaries are normalised rows as well. Your data is queryable, filterable, and aggregatable at the SQL level — no `JSON_VALUE` hacks, no full-table JSON scans, no cast errors at runtime. ### Measured against EF Core The examples project runs each task through redb and through an EF Core 10 twin that reads the same data from ordinary relational tables: the Employee class unfolded into 41 tables by `redb flat`, standard EF Core API, split queries, whole objects returned on both sides. Over the 98 tasks EF Core can do without raw SQL, redb Pro on PostgreSQL took 189 ms on average (median 114 ms), 160 ms on a repeated call and 154 ms with its built-in cache; EF Core took 703 ms (median 910 ms) and 730 ms on a repeated call. Both ran from the same client against the same PostgreSQL 18 server (Ryzen 5 5500U, 38 GB RAM, NVMe) over Wi-Fi; SQLite is a local file on the client (Ryzen 7 260, 32 GB RAM). In the load-by-id example EF Core sends 62 statements where redb sends 9, and every statement is a round trip to the database server. The figures show the order of magnitude, not a guarantee. Every example with its time and statement count is on the [results page](https://redbase.app/results); the code and the steps to repeat the run are in [redb.Examples](redb.Examples/README.md). ![Average and median time per example](https://raw.githubusercontent.com/redbase-app/redb/main/redb.Examples/images/results_e.png) *Mean and median time of one example, 98 examples, one timed run each. Suffixes: `.pro` redb Pro, `.ef` EF Core, `.repeat` second pass, `.cache` redb with its props cache. Compare the bars of one database: SQLite runs locally, PostgreSQL and SQL Server over the network.* ![Seeding 100 000 objects](https://raw.githubusercontent.com/redbase-app/redb/main/redb.Examples/images/E203.png) *Seeding 100 000 Employee objects in batches of 1000, index rebuild inside the time: redb on PostgreSQL, SQL Server and SQLite, and EF Core on PostgreSQL.* --- ## Quick Start ```csharp // 1. Define a schema — that's your "migration" [RedbScheme("Employee")] public class EmployeeProps { public string FirstName { get; set; } = ""; public string LastName { get; set; } = ""; public int Age { get; set; } public decimal Salary { get; set; } public string Department { get; set; } = ""; public string Position { get; set; } = ""; public DateTime HireDate { get; set; } public string[]? Skills { get; set; } public Address? HomeAddress { get; set; } public Dictionary? BonusByYear { get; set; } } // 2. Sync scheme (creates storage automatically) await redb.SyncSchemeAsync(); // 3. Save — from E001_SaveAsync.cs var employee = new RedbObject { name = "New Developer", Props = new EmployeeProps { FirstName = "Alice", LastName = "Johnson", Age = 28, Position = "Developer", Department = "Engineering", Salary = 85000m, HireDate = DateTime.Today, Skills = ["C#", "React", "SQL"] } }; await redb.SaveAsync(employee); // 4. Load — from E002_LoadAsync.cs var loaded = await redb.LoadAsync(employee.Id); // loaded.Props.FirstName → "Alice" // 5. Query — from E010_WhereSimple.cs var results = await redb.Query() .Where(e => e.Salary > 75000m) .OrderByDescending(e => e.Salary) .Take(100) .ToListAsync(); // 6. Projection — from E075_Select.cs var projected = await redb.Query() .Select(x => new { x.Props.FirstName, x.Props.LastName, x.Props.Salary }) .ToListAsync(); ``` ### Create from Template ```bash dotnet new install redb.Templates dotnet new redb -n MyProject --db postgres # --db postgres | mssql | sqlite (default), --pro true (default) | false cd MyProject dotnet run ``` Other templates: `redb-app`, `redb-worker`, `redb-razor`, `redb-blazor`, `redb-bff`, `redb-chat` (see [redb.Templates](redb.Templates/README.md)). --- ## Packages | Package | NuGet | Description | |---------|-------|-------------| | `redb.Core` | [![NuGet](https://img.shields.io/nuget/v/redb.Core?label=)](https://www.nuget.org/packages/redb.Core) | Core abstractions, query builder, LINQ provider | | `redb.Postgres` | [![NuGet](https://img.shields.io/nuget/v/redb.Postgres?label=)](https://www.nuget.org/packages/redb.Postgres) | PostgreSQL provider (free, Apache 2.0) | | `redb.MSSql` | [![NuGet](https://img.shields.io/nuget/v/redb.MSSql?label=)](https://www.nuget.org/packages/redb.MSSql) | Microsoft SQL Server provider (free, Apache 2.0) | | `redb.SQLite` | [![NuGet](https://img.shields.io/nuget/v/redb.SQLite?label=)](https://www.nuget.org/packages/redb.SQLite) | SQLite provider (free, Apache 2.0) — embedded/offline, native loadable extension | | `redb.Core.Pro` | [![NuGet](https://img.shields.io/nuget/v/redb.Core.Pro?label=)](https://www.nuget.org/packages/redb.Core.Pro) | Pro engine: SQL built in C#, parallel materialization, change tracking, data migrations | | `redb.Postgres.Pro` | [![NuGet](https://img.shields.io/nuget/v/redb.Postgres.Pro?label=)](https://www.nuget.org/packages/redb.Postgres.Pro) | PostgreSQL Pro provider with optimized query generation | | `redb.MSSql.Pro` | [![NuGet](https://img.shields.io/nuget/v/redb.MSSql.Pro?label=)](https://www.nuget.org/packages/redb.MSSql.Pro) | MSSQL Pro provider with optimized query generation | | `redb.SQLite.Pro` | [![NuGet](https://img.shields.io/nuget/v/redb.SQLite.Pro?label=)](https://www.nuget.org/packages/redb.SQLite.Pro) | SQLite Pro provider — pure C# (no native extension): Blazor WebAssembly & mobile | | `redb.Export` | [![NuGet](https://img.shields.io/nuget/v/redb.Export?label=)](https://www.nuget.org/packages/redb.Export) | Database export/import: `.redb` files (JSONL/ZIP) for backup and moves between PostgreSQL, SQL Server and SQLite | | `redb.CLI` | [![NuGet](https://img.shields.io/nuget/v/redb.CLI?label=)](https://www.nuget.org/packages/redb.CLI) | `redb` command line tool: `init`, `schema`, `export`, `import`, `flat` | | `redb.Templates` | [![NuGet](https://img.shields.io/nuget/v/redb.Templates?label=)](https://www.nuget.org/packages/redb.Templates) | `dotnet new` project templates | --- ## Installation ```bash # PostgreSQL (Free) dotnet add package redb.Postgres # or MSSQL (Free) dotnet add package redb.MSSql # or SQLite (Free) dotnet add package redb.SQLite # Pro — includes redb.Core.Pro automatically dotnet add package redb.Postgres.Pro # or redb.MSSql.Pro, redb.SQLite.Pro ``` Each provider package pulls in `redb.Core` (or `redb.Core.Pro`) as a transitive dependency. ### Setup & InitializeAsync ```csharp using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; // AddRedbPro using redb.Postgres.Pro.Extensions; // UsePostgres; or redb.MSSql.Pro.Extensions, redb.SQLite.Pro.Extensions var builder = WebApplication.CreateBuilder(args); // Register redb Pro builder.Services.AddRedbPro(options => options .UsePostgres("Host=localhost;Database=mydb;Username=postgres;Password=pass") // .UseMsSql("Server=localhost;Database=mydb;User Id=sa;Password=pass;TrustServerCertificate=true") .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Pro: writes only the changed values c.EnableLazyReferences = false; // true loads `virtual` references as stubs at any depth c.EnablePropsCache = true; })); var app = builder.Build(); // Initialize and sync schemes var redb = app.Services.GetRequiredService(); await redb.InitializeAsync(); await redb.SyncSchemeAsync(); ``` **The props cache pays off, and only while it fits.** `EnablePropsCache` keeps materialized Props in memory and validates a hit by the object hash. Measured on PostgreSQL Pro over 100 000 objects: a warm list of 300 objects takes 339 ms without the cache and 44 ms with it, a point load 10 ms against 2 ms, and 0.11 ms with `SkipHashValidationOnCacheCheck`, which costs no round trip at all. That speedup lasts only while the cache holds the objects in use. `PropsCacheMaxSize` (10 000 objects by default) has to fit the working set: when it does not, every load evicts an object the next load needs, hits drop to almost none, and what is left is the cost - memory, and a hash check on every lookup. In production this looks like a cache that was fast on the first day and slower than no cache once the data grew. The cache says so ("Props cache is full: N least recently used objects evicted within 10s"), and it also reports a slow hit check and a run of lookups that find entries and serve none, which is a read model that does not reproduce the saved graph and never matches its hash. Raise the size to fit the working set, or leave the cache off for that database. **Free version** — same pattern, just `AddRedb` instead of `AddRedbPro`: ```csharp using redb.Core.Extensions; // AddRedb using redb.Postgres.Extensions; // UsePostgres; or redb.MSSql.Extensions, redb.SQLite.Extensions builder.Services.AddRedb(options => options .UsePostgres("Host=localhost;Database=mydb;Username=postgres;Password=pass")); ``` ### Database Setup Options REDB provides several ways to create the database schema: **Option A — Automatic on startup (recommended):** ```csharp // Creates schema if missing, then initializes await redb.InitializeAsync(ensureCreated: true); ``` **Option B — Explicit call:** ```csharp await redb.EnsureDatabaseAsync(); // idempotent — safe to call every time await redb.InitializeAsync(); ``` **Option C — Export SQL script for DBA / CI:** ```csharp var sql = redb.GetSchemaScript(); File.WriteAllText("redb_schema.sql", sql); ``` **Option D — CLI tool:** ```bash dotnet tool install --global redb.CLI # Create schema in an existing database redb init --connection "Host=localhost;Database=mydb;..." --provider postgres # Export SQL to file redb schema --provider postgres --output redb_schema.sql ``` **Several nodes on one database.** The nodes of a cluster or the replicas of a service may start together against the same database, for example right after an upgrade. Start-up takes a schema lock for its schema work: creating the schema, deploying the SQL module, building the indexes of the streams form (Pro) and upgrading a SQLite file. Each step looks first without the lock; only a step that finds work takes it, looks again and does what is still missing. One node does the work; the others wait for the lock and find it done. A database already in step takes no lock at all. Scheme synchronization takes the same lock, at start-up and at run time alike (`SyncSchemeAsync`, modules loaded by several workers that share a Props class, a new field reaching every node at once). A sync first only reads: a scheme already in step, the usual case, takes no lock at all. A sync that has something to write takes the lock, looks again and writes what is still missing. A sync called inside a transaction of your own runs without the lock, since the lock would be released before your commit. The metadata cache of a scheme in step is not rebuilt at start-up; the service tables (`_schemes`, `_structures`, `_scheme_metadata_cache`) are not meant to be edited by hand. The lock is a session advisory lock on PostgreSQL and the write lock of the file on SQLite. On SQL Server it is an application lock (`sp_getapplock`) held in `master`; on Azure SQL Database it is held in the database itself. On a SQL Server of your own, schema work needs a login that can open `master` (every server login can, through its guest user). No other rights are needed. A waiting node logs the wait every thirty seconds and gives up after `SchemaLockTimeout` (15 minutes by default) with `RedbSchemaLockTimeoutException`: ```csharp services.AddRedb(options => options .UsePostgres(connectionString) .Configure(c => c.SchemaLockTimeout = TimeSpan.FromMinutes(30))); // a very large _values builds longer ``` **Schema deployed by a DBA.** The application may connect with limited rights: a login without DDL rights, or on SQL Server a contained database user with no access to `master`. The DBA deploys the schema with `GetSchemaScript()`, upgrades the module with `GetUpgradeScript()` and syncs the schemes once with a privileged login. A start against such a database in step needs no schema work, takes no lock and goes through. If schema work is found (a module behind the package, a scheme changed in code), the start stops with an error saying to give the login access to `master` or to deploy with the DBA scripts. **Upgrading a cluster.** A start applies the module of its own package when the database holds an older one, or none. From 4.8.0 on a start never puts its module over a newer one: the newer module states which packages it still serves, and an older node starts with a warning when it is among them, or stops with `RedbSchemaNewerException` ("Upgrade the redb packages of this application; the database was left unchanged") when it is not. A SQLite file does the same through its `_schema_compat` row. Nodes of 4.8.0 and later versions may therefore run against one database during a rolling upgrade. The script of `GetUpgradeScript()` / `redb schema --upgrade` holds to the same rule when a DBA runs it by hand: over a newer module it raises the same sentence before its first change. Run it so that an error stops it (`psql -v ON_ERROR_STOP=1`; on SQL Server the script stops the later batches itself). A node of 4.7.x or older does not know the rule and still puts its own module back over a newer one. For a rolling upgrade from 4.7.x to 4.8.0, upgrade every node together, or let the DBA apply the new module once from `GetUpgradeScript()` / `redb schema --upgrade` and start all nodes with `AutoApplyDatabaseUpgrades = false`: a node of the old version then stops at start instead of changing the database. **Schema problems.** Some problems of the schema do not stop the service but need a person, for example a root field of a scheme written twice by nodes of an older version (see UPGRADING.md, "Duplicate root structures"). Each one is logged as an error at every start until it is resolved, and `IRedbService.SchemaProblems` lists them, so a health check can report the service as degraded: ```csharp var problems = redb.SchemaProblems; // as found by the last start or scheme sync; reads no database // or: await redb.CheckSchemaAsync(ct); // looks again, read only if (problems.Count > 0) return HealthCheckResult.Degraded(string.Join("; ", problems.Select(p => p.Message))); ``` **Free provider: the value indexes read before 4.4.0.** redb 4.3.0 (PostgreSQL) and 4.4.0 (all three providers) replaced the value indexes that lead with the object, `(_id_structure, _id_object, )` and on PostgreSQL the covering `IX__values__structure_object_lookup`, with indexes that lead with the value: the new ones serve a filter on a field, the old ones served reading the values of a known object. If queries of the free provider got slower after that upgrade (on PostgreSQL, one query over a whole scheme of 38 million values went from 8.8 s to 18-20 s), a script per provider brings the old indexes back under names of their own, `IX__values__free_*`, which later upgrades neither drop nor check. Nothing runs it automatically and it is not part of the NuGet packages: take it from the repository and run it once per database. - PostgreSQL: [`redb.Postgres/sql/maintenance/free_value_indexes.sql`](redb.Postgres/sql/maintenance/free_value_indexes.sql), `psql -d -f free_value_indexes.sql`, outside a transaction (it builds `CONCURRENTLY`, reads and writes go on). - SQL Server: [`redb.MSSql/sql/maintenance/free_value_indexes.sql`](redb.MSSql/sql/maintenance/free_value_indexes.sql), `sqlcmd -S -d -i free_value_indexes.sql`. Writes to `_values` wait while an index is built; on Enterprise, Developer and Azure SQL add `WITH (ONLINE = ON)` to each `CREATE`. - SQLite: [`redb.SQLite/sql/maintenance/free_value_indexes.sql`](redb.SQLite/sql/maintenance/free_value_indexes.sql), `sqlite3 < free_value_indexes.sql`, with the application stopped or idle. Every index there is updated on each save of a value: on PostgreSQL the covering one took about 1.7 GB on 38 million values, and on SQLite the string index holds every string in full. Run the script only if free queries got slower; on SQL Server keep an index only if its usage counters show reads. Running it again is safe, and the file lists the statements that remove the indexes. Pro with the planner on (the default) does not need them; Pro with `EnablePvtPrefilter = false` reads the same forms as the free provider and may gain from them as well. **Planner statistics after a bulk load.** After a redb import, a seed or a large migration, refresh the planner statistics again once the application has saved its first new objects, or on a schedule: `await redb.Maintenance.AnalyzeAsync()` for the whole database, or `AnalyzeTableAsync("_values")` for the table that matters most. A refresh corrects estimates that went stale; it is not a cure for every slow plan. - SQL Server: `AnalyzeAsync` runs `sp_updatestats`, `AnalyzeTableAsync` runs `UPDATE STATISTICS`. The statistics of `_values` are built while every object id of the load sits in one block; objects saved later get ids beyond the block of value ids that follows it. `_objects` refreshes its statistics by itself long before `_values` reaches its own threshold, the two then disagree, and queries over a whole scheme can take a nested-loops plan that runs five to ten times slower. In our test a grouping went from 89 ms to 840 ms once a few hundred new objects were saved and the statistics of `_objects` were refreshed, and back to 109 ms after `UPDATE STATISTICS _values`, which took 3 seconds on 8.4 million rows. - SQLite never refreshes statistics by itself. `AnalyzeAsync` runs `PRAGMA analysis_limit = ; ANALYZE` with the limit from `MaintenanceAnalysisLimit` (default 1000): a bounded sample that is fast but gives rough counts per field. For a full pass set `MaintenanceAnalysisLimit = 0` before the call, or run `PRAGMA analysis_limit = 0; ANALYZE;` yourself; in our test that took 6 seconds on a 2.45 GB file. - PostgreSQL: autovacuum analyzes a table once enough of its rows changed, so statistics catch up on their own over time. After a bulk load run `ANALYZE` (or `AnalyzeAsync`) right away rather than wait for it. A new database is the other case: its small tables stay below autovacuum's threshold (50 rows plus 10 %) for a long time and have no statistics at all. While `_objects` or `_values` has none, Pro runs each query with nested loops off and checks the state every 30 seconds, which costs two extra round trips per query; a lookup by object id is exempt. Run `AnalyzeAsync()` once after the first data is in, and the extra round trips stop. ### Client-side: Blazor WebAssembly & mobile Both run on `redb.SQLite.Pro` — it is pure C#, while the Free tier hosts its SQL functions in a native loadable extension, which a browser cannot load. Pro is free of charge and needs no key. **Mobile (.NET MAUI)** needs nothing special: point the connection string at the app data directory. ```csharp builder.Services.AddRedbPro(o => o .UseSqlite($"Data Source={Path.Combine(FileSystem.AppDataDirectory, "app.db")}")); ``` **Blazor WebAssembly** needs three things beyond the usual setup: 1. **Native relink.** For `browser-wasm` SQLite arrives as a static archive (`e_sqlite3.a`) rather than a shared library, so it must be linked into the runtime at build time. Install the workload and, for Debug runs, enable the relink explicitly: ```bash dotnet workload install wasm-tools ``` ```xml true ``` Without it the app builds against the stock runtime and fails in the browser, not at compile time. 2. **Manual initialization.** `WebAssemblyHost` does not start hosted services, so the automatic startup initialization never runs: ```csharp var host = builder.Build(); var redb = host.Services.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await host.RunAsync(); ``` 3. **Persistence is yours to add.** The database file lives in the browser's in-memory filesystem, so it is gone on reload. Persisting it (IDBFS + `syncfs`, a copy into IndexedDB/Cache API, or OPFS) is application-level work — RedBase does not provide it. --- ## Capabilities ### CRUD | Feature | API | Notes | |---------|-----|-------| | Save single object | `SaveAsync(obj)` | Create or update | | Load by ID | `LoadAsync(id)` | Returns `RedbObject` with Props | | Bulk insert | `AddNewObjectsAsync(objects)` | New objects in bulk (COPY on PostgreSQL) instead of one INSERT each; a nested new object keeps the `ParentId` it carries, as in `SaveAsync`; `BulkInsertTimeout` sets how long one bulk load may run | | Batch save | `SaveAsync(IEnumerable)` | Save multiple objects at once | | Delete | `DeleteAsync(obj or id)`, `DeleteAsync(ids)` | Single or batch delete | | Delete in the background | `SoftDeleteAsync(...)`, `DeleteWithPurgeAsync(ids)` | Move to trash, purge in batches | | Unique keys | `ValueUnique`, `[RedbUnique]` | Enforced by the database, see [UNIQUE_KEYS.md](UNIQUE_KEYS.md) | | Load-modify-save | `LoadAsync` → modify → `SaveAsync` | Standard update pattern | ### Object Graph (RedbObject References in Props) Props can contain `RedbObject` properties — single, array, or dictionary. The entire graph is saved and loaded in one call. No JOINs, no Include chains, no manual assembly. ```csharp // Real model from redb.Examples/Models/ExampleModels.cs [RedbScheme("Employee")] public class EmployeeProps { public string FirstName { get; set; } = ""; public int Age { get; set; } public decimal Salary { get; set; } // Nested business class (Address with nested BuildingInfo) public Address? HomeAddress { get; set; } // Array of business classes public Contact[]? Contacts { get; set; } // RedbObject reference — single public RedbObject? CurrentProject { get; set; } // RedbObject references — array public RedbObject[]? PastProjects { get; set; } // Dictionary with RedbObject values public Dictionary>? ProjectMetrics { get; set; } // Dictionary with nested classes public Dictionary? DepartmentHistory { get; set; } // Tuple key dictionary public Dictionary<(int Year, string Quarter), string>? PerformanceReviews { get; set; } } // Save — entire graph persisted await redb.SaveAsync(employee); // Load — full graph reconstructed, all nested objects hydrated var loaded = await redb.LoadAsync(employee.Id); // loaded.Props.CurrentProject.Props — ready // loaded.Props.PastProjects[0].Props — ready // loaded.Props.ProjectMetrics["Q1"].Props — ready ``` Nested objects are real `RedbObject` instances with their own `id`, `name`, `DateCreate`, `DateModify`, and `Props`. They can be queried independently, updated in place, and participate in tree structures. ### Rich Props Structure Props fields can be any combination of scalars, nested classes, collections, and dictionaries — arbitrarily deep. Everything is stored and fully restored on load. No table per class, no mapping. ```csharp [RedbScheme("Analytics Record")] public class AnalyticsRecordProps { // Scalars public string Title { get; set; } = ""; public int Views { get; set; } public decimal Revenue { get; set; } // Primitive arrays public string[]? Tags { get; set; } public int[]? Scores { get; set; } // Nested business class public Address? HomeAddress { get; set; } // Array of business classes public Contact[]? Contacts { get; set; } // Dictionary public Dictionary? PhoneBook { get; set; } // Dictionary public Dictionary? PriceList { get; set; } // Dictionary public Dictionary? AddressBook { get; set; } // Dictionary public Dictionary? ComplexBook { get; set; } // Tuple key dictionary public Dictionary<(int, string), string>? TupleKeyDict { get; set; } } public class Address { public string City { get; set; } = ""; public string Street { get; set; } = ""; public BuildingDetails? Details { get; set; } // nesting goes deeper } public class ProjectInfo { public string Title { get; set; } = ""; public int Priority { get; set; } public string[]? Tags { get; set; } // arrays inside dict values public MetricTag[]? MetricTags { get; set; } // class arrays inside dict values public Dictionary? Scores { get; set; } // dict inside dict value } ``` All saved and loaded with a single `SaveAsync` / `LoadAsync`. Fields can be added or removed at any time — `SyncSchemeAsync` handles it. ### Where Filters | Feature | Example | Notes | |---------|---------|-------| | Comparison | `.Where(e => e.Salary > 75000)` | `>`, `<`, `>=`, `<=`, `==`, `!=` | | AND / OR / NOT | `.Where(e => e.Age >= 30 && e.Salary > 70000)` | SQL logic: see [Fields without a value](#fields-without-a-value) | | Chained Where | `.Where(...).Where(...)` | Multiple calls = AND | | WhereIn | `.WhereIn(e => e.Department, values)` | SQL `IN (...)` clause | | Nullable fields | `.Where(e => e.Code == null)` | IS NULL / IS NOT NULL | | Base field filters | `.WhereRedb(o => o.DateCreate.Year == 2025)` | Filter on `_objects` table fields directly | | WhereInRedb | `.WhereInRedb(x => x.Id, ids)` | IN on base fields — direct | ### Fields without a value An object can have no value for a field: a `null` that was saved, a field added after the object was, a dictionary entry with a key the object does not have, or (Pro) an element by an index past the end of its array. Filters treat it the way SQL treats `NULL`, on every provider, in Free and Pro alike: - `p.F == v` and `p.F != v` both leave it out. So do `!(p.F == v)`, `p.F != p.G` when either field has no value, and `!list.Contains(p.F)`. - To include it, say so: `p.F != v || p.F == null`, `p.F != p.G || p.F == null || p.G == null`, `!list.Contains(p.F) || p.F == null`. - A `null` inside the list of `Contains` is ignored: `[a, null]` filters as `[a]`. To match the objects without a value, add `|| p.F == null`. - `p.F == null` and `p.F != null` select exactly the objects without and with a value. - One exception: on SQL Server Free a negated comparison of a list item's `Id`, `Value` or `Alias`, such as `!(p.Status.Id == id)` or `!ids.Contains(p.Status.Id)`, also returns the objects without a list item. This differs from LINQ to objects, and from EF Core's default, which adds the `IS NULL` check to every `!=` itself unless the context is configured with `UseRelationalNulls()`. Measured with EF Core 10.0.15 on PostgreSQL over 1,000 rows, 142 of them without a value for `N`: `Where(p => p.N != 3)` returns 772 rows in redb and in plain SQL (`N <> 3`), 914 in EF Core and in LINQ. Sorting puts the objects without a value first when ascending and last when descending, as LINQ does, on every engine. ### DateTime **`DateTime` is a reading on a clock, `DateTimeOffset` is a moment in time.** `14:00` written as a `DateTime` comes back as `14:00` on any machine, in any zone, through any read path. A `DateTimeOffset` carries a real instant and keeps native .NET semantics. Base object fields (`DateCreate`, `DateModify`, `DateBegin`, `DateComplete`) are `DateTimeOffset`, therefore instants. `DateOnly` is stored as a date and `TimeOnly` and `TimeSpan` as their `Ticks`, so no stored form follows the host's culture: a row written on a `ru-RU` host reads identically on an `en-US` one. Nothing to configure. See **[DATETIME.md](DATETIME.md)** for the full type table, the precision differences between providers, and the one trap worth knowing. | Feature | Example | |---------|---------| | Comparison | `.Where(e => e.HireDate >= cutoffDate)` | | Range | `.Where(e => e.HireDate >= start && e.HireDate < end)` | | Extract parts | `.WhereRedb(o => o.DateCreate.Year == 2025)` | | Ordering | `.OrderBy(e => e.HireDate)` | | `DateOnly` / `TimeOnly` / `TimeSpan` | comparison, range and ordering on all three (`TimeOnly` and `TimeSpan` as their `Ticks`) | ### String Operations | Feature | Example | SQL | |---------|---------|-----| | Contains | `.Where(e => e.Name.Contains("Smith"))` | `LIKE '%Smith%'` | | StartsWith | `.Where(e => e.Name.StartsWith("John"))` | `LIKE 'John%'` | | Case-insensitive | `.Contains("smith", StringComparison.OrdinalIgnoreCase)` | `ILIKE` | | Case-insensitive, **non-English text** | needs `c.StringCollation = "und-x-icu"` — see below | `(col COLLATE "und-x-icu") ILIKE` | | ToLower / ToUpper | `.Where(e => e.Name.ToLower().Contains("s"))` | `LOWER()` | | Trim + Length | `.Where(e => e.Name.Trim().Length > 3)` | `TRIM()`, `LENGTH()` | > **Searching non-English text?** A case-insensitive search folds case the way the database does, and > two of the three fold **ASCII only**: `Contains("привет", OrdinalIgnoreCase)` finds `HELLO` but not > `ПРИВЕТ`. Always on SQLite; on PostgreSQL only when the database was created with `LC_CTYPE=C`; > never on SQL Server. One setting fixes every script at once, Cyrillic, Greek, Hungarian, Polish, > Czech and French alike: > ```csharp > .Configure(c => c.StringCollation = "und-x-icu") > ``` > It does not make search accent-insensitive, and on PostgreSQL it changes which index serves the search. > Read **[COLLATION.md](COLLATION.md)** before switching it on. > > **On PostgreSQL, check the database ctype first** > (`SELECT datctype FROM pg_database WHERE datname = current_database()`). With a UTF-8 ctype > (`en_US.utf8`, `ru_RU.utf8`) plain `ILIKE` already folds every script: leave `StringCollation` unset, and > the stock trigram index keeps serving the search. With ctype `C` or `POSIX` the setting gives correct > folding, but pg_trgm builds no trigram from non-ASCII text under that ctype, so a non-ASCII substring > search reads every row whatever the index; only a database with a UTF-8 ctype makes it indexed. > > With the setting on, Pro (planner on, the default) stops reading `IX__values__String_pattern` for > ignore-case searches. It needs a trigram index over the same collation, and the index must match the > configured collation exactly, so it differs per project: > ```sql > CREATE INDEX CONCURRENTLY "IX__values__String_pattern_und_x_icu" > ON _values USING gin ((_String COLLATE "und-x-icu") gin_trgm_ops) WHERE _String IS NOT NULL; > ``` > Start-up logs a Warning while it is missing, > [`redb.Postgres/sql/maintenance/string_collation_index.sql`](redb.Postgres/sql/maintenance/string_collation_index.sql) > builds it for any collation, and `c.CreateStringCollationIndex = true` has Pro build it at start-up > (`CREATE INDEX CONCURRENTLY`; under ctype `C` it serves ASCII patterns only). The free provider reads no trigram index for a substring search, with or > without the setting. ### Nested Properties | Feature | Example | |---------|---------| | Nested class field | `.Where(e => e.HomeAddress!.City == "London")` | | Deep nesting (3+ levels) | `.Where(e => e.HomeAddress!.Building!.Floor > 10)` | ### Array Operations | Feature | Example | |---------|---------| | Contains element | `.Where(e => e.Skills.Contains("C#"))` | | Contains any (OR) | `.Where(e => e.Skills.Contains("C#") \|\| e.Skills.Contains("Python"))` | | Contains all (AND) | `.Where(e => e.Skills.Contains("C#") && e.Skills.Contains("SQL"))` | | Exclude element | `.Where(e => e.Skills.Contains("C#") && !e.Skills.Contains("intern"))` | | Mixed with scalars | `.Where(e => e.Age > 30 && e.Skills.Contains("C#"))` | | Condition on an element of a class array (Pro) | `.Where(e => e.Contacts!.Any(c => c.Type == "email" && c.IsVerified))` | | Element by index (Pro) | `.Where(e => e.SkillLevels![0] == 5)`, `.Where(e => e.Contacts![0].Value == email)` | An element by index is read in a filter of redb Pro: an element of an array or a list field of the object, or one field of an element of a class, by a non-negative index given as a constant or a variable. An element past the end is a field without a value (see [Fields without a value](#fields-without-a-value)). Refused with `NotSupportedException`: an element that is a list item or an object reference (use `Any(...)`), a field of a class inside an element, an element of an element, an element in a sort, a group key or a window key, and any element by index on the free providers. In `Any` over an array or a list of classes, every condition reads the same element. The element's own fields of a simple type can be read; a field the element has no value for matches neither `==` nor `!=`. The free providers refuse the form with `NotSupportedException` before any SQL. ### Dictionary Operations | Feature | Example | |---------|---------| | ContainsKey | `.Where(e => e.PhoneDirectory!.ContainsKey("desk"))` | | Indexer filter | `.Where(e => e.BonusByYear![2023] > 6000)` | | Nested class in value | `.Where(e => e.OfficeLocations!["HQ"].City == "NY")` | | Tuple key | `.Where(e => e.PerformanceReviews![reviewKey] == "Excellent")` | A dictionary is stored as an unordered set of entries. A read lists them by key, the same on every provider: strings ordinally, numbers, dates and other simple keys by value, tuple and class keys by the text they are stored under. ### Projection & Pagination | Feature | API | Notes | |---------|-----|-------| | Select fields | `.Select(x => new { x.Props.FirstName, x.Props.Salary })` | Server-side projection, fetches only selected columns | | Distinct | `.Distinct()` | Pro: one object per Props hash | | DistinctBy | `.DistinctBy(x => x.Field)`, `.DistinctByRedb(x => x.Name)` | One object per key; in Pro with `OrderBy` (the key first), `Skip`/`Take`, and `CountAsync` counting the keys | | OrderBy | `.OrderBy(e => e.Salary)`, `.OrderByDescending(...)` | Ascending / descending | | ThenBy | `.ThenBy(...)`, `.ThenByDescending(...)` | Multi-field sorting | | Skip / Take | `.Skip(10).Take(10)` | Pagination | | FirstOrDefault | `.FirstOrDefaultAsync()` | Single result or null | ### Existence & Count | Feature | API | |---------|-----| | Count | `.CountAsync()` | | Any | `.AnyAsync()`, `.AnyAsync(predicate)` | | All | `.AllAsync(predicate)` | ### Arithmetic & Math | Feature | Example | SQL | |---------|---------|-----| | Arithmetic in Where | `.Where(e => e.Salary * 12 > 1_000_000)` | Inline `*`, `/`, `+`, `-` | | Multi-field formulas | `.Where(e => e.Age * 1000 + e.Salary > 120_000)` | Combined expressions | | Math.Abs | `.Where(e => Math.Abs(e.Age - 35) <= 5)` | `ABS()` | | Arbitrary SQL function | `Sql.Function("COALESCE", e.Age, 0)` | Any SQL function by name | ### Aggregation | Feature | API | Notes | |---------|-----|-------| | Sum | `.SumAsync(e => e.Salary)` | Server-side `SUM` | | Average | `.AverageAsync(e => e.Age)` | Server-side `AVG` | | Min / Max | `.MinAsync(e => e.Salary)`, `.MaxAsync(...)` | Server-side `MIN` / `MAX` | | Batch aggregation | `.AggregateAsync(x => new { Agg.Sum(...), Agg.Average(...), Agg.Count() })` | Multiple aggregations in one query | | Filtered aggregation | `.Where(...).SumAsync(...)` | Filter before aggregating | | Base-field aggregation | `.SumRedbAsync(x => x.Id)`, `.MinRedbAsync(x => x.DateCreate)` | Aggregate on `_objects` fields — direct | | Array element aggregation | `Agg.Sum(x.Props.SkillLevels.Select(s => s))` | Sum all array elements | ### GroupBy | Feature | API | Notes | |---------|-----|-------| | Group by field | `.GroupBy(x => x.Department).SelectAsync(g => new { g.Key, Agg.Sum(g, x => x.Salary) })` | Server-side GROUP BY | | Filter + group | `.Where(...).GroupBy(...)` | WHERE before GROUP BY | | Composite key | `.GroupBy(x => new { x.Department, x.Position })` | Multi-field grouping | | Group by base field | `.GroupByRedb(x => x.OwnerId)` | GROUP BY on `_objects` — direct | | Group by array element | `.GroupByArray(e => e.Contacts!, c => c.Type)` | Expands arrays into groups | | Inner array | `.GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!), m => m.Label)` | Groups the elements of an array inside an element | | Array of simple values | `.GroupByArray(e => e.Skills!, s => s)`, `.GroupByArray(e => e.Address!.Building!.Amenities!, a => a)` | The element itself is the key; `Agg.Sum(g, x => x)` sums it | | Field of a class in the element | `.GroupByArray(e => e.Items!, i => i.Place!.City)` | Nested classes of the element | | Conditional count | `Agg.Count(g, c => c.IsVerified && c.Type == "email")` | In `SelectAsync` and `Having`, for `GroupBy` and `GroupByArray` | | Window over array groups | `.GroupByArray(...).WithWindow(w => w.OrderBy(g => g.Key))` | Same windows as `GroupBy(...).WithWindow(...)` | | SQL of an array grouping | `.GroupByArray(...).ToSqlStringAsync(g => ...)` | The statement that runs | The array of `GroupByArray` is a chain of fields or `SelectMany` over an inner array; its key is a stored field, an anonymous type of fields, or the element itself. A condition of `Agg.Count` compares fields with constants or with each other, combines them with `&&`, `||`, `!`, tests for null and reads boolean fields. Everything else (a `SelectMany` with a result selector, a dictionary in the path, a computed key or aggregate, a string method in a condition, an array of list items or object references) throws `NotSupportedException` naming the form. A tree query groups only the elements of its subtree. ### Window Functions | Feature | API | Notes | |---------|-----|-------| | ROW_NUMBER | `Win.RowNumber()` | Rank within partition | | RANK / DENSE_RANK | `Win.Rank()`, `Win.DenseRank()` | Ranking with/without gaps | | Running sum | `Win.Sum(x.Props.Salary)` | Cumulative aggregation | | LAG / LEAD | `Win.Lag(x.Props.Salary)`, `Win.Lead(...)` | Previous / next row values | | FIRST_VALUE / LAST_VALUE | `Win.FirstValue(...)`, `Win.LastValue(...)` | Boundary values in partition | | NTILE | `Win.Ntile(4)` | Divide into equal buckets | | Custom frame | `.Frame(Frame.Rows(3))` | Sliding window: `ROWS BETWEEN N PRECEDING AND CURRENT ROW` | | Partition by base field | `.PartitionByRedb(x => x.SchemeId)` | Direct, no Props join | | Filter + window | `.Where(...).WithWindow(...)` | Pre-filter before windowing | | Page of a window | `.OrderBy(...).Skip(20).Take(10).WithWindow(...)` | Pro, flat and tree queries: the window over the whole filtered set, the page returned | | GroupBy + window | `.GroupBy(...).WithWindow(...).SelectAsync(...)` | Rank aggregated groups | With `Take`, Pro computes the window over the fields it needs (partition, ordering, arguments, filter) and reads the other selected fields only for the rows it returns. ### Tree Structures Built-in hierarchical data: each object points to its parent (`ParentId`), and subtrees are read by recursive queries. The tree services (`LoadTreeAsync`, `GetDescendantsAsync`, `GetPathToRootAsync`, `DeleteSubtreeAsync`, the cycle check of `MoveObjectAsync`) read the shape of a subtree or a chain of ancestors in one statement and the objects in one batch; a cycle in the parent links raises an error naming the object. | Feature | API | Notes | |---------|-----|-------| | Create child | `CreateChildAsync(child, parent)` | `child` is a `TreeRedbObject` | | Bulk create | `AddNewObjectsAsync(treeObjects)` | Batch insert with pre-assigned IDs | | Load tree | `LoadTreeAsync(root, maxDepth)` | Full hierarchy with depth limit | | Get children | `GetChildrenAsync(parent)` | Direct children only | | Get descendants | `GetDescendantsAsync(node)` | All descendants recursively | | Path to root | `GetPathToRootAsync(node)` | Breadcrumb trail | | Move subtree | `MoveObjectAsync(node, newParent)` | Reparent node and its subtree | | Tree LINQ queries | `TreeQuery().Where(...).OrderBy(...)` | Full LINQ on tree | | Filter roots | `.WhereRoots()` | Root nodes only | | Filter leaves | `.WhereLeaves()` | Leaf nodes only | | Filter by level | `.WhereLevel(2)` | Nodes at specific depth | | Children / descendants of a node | `.WhereChildrenOf(node)`, `.WhereDescendantsOf(node, maxDepth)` | Several tree filters in one query all apply | | Scoped subtree query | `TreeQuery(rootId, maxDepth)` | Query within a subtree | | Multiple roots | `TreeQuery(rootIds, maxDepth)` | Query across subtrees | | Ancestor filter | `.WhereHasAncestor(a => a.Budget > 500000)` | Filter by ancestor properties | | Descendant filter | `.WhereHasDescendant(d => d.Budget > 100000)` | Filter by descendant properties | | Relationship check | `node.IsDescendantOfAsync(ancestor, redb)` | Extension method, without loading the tree | | DFS / BFS traversal | `.DepthFirstTraversal()`, `.BreadthFirstTraversal()` | In-memory traversal | | Tree materialization | `.ToTreeListAsync()`, `.ToRootListAsync()`, `.ToFlatListAsync()` | Parent chains, recursive children, or flat | | Tree stats | `TreeCollection.GetStats()` | Depth, leaf count, max width | | Aggregation on trees | `TreeQuery().GroupBy(...)`, `.WithWindow(...)` | GroupBy and window functions in tree context | | Existence | `TreeQuery(root).AnyAsync(...)` | Pro stops at the first matching node | ### Lists (Reference Dictionaries) Named lookup lists with items, useful for statuses, categories, roles. | Feature | API | |---------|-----| | Create list | `RedbList.Create(name, alias)` | | Add items | `ListProvider.AddItemsAsync(list, values, aliases)` | | Get by name | `ListProvider.GetListByNameAsync(name)` | | Item with linked object | `RedbListItem(list, value, alias, linkedObject)` | | Store in Props | `Props.Status = listItem` (single), `Props.Roles = listItems` (array) | | Filter by item value | `.Where(p => p.Status!.Value == "Active")` | | Filter by item identity | `.Where(p => p.Status == activeItem)` | | WhereIn on item values | `.WhereIn(p => p.Status!.Value, values)` | | Any in item array | `.Where(p => p.Roles!.Any(r => r.Value == "Admin"))` | | No item with a value | `.Where(p => !p.Roles!.Any(r => r.Value == "Admin"))` (an empty or missing list included) | `Any` over list items compares an item's `Value`, `Alias` or `Id` with `==` only; another operator is refused with `NotSupportedException`. ### Export / Import (Database Portability) Full database export/import via `.redb` files (JSONL, optionally ZIP-compressed). Migrate between PostgreSQL and MSSQL, create backups, replicate data. | Feature | Notes | |---------|-------| | Export entire DB | `ExportService` — streams all schemes, objects, values, users, roles, permissions | | Export filtered | Export only selected schemes by ID | | Import | `ImportService` — streaming JSONL, bulk-insert batches | | Compression | Optional ZIP wrapping (auto-detected on import) | | Cross-platform | Export from PostgreSQL → Import to MSSQL (and vice versa) | | Dry run | Preview statistics without writing | | CLI | `redb export` / `redb import` commands | Restart every application that uses the target database after an import or a restore into it, the same process included when it runs `ImportService` itself. A running redb service keeps ids it reserved before the import, and those ids can belong to imported rows. A save that meets such an id fails once with an `InvalidOperationException` that says so, resets the reserved ids of that database and writes nothing; saved again, it takes fresh ids. ### Users, Roles & Permissions > **Object permissions and roles are deprecated** and will be removed in a future major version: the permission and > role methods (`CanUser…`, `GrantPermissionAsync`, `RoleProvider` and the rest) and the `DefaultCheckPermissionsOn…` > settings are marked `[Obsolete]`. In the 4.x line they keep working as they are and get no further development. > Authorise in the application, as redb.Identity does, or use the database's own roles and row-level security. Users > stay: they are the owner and the author of the last change of every object. Note that `DefaultCheckPermissionsOnQuery` > filters queries of the free providers only, row by row after the page is read (a page may come back short, a count is > not filtered); queries of redb Pro are not filtered by permissions. Built-in user management with password hashing, roles, and object-level permissions. No external identity provider required. | Feature | API | Notes | |---------|-----|-------| | Create user | `UserProvider.CreateUserAsync(request)` | Login, password, name, email, phone | | Authenticate | `UserProvider.ValidateUserAsync(login, password)` | Returns `IRedbUser?`, bcrypt by default (`IPasswordHasher`); legacy SHA256 + salt hashes keep verifying and rehash on the next password change | | Change password | `UserProvider.ChangePasswordAsync(user, current, new)` | Verifies the current password first | | Enable / disable | `UserProvider.EnableUserAsync(user)`, `DisableUserAsync(user)` | Soft disable | | Search users | `UserProvider.GetUsersAsync(criteria)` | Filter by login, email, role, date range | | Create role | `RoleProvider.CreateRoleAsync(request)` | Named role with optional description | | Assign role | `RoleProvider.AssignUserToRoleAsync(user, role)` | Many-to-many | | Grant permission | `GrantPermissionAsync(user or role, obj, actions)`, `CreatePermissionAsync(request)` | Per-object or per-scheme, CRUD flags | | Check permission | `CanUserSelectObject(obj)` | Select / Insert / Update / Delete | | Effective permissions | `GetEffectivePermissionsAsync(user, obj)` | Resolved from user + role inheritance | | Security context | `SetCurrentUser(user)`, `CreateSystemContext()` | Ambient via `AsyncLocal`, disposable elevation | ```csharp // Authenticate var user = await redb.UserProvider.ValidateUserAsync("admin", "password123"); if (user != null) { redb.SetCurrentUser(user); // All subsequent operations run as this user } // Temporary system elevation (skip permissions) using (redb.CreateSystemContext()) { await redb.SaveAsync(sensitiveObject); } ``` ### Save Interceptors `IRedbSaveInterceptor` sees every save and hard delete: `SavingAsync` and `DeletingAsync` before the transaction (an exception cancels the operation), `SavedAsync` and `DeletedAsync` after the commit. Under `ChangeTracking` the saved context carries the value-level changes. Inside `ExecuteAtomicAsync` all four run within the caller's transaction. With nothing registered the save pipeline pays nothing. | Source | How | Order | |--------|-----|-------| | DI | `services.AddSingleton()` | first, in registration order | | Run time | `IRedbSaveInterceptorRegistry.Add(interceptor)` returns an `IDisposable` | after DI, in subscription order | The registry is for code that cannot reach the container the redb service was built from, such as a module loaded into its own `AssemblyLoadContext`. `AddRedb` and `AddRedbPro` register it as a singleton with `TryAdd`, so a registry put into the container before them is kept and can be shared. - A subscription sees **every** save and delete of the process made through a redb service over that registry: scopes already open, other modules, and other redb services built over the same registry. - An exception from its `SavingAsync` or `DeletingAsync` therefore cancels **any** save or delete of the process, not only the subscriber's own. - It takes effect from the next operation. An operation already running keeps the set of interceptors it started with, so its Saving and Saved always reach the same interceptors. - Disposing the handle removes the interceptor for every later operation, and the registry keeps no reference to it, so the load context can unload once the running operations end. Disposing twice, or from another thread, is safe. ```csharp var registry = services.GetRequiredService(); using var subscription = registry.Add(new NotifyOnSave(hub)); // ... until the module stops ``` ### Deadlocks and retries When SQL Server (error 1205) or PostgreSQL (40P01) picks a transaction as a deadlock victim, the server has already rolled the whole transaction back. Only the code that owns the transaction can run its unit again, so redb retries only the units it owns: a save, a delete by ids, a soft-delete mark and a purge batch called outside any transaction run again up to three times with a short growing delay. Inside your transaction (`ExecuteAtomicAsync`, an explicit one, or a `TransactionScope`) nothing is retried and the deadlock reaches you unchanged; `ExecuteAtomicAsync` never runs your delegate twice. To retry your own unit, wrap the whole call made outside any transaction: ```csharp var reserved = await DeadlockRetryHelper.ExecuteWithRetryAsync(redb.Context, () => redb.Context.ExecuteAtomicAsync(async () => { /* read, then write */ return true; })); ``` The overload taking the context does not retry when that context is already in a transaction, and none of them retries inside a `TransactionScope`, so the same code is safe when it is later called from within one. ### Your own SQL in redb's transaction A command of your own that must commit or roll back together with a redb save runs on the connection redb works on. A second connection to the same database inside one transaction makes it distributed: SQL Server refuses or promotes it, PostgreSQL needs prepared transactions, and on SQLite the second connection waits for the write lock the first one holds. `IRedbConnection.LeaseAsync` lends that connection for your command, in the transaction redb's commands run in: your explicit transaction (`BeginTransactionAsync`, `ExecuteAtomicAsync`), else the ambient `TransactionScope`, else none. ```csharp using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await using (var lease = await redb.Context.Db.LeaseAsync()) { await using var command = lease.CreateCommand(); // bound to the transaction the driver needs command.CommandText = "UPDATE stock SET reserved = reserved + 1 WHERE sku = 'A-1'"; await command.ExecuteNonQueryAsync(); } await redb.SaveAsync(order); scope.Complete(); } ``` The lease is one command's hold: it enters the same gates a redb command does, so while it is held a redb call on that connection or in the same `TransactionScope` is refused at once. Release it with `await using` as soon as your commands are done. While it is held, never: - commit, roll back or dispose the transaction, or begin one of your own; - close, dispose or reopen the connection (the release reports it), or change its database; - change session settings (`SET`, `PRAGMA`, the isolation level): redb's next command runs on the same connection; - leave a data reader open past the release; - swallow a failure of your command and go on: on PostgreSQL a failed command aborts the transaction for every later command, redb's included. The lease is on the connection of the redb service you resolved; a named service lends its own. An explicit transaction belongs to the DI scope that began it, so lease through the service of that scope; inside a `TransactionScope` every scope of the database lends the scope's one connection. `GetUnderlyingConnectionAsync` stays the way for code that owns the connection for a whole piece of work, such as EF Core on redb's connection, PostgreSQL COPY or `SqlBulkCopy`: it takes no gate, so that work and redb's must run strictly one after the other. --- ## Architecture ```mermaid graph TD A["IRedbService"] --> B["Query<T>()"] A --> C["TreeQuery<T>()"] A --> D["SaveAsync / LoadAsync"] A --> E["SyncSchemeAsync"] A --> F["ListProvider"] A --> G["UserProvider / RoleProvider"] B --> H["ProSqlBuilder (Pro) / PVT SQL module (Free)"] C --> I["Recursive tree queries"] D --> J["IRedbContext (SQL)"] E --> K["Auto-migration"] H --> L["PostgreSQL / SQL Server / SQLite"] I --> L J --> L K --> L ``` ``` IRedbService ← single entry point ├── Query() ← flat LINQ queries ├── TreeQuery() ← hierarchical queries (CTE) ├── SaveAsync() ← create / update (full object graph) ├── LoadAsync() ← load by ID (with all nested objects) ├── ListProvider ← reference dictionaries ├── UserProvider ← users, authentication, passwords ├── RoleProvider ← roles and user-role assignments ├── SecurityContext ← current user, permission checks └── SyncSchemeAsync() ← auto-migration from C# class ``` Storage is provider-based. Each `[RedbScheme]` class maps to an internal structure in the target database. Schema changes (new fields, removed fields, type changes) are handled automatically by `SyncSchemeAsync` — no migration files needed. **Supported backends:** PostgreSQL 15+, Microsoft SQL Server 2019+, SQLite (Free through a native loadable extension, Pro in pure C#). ### Schema lifecycle and multi-version deployments **Read path is graceful.** When deployed code has a `Props` class without a field that exists in the database, the materializer silently skips it. Old binaries safely read newer data — no exception is thrown. **Taking data away needs a version.** `InitializeAsync()` synchronises every scheme with its Props class. Adding a property adds its structure. Removing a property, or changing its type, takes stored data away: the structure is deleted with every value of it, or the values are converted to the new type. The sync does that only for a class that says it is newer than the database, by a version the programmer raises: ```csharp [RedbScheme("Orders", Version = 2)] // raised when a property was removed or changed its type public class OrderProps { ... } ``` The database records the version each scheme was last synchronised with (`_schemes._version`, never lowered): | Class version against the database | The sync | A save | |---|---|---| | higher | deletes the structures the class no longer declares, converts changed types, records the version | as usual | | equal (also: no `Version`, which is 0) | adds what the class lacks; keeps removed fields and old types, with a warning | keeps the fields it does not know | | lower (an older build next to a newer one) | changes nothing, with a warning | refused with `RedbPropsClassOlderException` | A field kept this way stays in the database with its values; `DropUnknownStructuresAsync()` lists such fields with their value counts, and with `dryRun: false` deletes them. A change inside a nested class is a change of every scheme that uses that class: raise the version of each. `DefaultDestructiveSyncAtEqualVersion` (on in the Development profile, off otherwise) lets a class of the same version delete and convert too, for a local database during development. The Production profile, and no profile, keep the guard: a type (or collection kind) changed without a raised version is held, the property is read through the stored type's converter, and saves of that scheme are refused with `RedbPropertyTypeHeldException` until the version is raised. When a structure is deleted, its values go with it: on PostgreSQL and SQLite by the foreign key `_values._id_structure -> _structures._id ON DELETE CASCADE`, on SQL Server by the trigger `TR__structures__cascade_values` (SQL Server forbids the cascade path). An `ILogger.LogWarning` names the scheme and the structures, both when they are deleted and when the version rule keeps them. **Old and new builds side by side.** During a rolling upgrade a node on the old build may start and save while a new one runs: - A new property needs no version. The old build's sync keeps it, and its saves keep the new field's values. A new field under a nested class or a collection the old class knows cannot be kept when the old build replaces that part: that save is refused with `RedbPropsClassOlderException`, naming the fields. - A removed property or a changed type needs a raised version. Once the new build has synchronised, the old build's sync changes nothing and its saves of that scheme are refused, so it cannot write the old shape over the new one. Upgrade the old nodes, or route the writes of that scheme to the new ones, until the rollout ends. **A changed type with stored values.** The sync converts the values in the database before it changes the type; a value that does not convert stops it with `RedbTypeMigrationException`, and nothing changes. What some conversions mean: - A `long` or `int` changed to a date reads the number as Unix seconds; a date changed to `long` or `int` becomes whole Unix seconds. - `TimeSpan` or `TimeOnly` and a date (`DateTime`, `DateTimeOffset`, `DateOnly`), in either direction, have no common meaning: the change is refused with `RedbTypeMigrationException` while the property holds values. - `TimeSpan` or `TimeOnly` changed to `string` or `double` writes the tick count (`36000000000` for one hour), not `01:00:00`. - A changed dictionary key type keeps the stored keys as they are. It is refused with `RedbTypeMigrationException`, naming the keys, when a stored key does not read as the new key type or reads as other text. ### Renaming a property A property renamed in C# is, to the sync, a new property next to an old one: the old one keeps its values but the class no longer reads them, and a class of a raised version deletes it with them. Give the renamed property its previous name and the stored property is renamed in place instead: ```csharp public class OrderProps { [RedbRename("Title")] // stored as Title until now public string Heading { get; set; } = ""; public AddressProps Address { get; set; } = new(); } public class AddressProps { [RedbRename("City")] // nested classes work the same way public string Town { get; set; } = ""; } ``` - The structure keeps its id, so every stored value stays; the next start finds `Heading` and does nothing. - A chain of renames is the attribute repeated: `[RedbRename("Title")]` and `[RedbRename("Heading")]` on `Caption` renames a database at any point of the chain. - If the database holds both `Heading` and `Title`, the start stops with `RedbRenameConflictException` and changes nothing: each may hold values, and picking one would lose the other. - A rename together with a type change renames first, then migrates the type as for any property. - The previous names are kept in `_structures._renamed_from`. A node that still runs the class with `Title` stops at its sync with `RedbRenameConflictException`, instead of adding `Title` again and deleting `Heading`. Nodes of packages older than this feature do not know the column: upgrade the packages first, or roll out the rename with `DefaultStrictDeleteExtra = false`. - `[RedbRename]` stays on the property for good, the chain in order, its first name first. The first name orders the property in the object hash, so the hashes stored before the rename stay valid after it. A start whose class lost the attribute, or declares another first name than the history in `_renamed_from`, stops with `RedbRenameConflictException`. The one case the check cannot see: a database created directly with the renamed class has no history yet. - A freed name may be taken by a new property once the rename is applied: `[RedbRename("Title")]` on `Heading` next to a new `Title` is allowed. While the database still stores `Title` and not `Heading`, such a class is refused at start, since the stored `Title` could belong to either property; apply the rename first. - Two properties cannot swap names in one step (`[RedbRename("Right")]` on `Left` and `[RedbRename("Left")]` on `Right`): the start refuses it. Swap through a temporary name, one deployment per rename. A scheme is renamed the same way through `RedbScheme`, oldest previous name first; a previous FullName works too, for a class without an explicit name that was renamed or moved: ```csharp [RedbScheme(Name = "orders", RenamedFrom = ["order", "Shop.Models.OrderProps"])] public class OrderProps { /* ... */ } ``` ### Modules in a collectible AssemblyLoadContext A module that brings its own Props types (a Tsak module, a plugin) can live in a collectible `AssemblyLoadContext` and unload while the host's redb service goes on. redb keeps no strong reference to its types: the caches keyed by type hold them weakly, and when the context unloads redb drops the module's objects from the props and list caches. The host only calls `Unload()`. The .NET libraries keep caches of their own over the types they handled; System.Text.Json does not support unloadable assemblies otherwise ([dotnet/runtime#65323](https://github.com/dotnet/runtime/issues/65323)). On every unload redb therefore calls `ClearCache` of the hot reload handlers (`MetadataUpdateHandler`) of all loaded assemblies, as `dotnet watch` does: System.Text.Json, TypeDescriptor and the others. A failing handler is logged as a warning and the rest still run. The price is cold caches in those libraries once per unload. What the module must release itself: its interceptor subscriptions (`IRedbSaveInterceptorRegistry`), and any redb object or service it handed to the host. --- ## How It Compares ### vs Entity Framework Core ```csharp // EF Core — 28 related entities var order = await context.Orders .Include(o => o.Customer) .Include(o => o.Items).ThenInclude(i => i.Product).ThenInclude(p => p.Category) .Include(o => o.Items).ThenInclude(i => i.Discounts) .Include(o => o.Shipping).ThenInclude(s => s.Address) .Include(o => o.Payment).ThenInclude(p => p.Transactions) // ... 35 more Include lines ... .FirstOrDefaultAsync(o => o.Id == orderId); // RedBase — same data var order = await redb.LoadAsync(orderId); // All nested objects, arrays, dictionaries — loaded automatically. ``` ### vs MongoDB / JSONB | Aspect | MongoDB/CosmosDB | RedBase | |--------|------------------|---------| | Type safety | `dynamic`, `BsonDocument` | `RedbObject` — full IntelliSense | | LINQ support | Partial | Full (Where, GroupBy, Window, Aggregation) | | Transactions | Limited | Full ACID | | Referential integrity | None | Built-in | | Vendor lock-in | Yes | No (PostgreSQL / SQL Server / SQLite) | --- ## Pro Free and Pro take the same LINQ API; they differ in the engine. Free runs queries through the SQL module installed in the database (PL/pgSQL, T-SQL, or a native loadable extension on SQLite). Pro builds the SQL in C#, materializes Props in parallel, and adds: - the query planner (`EnablePvtPrefilter`, on by default) with the streams form, which reads a page, a count or an aggregate without pivoting every object of the scheme; `using (redb.WithQueryPlanner(false)) { ... }` switches it for one block of code without touching concurrent requests (it holds for the queries run inside the block, tasks started there included; on Free it changes nothing); - `PropsSaveStrategy.ChangeTracking`: a save writes only the values that changed; - data migrations of Props classes (`IRedbMigration`, `MigrateAsync`); - SQLite in pure C# (`redb.SQLite.Pro`), for Blazor WebAssembly and mobile; - the 4.4 query work: windows with `Take` and over trees, `AnyAsync` over a tree that stops at the first node, faster `DistinctBy` over trees. See [README-PRO.md](README-PRO.md). **Pro is free of charge and needs no key.** Just add the `redb.*.Pro` packages and use them. Pro packages are proprietary (closed-source), free in production too, with no request limits. **Need the Pro sources?** Larger companies that require them — for a security audit, source escrow, or to build in-house — can ask, and we hand them over. Write to [redbase.app](https://redbase.app). --- ## Documentation | Resource | Link | |----------|------| | Website & Docs (EN) | [redbase.app](https://redbase.app) | | Website & Docs (RU) | [redb.ru](https://redb.ru) | | API Reference | [redbase-app.github.io/redb](https://redbase-app.github.io/redb/) | | Architecture | [redbase.app/architecture](https://redbase.app/architecture) | | Quick Start | [redbase.app/quickstart](https://redbase.app/quickstart) | | Examples | [redb.Examples](redb.Examples/README.md) | | Pro edition | [README-PRO.md](README-PRO.md) | | Upgrading | [UPGRADING.md](UPGRADING.md): what to check and change for a new version | | Changelog | [CHANGELOG.md](CHANGELOG.md) | | Dates and times | [DATETIME.md](DATETIME.md) | | Case-insensitive search | [COLLATION.md](COLLATION.md) | | Unique keys | [UNIQUE_KEYS.md](UNIQUE_KEYS.md) | | Command line tool | [redb.CLI](redb.CLI/README.md) | | NuGet | [nuget.org/packages/redb.Core](https://www.nuget.org/packages/redb.Core) | --- ## License Core packages (`redb.Core`, `redb.Postgres`, `redb.MSSql`, `redb.SQLite`, `redb.Export`, `redb.CLI`, `redb.Templates`, `redb.PropsEditor`) are licensed under [Apache License 2.0](LICENSE) starting from version 2.0.0. Versions ≤ 1.3.0 published on nuget.org remain under MIT. Pro packages (`redb.Core.Pro`, `redb.Postgres.Pro`, `redb.MSSql.Pro`, `redb.SQLite.Pro`) are proprietary (closed-source), **free of charge and need no key**, commercial production use included. Larger companies that need the Pro **sources** (audit, escrow, in-house builds) can request them — see [Pro](#pro).