Skip to content

main · v3.2 (unreleased)

Upgrade a population

Users · How-to guide · CurrentMarkdownAgent index

Status: Current. Where this is implemented names the code and the tests.

Use this guide when a new version of an application changes its model or its setup, and a database that an earlier version populated has to follow. It assumes Populations, which explains saving, loading and the setup.

The example is the sample application. Its setup creates permissions and the Role Worker, which an earlier version of the sample did not; its command upgrade adds them to a population without them. The sample’s test of the command builds such a population by deleting them before it saves.

The command upgrade of the sample’s command-line tool, in sample/Database/Commands/Custom/Upgrade.cs, runs these steps:

  1. Load. It loads the file that the option -f names, or else the file of the setting populationFile, or else population.xml. The load starts with Init(): the database loses its population first.
  2. Accept what the new version removed. The load leaves out the objects of the classes, and the relations of the relation types, that the new model does not have, and reports them. The command accepts the omissions that concern the classes in ExcludedObjectTypes and the relation types in ExcludedRelationTypes: the objects of those classes, their relations, and those objects in the roles of the objects that the load keeps. A class or a relation type that the new model still has loads as usual, whether it is in these sets or not.
  3. Stop at any other omission that the load reports. The command logs the ids of the classes and the relation types concerned, empties the database with Init() and exits with code 1.
  4. Change the data. In one transaction it creates the permissions of the new model with Sync, runs Upgrade.Execute() of the domain, derives and commits.
  5. Grant again. It runs the security setup, so that every Role gets its permissions again, the new ones included, and commits.

Write what the new version needs in Execute of the domain class Upgrade, in the folder Custom of the domain project. For the setup’s objects, call the merges of the setup, which find what exists and create what is missing. sample/Database/Domain/Custom/Upgrade.cs:

