Bundle: redb / root files (_root.txt), 16 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/CHANGELOG.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/CHANGELOG.md ---- # Changelog All notable changes to RedBase will be documented in this file. This changelog covers the **NuGet-published packages** only: | Package | Edition | |---------|---------| | `redb.Core` | Free | | `redb.Postgres` | Free | | `redb.MSSql` | Free | | `redb.SQLite` | Free | | `redb.Export` | Free | | `redb.Core.Pro` | Pro | | `redb.Postgres.Pro` | Pro | | `redb.MSSql.Pro` | Pro | | `redb.SQLite.Pro` | Pro | | `redb.Licensing` | Pro | | `redb.CLI` | Tool | | `redb.Templates` | Tool | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] Pending changes live in `changelog/unreleased/` until the release; `pwsh scripts/changelog.ps1 -Preview` shows them. ## [4.8.0] — 2026-12-01 ### Breaking - **`ISqlDialect.Query_WrapPvtWithObjectJson` is replaced by `Query_WrapPvtWithObjectRows`.** Only code that implements `ISqlDialect` itself is affected: the new member returns the `_objects` rows of the inner id list, in its order. A new member `Query_WrapPvtWithIds` returns the ids of that list alone, for the Free query delete. Packages: `redb.Core`. Upgrade: [UPGRADING.md](UPGRADING.md#custom-dialects-query_wrappvtwithobjectrows). - **The packages target .NET 10 and .NET 11; .NET 8 and .NET 9 are no longer targets.** Both reached end of support on 10 November 2026. An application on .NET 8 or 9 stays on 4.7.x or moves to .NET 10. Packages: `redb.Core`, `redb.Core.Pro`, `redb.Postgres`, `redb.Postgres.Pro`, `redb.MSSql`, `redb.MSSql.Pro`, `redb.SQLite`, `redb.SQLite.Pro`, `redb.Export`. Upgrade: [UPGRADING.md](UPGRADING.md#net-10-and-net-11-only). - **Tree providers take the save-interceptor pipeline.** `TreeProviderBase`, `ProTreeProviderBase` and the six stock tree providers have a new last constructor argument, and `RedbServiceBase.CreateTreeProvider` a new parameter. Only code that subclasses a tree provider or overrides `CreateTreeProvider` is affected. Packages: `redb.Core`, `redb.Core.Pro`, `redb.Postgres`, `redb.Postgres.Pro`, `redb.MSSql`, `redb.MSSql.Pro`, `redb.SQLite`, `redb.SQLite.Pro`. Upgrade: [UPGRADING.md](UPGRADING.md#custom-tree-providers-the-interceptor-pipeline). - **`WhereHasAncestor` counts `maxDepth` up from the returned object, as `WhereHasDescendant` counts down.** `maxDepth: 1` keeps the objects whose parent matches; it used to limit how deep below the start of the query the ancestor was looked for. Calls without `maxDepth` are unchanged; calls with it set the distance they want. Packages: `redb.Core`, `redb.Core.Pro`, `redb.Postgres`, `redb.Postgres.Pro`, `redb.MSSql`, `redb.MSSql.Pro`, `redb.SQLite`, `redb.SQLite.Pro`. Upgrade: [UPGRADING.md](UPGRADING.md#wherehasancestor-maxdepth-counts-up-from-the-returned-object). - **One `UserConfigurationService`, in `redb.Core`.** Its constructor takes the `ISqlDialect` of the provider, and the PostgreSQL and SQLite copies of the class are removed. Code that resolves `IUserConfigurationService` from DI changes nothing; code that constructs the class or names a provider copy follows the upgrade notes. Packages: `redb.Core`, `redb.Postgres`, `redb.SQLite`. Upgrade: [UPGRADING.md](UPGRADING.md#user-configuration-one-service-class). - **`IRedbQueryProvider.ExecuteDeleteAsync(long, string? filterJson)` is removed.** It threw `NotSupportedException` on every shipped provider. Delete through `Query().DeleteAsync()` or pass a `FilterExpression` to the other overload. Packages: `redb.Core`. Upgrade: [UPGRADING.md](UPGRADING.md#custom-query-providers-executedeleteasync-with-a-json-filter-is-removed). - **Legacy search, aggregate and window members of `ISqlDialect` are removed.** They named functions no shipped database has and threw on every shipped dialect, or no provider called them; the base bodies of `QueryProviderBase` and `TreeQueryProviderBase` that called them are abstract or removed. Only code that implements a dialect or a provider is affected. Free on PostgreSQL and SQLite: `ExecuteAggregateAsync` with a JSON filter now runs instead of throwing. Packages: `redb.Core`, `redb.Postgres`, `redb.MSSql`, `redb.SQLite`. Upgrade: [UPGRADING.md](UPGRADING.md#custom-dialects-and-providers-removed-legacy-members). - **Custom dialects: `Schemes_UpdateName` is replaced by `Schemes_Rename`; `Schemes_SelectRenamed` and `Structures_Rename` are new.** Only code that implements `ISqlDialect` is affected: add the three members and read `_renamed_from` in the scheme and structure selects, as the shipped dialects do. Packages: `redb.Core`. Upgrade: [UPGRADING.md](UPGRADING.md#custom-dialects-rename-members). - **`AddNewObjectsAsync` no longer puts a nested new object under its referrer in the tree.** It keeps the `ParentId` it carries, as `SaveAsync` does; before, every nested new object went under the first object given. Set `ParentId` yourself or use `MoveObjectAsync` where you want the tree child. Packages: `redb.Core`. Upgrade: [UPGRADING.md](UPGRADING.md#addnewobjectsasync-a-nested-new-object-is-no-longer-put-under-its-referrer). - **Removing a field or changing a type now needs `RedbScheme.Version`.** The sync deletes a structure with its values, or converts a type, only for a class whose `Version` is higher than the one the database recorded; without it the field stays and a warning is logged. A type changed without a raised version stops saves of that scheme (`RedbPropertyTypeHeldException`); it does not lose data. An older build next to a newer one changes nothing and its saves of that scheme are refused. `DropUnknownStructuresAsync()` lists and deletes the fields a class no longer declares. Packages: `redb.Core`, `redb.Postgres`, `redb.MSSql`, `redb.SQLite`. Upgrade: [UPGRADING.md](UPGRADING.md#scheme-versions-removing-a-field-or-changing-a-type-needs-redbschemeversion). - **Unused public members of the Pro SQL generators and the batch methods of the provider connections are no longer public.** `PvtSqlGenerator.GenerateExistsClause` and `GeneratePvtSelect` (no query used them) are removed with the record `CompiledPvtQuery` and its namespace `redb.Core.Pro.Query.Models`. `NpgsqlRedbConnection.ExecuteJsonBetweenAsync`, `NpgsqlRedbConnection.QueryThenAsync` and `SqlRedbConnection.QueryResultSetsAsync` are now internal. Only code that calls these classes directly is affected. Packages: `redb.Core.Pro`, `redb.Postgres.Pro`, `redb.MSSql.Pro`, `redb.SQLite.Pro`, `redb.Postgres`, `redb.MSSql`. Upgrade: [UPGRADING.md](UPGRADING.md#pro-sql-generators-and-provider-connections-unused-public-members-removed). - **SQL Server: a save that names a missing object is refused, as on PostgreSQL.** A reference to an object that does not exist, or a parent id that names no object, was stored and read back as `null`; the save now throws the foreign key error of the server. The database module goes to `0.2.41`, and a role without schema rights no longer needs `ALTER` to save. Packages: `redb.MSSql`, `redb.MSSql.Pro`. Upgrade: [UPGRADING.md](UPGRADING.md#sql-server-saves-check-the-foreign-keys). - **Pro migrations: `OnTypeChange().Using(...)` is removed.** A migration configured with it threw `NotImplementedException` when it ran. A type change of a property is converted by the scheme sync; a conversion of your own goes to `Transform(...)`. Packages: `redb.Postgres.Pro`, `redb.MSSql.Pro`, `redb.SQLite.Pro`. Upgrade: [UPGRADING.md](UPGRADING.md#pro-migrations-ontypechange-removed). ### Added - **`IRedbService.WithQueryPlanner(bool)`: the query planner option `EnablePvtPrefilter` for one block of code.** `using (redb.WithQueryPlanner(false)) { ... }` runs the queries inside it with the query planner off (`true`: on); concurrent requests keep `EnablePvtPrefilter`, blocks nest. On Free, which has no planner, the block changes nothing; an own implementation of `IRedbService` gets that default. Packages: `redb.Core`, `redb.Postgres.Pro`, `redb.MSSql.Pro`, `redb.SQLite.Pro`. - **A filter of redb Pro reads an element of an array or a list by its index.** `Where(e => e.SkillLevels![0] == 5)` and `Where(e => e.Contacts![0].Value == email)` read the element itself or one field of an element of a class; an index past the end is a field without a value. These filters were refused before; the free providers still refuse them. Packages: `redb.Core`, `redb.Core.Pro`. - **Index check and repair.** `IRedbService.CheckBaseIndexesAsync()` and `redb indexes check` list every index of the base schema (and with Pro, of the modules in use) that the database lacks, has INVALID or has defined otherwise, with what it serves; `RepairBaseIndexesAsync()` and `redb indexes repair` build the missing ones online where the engine can. Packages: `redb.Core`, `redb.Postgres`, `redb.MSSql`, `redb.SQLite`, `redb.CLI`. - **`redb export` and `redb import` carry the rename history of schemes and properties.** An exported and re-imported database keeps the previous names that `[RedbRename]` and `RedbScheme.RenamedFrom` recorded, so a node with a class older than the rename still stops at its sync. A file written by an earlier version imports as before, with no history. Packages: `redb.Export`, `redb.CLI`. - **`[RedbRename("OldName")]` renames a stored property in place.** The scheme sync used to add the new name and, under the strict sync, delete the old one with its values. With the attribute, the stored property keeps its values; repeat it for a chain of renames. A node still running the class with the old name stops at its sync with `RedbRenameConflictException` instead of deleting the renamed property. The attribute stays on the property for good: its first name keeps the stored hashes valid. Upgrade: [UPGRADING.md](UPGRADING.md#properties-renamed-in-place-redbrename). - **`[RedbScheme(RenamedFrom = [...])]` renames a stored scheme in place.** A changed explicit name, or a renamed or moved class without one, used to get a new scheme and leave every object under the old one. List the previous names and the stored scheme is renamed, its objects stay; a node still running a class of the old name stops with `RedbRenameConflictException`. Upgrade: [UPGRADING.md](UPGRADING.md#properties-renamed-in-place-redbrename). ### Changed - **`redb init` on a SQLite file that already holds the redb schema upgrades it**, as an application start does. On PostgreSQL and SQL Server it refuses such a database before it runs anything, as since redb.CLI 4.7.3; upgrade it with `redb schema --upgrade`, or drop and create it to start over. Packages: `redb.CLI`. - **A filter path that is not a chain of fields of the queried object is refused with one `NotSupportedException`.** `ContainsKey` or a dictionary indexer on something that is not a field, and a field reference the parser cannot read, threw `ArgumentException` with wordings of their own; an indexer on such a dictionary even reached the database with a made-up field name. They now throw `NotSupportedException` with the same message as the other path refusals. Packages: `redb.Core`, `redb.Core.Pro`. - **`DeleteSubtreeAsync` runs the delete interceptors and clears the Props cache, as `DeleteAsync` does.** One `DeletingAsync` before the delete (an exception stops it) and one `DeletedAsync` after, with the start object and every descendant in `ObjectIds`; every deleted object leaves the Props cache. Before, no interceptor saw a subtree delete. Packages: `redb.Core`. - **An older package no longer puts its database module over a newer one.** It starts with a warning when the newer module serves it and stops without changing anything when it does not, so nodes of two versions from 4.8.0 on may share one database during a rolling upgrade. The upgrade script run by hand refuses a newer module the same way before any change. The module goes to `0.7.26` (PostgreSQL), `0.2.45` (SQL Server), schema 13 (SQLite). Packages: `redb.Core`, `redb.Postgres`, `redb.Postgres.Pro`, `redb.MSSql`, `redb.MSSql.Pro`, `redb.SQLite`, `redb.SQLite.Pro`. Upgrade: [UPGRADING.md](UPGRADING.md#the-database-module-is-never-taken-back-by-an-older-package). - **Free: `AnyAsync` stops at the first match.** A flat or tree query asks the database whether a matching object exists (`EXISTS`) instead of counting every match; the answer is the same. A query with `Skip`/`Take` still answers by the count of its page. Packages: `redb.Core`, `redb.Postgres`, `redb.MSSql`, `redb.SQLite`. - **A ChangeTracking save draws keys only for the value rows it inserts.** It used to draw one for every value row of the object and drop most of them, so the key sequence grew by the object's row count on every save. Value row ids are final in the `Saved` interceptor feed; nothing to do. Packages: `redb.Core`, `redb.Core.Pro`. - **Fewer round trips for base-field projections and lookups by id.** A `Select` that reads only base fields (id, name, dates, parent) no longer reads the scheme: it is one statement. On PostgreSQL Pro a query by object id no longer turns nested loops off while the tables have no planner statistics. See the README on statistics of a new database. Packages: `redb.Core`, `redb.Postgres.Pro`. - **A property that changes between a single value, an array and a dictionary is no longer flipped over stored values.** With values stored, the scheme sync stops with `RedbCollectionKindChangeException` naming the property and both kinds; before, the new class read the old rows wrong and the next save dropped them. A property without values changes as before. Packages: `redb.Core`. Upgrade: [UPGRADING.md](UPGRADING.md#scheme-versions-removing-a-field-or-changing-a-type-needs-redbschemeversion). - **Pro: a stored dictionary key that no longer reads stops the load with `RedbDictionaryKeyException`.** An enum key is stored by its member name; after a member is renamed or removed, loading an object with the old key now names the dictionary, the stored key and the key type, instead of a bare `ArgumentException`. No entry is skipped. Packages: `redb.Core`, `redb.Core.Pro`. - **Start-up warns about missing base indexes.** One Warning names every expected index the database lacks, has INVALID or has defined otherwise; nothing is built at start-up. `CheckBaseIndexesOnStart = false` turns it off. Packages: `redb.Core`. Upgrade: [UPGRADING.md](UPGRADING.md#index-check-at-start-up-and-the-repair). - **SQL Server: an OR of several `Contains` over one array reads its elements once.** `Skills.Contains("C#") || Skills.Contains("Python")` becomes one check with the values in a list instead of one per value; the answers are the same. Packages: `redb.MSSql.Pro`. - **PostgreSQL (Free): objects without a value for the sort key now come first when ascending and last when descending,** as on Pro, SQL Server and SQLite and as LINQ orders null. They came last ascending, so pages sorted by such a field start with other objects now; the module goes to `0.7.28` at the next start. Packages: `redb.Postgres`. Upgrade: [UPGRADING.md](UPGRADING.md#postgresql-free-objects-without-a-value-sort-first-ascending). - **The duplicate index `IX__values__array_parent_id` is dropped.** `IX__values__array_parent_index` serves the same lookups and the cascade of the parent key. The upgrade removes the duplicate only where that wider index exists, on PostgreSQL, SQL Server and SQLite; nothing to do, UPGRADING shows how to put it back. Packages: `redb.Postgres`, `redb.MSSql`, `redb.SQLite`. Upgrade: [UPGRADING.md](UPGRADING.md#ix__values__array_parent_id-is-dropped). - **`WhereHasAncestor(..., maxDepth: 1)` on a tree query without a root now reads the children of the matching ancestors in one statement.** Before, it collected them by one statement and sent their ids back to the server as an array parameter of the next. On 99 800 children of 20 ancestors a count went from 156 to 13 ms on PostgreSQL and from 746 to 58 ms on SQL Server; on 5 000 children from 15 to 3 ms and from 36 to 8 ms. On SQLite, `TreeQuery(parents, maxDepth: 1)` with several parents no longer reads every object of the scheme to find their children. Other depths and queries with a root keep the plans they have. Answers do not change. Packages: `redb.Postgres.Pro`, `redb.MSSql.Pro`, `redb.SQLite.Pro`. - **PostgreSQL: a `Contains` over an array of simple values reads a rare value from its elements.** When such a condition is the narrow one of a filter, the matching elements are read first, up to 5 000: fewer seed the query, more leave it as it was. A rare value no longer walks every object of the scheme; the answers are the same. Packages: `redb.Postgres.Pro`. - **Pro: the indexes of the streams query form are built once, at the upgrade that brings them.** Start-up no longer builds them again when they are missing; the index check reports them, and `RepairBaseIndexesAsync()` builds them. Packages: `redb.Postgres.Pro`, `redb.MSSql.Pro`. Upgrade: [UPGRADING.md](UPGRADING.md#pro-the-streams-indexes-are-built-once). - **A window that reads no base field no longer joins `_objects`.** Its rows come from the fields it reads, which already hold only the objects of the scheme; the statement of `ToSqlStringAsync` shows the shorter form. Results are the same. Packages: `redb.Postgres.Pro`, `redb.MSSql.Pro`, `redb.SQLite.Pro`. - **SQLite: start-up keeps the planner statistics of the file.** A file with no statistics and at least 10 000 value rows is analyzed once at start-up (a sampled `ANALYZE`, bounded by `MaintenanceAnalysisLimit`), and a file with statistics gets `PRAGMA optimize`. Without statistics SQLite could start a page from the whole scheme and take minutes on a large file. `KeepSqlitePlannerStatistics = false` turns it off. Packages: `redb.SQLite`, `redb.Core`. - **SQLite: a `Contains` over an array of simple values reads a rare value from its elements.** As on PostgreSQL, when such a condition is the narrow one of a filter, the matching elements are read first, up to 5 000: fewer seed the query, more leave it as it was; the answers are the same. Packages: `redb.SQLite.Pro`. - **Microsoft dependencies move to the 10.0.15 servicing line.** Microsoft.Extensions.*, Microsoft.Data.Sqlite, System.Security.Cryptography.Xml / Pkcs and the ASP.NET Core packages are referenced at 10.0.15 (was 10.0.13). An application that pins one of them lower raises its pin. ### Deprecated - **Object permissions and roles are deprecated** and will be removed in a future major version. The permission and role methods, `RoleProvider` and the `DefaultCheckPermissionsOn…` settings are marked `[Obsolete]` (a warning); nothing changes in their behaviour in 4.x. Authorise in the application, as redb.Identity does, or use the database's own roles and row-level security. Users stay as the owner and the author of changes of objects. Packages: `redb.Core`. ### Fixed - **`AddNewObjectsAsync` no longer inserts a referenced object that is already saved a second time.** Objects referring to an object saved before, by the same instance, failed with a duplicate key on `_objects`; the saved object is now written as a reference, as `SaveAsync` does, and is neither inserted nor changed. Packages: `redb.Core`. - **A clash on the primary key of a redb table is no longer reported as a `[RedbUnique]` violation.** On PostgreSQL and SQL Server, saving an object whose id is already taken threw `RedbUniqueViolationException` with the text of a unique key; the database's own primary-key error now comes through, as it already did on SQLite. Packages: `redb.Core`. - **A new object referred to from a class that is a dictionary value is saved with its referrer.** `SaveAsync` and `AddNewObjectsAsync` skipped it, and the save failed on a foreign key (SQL Server, SQLite) or stored a reference to an object that was never written. Packages: `redb.Core`. - **SQLite Pro: a page sorted by a field and led by that field's values no longer starts from another filter.** A filter such as `Age >= 30` beside `OrderByDescending(e => e.Salary).Take(100)` could drive the statement from every matching object and probe the walked values for each; the walked values now always come first. Packages: `redb.SQLite.Pro`. - **SQLite Pro: a page of a filter read from its matches no longer runs the filter once per object.** On a database without planner statistics a page such as `Where(e => e.Skills.Contains(x)).OrderByRedb(o => o.Id).Take(100)` could run for minutes on a scheme of a hundred thousand objects; the page is now read once and its objects by key. Packages: `redb.SQLite.Pro`. ## Earlier versions Earlier releases are archived by line in [changelog/](changelog/): [4.7.x](changelog/CHANGELOG-4.7.x.md), [4.6.x](changelog/CHANGELOG-4.6.x.md), [4.5.x](changelog/CHANGELOG-4.5.x.md), [4.4.x](changelog/CHANGELOG-4.4.x.md), [4.3.x](changelog/CHANGELOG-4.3.x.md), [4.2.x](changelog/CHANGELOG-4.2.x.md), [4.1.x](changelog/CHANGELOG-4.1.x.md), [4.0.x](changelog/CHANGELOG-4.0.x.md), [3.x](changelog/CHANGELOG-3.x.md), [2.x](changelog/CHANGELOG-2.x.md), [1.x](changelog/CHANGELOG-1.x.md). Path: redb/COLLATION.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/COLLATION.md ---- # Case-insensitive search in RedBase **Audience:** anyone whose data is not written in English. By default, a case-insensitive search in RedBase folds case the way the database does, and two of the three databases fold **ASCII only**. `Contains("привет", OrdinalIgnoreCase)` finds `HELLO` but not `ПРИВЕТ`. One setting fixes it: ```csharp services.AddRedb(options => options .UsePostgres(connectionString) .Configure(c => c.StringCollation = "und-x-icu")); ``` Read the rest of this page before you switch it on: it changes how PostgreSQL uses indexes, and it does not fix everything the name suggests. --- ## Do you have this problem? | Provider | Affected | Why | |---|---|---| | **PostgreSQL** | only if the database was created with `LC_CTYPE=C` or `POSIX` | folding comes from the collation's ctype | | **SQLite** | **always** | `LIKE`, `lower()`, `upper()` and `COLLATE NOCASE` are ASCII-only in every SQLite build; the one shipped with RedBase has no ICU | | **SQL Server** | no | the default collation is case-insensitive for every script | Check PostgreSQL in one line: ```sql SELECT 'Привет' ILIKE '%привет%'; -- false means you are affected ``` For SQLite there is nothing to check. It is always affected. ### PostgreSQL: decide by the database ctype ```sql SELECT datctype FROM pg_database WHERE datname = current_database(); ``` The ctype of the database decides both whether you need the setting and whether a substring search can be indexed at all. | `datctype` | What to do | |---|---| | UTF-8 (`en_US.utf8`, `ru_RU.utf8`, `C.UTF-8`) | Plain `ILIKE` already folds non-ASCII case. Leave `StringCollation` unset; the stock trigram index `IX__values__String_pattern` serves the search. Setting it here buys no correctness and costs the index (see below). | | `C` or `POSIX` | `StringCollation` gives correct folding. But pg_trgm takes letters from the database ctype, not from the collation, and under `C` it builds no trigram from non-ASCII text (`show_trgm('привет')` is empty). A non-ASCII substring search therefore reads every row on every tier, and no index changes that. The only way to an indexed non-ASCII search is a database with a UTF-8 ctype (a new database, or dump and restore), after which the row above applies. | On a `C` ctype with the setting on, the index described below keeps patterns with ASCII letters indexed; it does nothing for the others. --- ## What the setting fixes Every script whose case mapping is one character to one character. There is **no per-language work**: one setting covers all of them at once. | | Example | |---|---| | Cyrillic | `ПРИВЕТ` found by `привет` | | Greek | `ΑΘΗΝΑ` found by `αθηνα` | | Hungarian | `ŐSZ ÚTON` found by `ősz úton` | | Polish | `ŻÓŁW ŁÓDŹ` found by `żółw` | | Czech | `ŘEKA ČESKÁ` found by `řeka česká` | | French | `ÉTÉ À PARIS` found by `été à paris` | It applies to the whole family together, so a search can never disagree with a comparison: ```csharp .Where(x => x.Text.Contains(needle, StringComparison.OrdinalIgnoreCase)) .Where(x => x.Text.StartsWith(needle, StringComparison.OrdinalIgnoreCase)) .Where(x => x.Text.EndsWith(needle, StringComparison.OrdinalIgnoreCase)) .Where(x => x.Text.ToLower().Contains(needle)) .Where(x => x.Text.ToUpper().Contains(needle)) ``` --- ## What it does not fix Three classes, and no choice of collation reconciles them. They are stated here rather than discovered later. ### Diacritics are not case `Müller` is **not** found by `muller`, anywhere, on any provider. That is accent-insensitivity, a different feature. PostgreSQL refuses it outright for pattern matching: the nondeterministic collation it would require is rejected with *"nondeterministic collations are not supported for ILIKE"*. If you need it, the tool is `unaccent()` plus an expression index, not a collation. ### German ß against SS Pattern matching folds character by character and cannot change a string's length, while `UPPER` can and does expand `ß` to `SS`. So the two disagree with each other on the same database. `Straße` found by `strasse`? **PostgreSQL and SQLite: no. SQL Server: yes.** The providers genuinely differ here, and RedBase does not paper over it. ### Turkish and Azeri dotted i `İSTANBUL` found by `istanbul`? **PostgreSQL and SQLite: no. SQL Server: yes.** `İ` (U+0130) folds to `i` plus a combining dot, not to a plain `i`. This one is not merely unfixed but unfixable by a single installation-wide setting: Turkish wants `I`→`ı`, while every other locale wants `I`→`i`. Choosing `tr-x-icu` would fix Turkish and break everyone else. The right scope for it is a per-field or per-query collation, which RedBase does not offer today. --- ## The cost on PostgreSQL: indexes A collated operand cannot use an index built with the database's own collation. Which searches that touches depends on the tier, because only one of them reads a trigram index at all: | Tier | How a `Contains` / `StartsWith` / `EndsWith` filter runs | Trigram index read | |---|---|---| | **Pro, planner on** (`EnablePvtPrefilter`, on by default in `RedbServiceConfiguration` and in Tsak) | the predicate goes down to `_values`: `dv._String LIKE`, or `(dv._String COLLATE "") ILIKE` with the setting on | yes | | **Pro, planner off** | the free forms (row below) | no | | **Free** | the values of an object are pivoted first, then the pivoted value is filtered | no, with or without the setting | So the setting costs an index on Pro with the planner on, and only there. Turn it on without acting and every ignore-case search of that tier stops reading `IX__values__String_pattern` and reads every row of `_values` instead. Nothing errors. The index shows no reads and only the response time changes. Measured on 1 000 000 string values of one field, 100 of them holding `ПРИВЕТ`, PostgreSQL 18, the predicate Pro pushes down (`... ILIKE '%привет%'`): | Database ctype | Index on `_values` | Predicate | Plan | Time | |---|---|---|---|---| | `en_US.utf8` | stock `IX__values__String_pattern` | `_String ILIKE` (setting off) | Bitmap Index Scan | 0.34 ms | | `en_US.utf8` | stock | `(_String COLLATE "und-x-icu") ILIKE` | Seq Scan | 564 ms | | `en_US.utf8` | trigram over `(_String COLLATE "und-x-icu")` | same | Bitmap Index Scan | 0.68 ms | | `C` | either | same, Cyrillic pattern | Seq Scan (no trigrams, see the ctype section) | 550 ms | | `C` | trigram over the collated column | same, pattern `'%number 12345%'` | Bitmap Index Scan | 28 ms | The fix is an index over the same expression as the predicate. It must match the configured collation exactly, so it differs per project: ```sql CREATE EXTENSION IF NOT EXISTS pg_trgm; 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; ``` [`redb.Postgres/sql/maintenance/string_collation_index.sql`](redb.Postgres/sql/maintenance/string_collation_index.sql) runs it for any collation (`psql -v collation=und-x-icu -f string_collation_index.sql`) and rebuilds an index left INVALID by an interrupted build. RedBase finds the index by what it is, not by its name: a GIN index on `_values` with `gin_trgm_ops` over `_String` under the configured collation. Pro with the planner on checks for it at every start and logs a Warning while it is missing or INVALID, naming the collation, the statement, the script and what the ctype of the database means for it. ### Building it at start-up: `CreateStringCollationIndex` **Under ctype `C` the index serves patterns with ASCII letters only; under a UTF-8 ctype, leaving `StringCollation` unset serves every pattern with the stock index and needs no second index.** With that in mind: ```csharp .Configure(c => { c.StringCollation = "und-x-icu"; c.CreateStringCollationIndex = true; // Tsak: Tsak:Redb:CreateStringCollationIndex }) ``` Off by default. On, Pro with the planner on builds `IX__values__String_pattern_` at start-up when no index of the collation exists (the name takes the collation in lower case, every character other than a letter or a digit as `_`). The build is `CREATE INDEX CONCURRENTLY` on a connection of its own, under the schema lock, so several nodes starting together build it once; reads and writes go on, and start-up waits until it is built, which takes minutes on a large `_values`. An index left INVALID by an interrupted build is dropped and built again. An index that already serves the collation, under any name, is kept. Nothing is built, and start-up logs a Warning and goes on, when `AutoApplyDatabaseUpgrades` is off or the role may not create an index: run the script instead. The free provider and Pro with the planner off read no trigram index; there the option logs one Warning and builds nothing. ### Its price The cost is a second index on the largest table, about the size of the table itself (138 MB beside a 120 MB `_values` in the measurement above, 20 s to build), updated on each save of a string value. `IX__values__String_pattern` is not dead once the collation is set: case-sensitive `Contains`, `StartsWith` and `EndsWith` still run as plain `LIKE` without `COLLATE` and read it. Drop it only if the project does no case-sensitive substring search; the statement is at the end of the script, commented out. SQLite needs no such thing: `LIKE '%x%'` never used an index there in the first place. --- ## What the value means per provider The setting is one switch with three implementations, because the providers differ in kind and not merely in syntax. | Provider | What happens | |---|---| | **PostgreSQL** | the name is a real collation, attached as `COLLATE "..."` to each folded operand. It must exist in `pg_collation` and be **deterministic**; ICU collations such as `und-x-icu` and `ru-x-icu` qualify | | **SQLite** | there is nothing to attach a collation to, so the provider instead replaces the built-in `like`, `lower` and `upper` with Unicode-aware ones on every connection. The value is only a switch; it is still validated, so a typo fails at startup rather than turning into silence | | **SQL Server** | ignored. Its default collation already folds every script, and overriding a database deliberately created case-sensitive would defeat that decision | Leave it unset and nothing changes anywhere: the generated SQL is byte for byte what it was. ### A note for SQLite SQLite maps the case-sensitive and case-insensitive string operators onto the same `LIKE`, and always has, because its `LIKE` is case-insensitive for ASCII regardless. Enabling the setting therefore widens that to every script: a case-**sensitive** `Contains` will start matching a differently-cased Cyrillic string too. This is opt-in, but it is a real change in behaviour. --- ## Choosing a name `und-x-icu` is the root ICU collation and the right default for a multilingual database. Use a language-specific one such as `ru-x-icu` or `de-x-icu` only if you have a reason; they differ in sorting rules more than in case folding, and a language-specific choice makes the Turkish trade-off above worse rather than better. Names are validated when assigned, so a typo fails at startup with a message naming the setting rather than as a driver error on the first search. The name is also quoted where it is emitted, since a collation is an identifier and cannot be sent as a query parameter. List what your server offers: ```sql SELECT collname FROM pg_collation WHERE collprovider = 'i' ORDER BY 1; ``` ## Plain matching follows the database (BR-6, contract) `StartsWith` / `Contains` / `EndsWith` **without** a comparison argument translate to `LIKE` and keep each database's own case rules - redb does not decide for the programmer: | Provider | Plain `LIKE` semantics | |---|---| | **PostgreSQL** | case-sensitive | | **SQLite** | ASCII case-insensitive (non-ASCII is case-sensitive) | | **MSSQL** | whatever the column collation says - case-insensitive on the default | The same prefix query can therefore return different sets on different providers - by contract. When you need one behaviour everywhere, say so explicitly: the `*IgnoreCase` forms (`StartsWith(x, StringComparison.OrdinalIgnoreCase)`, `ContainsIgnoreCase`, ...) fold case on every provider, and `StringCollation` extends the folding beyond ASCII (the subject of this document). For a case-sensitive contract on top of a case-insensitive database, filter the candidates again in memory with an ordinal comparison - the server-side match stays an index-friendly prefilter. Path: redb/CONTRIBUTING.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/CONTRIBUTING.md ---- # Contributing to RedBase Thank you for your interest in RedBase! ## How to Contribute ### Reporting Issues - Use [GitHub Issues](https://github.com/redbase-app/redb/issues) for bug reports - Use [GitHub Discussions](https://github.com/redbase-app/redb/discussions) for questions and feature requests ### Bug Reports Please include: - RedBase package version (`redb.Core`, provider package) - .NET version - Database type and version (PostgreSQL / MSSQL / SQLite) - Minimal code to reproduce the issue - Expected vs actual behavior ### Feature Requests Open a [Discussion](https://github.com/redbase-app/redb/discussions/categories/ideas) with: - Description of the feature - Use case / motivation - Example code showing desired API (if applicable) ## Code Contributions This repository contains **examples, CLI tool, and export library**. The core packages (`redb.Core`, `redb.Postgres`, `redb.MSSql`, `redb.SQLite`) are developed in a separate repository. If you'd like to contribute examples: 1. Fork the repository 2. Create a branch: `git checkout -b my-example` 3. Add your example following the existing pattern in `redb.Examples/Examples/` 4. Submit a Pull Request ### Example Guidelines - Inherit from `ExampleBase` and add `[ExampleMeta]` attribute - Use `EmployeeProps` or other models from `Models/ExampleModels.cs` - Keep examples focused on one feature - Include clear comments explaining what the example demonstrates ## License By contributing, you agree that your contributions will be licensed under the [Apache License 2.0](LICENSE). Path: redb/DATETIME.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/DATETIME.md ---- # Dates and times in RedBase **Audience:** anyone storing a date or a time in a `*Props` class. One rule decides everything else: > **`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, exactly as you would expect outside RedBase. Pick by what the value *means*, not by which type you happen to have: | You are storing | Use | Why | |---|---|---| | A birthday, a contract date, a shift that starts at 09:00 local everywhere | `DateTime` or `DateOnly` | the number is the fact; a zone would corrupt it | | When a payment cleared, when a log line was emitted, a token expiry | `DateTimeOffset` | the instant is the fact; the wall clock differs per viewer | --- ## The full type table | C# type | Semantics | Stored in | Notes | |---|---|---|---| | `DateTime` | zone-less clock reading | `_values._DateTimeOffset` | `Kind` is set to `Utc` as a label, not a conversion | | `DateTimeOffset` | instant with an offset | `_values._DateTimeOffset` | read back normalised to UTC (`+00:00`), same instant | | `DateOnly` | zone-less date | `_values._DateTimeOffset` | midnight of that date | | `TimeOnly` | zone-less time of day | `_values._Long` | its `Ticks` | | `TimeSpan` | duration | `_values._Long` | its `Ticks`, keeps days and sign | Base fields of every object (`DateCreate`, `DateModify`, `DateBegin`, `DateComplete`) are `DateTimeOffset`, therefore instants. They line up with the database's own `now()` defaults. --- ## The one trap worth knowing Base fields are `DateTimeOffset`, Props fields may be `DateTime`. Assigning the same value to both does not give you the same value back: ```csharp var t = DateTime.Now; // 14:00 in a UTC+03:00 zone obj.DateBegin = t; // base field is DateTimeOffset -> implicit conversion applies the // local offset -> stored instant 11:00Z obj.Props.When = t; // Props DateTime -> the reading is kept -> stored 14:00 ``` Three hours apart, from one expression. This is the contract working as designed, not a defect: the two types mean different things. It is invisible on a machine running in UTC and reproducible on every other one, which is why it tends to surface late. If you want both to agree, be explicit about which meaning you want: ```csharp obj.DateBegin = DateTimeOffset.UtcNow; // instant obj.Props.When = DateTime.UtcNow; // reading, already UTC, no ambiguity ``` --- ## Locale: nothing to configure `TimeOnly` and `TimeSpan` are stored as a number and `DateOnly` as a date, so no stored form depends on the culture, in every tier and on every provider. A row written on a machine running `ru-RU` reads identically on one running `en-US`. There is no setting, and the host's `CultureInfo` cannot influence a stored value. The only thing to be aware of: `TimeOnly` and `TimeSpan` values written **before 4.8.0** are text in `_values._String` and are not read any more (a field reads as its default, a nullable one as `null`). [UPGRADING.md](UPGRADING.md) gives the statement that turns them into `Ticks`. --- ## Precision | Provider | Storage | Effective resolution | |---|---|---| | SQL Server | `DATETIMEOFFSET(7)` | 100 ns, identical to a .NET tick, lossless | | PostgreSQL | `timestamptz` | 1 microsecond | | SQLite | `REAL` Julian day | about 40 microseconds, and 1 millisecond when the object is read through the JSON projection | If you compare timestamps for exact equality, this matters: `DateTime.UtcNow` survives a round trip unchanged on SQL Server, loses sub-microsecond digits on PostgreSQL, and loses sub-millisecond digits on SQLite. Round to the precision you actually need before storing, or compare with a tolerance. --- ## Querying Everything you would expect works server-side, on all providers, for `DateTime`, `DateTimeOffset` and `DateOnly`: ```csharp // comparison and ranges .Where(e => e.HireDate >= cutoff) .Where(e => e.HireDate >= start && e.HireDate < end) // equality finds the row it was written from .Where(e => e.HireDate == exact) // ordering .OrderBy(e => e.HireDate) // date parts on base fields .WhereRedb(o => o.DateCreate.Year == 2025) ``` Two writings of the same instant select the same rows, so `10:30+03:00` and `07:30Z` are one cutoff. `TimeOnly` and `TimeSpan` compare, sort, group and take `Min`/`Max` chronologically: they are stored as their `Ticks` in `_values._Long`, so 10 days sort above 2 days and a negative duration below zero. Before 4.8.0 they were text and ordered comparison was wrong past a day and below zero; [UPGRADING.md](UPGRADING.md) says what to do with values stored then. `MinAsync` and `MaxAsync` over a **Props** date field are supported on SQLite only. The aggregate contract returns a number, which suits SQLite's numeric date storage and cannot represent the ISO string PostgreSQL and SQL Server return. `MinRedbAsync` and `MaxRedbAsync` over **base** date fields work everywhere. --- ## Upgrading an existing database `DateOnly` properties did not round-trip before RedBase 3.6: the value was written correctly and dropped on the way out, so every `DateOnly` materialised as `0001-01-01`. Databases created by 3.6 or later are correct out of the box. To fix an existing one, run the migration for your provider once: ``` redb.Postgres/sql/migrate_dateonly_db_type.sql redb.MSSql/sql/migrate_dateonly_db_type.sql redb.SQLite/sql/migrate_dateonly_db_type.sql ``` It is idempotent, changes no stored value, and refreshes the metadata cache of every scheme that has a `DateOnly` field. Stored data needs no rewriting: it was always in the right column. Path: redb/Directory.Build.props 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/Directory.Build.props ---- 4.8.0 RedBase RedBase Copyright (c) 2024-2026 RedBase https://redbase.app git $(MSBuildThisFileDirectory) $(MSBuildThisFileDirectory)redb.DB\ $(MSBuildThisFileDirectory) $(MSBuildThisFileDirectory)redb.Site\ 00240000048000009400000006020000002400005253413100040000010001003d0c6b552e047ad96e4b5f3f31429fe2b46bf822259ebcd5c99d589163312936e514015f67b7c0c4e76b24ef43342a7bc628a6b9306fd8cc495df080f7247753b55ff8472ae0d4fbe3b550534344707790ba032c208a91771c3277354897f39edeaea8cf8622f6e2a5d55b2935c0316f265a4a8051d1f3a49e00d2dcbfee79c9 Apache-2.0 LICENSE-PRO.txt Path: redb/Directory.Build.targets 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/Directory.Build.targets ---- true <_RedbCentral>true <_RedbNetMajor>$([System.Version]::Parse('$(TargetFrameworkVersion.TrimStart(`v`))').Major) 3.1.12 4.18.1 10.0.15 11.0.0 $(RedbSecAspNetCoreVersion) 10.0.15 11.0.0 10.0.15 true $(WarningsAsErrors);NU1506 true all moderate $(WarningsAsErrors);NU1902;NU1903;NU1904 Path: redb/Directory.Packages.props 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/Directory.Packages.props ---- redbase-app;tmp <_RedbCentralRoot>$([MSBuild]::EnsureTrailingSlash('$(MSBuildThisFileDirectory)')) <_RedbProjectRel>$([MSBuild]::MakeRelative('$(_RedbCentralRoot)', '$(MSBuildProjectDirectory)').Replace('/', '\')) <_RedbProjectTop>$(_RedbProjectRel.Split('\')[0]) 4.8.0 true Path: redb/LICENSE 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/LICENSE ---- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may accept and charge a fee in exchange for, or offer support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2024-2026 RedBase Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Path: redb/NOTICE 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/NOTICE ---- redb — Entity Database for .NET Copyright 2024-2026 RedBase This product includes software developed by RedBase (https://redbase.app). Licensed under the Apache License, Version 2.0 (the "License"); you may not use the open-source components of this product except in compliance with the License. You may obtain a copy of the License in the LICENSE file in the root of this distribution or at: http://www.apache.org/licenses/LICENSE-2.0 ------------------------------------------------------------------------ Components and licenses ------------------------------------------------------------------------ * Open-source projects (Apache License 2.0): redb.Core, redb.Postgres, redb.MSSql, redb.Tsak.Core, redb.Tsak.Web, redb.Tsak.CLI, redb.Tsak.Worker, redb.Tsak.Client, redb.Tsak.Contracts, redb.Identity, redb.Route, redb.CLI, redb.PropsEditor, redb.Templates, redb.Examples, and other non-".Pro" projects. * Commercial / Pro projects (REDBASE Commercial License — see LICENSE-PRO.txt): redb.Core.Pro, redb.Postgres.Pro, redb.MSSql.Pro, redb.Tsak.Core.Pro, redb.Tsak.Web.Pro, redb.Licensing (the licensing library is distributed alongside Pro components). * Third-party components: see project files (.csproj) for transitive package references and their respective licenses. Path: redb/README-PRO.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-PRO.md ---- # RedBase Pro **Data Platform for .NET** — the Pro engine of RedBase: SQL built in C#, a query planner, parallel materialization. [![NuGet](https://img.shields.io/nuget/v/redb.Core.Pro?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Core.Pro) [![.NET](https://img.shields.io/badge/.NET-10%20%7C%2011-purple)](https://dotnet.microsoft.com) [![Docs](https://img.shields.io/badge/docs-redbase.app-orange)](https://redbase.app) RedBase Pro replaces the query engine of the open-source [RedBase](https://github.com/redbase-app/redb) core. The API is the same: a project moves from Free to Pro by changing the packages and `AddRedb` to `AddRedbPro`. **Contents:** [Free and Pro](#free-and-pro) · [Packages](#packages) · [Quick Start](#quick-start) · [New in 4.4](#new-in-44) · [Supported Databases](#supported-databases) · [Documentation](#documentation) · [License](#license) --- ## Free and Pro Both editions take the same LINQ API: filters, nested fields, arrays and dictionaries, arithmetic, `Sql.Function()`, aggregation, `GroupBy`, window functions, trees, lists, users and permissions. They differ in how a query runs. | | Free | Pro | |---|---|---| | Query engine | SQL functions of the module installed in the database (PL/pgSQL, T-SQL, a native loadable extension on SQLite) | SQL built in C# by the provider and sent as one statement | | Materialization of Props | sequential | parallel | | Query planner (`EnablePvtPrefilter`) | no | yes, on by default: the streams form reads a page, a count or an aggregate without pivoting every object of the scheme | | `PropsSaveStrategy.ChangeTracking` | no (`DeleteInsert` only) | yes: a save writes only the values that changed | | Data migrations of Props classes | no | `IRedbMigration`, `MigrateAsync`, `AddRedbMigrations()` | | `Distinct()` | by object | one object per Props hash | | SQLite | needs the native extension | pure C#: Blazor WebAssembly and mobile (MAUI) | ``` Free: LINQ → SQL module in the database → rows as JSON → Props Pro: LINQ → SQL built in C# → rows → Props, materialized in parallel ``` --- ## Packages | Package | NuGet | Description | |---------|-------|-------------| | `redb.Core.Pro` | [![NuGet](https://img.shields.io/nuget/v/redb.Core.Pro?label=)](https://www.nuget.org/packages/redb.Core.Pro) | Pro engine, 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 | | `redb.MSSql.Pro` | [![NuGet](https://img.shields.io/nuget/v/redb.MSSql.Pro?label=)](https://www.nuget.org/packages/redb.MSSql.Pro) | SQL Server Pro provider | | `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 | ```bash dotnet add package redb.Postgres.Pro # or redb.MSSql.Pro, redb.SQLite.Pro ``` Each provider package brings `redb.Core.Pro` as a transitive dependency. ## Quick Start ```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); 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") // .UseSqlite("Data Source=app.db") .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.EnablePropsCache = true; })); var app = builder.Build(); var redb = app.Services.GetRequiredService(); await redb.InitializeAsync(); var results = await redb.Query() .Where(e => e.Salary > 75000m) .Take(100) .ToListAsync(); // Window functions — from E132_WindowRowNumber.cs var ranked = await redb.Query() .WithWindow(w => w .PartitionBy(x => x.Department) .OrderByDesc(x => x.Salary)) .SelectAsync(x => new { Name = x.Props.FirstName, Department = x.Props.Department, Salary = x.Props.Salary, Rank = Win.RowNumber() }); ``` ## New in 4.4 Pro query engine: - A window with `Take`, `Skip` and `OrderBy` returns the page; the window is computed over the whole filtered set on the fields it needs, and the other selected fields are read only for the rows returned. The same holds over a tree (`TreeQuery(...).Take(...).WithWindow(...)`), and `Win.Ntile(n)` over a tree uses `n`. - `AnyAsync` over a tree stops at the first matching node. - `DistinctBy` over a tree is faster on SQL Server and SQLite; `DistinctBy` keeps the ordering of the query, and `CountAsync` after `DistinctBy` counts the keys. Both editions (core): - Schema work at start-up and scheme synchronization run under a schema lock, so nodes sharing one database start together (`SchemaLockTimeout`). - `IRedbService.SchemaProblems` and `CheckSchemaAsync()` report problems of the schema that need a person, for a health check. - The tree services read a subtree or a chain of ancestors in one statement; several tree filters in one query all apply. The full list is in [CHANGELOG.md](CHANGELOG.md); what to check when upgrading is in [UPGRADING.md](UPGRADING.md). ## Free of charge All Pro features work out of the box: **Pro is free of charge and needs no key.** Install the Pro packages and use them, in development and in production alike. Pro is proprietary (closed-source) software, distributed free of charge. ## Supported Databases | Database | Version | Package | |----------|---------|---------| | PostgreSQL | 15+ | `redb.Postgres.Pro` | | SQL Server | 2019+ | `redb.MSSql.Pro` | | SQLite | 3.44+ | `redb.SQLite.Pro` — pure C#, runs in Blazor WebAssembly & mobile (MAUI) | Target frameworks: .NET 10.0 (LTS), .NET 11.0. ## Documentation | Resource | Link | |----------|------| | Website & Docs | [redbase.app](https://redbase.app) | | Architecture (deep dive) | [redbase.app/architecture](https://redbase.app/architecture) | | RedBase (Free edition, full API) | [README.md](README.md) | | Upgrading | [UPGRADING.md](UPGRADING.md) | | Changelog | [CHANGELOG.md](CHANGELOG.md) | ## License RedBase Pro is proprietary software (closed-source), distributed **free of charge and needs no key**. The license terms (`LICENSE-PRO.txt`) ship in every Pro package. 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). Path: redb/ROADMAP.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/ROADMAP.md ---- # RedBase Roadmap This document tracks what RedBase ships today, what is coming next, and the long-term direction for both the open-source (Apache 2.0) and Pro editions. It is intentionally high-level. Day-to-day changes live in [CHANGELOG.md](CHANGELOG.md); detailed design notes for individual features live under docs/. > **Editions in one sentence** > > - **Free (Apache 2.0)** — `redb.Core`, `redb.Postgres`, `redb.MSSql`, `redb.Export`, `redb.CLI`, `redb.Templates`, `redb.PropsEditor`. > - **Pro** — `redb.Core.Pro`, `redb.Postgres.Pro`, `redb.MSSql.Pro`. Same API surface, extra performance and tooling. --- ## Status legend | Symbol | Meaning | |--------|---------| | OK | Shipping today | | WIP | In active development | | PLANNED | Designed, not yet implemented | | RESEARCH | Under exploration, design not finalised | --- ## 1. What ships today ### Core data model - OK — Code-first schemas: plain C# classes decorated with `[RedbScheme]`, auto-synced by `InitializeAsync()` and `SyncSchemeAsync()`. - OK — Strongly-typed objects: `RedbObject`, full graph load with `LoadAsync` and `SaveAsync`. - OK — Bare `RedbObject` (no Props) for cases where only base fields matter, and mixed-schema batches: `SaveAsync(IEnumerable)`. - OK — Object references between schemes via `[ObjectReference]` — saved as typed links, resolved by the loader. - OK — Partial updates with change tracking — only modified Props fields are written back. - OK — Bulk insert and bulk delete: `BulkInsertAsync`, `DeleteAsync(ids)` for thousands of objects in one round-trip. - OK — Primitive arrays (`int[]`, `string[]`, …) and `List` of primitives. - OK — Nested classes (composition) and arrays of classes (`Address[]`, `List
`). - OK — `Dictionary` where the value is a primitive or a class; tuple keys (`Dictionary<(int, string), V>`) included. - OK — Multi-level collections **via a wrapper class** (`Dictionary` where `Class` contains an array or dictionary). ### Trees (with polymorphism) - OK — `TreeRedbObject` with first-class `Parent` / `Children` navigation and `parent_id` base field. - OK — Tree creation: `TreeCreate`, `TreeCreateBulk`, `TreeMove` (reparenting with subtree integrity checks). - OK — Tree loading: `TreeLoad`, `TreeChildren`, `TreeDescendants`, `TreePath` (materialised path), `TreeCount`, `TreeStats`. - OK — Traversals: `BFS`, `DFS` (pre-order and post-order), `GetLeaves`, `GetNodesAtLevel`, `IsBalanced`, `FlattenToList`. - OK — Predicate-based search inside a loaded tree: `Find(id)`, `FindAll(predicate)`. - OK — `TreeQuery()` — LINQ-style server-side queries over trees: `WhereRoot`, `WhereLeaves`, `WhereLevel`, `WhereChildrenOf(parentId)`, multi-root, `IsDescendant`/`IsAncestor`, `GetLevel`. - OK — **Polymorphic** ancestor/descendant filters: `WhereHasAncestor` / `WhereHasDescendant` work across **mixed Props types** in the same tree — a `Department` node and an `Employee` node coexist, and the filter traverses both. - OK — `Parent` relationships re-built across heterogeneous result sets via `TreeObjectConverter` so navigation works after a polymorphic load. - OK — Tree result shaping: `ToTreeList`, `ToRootList`, `ToFlatList`. - OK — Analytics on trees: `TreeQuery` composes with `GroupBy`, window functions, `DistinctBy` / `DistinctByRedb`, `OrderBy` / `OrderByDescending`. ### Query API - OK — LINQ-style query builder: `Where`, `OrderBy`/`OrderByDescending`/`ThenBy`, `Skip`, `Take`, `FirstOrDefault`/`Single`, async variants. - OK — Combinators: `And`, `Or`, `Not`, chained predicates, parentheses, ranges, nullable comparisons, booleans. - OK — String operators: `Contains`, `StartsWith`, `EndsWith`, case-insensitive (`ILIKE` on PostgreSQL, `COLLATE` on MSSQL), `ToLower`, `Trim`, `Length`, chained string ops. - OK — Arrays in `Where`: `Contains`, multiple-condition matches, `NotContains`, `Any` / `All` over arrays, `ArrayContainsAnd` / `ArrayContainsOr`. - OK — Dictionaries in `Where`: `ContainsKey`, indexer (`dict[key]`), filter by nested class fields inside dictionary values, tuple-key filters. - OK — Date/time operators: `>`/`<` / range, `DateTime.Year` and similar component extraction. - OK — Set operators: `Distinct` / `DistinctBy` / `DistinctByRedb`, `WhereIn` / `WhereInRedb`. - OK — Predicates over base fields (id, scheme, name, owner, timestamps) and across multiple base fields in one query. - OK — Projections: `Select(x => new { … })`, scalar selects, anonymous types, server-side projection of arithmetic expressions. - OK — Arithmetic & SQL functions in projections and predicates: `*`, `+`, `Abs`, `Power`, nested math, `Coalesce`, custom SQL function calls. - OK — Scalar reductions: `Count`, `Any`, `All`, `Sum`, `Avg`, `Min`, `Max`, `AggregateAsync` — both client-side and `*Redb` server-side variants, with and without filters. - OK — Group-by: single-key, filtered, multi-key, `GroupByRedb`, `GroupByArray`, group-by combined with windowing. - OK — Window functions: `ROW_NUMBER`, running sums, `LAG` / `LEAD`, `RANK`, `NTILE`, `FIRST_VALUE` / `LAST_VALUE`, custom frames, `PARTITION BY` / `ORDER BY` (also via `*Redb` variants), filtered windows. ### Security and validation - OK — Built-in users, roles and permissions: `IUserProvider`, `IRoleProvider`, `IPermissionProvider`. Permissions are checked centrally inside the storage and tree providers based on the current `IRedbSecurityContext` and configuration flags (`DefaultCheckPermissionsOnLoad`, `…OnSave`, `…OnDelete`). - OK — `IValidationProvider` runs Props-level validators (`[Required]`, `[Range]`, custom attributes) on save. - OK — Pluggable security context for multi-user / per-request impersonation. ### Soft-delete with background purge A first-class **Recycle Bin** model lives in `IObjectStorageProvider` and `IBackgroundDeletionService` — not a `_deleted = true` flag bolted on, but a real two-phase delete pipeline. - OK — `SoftDeleteAsync(ids | objects, [user], [trashParentId])` — atomically creates a **trash container** object, moves the targets *and their full descendant subtrees* underneath it, **and reassigns their `_id_scheme` to the reserved `@@__deleted` scheme (id `-10`)**. Returns a `DeletionMark(TrashId, MarkedCount)`. The application can show the user a "Deleted N items — Undo" toast instantly. - OK — **Marked rows disappear from all normal queries automatically.** Because `Query()`, `Tree()`, aggregations and window queries all filter by `_id_scheme = `, soft-deleted objects are invisible the moment marking commits — no `WHERE _deleted = false` glue in every query, no orphaned references in hot paths. - OK — **Marking 1 000 deeply-linked objects no longer means scanning a thousand FK cascades on the request thread.** The mark step is a single SQL function (`mark_for_deletion`) that re-parents and re-schemes via CTE; physical row removal (with all the `_values` / `_permissions` / FK clean-up cost) happens later in the purge worker, in batches. - OK — `DeleteWithPurgeAsync(ids, batchSize, IProgress, …)` — mark + physically purge in batches with a progress callback, cancellable. Suitable for "Empty Recycle Bin" UX. - OK — `IBackgroundDeletionService` — queue-backed fire-and-forget pipeline. Marking returns immediately; physical purge runs on a background worker against a **separate DB connection** so it never blocks the request thread. Progress (`Pending` / `Running` / `Completed`) is persisted **in the trash object itself** — survives process restarts and is **cluster-safe**: any node can pick up an in-progress purge job because all state lives in the database, not in the marking node's memory. - OK — `GetProgressAsync(trashId)` and `GetUserActiveProgressAsync(userId)` — query live or recent deletion jobs from any node, no shared in-memory state required. - OK — Configurable `trashParentId` — multiple parallel trash containers per tenant / per user / per workflow are supported out of the box. This is the "elegant" path most apps want: a familiar Recycle Bin UX (mark → undo → purge → progress) with zero glue code, persistent progress, no background-job framework dependency, and — critically — **no FK-cascade latency tax on the user-facing delete call**. ### Lists - OK — `IListProvider` — first-class named lists of objects (think tags, dictionaries, lookup catalogues) with `ListCreate`, `ListAddItems`, `ListGetByName`. - OK — List items can wrap full `RedbObject` payloads, query them by value, by `WhereIn`, by direct field compare, by props-array `Any`. ### Storage and tooling - OK — PostgreSQL provider (`redb.Postgres`), Microsoft SQL Server provider (`redb.MSSql`), and SQLite provider (`redb.SQLite` / `redb.SQLite.Pro` — embedded, Blazor WASM & mobile). - OK — Database bootstrap: `InitializeAsync(ensureCreated: true)`, `EnsureDatabaseAsync()`, `GetSchemaScript()`. - OK — Export/import as `.redb` files (JSONL/ZIP) for backup and PostgreSQL ↔ MSSQL migration. - OK — CLI tool (`redb.CLI`) for schema init, export, import. - OK — Visual props editor component (`redb.PropsEditor`). ### Developer experience - OK — Project templates (`redb.Templates`): `dotnet new install redb.Templates` then `dotnet new redb -n MyApp --db postgres|mssql --pro true|false` — a ready-to-run console app with CRUD, tree hierarchy, `SearchAsync`, and optional Pro LINQ/analytics wired up. - OK — Runnable, self-discovering examples library (`redb.Examples`): 190+ scenarios from `E000_BulkInsert` through `E195_GroupByWindowFiltered`, each tagged with category / difficulty / tier (`Free` / `Pro` / `Enterprise`) via `[ExampleMeta]`. The same project runs against PostgreSQL or MSSQL, doubles as the seed data for the docs site, and is the contract test for new operators. - OK — Integration test harness (`redb.Tests.Integration`): xUnit + FluentAssertions suite with shared `*TestsBase` classes (CRUD, Where, Tree, PolymorphicTree, Array, Dictionary, List, Aggregation, GroupBy, Window, Ordering, ProQuery) executed against both Postgres and MSSQL via per-provider fixtures — every feature ships with a parity test across both supported databases. - OK — Inline SQL inspection: any query exposes `ToSqlStringAsync()` so developers (and example authors) can paste the generated SQL into their query plan tool of choice. ### Connection isolation and caches RedBase is built around process-wide metadata caches (schemes, types, CLR registry, lists, props, field resolvers). To make those caches safe when an application talks to **more than one database** — multi-tenant deployments, sharded read-replicas, parallel integration tests against several ephemeral databases, or simply two `RedbService` instances in the same DI container — every cache is partitioned by a **cache domain**. - OK — `IRedbService.CacheDomain` — every service instance is bound to one domain. - OK — Domain key resolution: explicit `RedbServiceConfiguration.CacheDomain`, or computed automatically as the first 16 hex chars of `SHA-256(connectionString)` with the password stripped before hashing. - OK — Domain-isolated caches: `GlobalMetadataCache` (schemes, DB types, CLR type registry), `GlobalListCache` (lists and list items), `GlobalPropsCache` (per-object Props snapshots), `SchemeFieldResolver` (Pro). - OK — Per-domain enable/disable and statistics — turn caching off for a single connection without affecting others; query hit/miss counters per domain. - OK — Guarantees: a scheme cached for connection A is never returned to a query running on connection B, even when both processes share the same `_id_*` ranges or the same scheme name maps to a different `_id` in each database. Practical consequences this unlocks today: - Two `RedbService` instances pointing at different PostgreSQL databases in the same process share zero cache state — no cross-contamination of `schemeId`, no stale CLR-to-scheme mappings. - Test suites can spin up N temporary databases in parallel and each gets its own cache slice. - A future cluster / sharding layer can route requests to per-shard `IRedbService` instances without rebuilding the caching layer. --- ## 2. Near-term — next minor releases Focus: complete the **Props-as-anything** story so any C# shape round-trips through RedBase without a wrapper class. ### Props as collection / primitive — WIP Currently `Props` must be a class. The next milestone lets you store collections and primitives directly: ```csharp RedbObject> // PLANNED RedbObject // PLANNED RedbObject> // PLANNED RedbPrimitive // PLANNED RedbPrimitive // PLANNED ``` - SQL layer: **OK** — new `Array`, `Dictionary`, `JsonDocument`, `XDocument` types in `_types`; `_schemes._type` column added; storage hierarchy via the system `@@_value` structure. See docs/dict/DICTIONARY_ARRAY_IMPLEMENTATION.md. - .NET layer: **WIP** — serializer, query builder and materialiser updates. ### Direct nested collections — PLANNED Today, `Dictionary`, `List>`, `T[][]` and `T[,]` require a wrapper class. The plan is to lift this restriction so nested collections work out of the box. Tracked in docs/dict/NESTED_COLLECTIONS_LIMITATIONS.md. ### Custom scheme names — PLANNED Restore first-class support for `[RedbScheme("MyName")]` as the actual scheme identifier (currently `Alias` is cosmetic and the FQN is always used). Includes a one-shot migration that renames an existing FQN-named scheme to its custom name on first sync. Tracked in docs/dict/SCHEME_NAMING_ANALYSIS.md. ### JSON and XML documents — PLANNED `RedbObject` and `RedbObject` as first-class Props types. Stored via the same `@@_value` hierarchy as arrays and dictionaries — no opaque blobs, every node is indexable. --- ## 3. Mid-term — Path Query API Once JSON/XML documents are first-class, RedBase will gain a **JSONPath / XPath query API** that works directly against `_values` — no `jsonb`, no `XML.value(...)`, one indexed CTE for the whole engine. ### Filters ```csharp query.WherePath("$.store.name", name => name == "Amazon"); // PLANNED query.WherePath("$.price", ComparisonOperator.GreaterThan, 100); query.WherePath("$.price", p => p > 100 && p < 500); // Collections query.WherePath("$.books[*].price", PathOp.Any, p => p > 100); query.WherePath("$.items[*].status", PathOp.All, s => s == "active"); query.WherePath("$.orders[*]", PathOp.Count, c => c > 5); query.WherePath("$.items[*].price", PathOp.Sum, sum => sum > 1000); // JSONPath / XPath predicates inside the path query.WherePath("$.books[?(@.price > 100)].title"); query.WherePath("/books/book[@price > 100]/title"); ``` ### Projections ```csharp var names = await query.SelectPath("$.store.name").ToListAsync(); // PLANNED var prices = await query.SelectPathArray("$.items[*].price").ToListAsync(); var stats = await query.SelectPath(new { Total = ("$.items[*].price", PathAgg.Sum), Count = ("$.items[*]", PathAgg.Count), }).ToListAsync(); ``` ### Algorithm A **single CTE** with cumulative path tracking and early pruning. One algorithm covers JSON, XML, arrays and dictionaries — no per-shape special cases, no JOIN chains, no `jsonb_path_query` fallbacks. Full design in docs/dict/PATH_QUERY_API_PLAN.md. --- ## 4. Open-sourcing today's Pro features Several capabilities that currently live in `redb.Postgres.Pro` / `redb.MSSql.Pro` will be moved to the open-source providers. This is a deliberate shift: the OSS edition should be capable of running serious production workloads on its own. | Capability | Today | Plan | |---|---|---| | Optimised SQL generation (`ProSqlBuilderBase`, `ProFilterExpressionParser`) | Pro only | **PLANNED → OSS** | | Change-tracking save strategy (`PropsSaveStrategy.ChangeTracking`) | Pro only | **PLANNED → OSS** | | Schema migrations (`redb.Core.Pro/Migration`) | Pro only | **PLANNED → OSS** | | Pro lazy props loader | Pro only | **PLANNED → OSS** (basic version) | No timeline commitment yet — these move once the API has stabilised and the test coverage in `redb.Tests.Integration` covers both code paths. --- ## 5. What stays Pro After the migration above, the Pro edition focuses on **performance for large object graphs** and **operational tooling**. The OSS edition will remain fully usable on its own; Pro is for teams that need the extra throughput. - **Parallel materialisation** — `ProPropsMaterializer` / `ProLazyPropsLoader`: parallel hydration of large object graphs and list results across CPU cores. Significant speed-up on wide objects (10+ array/dictionary props). - **Tree-diff on `_values`** — server-side incremental change detection for tree updates, so saving a large tree writes only the rows that actually changed (instead of replacing the subtree). - License management and telemetry hooks. These features are deeply tied to the parallelisation primitives and incremental-write infrastructure, and are unlikely to be open-sourced. --- ## 6. Research and longer-term ideas Things we are looking at, with no commitment yet: - RESEARCH — More LLM-friendly schema discovery: `redb.CLI` emitting a machine-readable scheme catalogue suitable for prompt grounding (see docs/LLM_DISCOVERY_AND_TRAINING.md). - RESEARCH — Cluster mode for high-concurrency writes — builds on the existing per-connection cache domains; adds coordinated invalidation across nodes (see docs/CLUSTER_CONCURRENCY_PLAN.md). - RESEARCH — Native `Include` for `RedbObject` graph navigation across schemes (see docs/INCLUDE_REDBOBJECT_PLAN.md). - RESEARCH — `Where` expressions over tree shape (not just data) and `LINQ-over-tree` syntactic sugar (see docs/TreeLinqDemo.md). --- ## 7. How to influence this roadmap - Open a GitHub issue describing the use case (not just the feature) — concrete user stories shape priority. - Pro customers can request items via their support channel. - Connector roadmap for `redb.Route` lives in the [redbase-app/redb-route](https://github.com/redbase-app/redb-route) repo — see its `CONNECTORS_ROADMAP.md`. --- *Last updated: 2026-05* Path: redb/SECURITY.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/SECURITY.md ---- # Security Policy ## Supported Versions | Version | Supported | |---------|--------------------| | 1.2.x | :white_check_mark: | | < 1.2 | :x: | ## Reporting a Vulnerability If you discover a security vulnerability, please report it responsibly: 1. **Do NOT** open a public issue 2. Email: **support@redbase.app** 3. Include a description of the vulnerability and steps to reproduce We will acknowledge receipt within 48 hours and provide a timeline for a fix. ## Scope This policy applies to the following packages: - `redb.Core` - `redb.Postgres` / `redb.MSSql` - `redb.Core.Pro` / `redb.Postgres.Pro` / `redb.MSSql.Pro` - `redb.Export` - `redb.CLI` Path: redb/UNIQUE_KEYS.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/UNIQUE_KEYS.md ---- # Unique Keys in redb redb enforces uniqueness **in the database**, never by a read-then-write check that races. There are two independent mechanisms, and they compose: | | Object key (`ValueUnique`) | Property key (`[RedbUnique]`) | |---|---|---| | Lives on | the object row itself (`_objects._value_unique`) | a Props field (`_values._unique`) | | Type | `string`, up to 440 characters | any scalar: string, integer types, `Guid`, `bool`, `double`, `decimal`, date/time types, `byte[]` | | Scope | one value per **scheme** | one value per **scheme** per field | | Set by | the application, explicitly | computed from the field value on save | | Index | `UIX__objects__scheme_unique` | `UIX__values__structure_unique` | | Typical use | external identifier of the whole object | business keys: SKU, email, passport number | Both indexes are partial (`WHERE ... IS NOT NULL`), so objects without keys cost nothing — no index entries, no uniqueness checks on write. ## The object key: `ValueUnique` Every `RedbObject` carries an optional string key, unique within its scheme: ```csharp var order = new RedbObject { name = "order-1042", value_unique = "ERP-ORD-1042", // alias: ValueUnique Props = new OrderProps { Total = 99.90m } }; await redb.SaveAsync(order); // a second object with this key is rejected ``` - `null` never participates: any number of objects may leave the key empty. - The 440-character limit is enforced in C# (`RedbUniqueKeyValueException`), so every provider behaves identically — SQLite does not check VARCHAR lengths on its own. - Soft delete releases the key: the trash does not squat on business identifiers. ### Upsert by the object key `SaveByUniqueAsync` resolves the row by `(scheme, ValueUnique)` and saves onto it — creating the object when the key is free, updating the current holder when it is taken: ```csharp var flag = new RedbObject { value_unique = "checkout-v2", Props = new FeatureFlagProps { Enabled = true } }; var id = await redb.SaveByUniqueAsync(flag); // exactly one object per key, concurrency-safe ``` A lost object-key race is retried once onto the winner's row, so concurrent upserts of the same key are idempotent. A `[RedbUnique]` **property** violation inside the same save is never retried — it is not the object key's business and surfaces as-is. ## Property keys: `[RedbUnique]` Mark a scalar property of the Props class — or of a nested class reached without crossing a collection — and its value becomes unique within the scheme: ```csharp public class ProductProps { [RedbUnique] public string? Sku { get; set; } // root scalar key public IdentityBlock? Identity { get; set; } } public class IdentityBlock { [RedbUnique] public string? Passport { get; set; } // nested scalar key - same index, same contract } ``` The database stores a hash of the value's **canonical form** in `_values._unique`; the unique index enforces it. `null` values get no key and never take part in uniqueness. ### Subtree keys: the whole class, array or dictionary `[RedbUnique]` on a nested-class, array or dictionary property makes the **content of the whole subtree** the key — something classic SQL only approximates with indexed views or trigger-maintained hash columns: ```csharp public class TariffProps { [RedbUnique] public TariffConfig? Config { get; set; } // no two tariffs with identical config [RedbUnique] public List? Slots { get; set; } // ordered: [1,2] and [2,1] coexist [RedbUnique] public Dictionary? Limits { get; set; } // unordered: {a:1,b:2} IS {b:2,a:1} } ``` Semantics follow the canonical forms the storage already maintains: - a **dictionary** is an unordered set of pairs; a **list/array** is ordered; - **references** (`RedbObject`, list items) canonicalise by id — `[RedbUnique]` on a collection of references reads as "unique SET of references"; - an absent (`null`) or **empty** collection claims no key; - lookup by value works: `GetByUniqueAsync(p => p.Config, new TariffConfig { ... })` canonicalises the passed value exactly the way the save did (reference collections are outside the by-value lookup — enforcement still applies, only the lookup form differs). ### Element scopes: unique elements instead of unique content `Scope` on a collection key switches from the subtree-content reading to **element keys**: ```csharp public class TeamProps { [RedbUnique(Scope = UniqueScope.Collection)] public List>? Members { get; set; } // no duplicate links in one team [RedbUnique(Scope = UniqueScope.Scheme)] public List? Emails { get; set; } // an email appears in ONE team, whichever list } ``` - `Collection` — no duplicate elements inside one object's collection; different objects may repeat each other freely (each element's canonical form is salted with the owning collection's identity). A global by-value lookup is meaningless here and is rejected. - `Scheme` — element values unique across every object of the scheme, and globally probeable: `GetByUniqueAsync(p => p.Emails, "a@x.io")` returns the holder. - Reference elements canonicalise by **target id**: the key follows the link, not the linked object's content. - `Scope` on a scalar or a nested class is rejected — the bare attribute already carries the strongest reading there. What is rejected — at `SyncSchemeAsync`, with `RedbUniqueKeyDefinitionException`, not at insert where a misplaced key would silently never fire: - a property inside an **element** of a collection of classes: every element of every object shares one structure, so uniqueness would degenerate to one value across all elements; - enums (stored as their name in text, not a key type) and other non-scalar, non-subtree types; - `Scope` anywhere but on a collection property. ### Violations Every provider surfaces one typed exception: ```csharp try { await redb.SaveAsync(duplicate); } catch (RedbUniqueViolationException ex) { // ex.Kind: ObjectKey | Property | Unknown - branch on this, not on strings // ex.SchemeName: scheme of the object being saved // ex.PropertyName: the [RedbUnique] property, when the driver names the key tuple // ex.ConstraintName: the index the database reported // ex.Cause: the original driver exception, always attached } ``` PostgreSQL and MSSQL name the violated index and tuple; SQLite names only the columns — the `Kind` is classified correctly everywhere, but `PropertyName` detail may be absent on SQLite. ### Lookup by key value One server-side hash probe, no scan, returns the loaded object or `null`: ```csharp var bySku = await redb.GetByUniqueAsync(p => p.Sku, "SKU-1042"); var byPassport = await redb.GetByUniqueAsync(p => p.Identity!.Passport, "740-123"); var byPath = await redb.GetByUniqueAsync("Identity.Passport", "740-123"); ``` ### Key lifecycle - **Update** releases the old value and guards the new one in the same save. - **Soft delete** releases the key to the next claimant. - **Batch saves** enforce keys exactly like single saves. ### Recompute (backfill and repair) Keys are recomputed automatically at scheme synchronisation when they cannot be trusted: the attribute appeared on an already-populated structure, the canonicalisation version moved, or rows exist with a value but no key (the trace of a SQL-side writer). Explicit repair is available too: ```csharp var report = await redb.RecomputeUniqueAsync("Identity.Passport"); // report.HashedRows, report.Duplicates - first row of a duplicate group keeps the key, // the rest stay OUTSIDE the index (their _unique is NULL) and are reported, never thrown: // uniqueness holds for every keyed row; resolving the duplicates is the application's call. ``` ## Schema delivery Existing databases receive the columns and indexes automatically on `InitializeAsync` through each provider's versioned upgrade mechanism — no manual migration. ## See also - Runnable example: `redb.Examples`, **E003** (both mechanisms end to end). - Design history and decisions: `docs/V4/SUBTREE_UNIQUE_PLAN.md`. Path: redb/UPGRADING.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/UPGRADING.md ---- # Upgrading redb What to check and change when moving to a new version. Each section lists the changes that need action; [CHANGELOG.md](CHANGELOG.md) has the full list of what changed. ## Unreleased ### Object hashes of some values change; re-save subtree unique keys The object hash no longer lets two different values share it. The hash changes for an object whose values hold: - a string with `|` (any string property, also `Name`, `Note`, `ValueString`, `ValueUnique` of the object), or with `,` inside a collection element or a dictionary entry, or with `=` inside a dictionary key; - an empty string in a property or a collection element, or the string `"null"` in a collection element or a dictionary value; - a dictionary whose key is a tuple or a class. Every other object keeps its hash. Nothing needs doing for the hash itself: an object with a changed hash is rewritten once on its next save. Nodes of the old and the new version can run side by side: each rewrites such an object once more when it saves it after the other did, and a node of the old version keeps the old defect until it is replaced. One case needs action. A `[RedbUnique]` key on a class, collection or dictionary property is the hash of its content. Until an object with such content is saved again, its stored key is the old one: `GetByUniqueAsync` with that content does not find it, and a new object with the same content is not rejected. Load and save these objects once after the upgrade. ### SQLite: run the index repair once after the upgrade A SQLite file created before this version lacks the three unique indexes that keep one value per place (`UIX__values__structure_object`, `UIX__values__structure_object_parent`, `UIX__values__structure_object_array_index`); PostgreSQL and SQL Server always had them. Start-up does not build them; it logs one Warning naming them. Run `redb indexes repair` or `RepairBaseIndexesAsync()` once. Before it builds one of them, the repair looks for places that already hold more than one row: such an index is left unbuilt, the places (object, structure, row count) are listed in the output and in `RedbIndexRepairResult.Duplicates`, and nothing is deleted. A save through redb never writes such rows; they come from direct SQL against the file or from an import of a file that already carried them. To see the rows of one listed place (put in its object and structure): ```sql SELECT _id, _array_parent_id, _array_index, _String, _Long, _Guid, _Double, _DateTimeOffset, _Boolean, _Numeric, _ListItem, _Object FROM _values WHERE _id_object = AND _id_structure = ORDER BY _array_parent_id, _array_index, _id; ``` Decide which row is right, delete the other by its `_id`, and run the repair again. ### Dictionary keys that hold a ValueTuple A value tuple (`(int, string)` and the like) inside a dictionary key was stored empty, as `{}`. That hit a tuple key of eight or more fields, which keeps the fields after the seventh in a nested tuple, and any value tuple inside a key: a field of a tuple key (`((1, 2), 3)`), an item of a `Tuple<>`, a property of a key class. Such a key is now stored whole. A key with no value tuple inside it, a tuple key of up to seven plain fields included, keeps the stored text it had. - A key stored before the upgrade still reads, as before, with the lost parts at their defaults. They cannot be restored from the database; two keys that differed only there got the same stored key. - A save writes the key the object holds in full. An entry stored under the old text is written once more under its full key when its object is saved. If the object was loaded from the database, its keys are the ones read back, with the defaults; set the real keys from your own source before saving, if you have one. - The stored key is longer by the parts that were lost. On SQL Server a key over 430 characters is refused before the save writes. - A `[RedbUnique]` key over such a dictionary is the hash of the stored key text: load and save these objects once, as described above for the other hash changes. ### Collections redb does not store are refused redb stores a collection property declared as `T[]`, `List`, `IList`, `ICollection`, `IEnumerable`, `Dictionary` or `IDictionary`, with a single value or a class as the element. Two other shapes now stop the scheme sync, at any depth of the class, with an exception that names the class, the property and its type: - a collection directly inside a collection (`List>`, `T[][]`, `List`, `List>`, `Dictionary[]`, `Dictionary>`, `Dictionary>`) or a multi-dimensional array (`T[,]`): `RedbNestedCollectionException`; - any other collection type (`HashSet`, `ISet`, `ObservableCollection`, `Queue`, `Stack`, `IReadOnlyList`, `IReadOnlyCollection`, `SortedDictionary`, `IReadOnlyDictionary` and the like): `RedbUnsupportedCollectionException`, whose text lists the supported types. The sync at start runs for every `[RedbScheme]` class, so an application with such a property does not start until the class is changed. A save against a scheme synced by an earlier version refuses the same way before it writes. Such a property was never stored: the value (or each inner collection) was written as the name of its type (a `T[,]` as a flat list of its cells), and an object holding one could not be loaded. The content is not in the database and cannot be recovered from it. A property of such a type that was always null stored nothing and loaded; it is refused too. What to do: - Declare a supported type: `List` for a set, a queue or a stack, `Dictionary` for a sorted or read-only dictionary (sort or wrap it in your code after the load). - Wrap an inner collection in a class: `List` with `class Group { List Items { get; set; } }`, a dictionary of such a class instead of a dictionary of lists, a list of rows instead of `T[,]`. A collection inside a class element is stored and loaded as before. `List` and `Dictionary` are single values per element and are not refused. - Give the new shape a new property name, remove the old property and raise `RedbScheme.Version`. The sync then deletes the old structure with its rows (they hold only type names), and the objects that held it load again. - Fill the new property from your own source, if you have one. ## 4.8.0 ### Scheme versions: removing a field or changing a type needs RedbScheme.Version The sync no longer deletes a field or converts a type because the class says so; the class must also say it is newer than the database, with `[RedbScheme(Version = n)]`. The database records the version each scheme was last synchronised with (`_schemes._version`, added by the module step: PostgreSQL module 0.7.32, SQL Server 0.2.49, SQLite file schema 16). What changes for a class without `Version` (version 0) once the database is upgraded: - A property removed from the class: its structure and its values stay in the database; the sync logs a warning and the class does not read them. Before, the sync deleted them (with `DefaultStrictDeleteExtra = true`, the default). - A property whose type (or collection kind) changed: the stored values are not converted, the structure keeps its type, the sync logs a warning, the property is read through the stored type's converter, and every save of objects of that scheme is refused with `RedbPropertyTypeHeldException` (scheme, class, property, both types) until the version is raised. A missed raise on a type change stops saves of that scheme; it does not lose data. Before, the sync converted the values. - Adding a property works as before. What to do: - For a release that removes properties or changes types, raise `Version` on the Props class (`Version = 1`, then 2, and so on). A class of a higher version than the database's deletes and converts as before, and records its version. - A change of the collection kind of a property (a single value, an array or a dictionary) is not converted at any version. With values stored, the sync of that scheme stops with `RedbCollectionKindChangeException` (scheme, property, stored and declared kind) and the scheme keeps its version; before, the kind flipped over the stored rows, which the new class read wrong (a single value as an empty array, an array as null) until a save dropped them. Give the new shape a new property name, or move the values by hand before the upgrade. A property with no stored values changes its kind as before. A change inside a nested class counts for every scheme that uses that class. - To delete the fields a class no longer declares without a new version, call `DropUnknownStructuresAsync()`: it lists them with their value counts (`dryRun` is the default); with `dryRun: false` it deletes them, values included. - On a development machine, `DefaultDestructiveSyncAtEqualVersion = true` (set in the Development profile) keeps the old behaviour for a class of the same version, so a type changed without a version is still converted: without it the class would read and write the wrong column. A host on the Production profile, or on no profile, gets the guard. Rolling upgrades. A node on an older build (a lower `Version`) next to one that raised the version changes no structure at its start and is refused with `RedbPropsClassOlderException` when it saves objects of that scheme, so it cannot take the new build's fields away or write the old types over the new ones. Upgrade the old nodes, or send the writes of those schemes to the new ones, until the rollout ends. A new property alone needs no version: the old build keeps it and its saves keep its values. The version rule needs 4.8.0 on every node: a 4.7.x node ignores `_version` and deletes and migrates as before. For a rolling upgrade from 4.7.x, upgrade every node together, or let the DBA apply the 4.8.0 module once (`GetUpgradeScript()` / `redb schema --upgrade`) and start all nodes with `AutoApplyDatabaseUpgrades = false`, so a 4.7.x node stops at its start instead of changing the database (README, "Upgrading a cluster"). Custom dialects: `ISqlDialect` has the new member `Schemes_UpdateVersion()` (`UPDATE _schemes SET _version = $1 WHERE _id = $2 AND COALESCE(_version, 0) < $1`), and the scheme selects read `_version`; `ObjectStorage_SelectExistingCreateDates()` may return the scheme's `_structure_hash` as `SchemeHash`, which lets a save notice a scheme changed by another node (without it the save trusts its cache). ### AddNewObjectsAsync: a nested new object is no longer put under its referrer A new object that is saved because another object refers to it (a `RedbObject` field, a list, an array or a dictionary of them) keeps the `ParentId` it carries, `null` when none was set. `SaveAsync` always did this. `AddNewObjectsAsync` put every such object under the first object it was given, so with one root the nested object became a child of that root in the tree (`GetChildrenAsync`, tree queries, `DeleteSubtreeAsync`), and with several roots the objects nested under the second and later roots went under the first. A reference is not a place in the tree. Action: if you want a nested object to be a child of its referrer in the tree, set its `ParentId` yourself when the parent already has an id, or move it under the referrer after the insert with `MoveObjectAsync`. Rows already stored keep their parent. ### PostgreSQL (Free): objects without a value sort first ascending On PostgreSQL with the free provider (`redb.Postgres`), a sort by a field that some objects have no value for put those objects last when ascending and first when descending. They now come first when ascending and last when descending, as on redb Pro, on SQL Server and SQLite, and as LINQ orders null. This holds for `OrderBy`, `ThenBy`, their `Descending` forms, pages (`Skip`/`Take`), tree queries, windows and `DistinctBy` after a sort. - A page sorted by such a field now starts, ascending, with the objects without a value. If a screen expects them at the end, sort descending, or filter them out with `Where(p => p.Field != null)`. - Nothing to run by hand: the SQL module goes to `0.7.28` at the next start (or with `redb schema --upgrade --provider postgres` where the schema is deployed by a DBA). ### Properties renamed in place: RedbRename A property renamed in the Props class used to reach the database as a new property: the sync added the new name and, under the strict sync (`DefaultStrictDeleteExtra = true`, the default), deleted the old one together with its values. Mark the renamed property with its previous name and the stored property is renamed instead; its id and values stay: ```csharp public class OrderProps { [RedbRename("Title")] public string Heading { get; set; } = ""; } ``` Repeat the attribute for a chain (`[RedbRename("Title")]` and `[RedbRename("Heading")]` on `Caption`), so that a database which missed a version is renamed too. A property of a nested class is renamed the same way. When the database holds both the new name and a previous one, the start stops with `RedbRenameConflictException` and changes nothing: move the values to one of them and delete the other by hand. Schema. The previous names are kept in a new column, `_structures._renamed_from` (and `_schemes._renamed_from`), a JSON array of names, oldest first. The start adds it: the module goes to `0.7.27` on PostgreSQL and `0.2.46` on SQL Server, and a SQLite file to schema version 14. Older packages ignore the column. A database deployed by the DBA gets it from the upgrade script (`GetUpgradeScript()`, `redb schema --upgrade`). Rolling deployments. A node that still runs the class with the old name stops at its sync with `RedbRenameConflictException` instead of adding the old name again and deleting the renamed property. That protects nodes on this package only: a node of an older package does not read the column and, under the strict sync, deletes the renamed property with its values. Upgrade every node to this package before the class with the rename goes out, or run the rollout with `DefaultStrictDeleteExtra = false`. The attribute stays for good. Its first name orders the property in the object hash (`_objects._hash`, the content hashes of nested classes and the unique keys built on them), so the hashes stored before the rename stay valid after it and no stored hash has to be recomputed. A class without the attribute hashes exactly as before. Keep the chain in order, the first name first: a start whose class lost the attribute, or declares another first name than the history in `_renamed_from`, stops with `RedbRenameConflictException`. The one case this check cannot see is a database created directly with the renamed class: it has no history yet. A freed name may be taken again 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 (`InvalidOperationException`), since the stored `Title` could belong to either property: roll out the rename first, the new property in a later version. Schemes. `[RedbScheme(Name = "orders", RenamedFrom = ["order"])]` renames a stored scheme the same way, oldest name first; it also takes a previous FullName, for a class without an explicit name that was renamed or moved to another namespace. Before, such a change created a new scheme and left every object under the old one. Both names stored stops the start with `RedbRenameConflictException`. Every scheme rename now records the name it came from in `_schemes._renamed_from`, the FullName-to-explicit-name rename included; a node whose class still names a scheme that was renamed away, and that has no class of the scheme under its new name, stops with `RedbRenameConflictException` instead of creating the old scheme again. Action: none for an existing application. Use `[RedbRename]` or `RenamedFrom` for the next rename. ### Custom dialects: rename members Only for code that implements `ISqlDialect`. `Schemes_UpdateName` is removed; three members are added: - `Schemes_Rename()`: `UPDATE _schemes SET _name = $1, _renamed_from = $2 WHERE _id = $3`. It replaces `Schemes_UpdateName`, which every scheme rename of the sync used. - `Schemes_SelectRenamed()`: `SELECT _id, _name, _renamed_from FROM _schemes WHERE _renamed_from IS NOT NULL`. - `Structures_Rename()`: `UPDATE _structures SET _name = $1, _renamed_from = $2 WHERE _id = $3`. The selects of schemes (`Schemes_SelectByName`, `Schemes_SelectById`, `Schemes_SelectAll`, `Schemes_SelectObjectByName`) and of structures (`Structures_SelectByScheme`, `Structures_SelectById`) read `_renamed_from` too. The shipped dialects show the statements. ### The database module is never taken back by an older package A start applies the module of its own package when the database holds an older one, as before; it no longer applies it over a newer one. The newer module states which packages it still serves (`pvt_module_compat()` on PostgreSQL and SQL Server, the `_schema_compat` table of a SQLite file): an older package among them starts and logs one warning, one that is not stops with `RedbSchemaNewerException`, which names the package version to upgrade to, and changes nothing. The module goes to `0.7.26` on PostgreSQL and `0.2.45` on SQL Server, and a SQLite file to schema version 13; the same versions carry the delete count fix below. The upgrade script (`GetUpgradeScript()`, `redb schema --upgrade`) follows the rule too: run by hand over a newer module, it raises the sentence of `RedbSchemaNewerException` before its first change. psql goes on after an error unless told to stop, so run the PostgreSQL script with `psql -v ON_ERROR_STOP=1`; the SQL Server script sets `NOEXEC ON` on refusal, so SSMS and sqlcmd compile the rest without running it. SQLite has no script. Action: none for an application. A host that tells start-up failures apart can catch `RedbSchemaNewerException`: the application, not the database, needs upgrading. With `AutoApplyDatabaseUpgrades = false` a newer module that serves the package no longer stops the start. No new rights are needed: the function is one more of the module (`GRANT EXECUTE TO` the application on SQL Server covers it). The rule holds for packages from 4.8.0 on. A node of 4.7.x or older still puts its own module back over a newer one, so a rolling upgrade from 4.7.x to 4.8.0 keeps the advice of README, "Upgrading a cluster": upgrade every node together, or let the DBA apply the new module once and start all nodes with `AutoApplyDatabaseUpgrades = false`. From 4.8.0 on nodes of two versions may run against one database. ### WhereHasAncestor: maxDepth counts up from the returned object All providers. `WhereHasAncestor(condition, maxDepth)` used to read `maxDepth` as how deep below the start of the query a matching ancestor was looked for, and returned every descendant of such an ancestor however far below it lay. It now counts up from the object returned, as `WhereHasDescendant` counts down: `maxDepth: 1` keeps the objects whose parent matches, `maxDepth: 2` those whose parent or grandparent matches. Without `maxDepth` any ancestor counts, as before. The ancestor is still looked for below the start of the query, and the depth of the query (`TreeQuery(root, maxDepth)`) still counts from its start; a query started from several parents now looks for the ancestor below them on every provider. Action: find the calls that pass `maxDepth` to `WhereHasAncestor` and set it to the distance between the ancestor and the objects you want, or drop it when any distance will do. Calls without `maxDepth` need nothing. A third-party `ISqlDialect` implements one more member, `Query_GetDescendantIdsFromAncestorsSql`. ### IX__values__array_parent_id is dropped All providers. The index on `_values (_array_parent_id)` is the leading column of `IX__values__array_parent_index` (`_array_parent_id, _array_index`), which serves the same lookups and the cascade of the parent key (the foreign key on PostgreSQL and SQLite, the key check and the cascade trigger on SQL Server). A new database no longer creates it. On an existing database it is removed when the upgrade runs (the module on PostgreSQL and SQL Server, schema step 17 on SQLite), but only while another index whose first column is `_array_parent_id` remains: valid and not partial, not filtered on SQL Server. A database created by an old version may lack `IX__values__array_parent_index`; there the index stays. `DROP INDEX` takes a short exclusive lock on `_values`. Action: nothing. To put the index back: ```sql -- PostgreSQL, without blocking writes CREATE INDEX CONCURRENTLY IF NOT EXISTS "IX__values__array_parent_id" ON _values (_array_parent_id); -- SQL Server (ONLINE = ON only on editions that support it; leave it out on Standard and Express) CREATE INDEX [IX__values__array_parent_id] ON [dbo].[_values]([_array_parent_id]) WITH (ONLINE = ON); -- SQLite CREATE INDEX IF NOT EXISTS "IX__values__array_parent_id" ON _values (_array_parent_id); ``` On PostgreSQL and SQL Server the module drops it again on its next version change while the wider index exists; on SQLite the step runs once, so an index put back by hand stays. ### Index check at start-up, and the repair All providers. At start-up redb compares the indexes of the database with those a fresh database of this version has (the base schema, and with Pro and the planner on the indexes of the streams query form), and logs one Warning naming every index that is missing, INVALID (PostgreSQL, an interrupted concurrent build) or defined otherwise, with what it serves. Nothing is built at start-up: an index may have been dropped on purpose. Indexes beyond the expected ones are not reported. A database created by an old version may lack some base indexes, for example `IX__values__parent_structure` on PostgreSQL databases created before 3.3. Action: read the Warning after the upgrade. To build what it names: ``` redb indexes check -p postgres -c "" # read only; exit code 2 when an index is reported redb indexes repair -p postgres -c "" # builds the missing and INVALID base indexes ``` or `IRedbService.CheckBaseIndexesAsync()` and `RepairBaseIndexesAsync()` from the application, which also cover the Pro indexes. The repair builds with `CREATE INDEX CONCURRENTLY` on PostgreSQL (reads and writes go on), `WITH (ONLINE = ON)` on SQL Server editions that have it (Enterprise, Developer, Azure SQL); on Standard and Express it prints the statements instead, and builds them offline only with `--offline` (`allowOffline: true`), which blocks writes to the table while each one builds. An index reported as defined otherwise is never changed: compare the two definitions in the report and decide. Where indexes were dropped on purpose, `CheckBaseIndexesOnStart = false` silences the Warning. ### Pro: the streams indexes are built once PostgreSQL Pro and SQL Server Pro with the planner on. The indexes of the streams query form (`pvt_streams_indexes.sql`) were built at every start-up where one was missing. They are now built once, at the upgrade that brings them (and on a database redb creates); afterwards a missing one is reported by the index check and not built again, since it may have been dropped on purpose. A database whose planner is turned on later, after that upgrade, does not get them at start-up either. Action: if you relied on start-up to bring a dropped streams index back, run `RepairBaseIndexesAsync()` from the application (the CLI checks the base indexes only). The trigram index of `StringCollation` is unchanged: it is still built at start-up while `CreateStringCollationIndex` is on. ### .NET 10 and .NET 11 only The packages (`redb.Core`, `redb.Core.Pro`, the PostgreSQL, SQL Server and SQLite providers with their Pro variants, `redb.Export`) target `net10.0` and `net11.0`. The `net8.0` and `net9.0` builds are gone: .NET 8 and .NET 9 reached end of support on 10 November 2026. The `redb` command-line tool already required .NET 10. Action: an application on .NET 8 or .NET 9 either stays on 4.7.x or moves its target framework to `net10.0` (or `net11.0`) before taking this version. Nothing changes in the API or in the database module. ### SQL Server: saves check the foreign keys Only for SQL Server (`redb.MSSql`, `redb.MSSql.Pro`). New objects and values are written by a bulk copy, which until now skipped the foreign keys of `_objects` and `_values`: a reference to an object that does not exist, or a parent id that names no object, was stored, and the reference read back as `null`. PostgreSQL refuses such a save, and now SQL Server does too: the save throws the foreign key error of the server (`SqlException`, "The INSERT statement conflicted with the FOREIGN KEY constraint ..."), and nothing of it is stored. Action: an application that saves references by id must save the referenced object first, as on PostgreSQL. Nothing to do if your saves never name missing objects. The database module goes to `0.2.41`. It is applied on the first start, or by the DBA from `IRedbService.GetUpgradeScript()` or `redb schema --upgrade` when `AutoApplyDatabaseUpgrades = false`. It disables the trigger `tr_auto_create_node_permissions`, as the PostgreSQL schema always had it, so a save creates the same rows on both. An application under a role without schema rights no longer needs `ALTER` on the redb tables to save. A cluster upgrades from 4.7.x as README, "Upgrading a cluster" says: all nodes together, or the DBA applies the script once and the nodes start with `AutoApplyDatabaseUpgrades = false`. A node of 4.7.x applying its own module puts the database back to `0.2.40`. Rows stored before the upgrade are not checked, and SQL Server keeps the foreign keys of `_objects` and `_values` marked as untrusted until they are validated. A DBA who wants them validated first looks for rows that name missing objects: ```sql SELECT 'value' AS kind, v._id, v._Object AS missing_id FROM dbo._values v WHERE v._Object IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dbo._objects o WHERE o._id = v._Object) UNION ALL SELECT 'object', c._id, c._id_parent FROM dbo._objects c WHERE c._id_parent IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dbo._objects p WHERE p._id = c._id_parent); ``` and, when it returns nothing, validates the keys once (this reads both tables and holds a schema lock while it runs): ```sql ALTER TABLE dbo._objects WITH CHECK CHECK CONSTRAINT ALL; ALTER TABLE dbo._values WITH CHECK CHECK CONSTRAINT ALL; ``` ### Custom dialects: Query_WrapPvtWithObjectRows Only for code that implements `ISqlDialect` itself. `Query_WrapPvtWithObjectJson(innerSql, maxDepth)` is replaced by `Query_WrapPvtWithObjectRows(innerSql)`: the `_objects` row of every id of the inner list, in its order, with the columns of `ObjectStorage_SelectObjectsByIds`. A Free list read no longer builds object JSON in that statement; the lazy loader reads the Props. On SQL Server and PostgreSQL the inner list returns `_ord` next to `_id` (modules `0.2.45` and `0.7.26`), the position of the row in the order of the query: sort by it after the join, since a derived table keeps no order. Implement the new member `Query_WrapPvtWithIds(innerSql)` as well: the ids of the inner list alone, one column (`SELECT t._id FROM (innerSql) t` on the stock dialects). `Query().DeleteAsync()` on Free reads them before it deletes them through `ObjectStorage_DeleteByIds`; return null when the dialect has no v2-pvt module. ### Custom tree providers: the interceptor pipeline `DeleteSubtreeAsync` now runs the delete interceptors (`DeletingAsync`, `DeletedAsync`) with the whole subtree, and removes the deleted objects from the Props cache, as `DeleteAsync` does. For that the tree provider receives the same interceptor pipeline as the object storage. Only for code that subclasses a tree provider or a service: - `TreeProviderBase`, `ProTreeProviderBase` and the stock tree providers take a last constructor argument `RedbSaveInterceptorPipeline? saveInterceptors = null`. Pass the pipeline your object storage gets, or the delete interceptors do not run on a subtree delete. - `RedbServiceBase.CreateTreeProvider` has a last parameter `RedbSaveInterceptorPipeline? saveInterceptors`: add it to an override and hand it to the tree provider. An interceptor that handles deletes now also sees subtree deletes: `ObjectIds` holds the start object and every descendant, `DeletedCount` the objects of the subtree this call deleted. ### Custom query providers: ExecuteDeleteAsync with a JSON filter is removed `IRedbQueryProvider.ExecuteDeleteAsync(long schemeId, string? filterJson)` is removed, with its implementations in `QueryProviderBase` and `TreeQueryProviderBase`. It asked the database for a function of the legacy search module, which no shipped provider installs any more, and threw `NotSupportedException` on every one of them. - Delete through a query: `await redb.Query().Where(...).DeleteAsync()` (or `TreeQuery(...)`). - Code that calls the provider directly passes a `FilterExpression`: `ExecuteDeleteAsync(schemeId, filter, cancellationToken)`, `null` for every object of the scheme. - A provider that overrode the removed method drops the override; the `FilterExpression` overload is the one that runs. ### Custom dialects and providers: removed legacy members Only for code that implements `ISqlDialect` or subclasses `QueryProviderBase` / `TreeQueryProviderBase`. Every query of a shipped provider runs through the v2-pvt module of its dialect (`Query_BuildPvtSqlFunction`, `pvt_build_*_sql`); the legacy search, aggregate and window functions are gone from every shipped database, and the members that named them threw `NotSupportedException` on every shipped dialect. They are removed. `ISqlDialect`, removed (delete the implementations from a custom dialect): - Search: `Query_SearchObjectsFunction`, `Query_SearchObjectsBaseFunction`, `Query_SearchTreeObjectsFunction`, `Query_SearchTreeObjectsBaseFunction`, `Query_SearchObjectsSimpleSql`, `Query_SearchTemplate`, `Query_SearchWithDistinctTemplate`. Replaced by `Query_BuildPvtSqlInvocation` and the `Query_WrapPvtWith*` wrappers. - Projection: `Query_SearchObjectsProjectionByPathsFunction`, `Query_SearchObjectsProjectionByIdsFunction`, `Query_ProjectionByPathsTemplate`, `Query_ProjectionByIdsTemplate`. Replaced by `Query_BuildPvtProjectionSqlFunction`; a projection the module cannot build reads whole objects through `Query_BuildPvtSqlInvocation`. - Trees: `Query_TreeCountNormalSql`, `Query_TreeCountWithParentIdsSql`, `Query_TreeSearchNormalSql`, `Query_TreeSearchWithParentIdsSql`, `Query_HasAncestorTreeSql`, `Query_HasAncestorNormalSql`, `Query_HasDescendantSql`. The tree providers build their statements with `pvt_build_query_sql` (tree source modes). - Aggregates and windows: `Query_AggregateFieldSql`, `Query_AggregateBatchSql`, `Query_AggregateBatchPreviewSql`, `Query_AggregateGroupedSql`, `Query_WindowSql`. The providers call `pvt_build_aggregate_sql`, `pvt_build_groupby_sql` and `pvt_build_window_sql`. - Unused by any provider: `Query_CountTemplate`, `Query_SearchFullTemplate`, `Query_TreeSqlPreviewFunction` (the templates of the removed search functions), `Query_JsonCast`, `Query_TextArrayCast`, `Query_BigintArrayCast` (parameter casts no statement takes any more), `Tree_GetObjectJson`, `Tree_SelectChildrenIds`, `Tree_SelectParentId` (the tree providers read through `pvt_build_query_sql` and the props loader). Nothing replaces them. `QueryProviderBase`: - `ExecuteToListAsync` and `ExecuteCountAsync` read through the v2-pvt module only; a dialect whose `Query_BuildPvtSqlFunction` returns null gets `NotSupportedException`. They fell back to the removed search functions. - Abstract now, implemented by every shipped provider: `ExecuteAggregateBatchAsync(..., string? filterJson)`, `ExecuteGroupedAggregateAsync(..., string? filterJson, ...)`, `ExecuteWindowQueryAsync(..., string? filterJson, ...)` and `GetAggregateSqlPreviewAsync`. A provider that relied on the base bodies implements them; build the preview from `ParseAggregateRequests(selector)`, the requests the execution reads. - `ExecuteAggregateAsync(..., string? filterJson)` runs as a one-request `ExecuteAggregateBatchAsync`. - Removed: `ParseAggregateExpressionForPreview`. Use `ParseAggregateRequests`. `TreeQueryProviderBase`: - Abstract now: `ExecuteTreeToListAsync` and `ExecuteTreeCountAsync`; their base bodies read the removed tree functions. - Removed: `ExecuteOptimizedWhereHasAncestor` and `ExecuteOptimizedWhereHasDescendant`. Resolve a has-filter into object ids with `pvt_build_query_sql` and run the rest of the query, as the stock tree providers do; a filter without a target scheme ends in `UnresolvedTreeFilter()`. ### User configuration: one service class `redb.Core.Configuration.UserConfigurationService` is the user configuration service of every provider and takes its statements from the dialect. `redb.Postgres.Configuration.UserConfigurationService` and `redb.SQLite.Configuration.UserConfigurationService`, copies with the same SQL written into them, are removed. Who is affected: - Code that resolves `IUserConfigurationService` from DI changes nothing. - Code that constructs `redb.Core.Configuration.UserConfigurationService` by hand passes the dialect as a fourth argument: `new UserConfigurationService(redb, context, configuration, dialect)`, the `ISqlDialect` of the provider (`PostgreSqlDialect`, `MsSqlDialect`, `SqliteDialect`). - Code that names `redb.Postgres.Configuration.UserConfigurationService` or `redb.SQLite.Configuration.UserConfigurationService` uses `redb.Core.Configuration.UserConfigurationService`. ### Pro migrations: OnTypeChange removed `IPropertyMigrationBuilder.OnTypeChange()`, `ITypeChangeMigrationBuilder` with its `Using(...)` and `MigrationType.TypeChange` are removed. A migration configured with them compiled, and threw `NotImplementedException` when it ran: no version converted a value through them. - A change of a property's type needs no migration: the scheme sync converts the stored values when the Props class changes the type (`SyncSchemeAsync`, on start). - A conversion of your own on top of it (a unit change, a rounding) goes to `Transform(...)` on the property, which reads the values already of the new type, or to `ComputedFrom(...)` from another property. - Code that names the removed members does not compile: delete the `OnTypeChange` call and its `Using`. ### Pro SQL generators and provider connections: unused public members removed Only for code that calls the SQL generators of the Pro providers or the connection classes of the providers directly. Queries through `IRedbService` and `IRedbQueryable` are not affected. - `PvtSqlGenerator.GenerateExistsClause(...)` and `PvtSqlGenerator.GeneratePvtSelect(...)` of redb.Postgres.Pro, redb.MSSql.Pro and redb.SQLite.Pro are removed, with the record `CompiledPvtQuery` and the namespace `redb.Core.Pro.Query.Models` that held it. No query of the providers used them; a statement of your own built from them goes through the query API (`Query()`, `ToSqlStringAsync()` shows the statement it sends). - `NpgsqlRedbConnection.ExecuteJsonBetweenAsync(...)` and `NpgsqlRedbConnection.QueryThenAsync(...)` of redb.Postgres and `SqlRedbConnection.QueryResultSetsAsync(...)` of redb.MSSql are internal: they serve the batches of the Pro providers. Send statements of your own through `QueryAsync(...)`, `ExecuteJsonAsync(...)` and `ExecuteAsync(...)` inside a transaction. - Delete `using redb.Core.Pro.Query.Models;` where it stands: the namespace is gone. ## 4.7.5 ### TimeSpan and TimeOnly are stored as ticks `TimeSpan` and `TimeOnly` values are stored as their `Ticks` in the number column of `_values` (`_Long`), no longer as text. They now compare, sort, group and take `Min`/`Max` correctly on every provider; as text, a value over a day and a negative value compared and sorted wrong (`23:00:00` above `1.00:00:00`, `10.00:00:00` below `2.00:00:00`). Read this before you upgrade a database that holds `TimeSpan` or `TimeOnly` values: - **Every node and every image of the database runs 4.7.5**: the applications, and the Tsak and Identity images and archives, which carry the redb packages in `Libs/shared`. A node of 4.7.4 or older writes the values as text again, and at its start puts its own database module back over the new one. Packages published before 4.7.5 do not know the rule of the next section. - **There is no way back except a backup.** Once the values are converted, a package before 4.7.5 does not read them. - **Convert the stored values before the first start of 4.7.5**: stop every node, back up the database, run the statement for your database below, then start the nodes on 4.7.5. The statements work on a database of an older version, as they find the fields by their type name. The schema follows by itself at the first start: the type rows of the two types say `Long` (on PostgreSQL and SQL Server the SQL module does it, or `redb schema --upgrade`; on SQLite the file upgrade). **Values still stored as text are not converted by the start.** Such a field reads as `00:00:00` (Pro) or fails to load (Free), a nullable one as `null`, and an array of them as empty; saving the object again writes those empty values. PostgreSQL: ```sql UPDATE _values v SET _Long = x.ticks, _String = NULL FROM (SELECT o._id, CASE WHEN m[1] = '-' THEN -1 ELSE 1 END * ( (COALESCE(m[2], '0')::bigint * 86400 + m[3]::bigint * 3600 + m[4]::bigint * 60 + m[5]::bigint) * 10000000 + rpad(COALESCE(m[6], ''), 7, '0')::bigint) AS ticks FROM _values o JOIN _structures s ON s._id = o._id_structure JOIN _types t ON t._id = s._id_type AND t._name IN ('TimeSpan', 'TimeOnly') CROSS JOIN LATERAL regexp_match(o._String, '^(-)?(?:(\d+)\.)?(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?$') m WHERE o._String IS NOT NULL AND m IS NOT NULL) x WHERE v._id = x._id; ``` SQL Server: ```sql UPDATE v SET _Long = x.ticks, _String = NULL FROM _values v JOIN _structures s ON s._id = v._id_structure JOIN _types t ON t._id = s._id_type AND t._name IN (N'TimeSpan', N'TimeOnly') CROSS APPLY (SELECT IIF(LEFT(v._String, 1) = N'-', 1, 0) AS neg, IIF(LEFT(v._String, 1) = N'-', STUFF(v._String, 1, 1, N''), v._String) AS body) b CROSS APPLY (SELECT IIF(CHARINDEX(N'.', b.body) BETWEEN 1 AND CHARINDEX(N':', b.body), CAST(LEFT(b.body, CHARINDEX(N'.', b.body) - 1) AS bigint), 0) AS days, IIF(CHARINDEX(N'.', b.body) BETWEEN 1 AND CHARINDEX(N':', b.body), STUFF(b.body, 1, CHARINDEX(N'.', b.body), N''), b.body) AS rest) d CROSS APPLY (SELECT (d.days * 864000000000 + DATEDIFF_BIG(NANOSECOND, CAST('00:00' AS time(7)), TRY_CAST(d.rest AS time(7))) / 100) * IIF(b.neg = 1, -1, 1) AS ticks) x WHERE v._String IS NOT NULL AND TRY_CAST(d.rest AS time(7)) IS NOT NULL; ``` SQLite: ```sql UPDATE _values SET _Long = (SELECT sign * (days * 864000000000 + (CAST(substr(rest, 1, 2) AS INTEGER) * 3600 + CAST(substr(rest, 4, 2) AS INTEGER) * 60 + CAST(substr(rest, 7, 2) AS INTEGER)) * 10000000 + CAST(substr(substr(rest, 10) || '0000000', 1, 7) AS INTEGER)) FROM (SELECT sign, CASE WHEN instr(b, '.') BETWEEN 1 AND instr(b, ':') THEN CAST(substr(b, 1, instr(b, '.') - 1) AS INTEGER) ELSE 0 END AS days, CASE WHEN instr(b, '.') BETWEEN 1 AND instr(b, ':') THEN substr(b, instr(b, '.') + 1) ELSE b END AS rest FROM (SELECT CASE WHEN substr(_values._String, 1, 1) = '-' THEN -1 ELSE 1 END AS sign, CASE WHEN substr(_values._String, 1, 1) = '-' THEN substr(_values._String, 2) ELSE _values._String END AS b))), _String = NULL WHERE _String IS NOT NULL AND _String GLOB '*[0-9][0-9]:[0-9][0-9]:[0-9][0-9]*' AND _id_structure IN (SELECT s._id FROM _structures s JOIN _types t ON t._id = s._id_type WHERE t._name IN ('TimeSpan', 'TimeOnly')); ``` The statements read the forms redb has written: `[-][d.]hh:mm:ss[.fffffff]` for `TimeSpan` and `hh:mm:ss[.fffffff]` for `TimeOnly`. A value they cannot read stays as it was; this lists them: ```sql SELECT v._id, v._String FROM _values v JOIN _structures s ON s._id = v._id_structure JOIN _types t ON t._id = s._id_type WHERE t._name IN ('TimeSpan', 'TimeOnly') AND v._String IS NOT NULL; ``` ### A newer database module is left in place From 4.7.5 on a start applies the module of its own package when the database holds an older one, as before, and no longer over a newer one. The newer module states which packages it still serves (`pvt_module_compat()` on PostgreSQL and SQL Server, the `_schema_compat` table of a SQLite file): a package among them starts and logs one warning, one that is not stops with `RedbSchemaNewerException`, which names the package version to upgrade to, and changes nothing. The upgrade script run by hand (`GetUpgradeScript()`, `redb schema --upgrade`) refuses a newer module the same way before its first change. The module goes to `0.7.23.1` on PostgreSQL and `0.2.40.2` on SQL Server, a SQLite file to schema version 13. The 4.7.5 module serves 4.7.5 and later packages only, because of the ticks above. Action: none for an application. A host that tells start-up failures apart can catch `RedbSchemaNewerException`: the application, not the database, needs upgrading. Packages published before 4.7.5 do not know the rule and still put their own module back, which is why every node runs 4.7.5. ### Custom dialects: Query_WrapPvtWithObjectRows Only for code that implements `ISqlDialect` itself; the dialects redb ships implement it. A Free list read now reads the `_objects` rows of the objects it finds and loads their Props once, so `ISqlDialect` has one more member, `Query_WrapPvtWithObjectRows(string innerSql)`: wrap the inner id list so that it returns the `_objects` row of every id, in the order of the inner list, with the columns of `ObjectStorage_SelectObjectsByIds`. A dialect without the v2-pvt module returns `null`. `Query_PvtModuleCompatFunction()` is new too and has a default (`null`, no compatibility function). ### SQL Server: a delete counts the requested objects only `DeleteAsync` over ids or objects returns the number of the requested objects it deleted, as on PostgreSQL and SQLite; on SQL Server it used to add every descendant removed with them. Code that compared that number with the size of a subtree reads the count of `DeleteSubtreeAsync` instead. ## 4.7.3 ### SQL Server: a database hit by a second redb init Up to this release, `redb init -p mssql` run on a database that already held the redb schema dropped every foreign key and the id sequence `global_identity`, then stopped with "There is already an object named '_types'". The data stayed; the next import failed at its end on `ALTER SEQUENCE`, and an application failed on its first new id. `redb init` now refuses such a database before it runs anything. The SQL Server script itself, as printed by `redb schema` and as run by `redb init`, now stops at its first statement on such a database too, also when a DBA runs it with sqlcmd or SSMS. The script reports that refusal as a message: sqlcmd without `-b` still exits with 0, so a script that runs it must read the output or call sqlcmd with `-b`. PostgreSQL and SQLite were not damaged by a second run. Check every SQL Server database on which `redb init` may have run twice: ```sql SELECT name FROM sys.sequences; -- must list global_identity SELECT COUNT(*) FROM sys.foreign_keys; -- must be 30 ``` If the sequence is missing or the count is lower, rebuild the database from an export. Stop the applications that use it first. 1. `redb export -p mssql -c "" -o backup.redb` 2. Create a new empty database and run `redb init -p mssql -c ""` once. 3. `redb import -p mssql -c "" -i backup.redb --clean` 4. Restart the id sequence past the imported ids. The export of a damaged database carries no sequence value, so the import leaves the new sequence at its start, below the imported ids: ```sql DECLARE @sql nvarchar(max) = ( SELECT N'SELECT @max = MAX(id) FROM (' + STRING_AGG(CAST(N'SELECT MAX(_id) AS id FROM dbo.' + QUOTENAME(t.name) AS nvarchar(max)), N' UNION ALL ') + N') x' FROM sys.tables t JOIN sys.columns c ON c.object_id = t.object_id AND c.name = N'_id' WHERE t.schema_id = SCHEMA_ID(N'dbo')); DECLARE @max bigint; EXEC sp_executesql @sql, N'@max bigint OUTPUT', @max = @max OUTPUT; DECLARE @restart nvarchar(200) = N'ALTER SEQUENCE dbo.global_identity RESTART WITH ' + CAST(CASE WHEN @max >= 1000000 THEN @max + 1 ELSE 1000000 END AS nvarchar(20)); EXEC (@restart); ``` 5. Check the new database with the two queries above, then point the applications at it. ## 4.7.1 ### SQL Server: the database module version Only for SQL Server. From 4.6.1 to 4.7.0 the package asked for module `0.2.40` while the module it installs reports `0.2.39`: every start applied the module again, and a start with `AutoApplyDatabaseUpgrades = false` or under a role without schema rights stopped with `RedbSchemaOutdatedException`, also right after the upgrade script was applied. Action: update to 4.7.1. The module goes to `0.2.40` once, and later starts leave it alone. If you cannot update the package yet: after the module is deployed (a normal start, or the script from `GetUpgradeScript()`), have the DBA run this once in the application database, as a batch of its own: ```sql ALTER FUNCTION dbo.pvt_module_version() RETURNS nvarchar(50) WITH SCHEMABINDING AS BEGIN RETURN N'0.2.40'; END ``` The application then starts with `AutoApplyDatabaseUpgrades = false` and no longer applies the module on every start. The later update to 4.7.1 finds `0.2.40` and changes nothing. ### SQL Server: rights of an application on a database the DBA deployed On SQL Server up to the 4.7 line, an application that did not deploy the schema needs these rights to save new objects: ```sql ALTER ROLE db_datareader ADD MEMBER [app]; ALTER ROLE db_datawriter ADD MEMBER [app]; GRANT EXECUTE TO [app]; GRANT ALTER ON OBJECT::dbo._objects TO [app]; GRANT ALTER ON OBJECT::dbo._values TO [app]; GRANT ALTER ON OBJECT::dbo._scheme_metadata_cache TO [app]; ``` Without `ALTER` on `_objects` and `_values` it starts, reads, updates and deletes, but every save of a new object fails with "Bulk copy failed. User does not have ALTER TABLE permission on table '_objects'". `ALTER` is a schema right on that table: the bulk copy of new rows asks for it. Without `ALTER` on `_scheme_metadata_cache` the start logs "Failed to warmup metadata cache during initialization" and goes on. The maintenance calls of `IMaintenanceProvider` need more: statistics need `ALTER` on the analysed tables, table statistics need `VIEW DATABASE PERFORMANCE STATE`. ## 4.6.0 ### Grouping: refusals instead of empty or default answers GroupBy, GroupByArray, their windows and their tree forms now throw where they used to answer with nothing or with a value that was not asked for: - `NotSupportedException` for a form that is not translated: a computed key or aggregate (`Agg.Sum(g, x => x.A * 2)`, `c => c.Name.Length`), `SelectMany` with a result selector or a dictionary in the array path of `GroupByArray`, a class as a key, an array of list items or object references, a string method in the condition of `Agg.Count`. A computed aggregate used to become `*`; an array path that was not a chain of fields became empty. - `InvalidOperationException` when a provider returns no array of rows, or a row without a column the selector reads. A missing column used to become the default value (0 for a number), which hid NULL keys dropped by SQL Server. - `ArgumentException` for a request without keys, where providers returned null and the query an empty list. `Having(...).WithWindow(...)` now keeps the HAVING (it was dropped), and `Win.Ntile(n)` uses `n` (it was always 4). A tree query's `GroupByArray` groups only its subtree (it grouped the whole scheme). Action: none for queries in the supported forms. A query that now throws was returning a wrong answer; rewrite the computation after the query, or group by a stored field. ### Free: tree queries return other rows Only for the free providers (`redb.Postgres`, `redb.MSSql`, `redb.SQLite`); the Pro providers already answered this way. From 3.0.0 to 4.5.1 a free tree query took the depth of its walk from the props depth (`WithMaxRecursionDepth`, 10 by default) and not from `maxDepth`. Three results change: - `TreeQuery(root, maxDepth)`, with one start node or several, stops at `maxDepth` levels below the start. It returned the whole subtree, so lists get shorter and counts and aggregates smaller. `WhereDescendantsOf(node, maxDepth)` likewise. - A tree query without `maxDepth` covers the whole subtree. A subtree deeper than the props depth was cut at that level, so a tree deeper than 10 levels now returns more rows. - `WhereLevel` on `TreeQuery(node)` counts from the node the query starts from: level 0 is the node, level 1 its children, as `maxDepth` counts. It counted from the root of the whole tree. `TreeQuery()` without a start node is unchanged. Action: review the code that reads a free tree query with `maxDepth` or `WhereLevel`, and the code that relied on the cut at 10 levels (page sizes, totals). A caller that worked around the old answer by filtering the levels in memory can drop the workaround. The answers come from the SQL module of the database together with the package: PostgreSQL `0.7.23`, SQL Server `0.2.39`, SQLite `0.6.13`. Start-up applies the module itself. With `AutoApplyDatabaseUpgrades = false`, or under a role that may not change the schema, start-up stops with `RedbSchemaOutdatedException` until the module is applied: take the script from `IRedbService.GetUpgradeScript()` or `redb schema --upgrade` and run it. SQLite has no script, its database file is upgraded by the process. ### Custom query providers: one method for array groupings Only for code that implements `IRedbQueryProvider` or `IRedbQueryable` itself: - The four `ExecuteArrayGroupedAggregateAsync` overloads are replaced by `ExecuteArrayGroupQueryAsync(ArrayGroupQuery)` and `GetArrayGroupQuerySqlAsync(ArrayGroupQuery)`; tree providers add `ExecuteTreeArrayGroupQueryAsync` and `GetTreeArrayGroupQuerySqlAsync`. `ArrayGroupQuery` carries the array path, keys, aggregates, condition, HAVING and window; call `EnsureValid()` first. - `GetGroupBySqlPreviewAsync` (two overloads) is part of `IRedbQueryProvider`; the grouped window methods (`ExecuteGroupedWindowQueryAsync`, `GetGroupedWindowSqlPreviewAsync` and their tree forms) take `havingJson`. - `IRedbQueryable.GroupByArray` and the grouping interfaces (`IRedbGrouping`, `IRedbGroupedQueryable`, `IGroupedWindowedQueryable`, `IGroupedWindowSpec`) no longer constrain the item type to `class, new()`: delete the constraint from an implementation, or it does not compile. - `ISqlDialect.Query_AggregateArrayGroupedSql` is removed (every dialect threw from it). ### Custom list providers: GetListItemsByIdsAsync Only for code that implements `IListProvider` or `ISqlDialect` itself: - `IListProvider.GetListItemsByIdsAsync(IEnumerable itemIds, CancellationToken)` returns the list items of the given ids: an id that names no item is left out, the order is free. A grouping whose key is a list item calls it once per result to turn the ids it grouped by into the items, so read them in one query. - `ISqlDialect.ListItems_SelectByIds()` is the statement the stock list provider runs for it: the columns of `ListItems_SelectById` for an array of ids passed as the first parameter. ### Custom contexts: QueryRowsAsJsonAsync Only for code that implements `IRedbContext` or derives from `RedbContextBase` itself: - `IRedbContext.QueryRowsAsJsonAsync(string sql, object[] parameters, CancellationToken)` returns the rows of `sql` as a JSON array of objects keyed by column name, NULL values included, `[]` when there are none. It is one command and one telemetry span, like the other methods of the context. The SQLite providers read their grouping, window and aggregate results through it; they used to read them on the raw connection, which opened no span. - `RedbContextBase` implements it inside the span over a new `protected abstract Task QueryRowsAsJsonCoreAsync(string sql, object[] parameters, CancellationToken)`. A context derived from it implements that method on its connection: read every row and serialize each as an object of its columns. The stock PostgreSQL, SQL Server and SQLite contexts do so. - A context that wraps another one (a decorator) forwards the call. ## 4.4.2 ### Duplicate root structures Nodes that synchronized one scheme at the same moment could write one root field of the scheme twice on PostgreSQL and SQLite (SQL Server refused it). Scheme synchronization now runs under the schema lock, and a new unique index, `UX__structures__root`, keeps one root field name per scheme. New databases get the index at creation. An existing database gets it at the next module upgrade (PostgreSQL) or at the next start (SQLite), and duplicates are handled first: - A duplicate that nothing points to (no value, no child structure with a value, no migration record) is removed with its child structures. The log names the scheme, the field and the removed ids. - A field whose copies hold values on more than one copy is left alone, and the index is not built. The service keeps working, logs an error naming the scheme, the field and the structure ids at every start, and lists the field in `IRedbService.SchemaProblems` (a health check can show the service as degraded). Scheme synchronization never removes such a copy; it reports it the same way. The index is built by the first upgrade (PostgreSQL) or start (SQLite) after the duplicates are resolved. Nothing is needed when no such error appears. To find the duplicates and the values on each copy: ```sql SELECT s._id_scheme, s._name, s._id, (SELECT COUNT(*) FROM _values v WHERE v._id_structure = s._id) AS values_count FROM _structures s JOIN (SELECT _id_scheme, _name FROM _structures WHERE _id_parent IS NULL GROUP BY _id_scheme, _name HAVING COUNT(*) > 1) d ON d._id_scheme = s._id_scheme AND d._name = s._name WHERE s._id_parent IS NULL ORDER BY s._id_scheme, s._name, s._id; ``` Each object normally has its value on one copy only: the copy the node that saved it had in its cache. To resolve a field, keep one copy (`:keep`) and move to it the values the other copy (`:dup`) holds for objects that have none on `:keep`. Then delete `:dup`; deleting a structure deletes the values still on it. Make a backup first, and stop the nodes of versions before this one: they may still write into the copy they cached. ```sql -- objects with a value on both copies: decide for each which value is right before going on SELECT d._id_object FROM _values d JOIN _values k ON k._id_object = d._id_object WHERE d._id_structure = :dup AND k._id_structure = :keep; UPDATE _values SET _id_structure = :keep WHERE _id_structure = :dup AND _id_object NOT IN (SELECT _id_object FROM _values WHERE _id_structure = :keep); DELETE FROM _structures WHERE _id = :dup; ``` For a field that is a nested class, an array or a dictionary, the values hang on the child structures and on the element rows of each copy: move them child by child with the same statements before the copy is deleted. ## 4.4 ### Npgsql 10 `redb.Postgres` and `redb.Postgres.Pro` bring Npgsql 10 (was 9), the version `Npgsql.EntityFrameworkCore.PostgreSQL` 10 requires; a process holds one Npgsql. redb itself is not affected, but your own code and logs on the same Npgsql are: - `PostgresException.BatchCommand` is `null` by default, so the SQL of a failed command no longer travels in the exception into logs. Add `Include Failed Batched Command=true` to the connection string to get it back. redb does not change your connection string. - With `Root Certificate` set in the connection string, the TLS chain is checked against that certificate only; the system certificate store is no longer consulted. A server whose chain ends in a CA of the system store, not in the given file, fails to connect: put the whole chain into the file, or drop `Root Certificate`. - An untyped read of a `date` or `time` column (`GetValue`, `ExecuteScalar` to `object`) returns `DateOnly` / `TimeOnly`, not `DateTime` / `TimeSpan`. `ExecuteScalarAsync` and the row mapper of `IRedbContext` still hand back `DateTime` / `TimeSpan`, as on Npgsql 9. The other drivers move too: Microsoft.Data.SqlClient 7.1.1 (a project that pins it below 7.0.3 gets a NU1605 downgrade error and has to raise the pin), Microsoft.Data.Sqlite 10.0.13 and native SQLite 3.53.3. ### Custom storage providers Only code that builds a storage provider itself is affected. The interceptor parameter of the provider constructors and of `CreateObjectStorageProvider` is now a `RedbSaveInterceptorPipeline` instead of the list of interceptors. Interceptors that reach redb through DI, or subscribe through `IRedbSaveInterceptorRegistry`, need no change. ### Empty values in sorting PostgreSQL Pro now sorts objects without a value for the sort key the way LINQ, SQL Server and SQLite do: first under `OrderBy`, last under `OrderByDescending`. PostgreSQL did the opposite. Sort keys over Props fields, expressions, window orderings and grouped windows are affected; base columns, which are never empty, are not. A page that relied on the old placement, for example to show filled values first in an ascending sort, has to filter out empty values or sort by a key of its own. ### SQLite: index on text values SQLite (schema version 12) adds `IX__values__structure_object_string`, from which SQLite Pro answers `Field == null` over a text field. An existing file builds it on its first start with this version, and on a large file that takes a while, the file busy meanwhile. Plan the first start of 4.4 on a large SQLite database for a quiet window. ### Value-leading indexes Every value column gets an index led by the value, so a filter on a field reads one range of it (on SQL Server every column but the string one: `nvarchar(max)` cannot be an index key): - **PostgreSQL** (PVT module 0.7.16): `(_id_structure, , _id_object) INCLUDE (_array_index)`, replacing `IX__values__{String,Long,DateTimeOffset,Numeric}_not_null` and `ix__values__array_null_structure`. - **SQL Server** (PVT module 0.2.30): eight `IX__values__structure__object` replace eleven `IX__values__*_not_null` and `IX__values__*_filter` indexes. - **SQLite** (schema step 11): the same shape, replacing the `_not_null` indexes, `ix__values__array_null_structure` and the four indexes SQLite Pro used to build at start-up. An existing database builds them on the first start with this version, inside the module transaction, and **writes to `_values` wait while they are built**: about a minute per index on 38 million rows on PostgreSQL, 84 s in all on SQL Server, 135 s on SQLite. Plan the first start for a quiet window. The statements that bring the old indexes back are in `v2-pvt/00_module_init.sql` of each provider; the aggregate form (planner off) read them and is 1.5-2x slower on some filters without them. On SQL Server only a role allowed to alter `_values` rebuilds an index; a role without schema rights gets `RedbSchemaOutdatedException`. Path: redb/redb.sln 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.sln ---- Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.Core", "redb.Core\redb.Core.csproj", "{A1B2C3D4-0001-0001-0001-000000000001}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.Postgres", "redb.Postgres\redb.Postgres.csproj", "{A1B2C3D4-0002-0002-0002-000000000002}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.MSSql", "redb.MSSql\redb.MSSql.csproj", "{A1B2C3D4-0003-0003-0003-000000000003}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.SQLite", "redb.SQLite\redb.SQLite.csproj", "{A1B2C3D4-0010-0010-0010-000000000010}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.Export", "redb.Export\redb.Export.csproj", "{A1B2C3D4-0004-0004-0004-000000000004}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.CLI", "redb.CLI\redb.CLI.csproj", "{A1B2C3D4-0005-0005-0005-000000000005}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.Examples", "redb.Examples\redb.Examples.csproj", "{A1B2C3D4-0006-0006-0006-000000000006}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.Templates", "redb.Templates\redb.Templates.csproj", "{A1B2C3D4-0007-0007-0007-000000000007}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.PropsEditor", "redb.PropsEditor\redb.PropsEditor.csproj", "{A1B2C3D4-0008-0008-0008-000000000008}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "redb.Tests.Integration", "redb.Tests.Integration\redb.Tests.Integration.csproj", "{A1B2C3D4-0009-0009-0009-000000000009}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A1B2C3D4-0001-0001-0001-000000000001}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0001-0001-0001-000000000001}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0001-0001-0001-000000000001}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0001-0001-0001-000000000001}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0003-0003-0003-000000000003}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0003-0003-0003-000000000003}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0003-0003-0003-000000000003}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0003-0003-0003-000000000003}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0010-0010-0010-000000000010}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0010-0010-0010-000000000010}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0010-0010-0010-000000000010}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0010-0010-0010-000000000010}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0004-0004-0004-000000000004}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0004-0004-0004-000000000004}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0004-0004-0004-000000000004}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0004-0004-0004-000000000004}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0005-0005-0005-000000000005}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0005-0005-0005-000000000005}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0005-0005-0005-000000000005}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0005-0005-0005-000000000005}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0006-0006-0006-000000000006}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0006-0006-0006-000000000006}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0007-0007-0007-000000000007}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0007-0007-0007-000000000007}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0007-0007-0007-000000000007}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0007-0007-0007-000000000007}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0008-0008-0008-000000000008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0008-0008-0008-000000000008}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0008-0008-0008-000000000008}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0008-0008-0008-000000000008}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0009-0009-0009-000000000009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0009-0009-0009-000000000009}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1B2C3D4-0009-0009-0009-000000000009}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1B2C3D4-0009-0009-0009-000000000009}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal