Status: Current. Where this is implemented names the code and the tests.
The SqlClient adapter for SQL Server and the Npgsql adapter for PostgreSQL keep a population in
tables that they create from the model. This page lists what they create and how they name it,
what a database object checks before its first transaction, and what Init() and the command
index change. The database adapters explains where these two adapters
stand among the others.
An application reads and writes its population through the API. The schema belongs to the adapters, and a version of the platform can change it: pull request #470 renamed every table and index, and the columns that hold relations, and the changelog says so. SQL of an application that reads these tables, for a report for example, has to follow such a change.
The schema
Section titled “The schema”The adapters create their tables in one schema of the database, allors. Init() creates the
schema when the database lacks it. The property SchemaName of the adapters’ Configuration
names another schema, which the adapter writes in lower case; a program that builds its database
from the setting adapter, as the sample’s programs do, uses allors.
In that schema the adapters own every table whose name starts with allors_, and on SQL Server
every table type whose name starts with allors_t_. They compare the prefix with the name as the
server stores it, including case. An independent table named ALLORS_REPORT therefore keeps its
rows when the adapter empties or rebuilds its tables. Objects attached to an adapter table can
still be affected, even in another schema. What Init changes gives the
consequences for indexes, triggers and PostgreSQL partitions and inherited tables.
A name carries the ids of the model, not its names: the name of a class or a role can be longer
than a server allows a name to be, and two of them can differ in case only. A name writes the
id of a class, an interface or a relation type as 26 characters: its sixteen bytes
in network
byte order, in the base32hex alphabet of
RFC 4648, 0 to 9 and a to v, in lower
case and without padding. A multiplicity takes one letter for each end, the association first,
o for one and m for many: oo, om, mo or mm.
| Name | What it is |
|---|---|
allors_o | The objects table. |
allors_<class> | The table of a class. |
allors_<relation type>_<multiplicity> | The table of a relation type. |
o, c and v | The id, the class and the version of an object, in the objects table; o and c in the table of a class. |
r_<relation type> | In the table of a class, the column of a unit role. |
r_<relation type>_<object type>_<multiplicity> | In the table of a class, the column of a composite role that holds one object, oo or mo, with the object type of the role. |
a_<relation type>_<object type>_om | In the table of a class, the column of the association of a one-to-many relation type, with the object type of the association. |
a_<object type> and r_<object type> | In the table of a relation type, the columns of the association and of the role, each with its object type. |
allors_i_<class>_<relation type> | The index on a column of the table of a class. |
allors_i_<relation type>_r | The index on the role column of the table of a relation type. |
allors_t_… | On SQL Server, a table type. |
The server names the primary keys: PostgreSQL as the table followed by _pkey, SQL Server as
PK__, the first eight characters of the name of the table, __ and sixteen hexadecimal digits.
In the sample, the class WorkItem has the id 8e78ae27-8c39-4bb9-89c5-e5b4f27507c1. Its table
and three of its columns are:
| Name | What it is |
|---|---|
allors_hpsas9sc755rj2e5smqf4t87o4 | The table of WorkItem. |
r_d69agobbd53hb5pq6ph76pqbv8 | The column of the unit role Title. |
r_3g844ghu3149h7773nl26t7it4 | The column of the unit role Done. |
r_t5v28v76755dl3bd0mvc98ib88_aqfi3b72h90lh307im4a5dup0s_mo | The column of the many-to-one role Assignee, whose object type is Person. Its index is allors_i_hpsas9sc755rj2e5smqf4t87o4_t5v28v76755dl3bd0mvc98ib88. |
Mapping, in the namespace Allors.Database.Adapters.Sql, writes these names from the model:
// allors_hpsas9sc755rj2e5smqf4t87o4var table = Mapping.TableNameFor(m.WorkItem);
// r_d69agobbd53hb5pq6ph76pqbv8var title = Mapping.RoleColumnNameFor(m.WorkItem.Title.RelationType);Its static members ObjectsTableName, TableNameFor, RoleColumnNameFor,
AssociationColumnNameFor, RelationTableAssociationColumnNameFor,
RelationTableRoleColumnNameFor and IndexNameFor give the names of the tables, the columns and
the indexes. The other way round, ModelId.Decode gives the id that 26 characters of a name
carry, and FindById of the meta population gives the class or the relation type with that id.
Tables
Section titled “Tables”The adapters store the classes and relations with Origin.Database. A role declared with
[Origin(Origin.Session)] exists only in the workspace session and has no SQL column, relation
table or index. See the model attributes.
The objects table
Section titled “The objects table”allors_o has a row for every object:
| Column | SQL Server | PostgreSQL | Holds |
|---|---|---|---|
o | bigint, IDENTITY(1,1), the primary key | bigint, GENERATED BY DEFAULT AS IDENTITY, the primary key | The id of the object. The server numbers a new object. |
c | uniqueidentifier | uuid | The id of its class. |
v | bigint | bigint | Its version. |
The table of a class
Section titled “The table of a class”allors_<class> has a row for every object of the class. Its column o, a bigint and its
primary key, holds the id of the object, and c the id of the class, as in the objects table.
The other columns hold relations of the class:
- A unit role of the class, also one that an interface of the class declares, has a column of the type of its unit; the types are listed below.
- A composite role that holds one object, of a one-to-one or a many-to-one relation type, has
a
bigintcolumn with the id of that object, in the table of the class of the association. - The association of a one-to-many relation type has a
bigintcolumn with the id of the association, in the table of the class of the role: the role holds several objects, and each of them has one association.
A composite relation type has such a column only when each end has exactly one database class. An end can be the class itself or an interface that just one database class implements. The other composite relation types have a table of their own.
The table of a relation type
Section titled “The table of a relation type”allors_<relation type>_<multiplicity> holds the relations of a composite relation type that is
many-to-many, or that has an end whose object type is an interface that no database class or more
than one database class implements. Each relation is a row:
| Column | Type | Holds |
|---|---|---|
a_<object type> | bigint | The id of the association. |
r_<object type> | bigint | The id of the role. |
The primary key is on the association column when the role holds one object, and on the association and role columns, in that order, when it holds several.
The types of the columns
Section titled “The types of the columns”| Unit | SQL Server | PostgreSQL |
|---|---|---|
String | nvarchar(<size>), or nvarchar(max) with a size above 4000 or without a limit | varchar(<size>), or text with a size above 4000 or without a limit |
Integer | int | integer |
Decimal | decimal(<precision>,<scale>) | numeric(<precision>,<scale>) |
Float | float | double precision |
Boolean | bit | boolean |
DateTime | datetime2 | timestamp |
Unique | uniqueidentifier | uuid |
Binary | varbinary(<size>), or varbinary(max) with a size above 8000 or without a limit | bytea |
The size, the precision and the scale are those of the role, as the
attributes of its declaration set them: without [Size] a String has the
size 256 and a Binary has no limit, [Size(-1)] takes the limit away, and without [Precision]
and [Scale] a Decimal has 19 and 2. A DateTime column holds the value in UTC, as
unit roles keep it.
Indexes
Section titled “Indexes”The adapters derive indexes from the relations with Origin.Database.
- On the column of every composite relation type: its column in the table of a class, named
allors_i_<class>_<relation type>, or the role column of its own table, namedallors_i_<relation type>_r. - On the column of every unit role that its declaration marks
[Indexed], in the table of each class that has the role, except aStringor aBinaryrole whose size has no limit or is above 4000, as aBinaryrole without[Size]has none.
An index counts as present when an index on the same table leads with the column, whatever its name and whoever created it. A partial, disabled, invalid or hypothetical index does not count, nor, on SQL Server, an index other than a clustered or nonclustered rowstore index.
Init(), a load, the command index of the command-line tool and
EnsureIndexes() of the database create the required indexes that are missing. The command and
EnsureIndexes() preserve the rows. Before the first transaction
describes the check a transaction makes.
On a table that stays in place, the adapter tries to drop an index only when it has the adapter’s
name for a unit role, leads with that role’s column, and the role no longer calls for an index,
as when its declaration loses [Indexed]. If the server refuses the drop or the adapter cannot
acquire the lock within two seconds, the index can remain after a successful command. The next
call to maintain the indexes tries again.
Table types on SQL Server
Section titled “Table types on SQL Server”The SqlClient adapter passes sets of ids, and of relations, to its statements as table-valued parameters. Their types are in the schema of the adapter:
| Table type | Columns |
|---|---|
allors_t_o | _o bigint |
allors_t_c | _a bigint, _r bigint |
allors_t_s | _a bigint, _r nvarchar(max) |
allors_t_i | _a bigint, _r int |
allors_t_f | _a bigint, _r float |
allors_t_bo | _a bigint, _r bit |
allors_t_da | _a bigint, _r datetime2 |
allors_t_u | _a bigint, _r uniqueidentifier |
allors_t_bi | _a bigint, _r varbinary(max) |
allors_t_de<precision>_<scale> | _a bigint, _r decimal(<precision>,<scale>), for each precision and scale of a Decimal role of the model |
Before the first transaction
Section titled “Before the first transaction”A database object of the SqlClient or Npgsql adapter reads the schema before its first
transaction. If the check fails, CreateTransaction() throws an exception. A later call to
CreateTransaction() or EnsureIndexes() on the same database object checks the schema again,
so either call can succeed once another program repairs it. After a successful check, the
database object reuses the result.
Tables and columns. Every table of the model must exist, with the expected columns, types
and primary key. An extra table whose name starts with allors_, or an extra column on a table
of the model, also prevents the transaction from opening. On SQL Server the required table types
must exist with the expected columns. The adapters also check the following properties.
- The objects table and each class table have their primary key on
o. Onlyallors_o.ois an identity column. It starts at 1, increments by 1 and, on PostgreSQL, cannot cycle. A relation table needs the key for its multiplicity. On PostgreSQL a key on the association column alone must also be non-deferrable. - Columns outside the primary key must allow
NULL. The adapters reject a column with a default, a generated or computed column, and, on SQL Server, a masked column. On PostgreSQL they also check the default,NOT NULLand check constraints supplied by a column’s domain. - A trigger, an additional constraint, such as a foreign key or check constraint, or a unique index besides the primary key makes the table invalid. On PostgreSQL the check also rejects an unlogged table, a rule, a policy or row level security. On SQL Server it rejects a security policy on the table.
- PostgreSQL checks the partitions of an adapter table in every schema. It rejects an unlogged
partition or a partition that requires a value in a column the model allows to be
NULL. It also checks for row triggers, constraints and unique indexes declared on the partition itself. A write through the parent reaches that partition.
Partitioning, an inherited child table, a non-unique index or a foreign key on another table that refers to an adapter table can all pass the table check. It does not inspect statistics, storage settings, grants or comments on the tables.
SQL Server database settings and permissions. The database must allow snapshot isolation.
The login needs permission to view definitions throughout the database so that the adapter can
check every security policy. A login with data access alone needs GRANT VIEW DEFINITION TO
followed by its database user. A denial of VIEW DEFINITION, VIEW SECURITY DEFINITION or
CONTROL on a schema or object to that user or one of its roles can hide a policy. The adapter
refuses the login in that case, except for the database owner and members of db_owner, who
can still see the policies. Init() also checks this permission before it changes the database.
Indexes. After the tables pass, the database object checks the required indexes. If any are missing, it refuses the transaction and checks the indexes again on the next attempt. It keeps a successful index check as well.
The refusal message. Missing Tables:, Obsolete Tables: and Invalid Tables: name the
affected tables and describe each one. An encoded table name identifies its class or relation
type even when the model no longer has it. Under an invalid table, the message lists differences,
including the expected and actual type of a column, the primary key or a constraint added by
hand. SQL Server reports database settings or permissions under Database: and table types under
Missing Table Types: and Invalid Table Types:. Removing the column of Title from the
sample’s WorkItem table gives this message.
Invalid Tables:- allors.allors_hpsas9sc755rj2e5smqf4t87o4: the table of the class WorkItem - r_d69agobbd53hb5pq6ph76pqbv8 is missing: the role of the relation type WorkItem.TitleA missing index gives a message that names the command index and EnsureIndexes(), followed by
a CREATE INDEX statement for each index, with a comment that says what the index is for: the
relation type and the class of its table, or the table of the relation type. When another index
has the name of a missing one, in the schema on PostgreSQL or on the same table on SQL Server, the
message names both and asks to drop or rename the other.
To keep the current population when a table was changed by hand, correct the difference in the
message and open a transaction again. To move a population into the tables of a new model,
follow Upgrade a population. A database that lacks only indexes gets
them from the command index, with a login that may create an index on the tables.
What Init changes
Section titled “What Init changes”Init() compares the tables with the model. On SQL Server it checks the login’s permission to
view definitions and enables ALLOW_SNAPSHOT_ISOLATION if it is off.
- When the tables and any required SQL Server table types fit the model,
Init()empties the tables, restarts object numbering and creates missing indexes in one transaction. On PostgreSQL, truncating a table also empties its partitions and inherited children, whatever their names or schemas. After the commit the adapter tries to drop obsolete indexes. - When the tables or table types need rebuilding,
Init()creates the schema if it is missing. The rebuild drops the adapter’s tables and creates those of the model in one transaction. If that transaction fails, the old tables keep their rows. Dropping a table also removes its indexes and triggers, including any added by hand. On PostgreSQL, dropping a partitioned table removes its attached partitions, including partitions in another schema.
On PostgreSQL the rebuild creates the required indexes in the same transaction. It holds a lock
on each table, index and sequence it drops or creates until it commits. One model with 132 tables
needed 1,697 locks. If the server’s lock table fills up, the rebuild rolls back. The exception
includes the server error 53200: out of shared memory and its hint to raise
max_locks_per_transaction.
On SQL Server the rebuild first drops the table types whose names start with allors_t_ in the
adapter’s schema, then replaces the tables and creates the required table types. A stored
procedure that uses one of those types stops the rebuild before it reaches the tables. A
security policy on an adapter table also prevents the table from being dropped. A rollback
restores the table types as well. The adapter creates the required indexes after that
transaction commits.
A load empties or rebuilds the tables in the same way, but postpones index maintenance until after it loads the rows. Saving and loading describes what the database holds if a load fails.
Where this is implemented
Section titled “Where this is implemented”MappingandModelId, indotnet/System/Database/Adapters/Allors.Database.Adapters.Sql/Schema, write the names,Validationthere writes the lines of a refusal, andIndexesderives the indexes from the model, checks them and creates them.Database, in the folder above, checks the schema and the indexes before the first transaction of a database object.- Each SQL adapter has a folder
Schema, inAllors.Database.Adapters.Sql.SqlClientandAllors.Database.Adapters.Sql.Npgsql:Mappinggives the types of the columns,Schemareads the catalogue of the server,Validationcompares it with the model and writes the message,Initializationempties or builds the tables, andIndexesreads, creates and drops the indexes. The table types are in theMappingof the SqlClient adapter. - In
dotnet/System/Database/Adapters/Tests.Static/Static/Sql,IndexTestholds the facts of the names,TheNamesOfTheSchemaCarryTheIdsOfTheModel, of a relation type whose storage changed,ARelationTypeWhoseStorageHasChangedRefusesTheTransaction, of a schema changed by hand,InitForgetsThatATransactionWasRefused, and of optional index cleanup,AnIndexThatCannotAcquireTheSchemaLockStays. InInitTest,AnInitThatFailsChangesNothingchecks the rollback of a failed rebuild. Each adapter’sInitRebuildsTablesChangedByHandcovers the table checks. The SqlClient testALoginThatMayNotViewTheDefinitionsOfTheDatabaseIsRefusedchecks the permissions needed to see security policies. The Npgsql testAPartitionedTableAndATableWithAChildAreEmptiedcovers truncation of partitions and inherited tables.