shutro 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/audit/index.d.ts +57 -0
- package/dist/audit/index.js +94 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +149 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +47 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +82 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +200 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/env/env.d.ts +295 -0
- package/dist/core/env/env.js +631 -0
- package/dist/core/env/identity.d.ts +33 -0
- package/dist/core/env/identity.js +49 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +242 -0
- package/dist/core/errors.js +339 -0
- package/dist/core/index.d.ts +43 -0
- package/dist/core/index.js +34 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +446 -0
- package/dist/core/model/field.js +398 -0
- package/dist/core/model/generated.d.ts +75 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +347 -0
- package/dist/core/model/model.js +538 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/money/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +60 -0
- package/dist/core/money/fx.js +109 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/audit.d.ts +25 -0
- package/dist/core/recordset/audit.js +205 -0
- package/dist/core/recordset/compute.d.ts +34 -0
- package/dist/core/recordset/compute.js +405 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +27 -0
- package/dist/core/recordset/domain.js +228 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +207 -0
- package/dist/core/recordset/recordset.d.ts +101 -0
- package/dist/core/recordset/recordset.js +723 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +42 -0
- package/dist/core/recordset/security.js +184 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +77 -0
- package/dist/core/recordset/types.d.ts +296 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +27 -0
- package/dist/core/recordset/values.js +147 -0
- package/dist/core/recordset/writes.d.ts +37 -0
- package/dist/core/recordset/writes.js +581 -0
- package/dist/core/registry/ddl.d.ts +22 -0
- package/dist/core/registry/ddl.js +127 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +80 -0
- package/dist/core/registry/module.js +96 -0
- package/dist/core/registry/registry.d.ts +105 -0
- package/dist/core/registry/registry.js +496 -0
- package/dist/driver-pg/driver.d.ts +86 -0
- package/dist/driver-pg/driver.js +176 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +195 -0
- package/dist/security/index.d.ts +123 -0
- package/dist/security/index.js +262 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +42 -0
- package/dist/sql/tag.js +95 -0
- package/package.json +82 -4
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders operations as DDL text. DDL can't take bind parameters, so every piece is validated before it becomes
|
|
3
|
+
* text: identifiers through `sql.id` (quoted), types and defaults through strict patterns, expressions from `sql`
|
|
4
|
+
* fragments that carried no parameters.
|
|
5
|
+
*/
|
|
6
|
+
import { compile, sql } from '../sql/index.js';
|
|
7
|
+
import { MigrationError } from './errors.js';
|
|
8
|
+
const TYPE = /^[a-z]+( [a-z]+)*(\(\d+(,\d+)?\))?(\[\])?$/;
|
|
9
|
+
const DEFAULT = /^(true|false|now\(\)|-?\d+(\.\d+)?|'(?:[^']|'')*')$/;
|
|
10
|
+
const METHOD = /^[a-z_]+$/;
|
|
11
|
+
function id(...parts) {
|
|
12
|
+
return compile(sql.id(...parts)).text;
|
|
13
|
+
}
|
|
14
|
+
function type(t) {
|
|
15
|
+
if (!TYPE.test(t))
|
|
16
|
+
throw new MigrationError(`${JSON.stringify(t)} is not a column type the migrator renders.`, 'Column types come from the field builders; this should not happen.');
|
|
17
|
+
return t;
|
|
18
|
+
}
|
|
19
|
+
function defaultExpr(d) {
|
|
20
|
+
if (!DEFAULT.test(d))
|
|
21
|
+
throw new MigrationError(`${JSON.stringify(d)} is not a default the migrator renders.`, 'Defaults are booleans, numbers, quoted strings or now().');
|
|
22
|
+
return d;
|
|
23
|
+
}
|
|
24
|
+
function columnDdl(column, primaryKey) {
|
|
25
|
+
const parts = [id(column.name)];
|
|
26
|
+
if (column.identity) {
|
|
27
|
+
parts.push('bigint GENERATED ALWAYS AS IDENTITY');
|
|
28
|
+
if (primaryKey.length === 1 && primaryKey[0] === column.name)
|
|
29
|
+
parts.push('PRIMARY KEY');
|
|
30
|
+
return parts.join(' ');
|
|
31
|
+
}
|
|
32
|
+
parts.push(type(column.type));
|
|
33
|
+
if (!column.nullable)
|
|
34
|
+
parts.push('NOT NULL');
|
|
35
|
+
if (column.default !== null)
|
|
36
|
+
parts.push(`DEFAULT ${defaultExpr(column.default)}`);
|
|
37
|
+
return parts.join(' ');
|
|
38
|
+
}
|
|
39
|
+
function createTable(table) {
|
|
40
|
+
const columns = Object.values(table.columns).map((c) => columnDdl(c, table.primaryKey));
|
|
41
|
+
const needsPk = !(table.primaryKey.length === 1 && table.columns[table.primaryKey[0] ?? '']?.identity);
|
|
42
|
+
if (needsPk && table.primaryKey.length > 0)
|
|
43
|
+
columns.push(`PRIMARY KEY (${table.primaryKey.map((c) => id(c)).join(', ')})`);
|
|
44
|
+
const partition = table.partition === undefined
|
|
45
|
+
? ''
|
|
46
|
+
: ` PARTITION BY ${table.partition.by.toUpperCase()} (${id(table.partition.column)})`;
|
|
47
|
+
return `CREATE TABLE ${id(table.name)} (${columns.join(', ')})${partition}`;
|
|
48
|
+
}
|
|
49
|
+
/** Renders one operation as a statement. */
|
|
50
|
+
export function renderOperation(op) {
|
|
51
|
+
switch (op.kind) {
|
|
52
|
+
case 'createExtension':
|
|
53
|
+
if (!METHOD.test(op.name))
|
|
54
|
+
throw new MigrationError(`${JSON.stringify(op.name)} is not an extension name.`, 'Extension names are lower-case identifiers.');
|
|
55
|
+
return `CREATE EXTENSION IF NOT EXISTS ${id(op.name)}`;
|
|
56
|
+
case 'createTable':
|
|
57
|
+
return createTable(op.table);
|
|
58
|
+
case 'dropTable':
|
|
59
|
+
return `DROP TABLE ${id(op.table)}`;
|
|
60
|
+
case 'addColumn':
|
|
61
|
+
return `ALTER TABLE ${id(op.table)} ADD COLUMN ${columnDdl(op.column, [])}`;
|
|
62
|
+
case 'dropColumn':
|
|
63
|
+
return `ALTER TABLE ${id(op.table)} DROP COLUMN ${id(op.column)}`;
|
|
64
|
+
case 'alterType':
|
|
65
|
+
return `ALTER TABLE ${id(op.table)} ALTER COLUMN ${id(op.column)} TYPE ${type(op.to)}`;
|
|
66
|
+
case 'setDefault':
|
|
67
|
+
return `ALTER TABLE ${id(op.table)} ALTER COLUMN ${id(op.column)} SET DEFAULT ${defaultExpr(op.default)}`;
|
|
68
|
+
case 'dropDefault':
|
|
69
|
+
return `ALTER TABLE ${id(op.table)} ALTER COLUMN ${id(op.column)} DROP DEFAULT`;
|
|
70
|
+
case 'backfill':
|
|
71
|
+
return `UPDATE ${id(op.table)} SET ${id(op.column)} = ${defaultExpr(op.default)} WHERE ${id(op.column)} IS NULL`;
|
|
72
|
+
case 'setNotNull':
|
|
73
|
+
return `ALTER TABLE ${id(op.table)} ALTER COLUMN ${id(op.column)} SET NOT NULL`;
|
|
74
|
+
case 'dropNotNull':
|
|
75
|
+
return `ALTER TABLE ${id(op.table)} ALTER COLUMN ${id(op.column)} DROP NOT NULL`;
|
|
76
|
+
case 'addForeignKey':
|
|
77
|
+
return `ALTER TABLE ${id(op.table)} ADD CONSTRAINT ${id(op.name)} FOREIGN KEY (${id(op.foreignKey.column)}) REFERENCES ${id(op.foreignKey.references)} (${id('id')}) ON DELETE ${op.foreignKey.onDelete}`;
|
|
78
|
+
case 'addUnique':
|
|
79
|
+
return `ALTER TABLE ${id(op.table)} ADD CONSTRAINT ${id(op.name)} UNIQUE (${op.columns.map((c) => id(c)).join(', ')})`;
|
|
80
|
+
case 'addCheck':
|
|
81
|
+
return `ALTER TABLE ${id(op.table)} ADD CONSTRAINT ${id(op.name)} CHECK (${op.expression})`;
|
|
82
|
+
case 'dropConstraint':
|
|
83
|
+
return `ALTER TABLE ${id(op.table)} DROP CONSTRAINT ${id(op.name)}`;
|
|
84
|
+
case 'createIndex': {
|
|
85
|
+
const { index } = op;
|
|
86
|
+
if (!METHOD.test(index.method))
|
|
87
|
+
throw new MigrationError(`${JSON.stringify(index.method)} is not an index method.`, 'Use btree, gin, gist or brin.');
|
|
88
|
+
const columns = index.columns
|
|
89
|
+
.map((c) => (index.opclass === undefined ? id(c) : `${id(c)} ${id(index.opclass)}`))
|
|
90
|
+
.join(', ');
|
|
91
|
+
const where = index.where === undefined ? '' : ` WHERE ${index.where}`;
|
|
92
|
+
return `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${id(op.name)} ON ${id(op.table)} USING ${index.method} (${columns})${where}`;
|
|
93
|
+
}
|
|
94
|
+
case 'dropIndex':
|
|
95
|
+
return `DROP INDEX ${id(op.name)}`;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Renders every operation, in order. */
|
|
99
|
+
export function renderOperations(operations) {
|
|
100
|
+
return operations.map(renderOperation);
|
|
101
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The intended database schema, derived from a registry (RFC 0001 §7.5 naming, RFC 0002 origins). The same shape
|
|
3
|
+
* describes the live schema read from `pg_catalog`, so the two can be diffed directly.
|
|
4
|
+
*/
|
|
5
|
+
import { type Registry } from '../core/index.js';
|
|
6
|
+
/** A column as PostgreSQL reports it (`format_type`), e.g. `numeric(32,2)`, `timestamp with time zone`. */
|
|
7
|
+
export interface ColumnSpec {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly type: string;
|
|
10
|
+
readonly nullable: boolean;
|
|
11
|
+
/** Database-level default expression (`true`, `1`, `now()`), or `null`. */
|
|
12
|
+
readonly default: string | null;
|
|
13
|
+
readonly identity: boolean;
|
|
14
|
+
/** Literal used to backfill existing rows when the column becomes NOT NULL (desired schema only). */
|
|
15
|
+
readonly backfill: string | null;
|
|
16
|
+
}
|
|
17
|
+
/** A foreign key. */
|
|
18
|
+
export interface ForeignKeySpec {
|
|
19
|
+
readonly column: string;
|
|
20
|
+
readonly references: string;
|
|
21
|
+
readonly onDelete: 'RESTRICT' | 'CASCADE' | 'SET NULL' | 'NO ACTION';
|
|
22
|
+
}
|
|
23
|
+
/** An index. */
|
|
24
|
+
export interface IndexSpec {
|
|
25
|
+
readonly columns: readonly string[];
|
|
26
|
+
readonly unique: boolean;
|
|
27
|
+
readonly method: string;
|
|
28
|
+
readonly opclass?: string;
|
|
29
|
+
readonly where?: string;
|
|
30
|
+
}
|
|
31
|
+
/** A table. Constraint and index names are the keys. */
|
|
32
|
+
export interface TableSpec {
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly columns: Readonly<Record<string, ColumnSpec>>;
|
|
35
|
+
readonly primaryKey: readonly string[];
|
|
36
|
+
readonly foreignKeys: Readonly<Record<string, ForeignKeySpec>>;
|
|
37
|
+
readonly uniques: Readonly<Record<string, readonly string[]>>;
|
|
38
|
+
/** Check constraints by name. Expressions are compared by name only (PostgreSQL normalizes them). */
|
|
39
|
+
readonly checks: Readonly<Record<string, string>>;
|
|
40
|
+
readonly indexes: Readonly<Record<string, IndexSpec>>;
|
|
41
|
+
/** `PARTITION BY` of a partitioned table (RFC 0015 §7.2). Partitions themselves are not diffed. */
|
|
42
|
+
readonly partition?: {
|
|
43
|
+
readonly by: 'range' | 'list' | 'hash';
|
|
44
|
+
readonly column: string;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** A whole schema: tables by name, plus required extensions. */
|
|
48
|
+
export interface Schema {
|
|
49
|
+
readonly tables: Readonly<Record<string, TableSpec>>;
|
|
50
|
+
readonly extensions: readonly string[];
|
|
51
|
+
}
|
|
52
|
+
/** The schema as read from the database (same shape). */
|
|
53
|
+
export type LiveSchema = Schema;
|
|
54
|
+
/** Maps the builders' type spellings to `format_type` output. */
|
|
55
|
+
export declare function canonicalType(pgType: string): string;
|
|
56
|
+
/** A SQL literal for a backfill (`'x'`, `1`, `true`). */
|
|
57
|
+
export declare function literalOf(value: unknown): string | null;
|
|
58
|
+
/** Builds the intended schema for every model in the registry. */
|
|
59
|
+
export declare function desiredSchema(registry: Registry): Schema;
|
|
60
|
+
/** Column name of a field key, as `defineModel` derives it (exported for callers building names). */
|
|
61
|
+
export declare function columnName(key: string, many2one: boolean): string;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The intended database schema, derived from a registry (RFC 0001 §7.5 naming, RFC 0002 origins). The same shape
|
|
3
|
+
* describes the live schema read from `pg_catalog`, so the two can be diffed directly.
|
|
4
|
+
*/
|
|
5
|
+
import { columnDefault, junctionTable, snakeCase, targetOf, } from '../core/index.js';
|
|
6
|
+
import { compile } from '../sql/index.js';
|
|
7
|
+
import { MigrationError } from './errors.js';
|
|
8
|
+
/** Maps the builders' type spellings to `format_type` output. */
|
|
9
|
+
export function canonicalType(pgType) {
|
|
10
|
+
const m = /^varchar\((\d+)\)$/.exec(pgType);
|
|
11
|
+
if (m)
|
|
12
|
+
return `character varying(${m[1]})`;
|
|
13
|
+
if (pgType === 'timestamptz')
|
|
14
|
+
return 'timestamp with time zone';
|
|
15
|
+
return pgType.replace(/\s+/g, ' ').replace(/numeric\((\d+), ?(\d+)\)/, 'numeric($1,$2)');
|
|
16
|
+
}
|
|
17
|
+
/** A SQL literal for a backfill (`'x'`, `1`, `true`). */
|
|
18
|
+
export function literalOf(value) {
|
|
19
|
+
if (typeof value === 'boolean')
|
|
20
|
+
return value ? 'true' : 'false';
|
|
21
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
22
|
+
return String(value);
|
|
23
|
+
if (typeof value === 'string')
|
|
24
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
25
|
+
if (typeof value === 'object' &&
|
|
26
|
+
value !== null &&
|
|
27
|
+
typeof value.toFixed === 'function')
|
|
28
|
+
return `'${value.toFixed()}'`;
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
function fragmentText(fragment, what) {
|
|
32
|
+
const compiled = compile(fragment);
|
|
33
|
+
if (compiled.params.length > 0) {
|
|
34
|
+
throw new MigrationError(`${what} contains ${compiled.params.length} parameter(s).`, 'DDL cannot take bind parameters: write the expression with literals only, e.g. sql`amount >= 0`.');
|
|
35
|
+
}
|
|
36
|
+
return compiled.text;
|
|
37
|
+
}
|
|
38
|
+
function columnOf(key, field, column) {
|
|
39
|
+
if (key === 'id')
|
|
40
|
+
return {
|
|
41
|
+
name: column,
|
|
42
|
+
type: 'bigint',
|
|
43
|
+
nullable: false,
|
|
44
|
+
default: null,
|
|
45
|
+
identity: true,
|
|
46
|
+
backfill: null,
|
|
47
|
+
};
|
|
48
|
+
const type = field.kind === 'many2one' ? 'bigint' : canonicalType(field.pgType);
|
|
49
|
+
const dbDefault = columnDefault(key, field);
|
|
50
|
+
const backfill = typeof field.default === 'function' ? null : literalOf(field.default);
|
|
51
|
+
return {
|
|
52
|
+
name: column,
|
|
53
|
+
type,
|
|
54
|
+
nullable: !field.required || field.computed, // stored computes are filled after insert (RFC 0008 §7.6)
|
|
55
|
+
default: dbDefault,
|
|
56
|
+
identity: false,
|
|
57
|
+
backfill,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
const ON_DELETE = {
|
|
61
|
+
restrict: 'RESTRICT',
|
|
62
|
+
cascade: 'CASCADE',
|
|
63
|
+
'set null': 'SET NULL',
|
|
64
|
+
};
|
|
65
|
+
/** Builds the intended schema for every model in the registry. */
|
|
66
|
+
export function desiredSchema(registry) {
|
|
67
|
+
const tables = {};
|
|
68
|
+
const extensions = new Set();
|
|
69
|
+
for (const { model } of registry.models.values()) {
|
|
70
|
+
const columns = {};
|
|
71
|
+
const foreignKeys = {};
|
|
72
|
+
const indexes = {};
|
|
73
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
74
|
+
const column = model.columns[key];
|
|
75
|
+
if (column === undefined) {
|
|
76
|
+
if (field.kind === 'many2many') {
|
|
77
|
+
const target = registry.get(targetOf(field) ?? '').model;
|
|
78
|
+
const j = junctionTable(model, field, target);
|
|
79
|
+
tables[j.table] = {
|
|
80
|
+
name: j.table,
|
|
81
|
+
columns: {
|
|
82
|
+
[j.sourceColumn]: {
|
|
83
|
+
name: j.sourceColumn,
|
|
84
|
+
type: 'bigint',
|
|
85
|
+
nullable: false,
|
|
86
|
+
default: null,
|
|
87
|
+
identity: false,
|
|
88
|
+
backfill: null,
|
|
89
|
+
},
|
|
90
|
+
[j.targetColumn]: {
|
|
91
|
+
name: j.targetColumn,
|
|
92
|
+
type: 'bigint',
|
|
93
|
+
nullable: false,
|
|
94
|
+
default: null,
|
|
95
|
+
identity: false,
|
|
96
|
+
backfill: null,
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
primaryKey: [j.sourceColumn, j.targetColumn],
|
|
100
|
+
foreignKeys: {
|
|
101
|
+
[`${j.table}_${j.sourceColumn}_fkey`]: {
|
|
102
|
+
column: j.sourceColumn,
|
|
103
|
+
references: j.sourceTable,
|
|
104
|
+
onDelete: 'CASCADE',
|
|
105
|
+
},
|
|
106
|
+
[`${j.table}_${j.targetColumn}_fkey`]: {
|
|
107
|
+
column: j.targetColumn,
|
|
108
|
+
references: j.targetTable,
|
|
109
|
+
onDelete: 'CASCADE',
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
uniques: {},
|
|
113
|
+
checks: {},
|
|
114
|
+
indexes: {},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
columns[column] = columnOf(key, field, column);
|
|
120
|
+
if (field.kind === 'many2one') {
|
|
121
|
+
const target = registry.get(targetOf(field) ?? '').model;
|
|
122
|
+
foreignKeys[`${model.table}_${column}_fkey`] = {
|
|
123
|
+
column,
|
|
124
|
+
references: target.table,
|
|
125
|
+
onDelete: ON_DELETE[field.ondelete] ?? 'RESTRICT',
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
if (field.index !== undefined && key !== 'id') {
|
|
129
|
+
const name = `${model.table}_${column}_idx`;
|
|
130
|
+
if (field.index === 'trigram') {
|
|
131
|
+
extensions.add('pg_trgm');
|
|
132
|
+
indexes[name] = {
|
|
133
|
+
columns: [column],
|
|
134
|
+
unique: false,
|
|
135
|
+
method: 'gin',
|
|
136
|
+
opclass: 'gin_trgm_ops',
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
else if (field.index === 'brin')
|
|
140
|
+
indexes[name] = { columns: [column], unique: false, method: 'brin' };
|
|
141
|
+
else
|
|
142
|
+
indexes[name] = { columns: [column], unique: field.index === 'unique', method: 'btree' };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
for (const index of model.indexes) {
|
|
146
|
+
indexes[index.name] = {
|
|
147
|
+
columns: [...index.columns],
|
|
148
|
+
unique: index.unique,
|
|
149
|
+
method: index.method,
|
|
150
|
+
...(index.where === undefined
|
|
151
|
+
? {}
|
|
152
|
+
: { where: fragmentText(index.where, `index ${index.name}`) }),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
const uniques = {};
|
|
156
|
+
const checks = {};
|
|
157
|
+
for (const c of model.sqlConstraints) {
|
|
158
|
+
if (c.kind === 'unique') {
|
|
159
|
+
if (c.where !== undefined) {
|
|
160
|
+
// A partial unique constraint is a unique partial index in PostgreSQL.
|
|
161
|
+
indexes[c.name] = {
|
|
162
|
+
columns: [...c.columns],
|
|
163
|
+
unique: true,
|
|
164
|
+
method: 'btree',
|
|
165
|
+
where: fragmentText(c.where, `constraint ${c.name}`),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
else
|
|
169
|
+
uniques[c.name] = [...c.columns];
|
|
170
|
+
}
|
|
171
|
+
else if (c.check !== undefined)
|
|
172
|
+
checks[c.name] = fragmentText(c.check, `constraint ${c.name}`);
|
|
173
|
+
}
|
|
174
|
+
tables[model.table] = {
|
|
175
|
+
name: model.table,
|
|
176
|
+
columns,
|
|
177
|
+
primaryKey: model.partition === undefined ? ['id'] : ['id', model.columns[model.partition.key] ?? ''],
|
|
178
|
+
foreignKeys,
|
|
179
|
+
uniques,
|
|
180
|
+
checks,
|
|
181
|
+
indexes,
|
|
182
|
+
...(model.partition === undefined
|
|
183
|
+
? {}
|
|
184
|
+
: {
|
|
185
|
+
partition: { by: model.partition.by, column: model.columns[model.partition.key] ?? '' },
|
|
186
|
+
}),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
return { tables, extensions: [...extensions].sort() };
|
|
190
|
+
}
|
|
191
|
+
/** Column name of a field key, as `defineModel` derives it (exported for callers building names). */
|
|
192
|
+
export function columnName(key, many2one) {
|
|
193
|
+
const snake = snakeCase(key);
|
|
194
|
+
return many2one ? `${snake}_id` : snake;
|
|
195
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** A security group. `implies` are inherited: a member of `sale.manager` is also a member of `sale.user`. */
|
|
2
|
+
export interface GroupDefinition {
|
|
3
|
+
/** `module.name`, e.g. `'sale.user'`. */
|
|
4
|
+
readonly code: string;
|
|
5
|
+
readonly label: string;
|
|
6
|
+
readonly implies: readonly string[];
|
|
7
|
+
}
|
|
8
|
+
export declare const GROUP_CODE: RegExp;
|
|
9
|
+
/** A security declaration that cannot be used. */
|
|
10
|
+
export declare class SecurityDefinitionError extends Error {
|
|
11
|
+
readonly hint: string;
|
|
12
|
+
constructor(problem: string, hint: string);
|
|
13
|
+
}
|
|
14
|
+
/** Validates a group. */
|
|
15
|
+
export declare function defineGroup(input: {
|
|
16
|
+
readonly code: string;
|
|
17
|
+
readonly label?: string;
|
|
18
|
+
readonly implies?: readonly string[];
|
|
19
|
+
}): GroupDefinition;
|
|
20
|
+
/** The transitive closure of `codes` over `implies` (unknown codes are kept as given). */
|
|
21
|
+
export declare function groupClosure(groups: ReadonlyMap<string, GroupDefinition>, codes: Iterable<string>): Set<string>;
|
|
22
|
+
/** What a group may do with a model. */
|
|
23
|
+
export type Perm = 'read' | 'write' | 'create' | 'unlink' | 'export' | 'import';
|
|
24
|
+
export declare const PERMS: readonly Perm[];
|
|
25
|
+
/** Group code → permissions. Absence means denied (default deny, RFC 0014 §7.2). */
|
|
26
|
+
export type AccessSpec = Readonly<Record<string, readonly Perm[]>>;
|
|
27
|
+
/** Validates an access declaration. */
|
|
28
|
+
export declare function assertAccessSpec(spec: AccessSpec, where: string): void;
|
|
29
|
+
/** True when any of the user's (closed) groups grants `perm`. */
|
|
30
|
+
export declare function allowed(spec: AccessSpec, groups: ReadonlySet<string>, perm: Perm): boolean;
|
|
31
|
+
/** Merges access declarations (an extension adds permissions, never removes). */
|
|
32
|
+
export declare function mergeAccess(base: AccessSpec, extra: AccessSpec): AccessSpec;
|
|
33
|
+
/** Operations a rule can restrict. */
|
|
34
|
+
export type RulePerm = 'read' | 'write' | 'create' | 'unlink';
|
|
35
|
+
/** A record rule: a domain over the model with `{ $env: ... }` placeholders (RFC 0005 §7.1). */
|
|
36
|
+
export interface RuleSpec {
|
|
37
|
+
/** Group codes the rule applies to, or `'global'` for everyone (including users with other rules). */
|
|
38
|
+
readonly groups: readonly string[] | 'global';
|
|
39
|
+
readonly perms: readonly RulePerm[];
|
|
40
|
+
/** The domain (serializable; `{ $env: 'uid' | 'companyId' | 'companyIds' }` where a value goes). */
|
|
41
|
+
readonly domain: Readonly<Record<string, unknown>>;
|
|
42
|
+
readonly label?: string;
|
|
43
|
+
}
|
|
44
|
+
/** Validates a rule. */
|
|
45
|
+
export declare function assertRuleSpec(rule: RuleSpec, where: string): void;
|
|
46
|
+
/** The rules that apply to a user for an operation: globals (ANDed) and group rules (ORed). */
|
|
47
|
+
export interface ApplicableRules {
|
|
48
|
+
readonly globals: readonly RuleSpec[];
|
|
49
|
+
readonly groupRules: readonly RuleSpec[];
|
|
50
|
+
/** True when at least one group rule for the operation exists in the model at all (then users without any applicable group rule are unrestricted by group rules, as in Odoo). */
|
|
51
|
+
readonly hasGroupRules: boolean;
|
|
52
|
+
}
|
|
53
|
+
/** Splits a model's rules for `perm` into what applies to `groups` (RFC 0014 §7.3). */
|
|
54
|
+
export declare function applicableRules(rules: Readonly<Record<string, RuleSpec>>, groups: ReadonlySet<string>, perm: RulePerm): ApplicableRules;
|
|
55
|
+
/** The environment values placeholders may name. */
|
|
56
|
+
export interface PlaceholderEnv {
|
|
57
|
+
readonly uid: number;
|
|
58
|
+
readonly companyId: number;
|
|
59
|
+
readonly companyIds: readonly number[];
|
|
60
|
+
}
|
|
61
|
+
/** Replaces `{ $env: name }` objects in a domain with the environment's values. */
|
|
62
|
+
export declare function resolvePlaceholders(domain: unknown, env: PlaceholderEnv): unknown;
|
|
63
|
+
/** Who may read / write a field. Empty means everyone with model access. */
|
|
64
|
+
export interface FieldGroups {
|
|
65
|
+
readonly read: readonly string[];
|
|
66
|
+
readonly write: readonly string[];
|
|
67
|
+
}
|
|
68
|
+
/** `groups: ['hr.manager']` (both) or `{ read: [...], write: [...] }`. */
|
|
69
|
+
export type FieldGroupsInput = readonly string[] | {
|
|
70
|
+
readonly read?: readonly string[];
|
|
71
|
+
readonly write?: readonly string[];
|
|
72
|
+
};
|
|
73
|
+
/** Normalizes a field's groups option. */
|
|
74
|
+
export declare function normalizeFieldGroups(input: FieldGroupsInput | undefined): FieldGroups;
|
|
75
|
+
/** True when the field has no restriction for `kind` or the user is in one of its groups. */
|
|
76
|
+
export declare function fieldAllowed(groups: FieldGroups, userGroups: ReadonlySet<string>, kind: 'read' | 'write'): boolean;
|
|
77
|
+
/** The session settings `shutro.run()` pushes (RFC 0003 §7.1) and RLS policies read. */
|
|
78
|
+
export declare const RLS_SETTINGS: Readonly<{
|
|
79
|
+
user: string;
|
|
80
|
+
company: string;
|
|
81
|
+
companies: string;
|
|
82
|
+
groups: string;
|
|
83
|
+
su: string;
|
|
84
|
+
}>;
|
|
85
|
+
/** SQL expressions for the placeholders, reading the session settings. */
|
|
86
|
+
export declare const RLS_PLACEHOLDERS: Readonly<Record<'uid' | 'companyId' | 'companyIds', string>>;
|
|
87
|
+
/** `true` when the session is a superuser scope. */
|
|
88
|
+
export declare const RLS_SU: string;
|
|
89
|
+
/** `true` when the session's groups intersect `codes`. */
|
|
90
|
+
export declare function rlsGroupCondition(codes: readonly string[]): string;
|
|
91
|
+
/** A policy to create. */
|
|
92
|
+
export interface PolicyInput {
|
|
93
|
+
readonly table: string;
|
|
94
|
+
readonly name: string;
|
|
95
|
+
readonly command: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE';
|
|
96
|
+
readonly permissive: boolean;
|
|
97
|
+
/** Boolean SQL over the table's columns and the session settings. */
|
|
98
|
+
readonly condition: string;
|
|
99
|
+
}
|
|
100
|
+
/** The DDL enabling RLS on a table and installing policies (idempotent: policies are dropped and recreated). */
|
|
101
|
+
export declare function rlsStatements(table: string, policies: readonly PolicyInput[]): string[];
|
|
102
|
+
/** Keys live in the application (env vars, a KMS), never in the database (RFC 0014 §7.6). */
|
|
103
|
+
export interface KeyRing {
|
|
104
|
+
/** The id new writes encrypt with. */
|
|
105
|
+
readonly current: string;
|
|
106
|
+
/** Every key still needed to decrypt stored values. 32 bytes each (raw or base64). */
|
|
107
|
+
readonly keys: Readonly<Record<string, Uint8Array | string>>;
|
|
108
|
+
}
|
|
109
|
+
/** Encryption failed or a token cannot be decrypted. */
|
|
110
|
+
export declare class EncryptionError extends Error {
|
|
111
|
+
readonly hint: string;
|
|
112
|
+
constructor(problem: string, hint: string, options?: {
|
|
113
|
+
readonly cause?: unknown;
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/** Validates a key ring. */
|
|
117
|
+
export declare function createKeyRing(ring: KeyRing): KeyRing;
|
|
118
|
+
/** AES-256-GCM; the token names the key so rotation only changes `current`. */
|
|
119
|
+
export declare function encrypt(ring: KeyRing, plaintext: string): string;
|
|
120
|
+
/** True for a value produced by {@link encrypt}. */
|
|
121
|
+
export declare function isEncrypted(value: unknown): value is string;
|
|
122
|
+
/** Decrypts a token; a wrong key or a tampered token is an {@link EncryptionError}. */
|
|
123
|
+
export declare function decrypt(ring: KeyRing, token: string): string;
|