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`.