@g9tm/lynxcontrols-sqlite 1.4.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/README.md +12 -0
- package/contract/cases.json +463 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/codecs/codecs.d.ts +68 -0
- package/dist/codecs/codecs.d.ts.map +1 -0
- package/dist/codecs/codecs.js +201 -0
- package/dist/codecs/codecs.js.map +1 -0
- package/dist/contract/run-contract.d.ts +94 -0
- package/dist/contract/run-contract.d.ts.map +1 -0
- package/dist/contract/run-contract.js +159 -0
- package/dist/contract/run-contract.js.map +1 -0
- package/dist/driver/types.d.ts +87 -0
- package/dist/driver/types.d.ts.map +1 -0
- package/dist/driver/types.js +14 -0
- package/dist/driver/types.js.map +1 -0
- package/dist/errors.d.ts +39 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +57 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +22 -0
- package/dist/query/builders.d.ts +216 -0
- package/dist/query/builders.d.ts.map +1 -0
- package/dist/query/builders.js +490 -0
- package/dist/query/builders.js.map +1 -0
- package/dist/query/compile.d.ts +42 -0
- package/dist/query/compile.d.ts.map +1 -0
- package/dist/query/compile.js +307 -0
- package/dist/query/compile.js.map +1 -0
- package/dist/query/expr.d.ts +201 -0
- package/dist/query/expr.d.ts.map +1 -0
- package/dist/query/expr.js +247 -0
- package/dist/query/expr.js.map +1 -0
- package/dist/repo/audit.d.ts +19 -0
- package/dist/repo/audit.d.ts.map +1 -0
- package/dist/repo/audit.js +36 -0
- package/dist/repo/audit.js.map +1 -0
- package/dist/repo/repository.d.ts +233 -0
- package/dist/repo/repository.d.ts.map +1 -0
- package/dist/repo/repository.js +715 -0
- package/dist/repo/repository.js.map +1 -0
- package/dist/schema/columns.d.ts +115 -0
- package/dist/schema/columns.d.ts.map +1 -0
- package/dist/schema/columns.js +112 -0
- package/dist/schema/columns.js.map +1 -0
- package/dist/schema/entity.d.ts +135 -0
- package/dist/schema/entity.d.ts.map +1 -0
- package/dist/schema/entity.js +227 -0
- package/dist/schema/entity.js.map +1 -0
- package/dist/schema/policies.d.ts +89 -0
- package/dist/schema/policies.d.ts.map +1 -0
- package/dist/schema/policies.js +54 -0
- package/dist/schema/policies.js.map +1 -0
- package/dist/session/ambient.d.ts +32 -0
- package/dist/session/ambient.d.ts.map +1 -0
- package/dist/session/ambient.js +28 -0
- package/dist/session/ambient.js.map +1 -0
- package/dist/session/cache.d.ts +62 -0
- package/dist/session/cache.d.ts.map +1 -0
- package/dist/session/cache.js +239 -0
- package/dist/session/cache.js.map +1 -0
- package/dist/session/database.d.ts +221 -0
- package/dist/session/database.d.ts.map +1 -0
- package/dist/session/database.js +430 -0
- package/dist/session/database.js.map +1 -0
- package/dist/session/locator.d.ts +33 -0
- package/dist/session/locator.d.ts.map +1 -0
- package/dist/session/locator.js +39 -0
- package/dist/session/locator.js.map +1 -0
- package/dist/session/migrations.d.ts +75 -0
- package/dist/session/migrations.d.ts.map +1 -0
- package/dist/session/migrations.js +88 -0
- package/dist/session/migrations.js.map +1 -0
- package/dist/session/mutex.d.ts +7 -0
- package/dist/session/mutex.d.ts.map +1 -0
- package/dist/session/mutex.js +27 -0
- package/dist/session/mutex.js.map +1 -0
- package/dist/session/rows.d.ts +17 -0
- package/dist/session/rows.d.ts.map +1 -0
- package/dist/session/rows.js +52 -0
- package/dist/session/rows.js.map +1 -0
- package/dist/session/schema-setup.d.ts +21 -0
- package/dist/session/schema-setup.d.ts.map +1 -0
- package/dist/session/schema-setup.js +227 -0
- package/dist/session/schema-setup.js.map +1 -0
- package/dist/session/scope.d.ts +117 -0
- package/dist/session/scope.d.ts.map +1 -0
- package/dist/session/scope.js +233 -0
- package/dist/session/scope.js.map +1 -0
- package/dist/session/write-hooks.d.ts +84 -0
- package/dist/session/write-hooks.d.ts.map +1 -0
- package/dist/session/write-hooks.js +55 -0
- package/dist/session/write-hooks.js.map +1 -0
- package/dist/values/ids.d.ts +46 -0
- package/dist/values/ids.d.ts.map +1 -0
- package/dist/values/ids.js +84 -0
- package/dist/values/ids.js.map +1 -0
- package/dist/values/int64.d.ts +33 -0
- package/dist/values/int64.d.ts.map +1 -0
- package/dist/values/int64.js +105 -0
- package/dist/values/int64.js.map +1 -0
- package/dist/values/local-date-time.d.ts +61 -0
- package/dist/values/local-date-time.d.ts.map +1 -0
- package/dist/values/local-date-time.js +122 -0
- package/dist/values/local-date-time.js.map +1 -0
- package/dist/values/sql-value.d.ts +36 -0
- package/dist/values/sql-value.d.ts.map +1 -0
- package/dist/values/sql-value.js +70 -0
- package/dist/values/sql-value.js.map +1 -0
- package/package.json +27 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { G9AbortSignal } from '@g9tm/lynxcontrols-foundation';
|
|
2
|
+
import type { G9EntityDescriptor } from '../schema/entity.js';
|
|
3
|
+
/** What a migration or initializer works with (MAUI `IG9SqliteMigrationContext`), inside its transaction. */
|
|
4
|
+
export interface G9MigrationContext {
|
|
5
|
+
/** MAUI `ExecuteAsync`: DDL or DML; returns changed rows. */
|
|
6
|
+
execute(sql: string, ...params: unknown[]): Promise<number>;
|
|
7
|
+
/** MAUI `QueryAsync<T>`: rows as records (int64 beyond 2^53 as decimal strings, BLOBs as ArrayBuffer). */
|
|
8
|
+
query(sql: string, ...params: unknown[]): Promise<Record<string, unknown>[]>;
|
|
9
|
+
/** MAUI `ColumnExistsAsync`. */
|
|
10
|
+
columnExists(table: string, column: string): Promise<boolean>;
|
|
11
|
+
/** MAUI `TableExistsAsync`. */
|
|
12
|
+
tableExists(table: string): Promise<boolean>;
|
|
13
|
+
/** `CREATE TABLE IF NOT EXISTS` from an entity descriptor (GUID columns `COLLATE NOCASE`, key, types). */
|
|
14
|
+
createTable(entity: G9EntityDescriptor): Promise<void>;
|
|
15
|
+
/** Creates the entity's declared indexes (N07); fails with an actionable error when existing rows violate one. */
|
|
16
|
+
createIndexes(entity: G9EntityDescriptor): Promise<void>;
|
|
17
|
+
readonly signal: G9AbortSignal | undefined;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* One ordered schema change (MAUI `IG9SqliteMigration` and the legacy `ISqliteMigration`; one runner survives).
|
|
21
|
+
* `version` is explicit; gaps are fine; duplicates are rejected when the database is created. Applied versions are
|
|
22
|
+
* recorded with a checksum in `g9lynx_schema_history`; a changed checksum of an applied migration fails the open.
|
|
23
|
+
*/
|
|
24
|
+
export interface G9Migration {
|
|
25
|
+
readonly version: number;
|
|
26
|
+
readonly name: string;
|
|
27
|
+
/** Change detection for an applied migration. Computed from `sql` when given; otherwise supply one. */
|
|
28
|
+
readonly checksum: string;
|
|
29
|
+
/** `false` for statements SQLite refuses inside a transaction (VACUUM, journal_mode). Default `true`. */
|
|
30
|
+
readonly transactional: boolean;
|
|
31
|
+
/** May return anything (a promise is awaited); the value is ignored. */
|
|
32
|
+
up(context: G9MigrationContext): unknown;
|
|
33
|
+
}
|
|
34
|
+
/** Runs after successful migrations (MAUI `IG9SqliteInitializer`). `once` is recorded; `everyOpen` runs each open. */
|
|
35
|
+
export interface G9Initializer {
|
|
36
|
+
readonly name: string;
|
|
37
|
+
readonly mode: 'once' | 'everyOpen';
|
|
38
|
+
/** May return anything (a promise is awaited); the value is ignored. */
|
|
39
|
+
run(context: G9MigrationContext): unknown;
|
|
40
|
+
}
|
|
41
|
+
/** FNV-1a 64-bit over UTF-16 code units, as 16 hex digits (two 32-bit halves; no BigInt). */
|
|
42
|
+
export declare function checksumText(text: string): string;
|
|
43
|
+
/**
|
|
44
|
+
* Defines a migration. Give `sql` (statements run in order; the checksum is derived from them) or `up` with an
|
|
45
|
+
* explicit `checksum` (bump it whenever the code changes meaning).
|
|
46
|
+
*/
|
|
47
|
+
export declare function defineMigration(definition: {
|
|
48
|
+
version: number;
|
|
49
|
+
name: string;
|
|
50
|
+
sql: readonly string[];
|
|
51
|
+
transactional?: boolean;
|
|
52
|
+
} | {
|
|
53
|
+
version: number;
|
|
54
|
+
name: string;
|
|
55
|
+
checksum: string;
|
|
56
|
+
up: G9Migration['up'];
|
|
57
|
+
transactional?: boolean;
|
|
58
|
+
}): G9Migration;
|
|
59
|
+
/** Defines an initializer (`once` by default: a durable, recorded seed). */
|
|
60
|
+
export declare function defineInitializer(definition: {
|
|
61
|
+
name: string;
|
|
62
|
+
mode?: 'once' | 'everyOpen';
|
|
63
|
+
run: G9Initializer['run'];
|
|
64
|
+
}): G9Initializer;
|
|
65
|
+
/** MAUI `SqliteMigrationRunner.GetLatestRegisteredVersion`: the highest registered version, or `null`. */
|
|
66
|
+
export declare function latestMigrationVersion(migrations: readonly G9Migration[]): number | null;
|
|
67
|
+
/** Validates and sorts a migration list (duplicate versions and names are configuration errors). */
|
|
68
|
+
export declare function sortMigrations(migrations: readonly G9Migration[]): readonly G9Migration[];
|
|
69
|
+
/** The G9 history table (never `PRAGMA user_version`, which G9SyncData may own). */
|
|
70
|
+
export declare const G9_SCHEMA_HISTORY_TABLE = "g9lynx_schema_history";
|
|
71
|
+
/** DDL of the schema-history table (applied migrations and initializers, with checksums). */
|
|
72
|
+
export declare const G9_SCHEMA_HISTORY_DDL: string;
|
|
73
|
+
/** Columns the history table must have; anything else under that name is a collision, not ours. */
|
|
74
|
+
export declare const G9_SCHEMA_HISTORY_COLUMNS: readonly ["Kind", "Key", "Version", "Name", "Checksum", "AppliedAt"];
|
|
75
|
+
//# sourceMappingURL=migrations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../../src/session/migrations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAEnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,6GAA6G;AAC7G,MAAM,WAAW,kBAAkB;IACjC,6DAA6D;IAC7D,OAAO,CAAC,GAAG,EAAE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|
+
let h3 = 0xcbf2;
|
|
7
|
+
for(let i = 0; i < text.length; i++){
|
|
8
|
+
h0 ^= text.charCodeAt(i);
|
|
9
|
+
const t0 = 0x1b3 * h0;
|
|
10
|
+
const t1 = 0x1b3 * h1;
|
|
11
|
+
const t2 = 0x1b3 * h2 + (h0 << 8);
|
|
12
|
+
const t3 = 0x1b3 * h3 + (h1 << 8);
|
|
13
|
+
const c1 = t1 + (t0 >>> 16);
|
|
14
|
+
const c2 = t2 + (c1 >>> 16);
|
|
15
|
+
h0 = 0xffff & t0;
|
|
16
|
+
h1 = 0xffff & c1;
|
|
17
|
+
h2 = 0xffff & c2;
|
|
18
|
+
h3 = t3 + (c2 >>> 16) & 0xffff;
|
|
19
|
+
}
|
|
20
|
+
const hex = (n)=>`000${n.toString(16)}`.slice(-4);
|
|
21
|
+
return hex(h3) + hex(h2) + hex(h1) + hex(h0);
|
|
22
|
+
}
|
|
23
|
+
function defineMigration(definition) {
|
|
24
|
+
if (!Number.isSafeInteger(definition.version) || definition.version < 1) throw new G9SqliteError('misuse', `Migration '${definition.name}': version must be an integer ≥ 1.`);
|
|
25
|
+
if ('string' != typeof definition.name || '' === definition.name.trim()) throw new G9SqliteError('misuse', `Migration ${definition.version} needs a name.`);
|
|
26
|
+
const transactional = false !== definition.transactional;
|
|
27
|
+
if ('sql' in definition) {
|
|
28
|
+
const statements = [
|
|
29
|
+
...definition.sql
|
|
30
|
+
];
|
|
31
|
+
return Object.freeze({
|
|
32
|
+
version: definition.version,
|
|
33
|
+
name: definition.name,
|
|
34
|
+
checksum: checksumText(statements.join('\n;\n')),
|
|
35
|
+
transactional,
|
|
36
|
+
async up (context) {
|
|
37
|
+
for (const sql of statements)await context.execute(sql);
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
if ('string' != typeof definition.checksum || '' === definition.checksum.trim()) throw new G9SqliteError('misuse', `Migration '${definition.name}': a code migration needs a checksum.`);
|
|
42
|
+
return Object.freeze({
|
|
43
|
+
version: definition.version,
|
|
44
|
+
name: definition.name,
|
|
45
|
+
checksum: definition.checksum,
|
|
46
|
+
transactional,
|
|
47
|
+
up: definition.up
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function defineInitializer(definition) {
|
|
51
|
+
var _definition_mode;
|
|
52
|
+
if ('string' != typeof definition.name || '' === definition.name.trim()) throw new G9SqliteError('misuse', 'An initializer needs a name.');
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
name: definition.name,
|
|
55
|
+
mode: null != (_definition_mode = definition.mode) ? _definition_mode : 'once',
|
|
56
|
+
run: definition.run
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function latestMigrationVersion(migrations) {
|
|
60
|
+
let max = null;
|
|
61
|
+
for (const m of migrations)if (null === max || m.version > max) max = m.version;
|
|
62
|
+
return max;
|
|
63
|
+
}
|
|
64
|
+
function sortMigrations(migrations) {
|
|
65
|
+
const sorted = [
|
|
66
|
+
...migrations
|
|
67
|
+
].sort((a, b)=>a.version - b.version);
|
|
68
|
+
for(let i = 1; i < sorted.length; i++)if (sorted[i].version === sorted[i - 1].version) throw new G9SqliteError('misuse', `Two migrations claim version ${sorted[i].version}: one would silently never run.`);
|
|
69
|
+
const names = new Set();
|
|
70
|
+
for (const i of migrations){
|
|
71
|
+
if (names.has(i.name)) throw new G9SqliteError('misuse', `Two migrations are named '${i.name}'.`);
|
|
72
|
+
names.add(i.name);
|
|
73
|
+
}
|
|
74
|
+
return Object.freeze(sorted);
|
|
75
|
+
}
|
|
76
|
+
const G9_SCHEMA_HISTORY_TABLE = 'g9lynx_schema_history';
|
|
77
|
+
const G9_SCHEMA_HISTORY_DDL = `CREATE TABLE IF NOT EXISTS "${G9_SCHEMA_HISTORY_TABLE}" ("Kind" TEXT NOT NULL, "Key" TEXT NOT NULL, "Version" INTEGER, "Name" TEXT NOT NULL, "Checksum" TEXT NOT NULL, "AppliedAt" TEXT NOT NULL, PRIMARY KEY ("Kind", "Key"))`;
|
|
78
|
+
const G9_SCHEMA_HISTORY_COLUMNS = [
|
|
79
|
+
'Kind',
|
|
80
|
+
'Key',
|
|
81
|
+
'Version',
|
|
82
|
+
'Name',
|
|
83
|
+
'Checksum',
|
|
84
|
+
'AppliedAt'
|
|
85
|
+
];
|
|
86
|
+
export { G9_SCHEMA_HISTORY_COLUMNS, G9_SCHEMA_HISTORY_DDL, G9_SCHEMA_HISTORY_TABLE, checksumText, defineInitializer, defineMigration, latestMigrationVersion, sortMigrations };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=migrations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session/migrations.js","sources":["../../src/session/migrations.ts"],"sourcesContent":["import type { G9AbortSignal } from '@g9tm/lynxcontrols-foundation';\nimport { G9SqliteError } from '../errors';\nimport type { G9EntityDescriptor } from '../schema/entity';\n\n/** What a migration or initializer works with (MAUI `IG9SqliteMigrationContext`), inside its transaction. */\nexport interface G9MigrationContext {\n /** MAUI `ExecuteAsync`: DDL or DML; returns changed rows. */\n execute(sql: string, ...params: unknown[]): Promise<number>;\n /** MAUI `QueryAsync<T>`: rows as records (int64 beyond 2^53 as decimal strings, BLOBs as ArrayBuffer). */\n query(sql: string, ...params: unknown[]): Promise<Record<string, unknown>[]>;\n /** MAUI `ColumnExistsAsync`. */\n columnExists(table: string, column: string): Promise<boolean>;\n /** MAUI `TableExistsAsync`. */\n tableExists(table: string): Promise<boolean>;\n /** `CREATE TABLE IF NOT EXISTS` from an entity descriptor (GUID columns `COLLATE NOCASE`, key, types). */\n createTable(entity: G9EntityDescriptor): Promise<void>;\n /** Creates the entity's declared indexes (N07); fails with an actionable error when existing rows violate one. */\n createIndexes(entity: G9EntityDescriptor): Promise<void>;\n readonly signal: G9AbortSignal | undefined;\n}\n\n/**\n * One ordered schema change (MAUI `IG9SqliteMigration` and the legacy `ISqliteMigration`; one runner survives).\n * `version` is explicit; gaps are fine; duplicates are rejected when the database is created. Applied versions are\n * recorded with a checksum in `g9lynx_schema_history`; a changed checksum of an applied migration fails the open.\n */\nexport interface G9Migration {\n readonly version: number;\n readonly name: string;\n /** Change detection for an applied migration. Computed from `sql` when given; otherwise supply one. */\n readonly checksum: string;\n /** `false` for statements SQLite refuses inside a transaction (VACUUM, journal_mode). Default `true`. */\n readonly transactional: boolean;\n /** May return anything (a promise is awaited); the value is ignored. */\n up(context: G9MigrationContext): unknown;\n}\n\n/** Runs after successful migrations (MAUI `IG9SqliteInitializer`). `once` is recorded; `everyOpen` runs each open. */\nexport interface G9Initializer {\n readonly name: string;\n readonly mode: 'once' | 'everyOpen';\n /** May return anything (a promise is awaited); the value is ignored. */\n run(context: G9MigrationContext): unknown;\n}\n\n/** FNV-1a 64-bit over UTF-16 code units, as 16 hex digits (two 32-bit halves; no BigInt). */\nexport function checksumText(text: string): string {\n let h0 = 0x2325;\n let h1 = 0x8422;\n let h2 = 0x9ce4;\n let h3 = 0xcbf2;\n for (let i = 0; i < text.length; i++) {\n h0 ^= text.charCodeAt(i);\n // multiply by the FNV prime 0x100000001b3 in 16-bit limbs\n const t0 = h0 * 0x1b3;\n const t1 = h1 * 0x1b3;\n const t2 = h2 * 0x1b3 + (h0 << 8);\n const t3 = h3 * 0x1b3 + (h1 << 8);\n const c1 = t1 + (t0 >>> 16);\n const c2 = t2 + (c1 >>> 16);\n h0 = t0 & 0xffff;\n h1 = c1 & 0xffff;\n h2 = c2 & 0xffff;\n h3 = (t3 + (c2 >>> 16)) & 0xffff;\n }\n const hex = (n: number) => `000${n.toString(16)}`.slice(-4);\n return hex(h3) + hex(h2) + hex(h1) + hex(h0);\n}\n\n/**\n * Defines a migration. Give `sql` (statements run in order; the checksum is derived from them) or `up` with an\n * explicit `checksum` (bump it whenever the code changes meaning).\n */\nexport function defineMigration(\n definition:\n | { version: number; name: string; sql: readonly string[]; transactional?: boolean }\n | { version: number; name: string; checksum: string; up: G9Migration['up']; transactional?: boolean },\n): G9Migration {\n if (!Number.isSafeInteger(definition.version) || definition.version < 1) {\n throw new G9SqliteError('misuse', `Migration '${definition.name}': version must be an integer ≥ 1.`);\n }\n if (typeof definition.name !== 'string' || definition.name.trim() === '') {\n throw new G9SqliteError('misuse', `Migration ${definition.version} needs a name.`);\n }\n const transactional = definition.transactional !== false;\n if ('sql' in definition) {\n const statements = [...definition.sql];\n return Object.freeze({\n version: definition.version,\n name: definition.name,\n checksum: checksumText(statements.join('\\n;\\n')),\n transactional,\n async up(context: G9MigrationContext) {\n for (const sql of statements) await context.execute(sql);\n },\n });\n }\n if (typeof definition.checksum !== 'string' || definition.checksum.trim() === '') {\n throw new G9SqliteError('misuse', `Migration '${definition.name}': a code migration needs a checksum.`);\n }\n return Object.freeze({\n version: definition.version,\n name: definition.name,\n checksum: definition.checksum,\n transactional,\n up: definition.up,\n });\n}\n\n/** Defines an initializer (`once` by default: a durable, recorded seed). */\nexport function defineInitializer(definition: {\n name: string;\n mode?: 'once' | 'everyOpen';\n run: G9Initializer['run'];\n}): G9Initializer {\n if (typeof definition.name !== 'string' || definition.name.trim() === '') {\n throw new G9SqliteError('misuse', 'An initializer needs a name.');\n }\n return Object.freeze({ name: definition.name, mode: definition.mode ?? 'once', run: definition.run });\n}\n\n/** MAUI `SqliteMigrationRunner.GetLatestRegisteredVersion`: the highest registered version, or `null`. */\nexport function latestMigrationVersion(migrations: readonly G9Migration[]): number | null {\n let max: number | null = null;\n for (const m of migrations) if (max === null || m.version > max) max = m.version;\n return max;\n}\n\n/** Validates and sorts a migration list (duplicate versions and names are configuration errors). */\nexport function sortMigrations(migrations: readonly G9Migration[]): readonly G9Migration[] {\n const sorted = [...migrations].sort((a, b) => a.version - b.version);\n for (let i = 1; i < sorted.length; i++) {\n if ((sorted[i] as G9Migration).version === (sorted[i - 1] as G9Migration).version) {\n throw new G9SqliteError(\n 'misuse',\n `Two migrations claim version ${(sorted[i] as G9Migration).version}: one would silently never run.`,\n );\n }\n }\n const names = new Set<string>();\n for (const i of migrations) {\n if (names.has(i.name)) throw new G9SqliteError('misuse', `Two migrations are named '${i.name}'.`);\n names.add(i.name);\n }\n return Object.freeze(sorted);\n}\n\n/** The G9 history table (never `PRAGMA user_version`, which G9SyncData may own). */\nexport const G9_SCHEMA_HISTORY_TABLE = 'g9lynx_schema_history';\n\n/** DDL of the schema-history table (applied migrations and initializers, with checksums). */\nexport const G9_SCHEMA_HISTORY_DDL =\n `CREATE TABLE IF NOT EXISTS \"${G9_SCHEMA_HISTORY_TABLE}\" (` +\n '\"Kind\" TEXT NOT NULL, \"Key\" TEXT NOT NULL, \"Version\" INTEGER, \"Name\" TEXT NOT NULL, \"Checksum\" TEXT NOT NULL, ' +\n '\"AppliedAt\" TEXT NOT NULL, PRIMARY KEY (\"Kind\", \"Key\"))';\n\n/** Columns the history table must have; anything else under that name is a collision, not ours. */\nexport const G9_SCHEMA_HISTORY_COLUMNS = ['Kind', 'Key', 'Version', 'Name', 'Checksum', 'AppliedAt'] as const;\n"],"names":["checksumText","text","h0","h1","h2","h3","i","t0","t1","t2","t3","c1","c2","hex","n","defineMigration","definition","Number","G9SqliteError","transactional","statements","Object","context","sql","defineInitializer","_definition_mode","latestMigrationVersion","migrations","max","m","sortMigrations","sorted","a","b","names","Set","G9_SCHEMA_HISTORY_TABLE","G9_SCHEMA_HISTORY_DDL","G9_SCHEMA_HISTORY_COLUMNS"],"mappings":";AA8CO,SAASA,aAAaC,IAAY;IACvC,IAAIC,KAAK;IACT,IAAIC,KAAK;IACT,IAAIC,KAAK;IACT,IAAIC,KAAK;IACT,IAAK,IAAIC,IAAI,GAAGA,IAAIL,KAAK,MAAM,EAAEK,IAAK;QACpCJ,MAAMD,KAAK,UAAU,CAACK;QAEtB,MAAMC,KAAKL,AAAK,QAALA;QACX,MAAMM,KAAKL,AAAK,QAALA;QACX,MAAMM,KAAKL,AAAK,QAALA,KAAcF,CAAAA,MAAM;QAC/B,MAAMQ,KAAKL,AAAK,QAALA,KAAcF,CAAAA,MAAM;QAC/B,MAAMQ,KAAKH,KAAMD,CAAAA,OAAO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I,CAAC,EAAE,CAAC;QAChG4B,MAAM,GAAG,CAAC5B,EAAE,IAAI;IAClB;IACA,OAAOe,OAAO,MAAM,CAACU;AACvB;AAGO,MAAMK,0BAA0B;AAGhC,MAAMC,wBACX,CAAC,4BAA4B,EAAED,wBAAwB,wKAAG,CAAC;AAKtD,MAAME,4BAA4B;IAAC;IAAQ;IAAO;IAAW;IAAQ;IAAY;CAAY"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** A FIFO async lock: one holder at a time, waiters in arrival order. */
|
|
2
|
+
export declare class G9AsyncLock {
|
|
3
|
+
private tail;
|
|
4
|
+
/** Waits for the lock; resolves with the release function (calling it twice is harmless). */
|
|
5
|
+
acquire(): Promise<() => void>;
|
|
6
|
+
}
|
|
7
|
+
//# sourceMappingURL=mutex.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mutex.d.ts","sourceRoot":"","sources":["../../src/session/mutex.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,qBAAa,WAAW;IACtB,OAAO,CAAC,IAAI,CAAoC;IAEhD,6FAA6F;IAC7F,OAAO,IAAI,OAAO,CAAC,MAAM,IAAI,CAAC;CAS/B"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
function _define_property(obj, key, value) {
|
|
2
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
3
|
+
value: value,
|
|
4
|
+
enumerable: true,
|
|
5
|
+
configurable: true,
|
|
6
|
+
writable: true
|
|
7
|
+
});
|
|
8
|
+
else obj[key] = value;
|
|
9
|
+
return obj;
|
|
10
|
+
}
|
|
11
|
+
class G9AsyncLock {
|
|
12
|
+
acquire() {
|
|
13
|
+
let release;
|
|
14
|
+
const next = new Promise((resolve)=>{
|
|
15
|
+
release = resolve;
|
|
16
|
+
});
|
|
17
|
+
const previous = this.tail;
|
|
18
|
+
this.tail = previous.then(()=>next);
|
|
19
|
+
return previous.then(()=>release);
|
|
20
|
+
}
|
|
21
|
+
constructor(){
|
|
22
|
+
_define_property(this, "tail", Promise.resolve());
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export { G9AsyncLock };
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=mutex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session/mutex.js","sources":["../../src/session/mutex.ts"],"sourcesContent":["/** A FIFO async lock: one holder at a time, waiters in arrival order. */\nexport class G9AsyncLock {\n private tail: Promise<void> = Promise.resolve();\n\n /** Waits for the lock; resolves with the release function (calling it twice is harmless). */\n acquire(): Promise<() => void> {\n let release!: () => void;\n const next = new Promise<void>((resolve) => {\n release = resolve;\n });\n const previous = this.tail;\n this.tail = previous.then(() => next);\n return previous.then(() => release);\n }\n}\n"],"names":["G9AsyncLock","release","next","Promise","resolve","previous"],"mappings":";;;;;;;;;;AACO,MAAMA;IAIX,UAA+B;QAC7B,IAAIC;QACJ,MAAMC,OAAO,IAAIC,QAAc,CAACC;YAC9BH,UAAUG;QACZ;QACA,MAAMC,WAAW,IAAI,CAAC,IAAI;QAC1B,IAAI,CAAC,IAAI,GAAGA,SAAS,IAAI,CAAC,IAAMH;QAChC,OAAOG,SAAS,IAAI,CAAC,IAAMJ;IAC7B;;QAXA,uBAAQ,QAAsBE,QAAQ,OAAO;;AAY/C"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { G9CodecContext } from '../codecs/codecs.js';
|
|
2
|
+
import type { G9SqlResult } from '../driver/types.js';
|
|
3
|
+
import type { G9ResultShape } from '../query/builders.js';
|
|
4
|
+
import type { G9EntityDescriptor } from '../schema/entity.js';
|
|
5
|
+
import { type G9SqlValue } from '../values/sql-value.js';
|
|
6
|
+
/** A stored value without a codec: int64 tags become their decimal string, everything else stays. */
|
|
7
|
+
export declare function decodeGeneric(value: G9SqlValue): unknown;
|
|
8
|
+
/** Rows of a raw query as records keyed by result column name. */
|
|
9
|
+
export declare function decodeGenericRows(result: G9SqlResult): Record<string, unknown>[];
|
|
10
|
+
/**
|
|
11
|
+
* Entity rows from a result: result columns map to properties by stored name (case-insensitive, as SQLite does);
|
|
12
|
+
* result columns the entity does not declare are ignored; declared columns the result lacks are left out.
|
|
13
|
+
*/
|
|
14
|
+
export declare function decodeEntityRows<R>(entity: G9EntityDescriptor, result: G9SqlResult, context: G9CodecContext): R[];
|
|
15
|
+
/** Rows of a built SELECT, decoded by its shape. */
|
|
16
|
+
export declare function decodeShaped<R>(shape: G9ResultShape, result: G9SqlResult, context: G9CodecContext): R[];
|
|
17
|
+
//# sourceMappingURL=rows.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rows.d.ts","sourceRoot":"","sources":["../../src/session/rows.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,KAAK,EAAkB,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,KAAK,UAAU,EAAc,MAAM,qBAAqB,CAAC;AAElE,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAExD;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAQhF;AAsBD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,GAAG,CAAC,EAAE,CAUjH;AAED,oDAAoD;AACpD,wBAAgB,YAAY,CAAC,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,GAAG,CAAC,EAAE,CAWvG"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { G9SqliteError } from "../errors.js";
|
|
2
|
+
import { isInt64Tag } from "../values/sql-value.js";
|
|
3
|
+
function decodeGeneric(value) {
|
|
4
|
+
return isInt64Tag(value) ? value.int64 : value;
|
|
5
|
+
}
|
|
6
|
+
function decodeGenericRows(result) {
|
|
7
|
+
return result.rows.map((row)=>{
|
|
8
|
+
const record = {};
|
|
9
|
+
for(let i = 0; i < result.columns.length; i++)record[result.columns[i]] = decodeGeneric(row[i]);
|
|
10
|
+
return record;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
function decodeColumn(column, value, context, entity) {
|
|
14
|
+
if (null === value) {
|
|
15
|
+
if (!column.nullable) throw new G9SqliteError('misuse', `'${entity}.${column.property}' is NULL in the database but declared non-nullable; declare it .nullable().`);
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
return column.codec.decode(value, context);
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (error instanceof G9SqliteError) throw new G9SqliteError('misuse', `'${entity}.${column.property}': ${error.message}`, {
|
|
22
|
+
cause: error
|
|
23
|
+
});
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function decodeEntityRows(entity, result, context) {
|
|
28
|
+
const map = result.columns.map((name)=>entity.byColumn.get(name.toLowerCase()));
|
|
29
|
+
return result.rows.map((row)=>{
|
|
30
|
+
const out = {};
|
|
31
|
+
for(let i = 0; i < map.length; i++){
|
|
32
|
+
const column = map[i];
|
|
33
|
+
if (column) out[column.property] = decodeColumn(column, row[i], context, entity.name);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
function decodeShaped(shape, result, context) {
|
|
39
|
+
if ('entity' === shape.kind) return decodeEntityRows(shape.entity, result, context);
|
|
40
|
+
if ('raw' === shape.kind) return decodeGenericRows(result);
|
|
41
|
+
return result.rows.map((row)=>{
|
|
42
|
+
const out = {};
|
|
43
|
+
shape.columns.forEach((c, i)=>{
|
|
44
|
+
const v = row[i];
|
|
45
|
+
out[c.alias] = null !== v && c.codec ? c.codec.decode(v, context) : decodeGeneric(v);
|
|
46
|
+
});
|
|
47
|
+
return out;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
export { decodeEntityRows, decodeGeneric, decodeGenericRows, decodeShaped };
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=rows.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session/rows.js","sources":["../../src/session/rows.ts"],"sourcesContent":["import type { G9CodecContext } from '../codecs/codecs';\nimport type { G9SqlResult } from '../driver/types';\nimport { G9SqliteError } from '../errors';\nimport type { G9ResultShape } from '../query/builders';\nimport type { G9EntityColumn, G9EntityDescriptor } from '../schema/entity';\nimport { type G9SqlValue, isInt64Tag } from '../values/sql-value';\n\n/** A stored value without a codec: int64 tags become their decimal string, everything else stays. */\nexport function decodeGeneric(value: G9SqlValue): unknown {\n return isInt64Tag(value) ? value.int64 : value;\n}\n\n/** Rows of a raw query as records keyed by result column name. */\nexport function decodeGenericRows(result: G9SqlResult): Record<string, unknown>[] {\n return result.rows.map((row) => {\n const record: Record<string, unknown> = {};\n for (let i = 0; i < result.columns.length; i++) {\n record[result.columns[i] as string] = decodeGeneric(row[i] as G9SqlValue);\n }\n return record;\n });\n}\n\nfunction decodeColumn(column: G9EntityColumn, value: G9SqlValue, context: G9CodecContext, entity: string): unknown {\n if (value === null) {\n if (!column.nullable) {\n throw new G9SqliteError(\n 'misuse',\n `'${entity}.${column.property}' is NULL in the database but declared non-nullable; declare it .nullable().`,\n );\n }\n return null;\n }\n try {\n return column.codec.decode(value, context);\n } catch (error) {\n if (error instanceof G9SqliteError) {\n throw new G9SqliteError('misuse', `'${entity}.${column.property}': ${error.message}`, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Entity rows from a result: result columns map to properties by stored name (case-insensitive, as SQLite does);\n * result columns the entity does not declare are ignored; declared columns the result lacks are left out.\n */\nexport function decodeEntityRows<R>(entity: G9EntityDescriptor, result: G9SqlResult, context: G9CodecContext): R[] {\n const map: (G9EntityColumn | undefined)[] = result.columns.map((name) => entity.byColumn.get(name.toLowerCase()));\n return result.rows.map((row) => {\n const out: Record<string, unknown> = {};\n for (let i = 0; i < map.length; i++) {\n const column = map[i];\n if (column) out[column.property] = decodeColumn(column, row[i] as G9SqlValue, context, entity.name);\n }\n return out as R;\n });\n}\n\n/** Rows of a built SELECT, decoded by its shape. */\nexport function decodeShaped<R>(shape: G9ResultShape, result: G9SqlResult, context: G9CodecContext): R[] {\n if (shape.kind === 'entity') return decodeEntityRows<R>(shape.entity, result, context);\n if (shape.kind === 'raw') return decodeGenericRows(result) as R[];\n return result.rows.map((row) => {\n const out: Record<string, unknown> = {};\n shape.columns.forEach((c, i) => {\n const v = row[i] as G9SqlValue;\n out[c.alias] = v === null || !c.codec ? decodeGeneric(v) : c.codec.decode(v, context);\n });\n return out as R;\n });\n}\n"],"names":["decodeGeneric","value","isInt64Tag","decodeGenericRows","result","row","record","i","decodeColumn","column","context","entity","G9SqliteError","error","decodeEntityRows","map","name","out","decodeShaped","shape","c","v"],"mappings":";;AAQO,SAASA,cAAcC,KAAiB;IAC7C,OAAOC,WAAWD,SAASA,MAAM,KAAK,GAAGA;AAC3C;AAGO,SAASE,kBAAkBC,MAAmB;IACnD,OAAOA,OAAO,IAAI,CAAC,GAAG,CAAC,CAACC;QACtB,MAAMC,SAAkC,CAAC;QACzC,IAAK,IAAIC,IAAI,GAAGA,IAAIH,OAAO,OAAO,CAAC,MAAM,EAAEG,IACzCD,MAAM,CAACF,OAAO,OAAO,CAACG,EAAE,CAAW,GAAGP,cAAcK,GAAG,CAACE,EAAE;QAE5D,OAAOD;IACT;AACF;AAEA,SAASE,aAAaC,MAAsB,EAAER,KAAiB,EAAES,OAAuB,EAAEC,MAAc;IACtG,IAAIV,AAAU,SAAVA,O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C,OAAO,CAAC,CAACC,GAAGb;YACxB,MAAMc,IAAIhB,GAAG,CAACE,EAAE;YAChBU,GAAG,CAACG,EAAE,KAAK,CAAC,GAAGC,AAAM,SAANA,KAAeD,EAAE,KAAK,GAAsBA,EAAE,KAAK,CAAC,MAAM,CAACC,GAAGX,WAArCV,cAAcqB;QACxD;QACA,OAAOJ;IACT;AACF"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type G9CodecContext } from '../codecs/codecs.js';
|
|
2
|
+
import type { G9SessionToken } from '../driver/types.js';
|
|
3
|
+
import type { G9EntityDescriptor } from '../schema/entity.js';
|
|
4
|
+
import type { G9SqliteDatabase } from './database.js';
|
|
5
|
+
/** Deterministic `CREATE TABLE IF NOT EXISTS` for an entity. */
|
|
6
|
+
export declare function createTableSql(entity: G9EntityDescriptor): string;
|
|
7
|
+
/** Name of a declared index (`IX_Table_A_B`, `UX_…` for unique) unless the declaration names it. */
|
|
8
|
+
export declare function indexName(entity: G9EntityDescriptor, index: G9EntityDescriptor['indexes'][number]): string;
|
|
9
|
+
/**
|
|
10
|
+
* Deterministic DDL for an entity's declared indexes (N07): order, collation, partial predicate; a unique index on
|
|
11
|
+
* a soft-delete entity covers live rows only unless `includeDeleted`. Partial predicates are inlined (SQLite does not
|
|
12
|
+
* allow parameters in index definitions).
|
|
13
|
+
*/
|
|
14
|
+
export declare function createIndexSql(entity: G9EntityDescriptor, codecContext?: G9CodecContext): string[];
|
|
15
|
+
/**
|
|
16
|
+
* Runs once per database path on its first connection, inside the connection lock: history-table collision check,
|
|
17
|
+
* migrations (N01), declared indexes of registered entities (N07), then initializers (N02). Any failure closes the
|
|
18
|
+
* connection; the next call retries from the first unapplied step.
|
|
19
|
+
*/
|
|
20
|
+
export declare function runSchemaSetup(db: G9SqliteDatabase, session: G9SessionToken): Promise<void>;
|
|
21
|
+
//# sourceMappingURL=schema-setup.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-setup.d.ts","sourceRoot":"","sources":["../../src/session/schema-setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAyB,MAAM,kBAAkB,CAAC;AAC9E,OAAO,KAAK,EAAmC,cAAc,EAA0B,MAAM,iBAAiB,CAAC;AAI/G,OAAO,KAAK,EAAkB,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAUnD,gEAAgE;AAChE,wBAAgB,cAAc,CAAC,MAAM,EAAE,kBAAkB,GAAG,MAAM,CAajE;AAED,oGAAoG;AACpG,wBAAgB,SAAS,CAAC,MAAM,EAAE,kBAAkB,EAAE,KAAK,EAAE,kBAAkB,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,GAAG,MAAM,CAK1G;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,kBAAkB,EAC1B,YAAY,GAAE,cAAsC,GACnD,MAAM,EAAE,CA8BV;AAkDD;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,EAAE,EAAE,gBAAgB,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAsGjG"}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { g9DefaultCodecContext } from "../codecs/codecs.js";
|
|
2
|
+
import { G9SqliteError, isG9SqliteError } from "../errors.js";
|
|
3
|
+
import { compileExpr, inlineSql, quoteIdentifier } from "../query/compile.js";
|
|
4
|
+
import { and, not } from "../query/expr.js";
|
|
5
|
+
import { formatLegacyDateTime } from "../values/local-date-time.js";
|
|
6
|
+
import { G9_SCHEMA_HISTORY_COLUMNS, G9_SCHEMA_HISTORY_DDL, G9_SCHEMA_HISTORY_TABLE } from "./migrations.js";
|
|
7
|
+
import { decodeGenericRows } from "./rows.js";
|
|
8
|
+
function createTableSql(entity) {
|
|
9
|
+
const singleKey = 1 === entity.primaryKey.length ? entity.primaryKey[0] : void 0;
|
|
10
|
+
const columns = entity.columns.map((c)=>{
|
|
11
|
+
let sql = `${quoteIdentifier(c.column)} ${c.codec.sqlType}`;
|
|
12
|
+
if (!c.nullable) sql += ' NOT NULL';
|
|
13
|
+
if (c.collation) sql += ` COLLATE ${c.collation}`;
|
|
14
|
+
if (singleKey === c) sql += c.autoIncrement ? ' PRIMARY KEY AUTOINCREMENT' : ' PRIMARY KEY';
|
|
15
|
+
return sql;
|
|
16
|
+
});
|
|
17
|
+
if (entity.primaryKey.length > 1) columns.push(`PRIMARY KEY (${entity.primaryKey.map((c)=>quoteIdentifier(c.column)).join(', ')})`);
|
|
18
|
+
return `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(entity.table)} (${columns.join(', ')})`;
|
|
19
|
+
}
|
|
20
|
+
function indexName(entity, index) {
|
|
21
|
+
if (index.name) return index.name;
|
|
22
|
+
const columns = index.parts.map((p)=>entity.byProperty.get(p.property).column);
|
|
23
|
+
return `${index.unique ? 'UX' : 'IX'}_${entity.table}_${columns.join('_')}`;
|
|
24
|
+
}
|
|
25
|
+
function createIndexSql(entity, codecContext = g9DefaultCodecContext) {
|
|
26
|
+
return entity.indexes.map((index)=>{
|
|
27
|
+
const parts = index.parts.map((p)=>{
|
|
28
|
+
const column = entity.byProperty.get(p.property);
|
|
29
|
+
if (!column) throw new G9SqliteError('misuse', `Index on '${entity.name}' names no column '${p.property}'.`);
|
|
30
|
+
let sql = quoteIdentifier(column.column);
|
|
31
|
+
if (p.collate) sql += ` COLLATE ${p.collate}`;
|
|
32
|
+
if (p.descending) sql += ' DESC';
|
|
33
|
+
return sql;
|
|
34
|
+
});
|
|
35
|
+
const predicates = [];
|
|
36
|
+
if (index.where) predicates.push(index.where(entity.refs));
|
|
37
|
+
if (index.unique && entity.softDelete && !index.includeDeleted) predicates.push(not(entity.refs[entity.softDelete.flag]));
|
|
38
|
+
let sql = `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS ${quoteIdentifier(indexName(entity, index))} ON ${quoteIdentifier(entity.table)} (${parts.join(', ')})`;
|
|
39
|
+
if (predicates.length) {
|
|
40
|
+
const f = compileExpr(1 === predicates.length ? predicates[0] : and(...predicates), {
|
|
41
|
+
codec: codecContext,
|
|
42
|
+
culture: null,
|
|
43
|
+
localized: new Set(),
|
|
44
|
+
qualify: false,
|
|
45
|
+
maxInListParameters: Number.MAX_SAFE_INTEGER
|
|
46
|
+
});
|
|
47
|
+
sql += ` WHERE ${inlineSql(f.sql, f.params)}`;
|
|
48
|
+
}
|
|
49
|
+
return sql;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function makeContext(db, runner, tx) {
|
|
53
|
+
const codec = db.options.codec;
|
|
54
|
+
const ctx = {
|
|
55
|
+
signal: void 0,
|
|
56
|
+
execute: (sql, ...params)=>runner.changes(sql, params, tx),
|
|
57
|
+
async query (sql, ...params) {
|
|
58
|
+
const [rows] = await runner.run([
|
|
59
|
+
{
|
|
60
|
+
sql,
|
|
61
|
+
params: db.encodeRaw(params)
|
|
62
|
+
}
|
|
63
|
+
], tx);
|
|
64
|
+
return rows;
|
|
65
|
+
},
|
|
66
|
+
async tableExists (table) {
|
|
67
|
+
var _rows_;
|
|
68
|
+
const rows = await ctx.query("SELECT COUNT(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ?", table);
|
|
69
|
+
return Number(null == (_rows_ = rows[0]) ? void 0 : _rows_.n) > 0;
|
|
70
|
+
},
|
|
71
|
+
async columnExists (table, column) {
|
|
72
|
+
var _rows_;
|
|
73
|
+
const rows = await ctx.query('SELECT COUNT(*) AS n FROM pragma_table_info(?) WHERE lower(name) = lower(?)', table, column);
|
|
74
|
+
return Number(null == (_rows_ = rows[0]) ? void 0 : _rows_.n) > 0;
|
|
75
|
+
},
|
|
76
|
+
async createTable (entity) {
|
|
77
|
+
await ctx.execute(createTableSql(entity));
|
|
78
|
+
},
|
|
79
|
+
async createIndexes (entity) {
|
|
80
|
+
for (const sql of createIndexSql(entity, codec))try {
|
|
81
|
+
await ctx.execute(sql);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (!isG9SqliteError(error, 'constraint')) throw error;
|
|
84
|
+
throw new G9SqliteError('constraint', `Cannot create a unique index on '${entity.table}': existing rows violate it. No data was changed; resolve the duplicates in a migration before declaring the index. (${sql})`, {
|
|
85
|
+
sql,
|
|
86
|
+
cause: error
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
return ctx;
|
|
92
|
+
}
|
|
93
|
+
async function runSchemaSetup(db, session) {
|
|
94
|
+
const { driver, migrations, initializers, entities, readOnly } = db.options;
|
|
95
|
+
const runner = {
|
|
96
|
+
async run (statements, tx) {
|
|
97
|
+
const options = tx ? {
|
|
98
|
+
tx
|
|
99
|
+
} : {};
|
|
100
|
+
const results = await driver.run(session, statements, options);
|
|
101
|
+
return results.map((r)=>decodeGenericRows(r));
|
|
102
|
+
},
|
|
103
|
+
async changes (sql, params, tx) {
|
|
104
|
+
const options = tx ? {
|
|
105
|
+
tx
|
|
106
|
+
} : {};
|
|
107
|
+
const [result] = await driver.run(session, [
|
|
108
|
+
{
|
|
109
|
+
sql,
|
|
110
|
+
params: db.encodeRaw(params)
|
|
111
|
+
}
|
|
112
|
+
], options);
|
|
113
|
+
return result.changes;
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const needsHistory = migrations.length > 0 || initializers.some((i)=>'once' === i.mode);
|
|
117
|
+
const indexed = entities.filter((e)=>e.indexes.length > 0);
|
|
118
|
+
if (!needsHistory && 0 === indexed.length && 0 === initializers.length) return;
|
|
119
|
+
if (readOnly) {
|
|
120
|
+
if (needsHistory || initializers.length) throw new G9SqliteError('readonly', 'Migrations and initializers cannot run on a read-only database.');
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
async function inTx(work) {
|
|
124
|
+
const tx = await driver.begin(session, 'immediate');
|
|
125
|
+
try {
|
|
126
|
+
const value = await work(tx);
|
|
127
|
+
await driver.commit(tx);
|
|
128
|
+
return value;
|
|
129
|
+
} catch (error) {
|
|
130
|
+
await driver.rollback(tx).catch(()=>void 0);
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (needsHistory) {
|
|
135
|
+
const [info] = await runner.run([
|
|
136
|
+
{
|
|
137
|
+
sql: `SELECT name FROM pragma_table_info('${G9_SCHEMA_HISTORY_TABLE}')`,
|
|
138
|
+
params: []
|
|
139
|
+
}
|
|
140
|
+
], null);
|
|
141
|
+
const existing = info.map((r)=>String(r.name));
|
|
142
|
+
if (existing.length > 0 && G9_SCHEMA_HISTORY_COLUMNS.some((c)=>existing.indexOf(c) < 0)) throw new G9SqliteError('other', `A table named '${G9_SCHEMA_HISTORY_TABLE}' exists with other columns (${existing.join(', ')}); it is not G9 migration history. Rename it before using migrations.`);
|
|
143
|
+
if (0 === existing.length) await runner.changes(G9_SCHEMA_HISTORY_DDL, [], null);
|
|
144
|
+
}
|
|
145
|
+
const now = ()=>formatLegacyDateTime(db.options.clock.now(), 'provider');
|
|
146
|
+
const history = async (tx)=>{
|
|
147
|
+
const [rows] = await runner.run([
|
|
148
|
+
{
|
|
149
|
+
sql: `SELECT "Kind", "Key", "Version", "Checksum" FROM "${G9_SCHEMA_HISTORY_TABLE}"`,
|
|
150
|
+
params: []
|
|
151
|
+
}
|
|
152
|
+
], tx);
|
|
153
|
+
return rows;
|
|
154
|
+
};
|
|
155
|
+
if (migrations.length > 0) {
|
|
156
|
+
const applied = await history(null);
|
|
157
|
+
const appliedMigrations = applied.filter((r)=>'migration' === r.Kind);
|
|
158
|
+
for (const m of migrations){
|
|
159
|
+
const row = appliedMigrations.find((r)=>Number(r.Version) === m.version);
|
|
160
|
+
if (row && row.Checksum !== m.checksum) throw new G9SqliteError('other', `Migration ${m.version} ('${m.name}') was applied with checksum ${String(row.Checksum)} but is now ${m.checksum}. An applied migration must never change; add a new one instead.`);
|
|
161
|
+
}
|
|
162
|
+
for (const m of migrations)if (!appliedMigrations.some((r)=>Number(r.Version) === m.version)) await applyMigration(db, runner, inTx, m, now);
|
|
163
|
+
}
|
|
164
|
+
for (const entity of indexed){
|
|
165
|
+
const ctx = makeContext(db, runner, null);
|
|
166
|
+
if (await ctx.tableExists(entity.table)) await inTx(async (tx)=>makeContext(db, runner, tx).createIndexes(entity));
|
|
167
|
+
}
|
|
168
|
+
for (const initializer of initializers){
|
|
169
|
+
if ('everyOpen' === initializer.mode) {
|
|
170
|
+
await inTx(async (tx)=>initializer.run(makeContext(db, runner, tx)));
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
await inTx(async (tx)=>{
|
|
174
|
+
const rows = await history(tx);
|
|
175
|
+
if (rows.some((r)=>'initializer' === r.Kind && r.Key === initializer.name)) return;
|
|
176
|
+
await initializer.run(makeContext(db, runner, tx));
|
|
177
|
+
await runner.changes(`INSERT INTO "${G9_SCHEMA_HISTORY_TABLE}" ("Kind", "Key", "Version", "Name", "Checksum", "AppliedAt") VALUES ('initializer', ?, NULL, ?, '', ?)`, [
|
|
178
|
+
initializer.name,
|
|
179
|
+
initializer.name,
|
|
180
|
+
now()
|
|
181
|
+
], tx);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
async function applyMigration(db, runner, inTx, m, now) {
|
|
186
|
+
const record = (tx)=>runner.changes(`INSERT INTO "${G9_SCHEMA_HISTORY_TABLE}" ("Kind", "Key", "Version", "Name", "Checksum", "AppliedAt") VALUES ('migration', ?, ?, ?, ?, ?)`, [
|
|
187
|
+
String(m.version),
|
|
188
|
+
m.version,
|
|
189
|
+
m.name,
|
|
190
|
+
m.checksum,
|
|
191
|
+
now()
|
|
192
|
+
], tx);
|
|
193
|
+
const check = async (tx)=>{
|
|
194
|
+
const [rows] = await runner.run([
|
|
195
|
+
{
|
|
196
|
+
sql: `SELECT "Version", "Checksum" FROM "${G9_SCHEMA_HISTORY_TABLE}" WHERE "Kind" = 'migration'`,
|
|
197
|
+
params: []
|
|
198
|
+
}
|
|
199
|
+
], tx);
|
|
200
|
+
const list = rows;
|
|
201
|
+
if (list.some((r)=>Number(r.Version) === m.version)) return 'applied';
|
|
202
|
+
const newer = list.map((r)=>Number(r.Version)).filter((v)=>v > m.version);
|
|
203
|
+
if (newer.length > 0) throw new G9SqliteError('other', `Migration ${m.version} ('${m.name}') is registered below already-applied version ${Math.max(...newer)}: it would never run in order. Give it a version above the newest applied one.`);
|
|
204
|
+
return 'pending';
|
|
205
|
+
};
|
|
206
|
+
try {
|
|
207
|
+
if (!m.transactional) {
|
|
208
|
+
if (await check(null) === 'applied') return;
|
|
209
|
+
await m.up(makeContext(db, runner, null));
|
|
210
|
+
await record(null);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
await inTx(async (tx)=>{
|
|
214
|
+
if (await check(tx) === 'applied') return;
|
|
215
|
+
await m.up(makeContext(db, runner, tx));
|
|
216
|
+
await record(tx);
|
|
217
|
+
});
|
|
218
|
+
} catch (error) {
|
|
219
|
+
if (isG9SqliteError(error) && error.message.startsWith('Migration ')) throw error;
|
|
220
|
+
throw new G9SqliteError(isG9SqliteError(error) ? error.code : 'other', `Migration ${m.version} ('${m.name}') failed and was rolled back; it runs again on the next open. ${error instanceof Error ? error.message : String(error)}`, {
|
|
221
|
+
cause: error
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
export { createIndexSql, createTableSql, indexName, runSchemaSetup };
|
|
226
|
+
|
|
227
|
+
//# sourceMappingURL=schema-setup.js.map
|