public void Execute()
{
// A population that an earlier version saved can lack the Role Worker, the user group Workers
// and their grant on the default security token, which the setup creates. The merges of the setup create
// what is missing, and leave the members of the user group as they are.
new Roles(this.Transaction).MergeWorker();
new UserGroups(this.Transaction).MergeWorkers();
var workers = new Grants(this.Transaction).MergeWorkers();
new SecurityTokens(this.Transaction).DefaultSecurityToken.AddGrant(workers);
}
The new versionWhat to do
adds a class, a method type or a role that can start emptyNo data change is needed in Execute. Sync creates the permissions.
adds a derived role whose value depends on existing data, or changes how a rule derives oneCompute its value for each affected object in Execute. The load finishes before the upgrade transaction starts, so unchanged inputs in the saved population do not trigger the rule.
requires a role that existing objects have no value forGive every existing object a value in Execute. The derivation checks the required roles only of the objects that the upgrade changes.
creates an object in its setupMerge the object in Execute, with the merge of the setup; Grant access shows such merges.
gives a Role other permissionsNothing: the command runs the security setup.
lets an object be the role of one association only, where it could be the role of several: a many-to-one relation type that becomes one-to-one, or a many-to-many relation type that becomes one-to-manyBefore the save in step 3, give each such object at most one association with the earlier version. The load does not check it: it keeps both associations of an object, and the association of that object then reads one of them (#339).
removes a class or a relation typeDeclare it, as the next step shows.

Add the id of every class and every relation type that the new version removed on purpose to the command, in sample/Database/Commands/Custom/Upgrade.cs:

public HashSet<Guid> ExcludedObjectTypes { get; } = new HashSet<Guid>
{
};
public HashSet<Guid> ExcludedRelationTypes { get; } = new HashSet<Guid>
{
};

The ids are those of the [Id] attributes that the earlier model declared. The command stops at any other omission that the load reports, so a class or a relation type that the new model lost by mistake does not pass for an upgrade. The load does not report every change, though: Populations says what it lets pass.

3. Save the population with the running version

Section titled “3. Save the population with the running version”

Before the final save, stop accepting writes and let active transactions finish. Keep all programs that write to the database stopped until the upgrade succeeds. Any change committed after the save will be lost when the upgrade loads the file.

Use the command-line tool of the deployed version. The population has to outlive the process, so use SQL Server or PostgreSQL. For the sample, generate that version in its own clone and save to a new file outside the clone, here on PostgreSQL:

Terminal window
export ALLORS_CONFIG_ROOT="$PWD/config/snapshot"
./build.sh SampleGenerate
export adapter=npgsql
export ConnectionStrings__DefaultConnection='Host=localhost;Database=sample;Username=…;Password=…'
dotnet run --project sample/Database/Commands -- save -f ~/population.xml

The first line names a configuration root, which the build and the tool need; the two settings that follow override its file.

Check that save exits with code 0 before running upgrade. A failed save can leave a partial file, and the upgrade empties the database before reading it. Keep the file until the upgraded application runs.

Stop any remaining programs that read the database. Before running upgrade, choose the database that will receive the saved population: a new, empty database, or the database of the earlier version. upgrade does not create a database.

With the SqlClient and Npgsql adapters, create a new, empty database when the earlier version names its tables otherwise than the new version, as The names of the tables describes. The database of the earlier version then stays as it was, for that version. When both versions name their tables alike, you can reuse the database of the earlier version: the upgrade replaces its population with the one in the saved file.

In a clone at the new version, name a configuration root, generate the sample and set ConnectionStrings__DefaultConnection to the chosen database. In this PostgreSQL example, init of the command-line tool creates a new database named sample_upgraded, through the admin connection, and upgrade loads the population saved from sample in step 3 into it. Leave out init when you reuse a database: it drops the database of the connection string and creates it again.

Terminal window
export ALLORS_CONFIG_ROOT="$PWD/config/snapshot"
./build.sh SampleGenerate
export adapter=npgsql
export ConnectionStrings__DefaultConnection='Host=localhost;Database=sample_upgraded;Username=…;Password=…'
dotnet run --project sample/Database/Commands -- init
dotnet run --project sample/Database/Commands -- upgrade -f ~/population.xml

The load gives the database the tables of the new model. The command logs Begin, the file that it loads and End, and exits with code 0. After it succeeds, point the new application at the database you upgraded (sample_upgraded in the example), then start it.

The SqlClient and Npgsql adapters name their tables, columns and indexes after the ids of the model, as Names lists. Earlier versions named their tables after classes and roles, such as person, and their objects table _o.

A relation type keeps its id when its multiplicity or the object type at either end changes. Its table name, column names or column types can still change. If a relation leaves the database, its old table or column can remain. The first transaction reports where the schema differs from the new model. Loading the saved population as part of the upgrade builds the tables the new model needs.

A refusal can also arise with the same model. For example, if the message names a trigger that someone added to a table, removing it preserves the population. If SQL Server reports a missing permission, correct the login’s permissions. The same database object checks again on the next transaction. Before the first transaction explains the messages and how to act on them.

When the earlier version used names such as person and _o, its tables are independent of the new allors_ tables. A load into that database creates the new tables alongside the old ones, which keep their rows.

The command exits with code 1 whenever it fails, and logs the message of the error. What the database then holds depends on where the command stopped:

  • Before the load, at a missing file or a missing setting: the database is unchanged.
  • During the SQL schema rebuild, a failure rolls back the rebuild and preserves the original tables and rows. See What Init changes.
  • During the load, at a file that the load refuses: the database is empty. On SQL Server and PostgreSQL a failure to build the indexes after the load leaves the loaded rows.
  • At an omission that is not declared: the command logs which classes or relation types the file holds that the new version could not load, and leaves the database empty. Declare what the new version removed on purpose, or correct the model.
  • At an error of the derivation after Execute: Derive() throws, and nothing of the transaction of step 4 of How the command works is committed. The database holds the population as the load left it, without the changes of the upgrade, the new permissions or the security setup. Correct Execute.
  • In the security setup: the changes of Execute and the new permissions are committed, and the security setup is not.

In each case, correct the cause and upgrade again from the same file: the upgrade starts by emptying the database. Start the application only after an upgrade that exits with code 0.

The sample tests its command in sample/Database/Commands.Tests/UpgradeTests.cs. The tests run the tool’s commands in one process, on the Snapshot adapter, which they set in the environment. One populates a database with one Program, removes what an earlier version did not have, saves, and upgrades with a second Program; then it checks the objects, the setup that the upgrade added and what a worker may do. Another checks that the upgrade keeps the members of Workers. The others change the saved file: they check that the upgrade leaves out the objects of a declared class, and that it stops, leaving the database as Init() leaves it, at four kinds of omission that are not declared.

Terminal window
export ALLORS_CONFIG_ROOT="$PWD/config/snapshot"
./build.sh SampleGenerate
dotnet test sample/Database/Commands.Tests
  • The command is in sample/Database/Commands/Custom/Upgrade.cs, the domain class Upgrade in sample/Database/Domain/Custom/Upgrade.cs, and the tests in sample/Database/Commands.Tests/UpgradeTests.cs.
  • Core’s command-line tool for its test domain has an upgrade of its own, in dotnet/Core/Database/Commands/Custom/Upgrade.cs. An application does not include it, and it differs from the sample’s: issues #424 and #425 record two of the differences. It also commits the changes of its Upgrade without deriving them, and does not read the setting populationFile.
  • The events of the load are described in Populations.
  • The database schema names the adapter code and tests, including ARelationTypeWhoseStorageHasChangedRefusesTheTransaction for a changed multiplicity, a role of another class and a relation type that leaves the database.