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.
How the command works
Section titled “How the command works”The command upgrade of the sample’s command-line tool, in
sample/Database/Commands/Custom/Upgrade.cs, runs these steps:
- Load. It loads the file that the option
-fnames, or else the file of the settingpopulationFile, or elsepopulation.xml. The load starts withInit(): the database loses its population first. - 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
ExcludedObjectTypesand the relation types inExcludedRelationTypes: 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. - 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. - Change the data. In one transaction it creates the permissions of the new model with
Sync, runsUpgrade.Execute()of the domain, derives and commits. - Grant again. It runs the security setup, so that every
Rolegets its permissions again, the new ones included, and commits.
1. Write the changes of the data
Section titled “1. Write the changes of the data”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 version | What to do |
|---|---|
| adds a class, a method type or a role that can start empty | No 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 one | Compute 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 for | Give 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 setup | Merge the object in Execute, with the merge of the setup; Grant access shows such merges. |
gives a Role other permissions | Nothing: 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-many | Before 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 type | Declare it, as the next step shows. |
2. Declare what the new version removed
Section titled “2. Declare what the new version removed”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:
export ALLORS_CONFIG_ROOT="$PWD/config/snapshot"./build.sh SampleGenerateexport adapter=npgsqlexport ConnectionStrings__DefaultConnection='Host=localhost;Database=sample;Username=…;Password=…'dotnet run --project sample/Database/Commands -- save -f ~/population.xmlThe 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.
4. Upgrade with the new version
Section titled “4. Upgrade with the new version”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.
export ALLORS_CONFIG_ROOT="$PWD/config/snapshot"./build.sh SampleGenerateexport adapter=npgsqlexport ConnectionStrings__DefaultConnection='Host=localhost;Database=sample_upgraded;Username=…;Password=…'dotnet run --project sample/Database/Commands -- initdotnet run --project sample/Database/Commands -- upgrade -f ~/population.xmlThe 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 names of the tables
Section titled “The names of the tables”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.
5. When the upgrade stops
Section titled “5. When the upgrade stops”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. CorrectExecute. - In the security setup: the changes of
Executeand 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.
6. Test the upgrade
Section titled “6. Test the upgrade”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.
export ALLORS_CONFIG_ROOT="$PWD/config/snapshot"./build.sh SampleGeneratedotnet test sample/Database/Commands.TestsWhere this is implemented
Section titled “Where this is implemented”- The command is in
sample/Database/Commands/Custom/Upgrade.cs, the domain classUpgradeinsample/Database/Domain/Custom/Upgrade.cs, and the tests insample/Database/Commands.Tests/UpgradeTests.cs. - Core’s command-line tool for its test domain has an
upgradeof its own, indotnet/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 itsUpgradewithout deriving them, and does not read the settingpopulationFile. - The events of the load are described in Populations.
- The database schema names the adapter code
and tests, including
ARelationTypeWhoseStorageHasChangedRefusesTheTransactionfor a changed multiplicity, a role of another class and a relation type that leaves the database.