@omnitron-dev/titan-database 0.3.0 → 0.3.2
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 +75 -0
- package/dist/coordination/postgres-lease.d.ts +33 -0
- package/dist/coordination/postgres-lease.d.ts.map +1 -0
- package/dist/coordination/postgres-lease.js +121 -0
- package/dist/coordination/postgres-lease.js.map +1 -0
- package/dist/database.manager.d.ts.map +1 -1
- package/dist/database.manager.js +2 -7
- package/dist/database.manager.js.map +1 -1
- package/dist/exports/coordination.d.ts +2 -0
- package/dist/exports/coordination.d.ts.map +1 -0
- package/dist/exports/coordination.js +2 -0
- package/dist/exports/coordination.js.map +1 -0
- package/dist/exports/migration.d.ts +6 -3
- package/dist/exports/migration.d.ts.map +1 -1
- package/dist/exports/migration.js +4 -2
- package/dist/exports/migration.js.map +1 -1
- package/dist/exports/readiness.d.ts +3 -0
- package/dist/exports/readiness.d.ts.map +1 -0
- package/dist/exports/readiness.js +2 -0
- package/dist/exports/readiness.js.map +1 -0
- package/dist/exports/sqlite.d.ts +3 -0
- package/dist/exports/sqlite.d.ts.map +1 -0
- package/dist/exports/sqlite.js +21 -0
- package/dist/exports/sqlite.js.map +1 -0
- package/dist/migration/cli.d.ts +11 -1
- package/dist/migration/cli.d.ts.map +1 -1
- package/dist/migration/cli.js +61 -31
- package/dist/migration/cli.js.map +1 -1
- package/dist/migration/hardened-runner.d.ts +20 -32
- package/dist/migration/hardened-runner.d.ts.map +1 -1
- package/dist/migration/hardened-runner.js +55 -251
- package/dist/migration/hardened-runner.js.map +1 -1
- package/dist/migration/index.d.ts +1 -1
- package/dist/migration/index.d.ts.map +1 -1
- package/dist/migration/index.js +1 -1
- package/dist/migration/index.js.map +1 -1
- package/dist/migration/postgres.d.ts +12 -0
- package/dist/migration/postgres.d.ts.map +1 -0
- package/dist/migration/postgres.js +26 -0
- package/dist/migration/postgres.js.map +1 -0
- package/dist/readiness/postgres.d.ts +65 -0
- package/dist/readiness/postgres.d.ts.map +1 -0
- package/dist/readiness/postgres.js +183 -0
- package/dist/readiness/postgres.js.map +1 -0
- package/dist/transaction/transaction.context.d.ts +3 -0
- package/dist/transaction/transaction.context.d.ts.map +1 -1
- package/dist/transaction/transaction.context.js +41 -30
- package/dist/transaction/transaction.context.js.map +1 -1
- package/dist/utils/describe-error.d.ts +1 -1
- package/dist/utils/describe-error.d.ts.map +1 -1
- package/dist/utils/describe-error.js +1 -36
- package/dist/utils/describe-error.js.map +1 -1
- package/package.json +41 -20
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { sql } from 'kysely';
|
|
3
|
+
import { createPostgresMigrationDatabase } from '../migration/postgres.js';
|
|
4
|
+
export const requiredColumn = (type) => ({ type, nullable: false });
|
|
5
|
+
export const nullableColumn = (type) => ({ type, nullable: true });
|
|
6
|
+
export class SchemaReadinessError extends Error {
|
|
7
|
+
constructor(component, violations) {
|
|
8
|
+
super(`Database schema is incompatible with ${component}: ${violations.join('; ')}. Apply the declared project migrations before starting the application.`);
|
|
9
|
+
this.component = component;
|
|
10
|
+
this.violations = violations;
|
|
11
|
+
this.code = 'database_schema_incompatible';
|
|
12
|
+
this.name = 'SchemaReadinessError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export async function requirePostgresSchema(pool, contract, options = {}) {
|
|
16
|
+
const timeout = (name, value) => {
|
|
17
|
+
if (!Number.isInteger(value) || value < 1 || value > 2_147_483_647)
|
|
18
|
+
throw new TypeError(`${name} must be a positive PostgreSQL timeout in milliseconds`);
|
|
19
|
+
return `${value}ms`;
|
|
20
|
+
};
|
|
21
|
+
const statementTimeout = timeout('statementTimeoutMs', options.statementTimeoutMs ?? 10_000);
|
|
22
|
+
const lockTimeout = timeout('lockTimeoutMs', options.lockTimeoutMs ?? 1_000);
|
|
23
|
+
const db = createPostgresMigrationDatabase(pool);
|
|
24
|
+
try {
|
|
25
|
+
await db
|
|
26
|
+
.transaction()
|
|
27
|
+
.setIsolationLevel('repeatable read')
|
|
28
|
+
.setAccessMode('read only')
|
|
29
|
+
.execute(async (tx) => {
|
|
30
|
+
await sql `SELECT set_config('statement_timeout', ${statementTimeout}, true), set_config('lock_timeout', ${lockTimeout}, true)`.execute(tx);
|
|
31
|
+
const { rows: [namespace], } = await sql `SELECT coalesce(${contract.schema ?? null}::text, current_schema()) AS schema, pg_catalog.quote_ident(coalesce(${contract.schema ?? null}::text, current_schema())) AS quoted_schema`.execute(tx);
|
|
32
|
+
if (!namespace?.schema)
|
|
33
|
+
throw new SchemaReadinessError(contract.name, ['schema: unavailable']);
|
|
34
|
+
const tables = await tx.introspection.getTables();
|
|
35
|
+
const names = Object.keys(contract.tables);
|
|
36
|
+
const { rows: uniqueKeys } = await sql `
|
|
37
|
+
SELECT c.relname AS table,
|
|
38
|
+
ARRAY(SELECT a.attname::text FROM unnest(i.indkey) WITH ORDINALITY x(n,position)
|
|
39
|
+
JOIN pg_catalog.pg_attribute a ON a.attrelid=c.oid AND a.attnum=x.n
|
|
40
|
+
WHERE x.position<=i.indnkeyatts ORDER BY x.position) AS columns
|
|
41
|
+
FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class c ON c.oid=i.indrelid
|
|
42
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
43
|
+
WHERE n.nspname=${namespace.schema} AND c.relname=ANY(${names}::text[])
|
|
44
|
+
AND i.indisunique AND i.indisvalid AND i.indisready AND i.indislive AND i.indimmediate
|
|
45
|
+
AND i.indpred IS NULL AND i.indexprs IS NULL`.execute(tx);
|
|
46
|
+
const { rows: foreignKeys } = await sql `SELECT c.relname AS table, k.convalidated AS valid,
|
|
47
|
+
ARRAY(SELECT a.attname::text FROM unnest(k.conkey) WITH ORDINALITY x(n,i) JOIN pg_catalog.pg_attribute a ON a.attrelid=c.oid AND a.attnum=x.n ORDER BY x.i) AS columns,
|
|
48
|
+
tn.nspname AS target_schema, tc.relname AS target_table,
|
|
49
|
+
ARRAY(SELECT a.attname::text FROM unnest(k.confkey) WITH ORDINALITY x(n,i) JOIN pg_catalog.pg_attribute a ON a.attrelid=tc.oid AND a.attnum=x.n ORDER BY x.i) AS targets,
|
|
50
|
+
k.confdeltype AS delete_action,k.confupdtype AS update_action
|
|
51
|
+
FROM pg_catalog.pg_constraint k JOIN pg_catalog.pg_class c ON c.oid=k.conrelid JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
52
|
+
LEFT JOIN pg_catalog.pg_class tc ON tc.oid=k.confrelid LEFT JOIN pg_catalog.pg_namespace tn ON tn.oid=tc.relnamespace
|
|
53
|
+
WHERE k.contype='f' AND n.nspname=${namespace.schema} AND c.relname=ANY(${names}::text[])`.execute(tx);
|
|
54
|
+
const { rows: triggers } = await sql `SELECT c.relname AS table,t.tgenabled AS enabled,t.tgtype::integer AS type,
|
|
55
|
+
t.tgqual IS NOT NULL AS qualified,p.proname AS function,pn.nspname AS function_schema,
|
|
56
|
+
p.prosrc AS body,l.lanname AS language,t.tgnargs AS args,t.tgattr::text AS columns,
|
|
57
|
+
format_type(p.prorettype,NULL) AS return_type,p.proconfig AS configuration,p.prosecdef AS security
|
|
58
|
+
FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace
|
|
59
|
+
JOIN pg_proc p ON p.oid=t.tgfoid JOIN pg_language l ON l.oid=p.prolang JOIN pg_namespace pn ON pn.oid=p.pronamespace
|
|
60
|
+
WHERE NOT t.tgisinternal AND n.nspname=${namespace.schema} AND c.relname=ANY(${names}::text[])`.execute(tx);
|
|
61
|
+
const { rows: columns } = await sql `
|
|
62
|
+
SELECT c.relname AS table,a.attname AS column,a.attgenerated<>'' AS generated,pg_get_expr(d.adbin,d.adrelid) AS expression,format_type(a.atttypid,a.atttypmod) AS formatted_type
|
|
63
|
+
FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace
|
|
64
|
+
LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum
|
|
65
|
+
WHERE n.nspname=${namespace.schema} AND c.relname=ANY(${names}::text[]) AND a.attnum>0 AND NOT a.attisdropped`.execute(tx);
|
|
66
|
+
const { rows: routines } = await sql `
|
|
67
|
+
SELECT p.proname AS name,p.prosrc AS body,l.lanname AS language,p.provolatile AS volatility,p.prosecdef AS security,format_type(p.prorettype,NULL) AS return_type,p.proconfig AS configuration,
|
|
68
|
+
ARRAY(SELECT pg_catalog.format_type(argument,NULL) FROM unnest(p.proargtypes::oid[]) WITH ORDINALITY a(argument,i) ORDER BY i) AS argument_types,
|
|
69
|
+
p.provariadic<>0 AS variadic,p.pronargdefaults AS default_arguments,p.proretset AS returns_set
|
|
70
|
+
FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace JOIN pg_language l ON l.oid=p.prolang
|
|
71
|
+
WHERE n.nspname=${namespace.schema} AND p.prokind='f' AND p.proname=ANY(${(contract.routines ?? []).map((r) => r.name)}::text[])`.execute(tx);
|
|
72
|
+
const actions = {
|
|
73
|
+
'no action': 'a',
|
|
74
|
+
restrict: 'r',
|
|
75
|
+
cascade: 'c',
|
|
76
|
+
'set null': 'n',
|
|
77
|
+
'set default': 'd',
|
|
78
|
+
};
|
|
79
|
+
const sameSettings = (actual, expected = [], schemaSearchPath = false) => {
|
|
80
|
+
const selected = schemaSearchPath ? [...expected, `search_path=pg_catalog, ${namespace.quoted_schema}, pg_temp`] : expected;
|
|
81
|
+
const sorted = [...(actual ?? [])].sort();
|
|
82
|
+
return sorted.length === selected.length && [...selected].sort().every((value, i) => value === sorted[i]);
|
|
83
|
+
};
|
|
84
|
+
const violations = [];
|
|
85
|
+
for (const expected of contract.routines ?? []) {
|
|
86
|
+
if (!routines.some((r) => r.name === expected.name &&
|
|
87
|
+
!r.variadic && r.default_arguments === 0 && !r.returns_set &&
|
|
88
|
+
r.argument_types.length === (expected.argumentTypes ?? []).length &&
|
|
89
|
+
r.argument_types.every((type, index) => type === (expected.argumentTypes ?? [])[index]) &&
|
|
90
|
+
!r.security &&
|
|
91
|
+
r.language === expected.language &&
|
|
92
|
+
r.volatility === expected.volatility &&
|
|
93
|
+
(expected.returnType === undefined || r.return_type === expected.returnType) &&
|
|
94
|
+
sameSettings(r.configuration, expected.configuration, expected.schemaSearchPath) &&
|
|
95
|
+
createHash('sha256').update(r.body).digest('hex') === expected.bodySha256)) {
|
|
96
|
+
violations.push(`${expected.name}: required database routine`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const same = (a, b) => a?.length === b.length && a.every((x, i) => x === b[i]);
|
|
100
|
+
for (const [name, expected] of Object.entries(contract.tables)) {
|
|
101
|
+
const table = tables.find((t) => t.name === name && t.schema === namespace.schema);
|
|
102
|
+
if (!table || table.isView || table.isForeign) {
|
|
103
|
+
violations.push(`${name}: physical table required`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
for (const [nameOfColumn, spec] of Object.entries(expected.columns)) {
|
|
107
|
+
const column = table.columns.find((c) => c.name === nameOfColumn);
|
|
108
|
+
if (!column ||
|
|
109
|
+
column.dataType !== spec.type ||
|
|
110
|
+
column.dataTypeSchema !== (spec.typeSchema ?? 'pg_catalog') ||
|
|
111
|
+
(spec.formattedType !== undefined && !columns.some((c) => c.table === name && c.column === nameOfColumn && c.formatted_type === spec.formattedType)) ||
|
|
112
|
+
column.isNullable !== spec.nullable ||
|
|
113
|
+
(spec.default !== undefined && column.hasDefaultValue !== spec.default) ||
|
|
114
|
+
(spec.defaultExpression !== undefined &&
|
|
115
|
+
!columns.some((c) => c.table === name && c.column === nameOfColumn && !c.generated && c.expression === spec.defaultExpression)) ||
|
|
116
|
+
((spec.generated === false || (expected.insert && spec.generated === undefined)) && columns.some((c) => c.table === name && c.column === nameOfColumn && c.generated)) ||
|
|
117
|
+
(typeof spec.generated === 'string' &&
|
|
118
|
+
!columns.some((c) => c.table === name &&
|
|
119
|
+
c.column === nameOfColumn &&
|
|
120
|
+
c.generated &&
|
|
121
|
+
c.expression === spec.generated))) {
|
|
122
|
+
violations.push(`${name}.${nameOfColumn}: required column shape`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (expected.insert)
|
|
126
|
+
for (const column of table.columns) {
|
|
127
|
+
if (!(column.name in expected.columns) &&
|
|
128
|
+
!column.isNullable &&
|
|
129
|
+
!column.hasDefaultValue &&
|
|
130
|
+
!column.isAutoIncrementing &&
|
|
131
|
+
!columns.some((c) => c.table === name && c.column === column.name && c.generated)) {
|
|
132
|
+
violations.push(`${name}.${column.name}: additional column requires a value`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
for (const key of expected.unique ?? []) {
|
|
136
|
+
if (!uniqueKeys.some((index) => index.table === name && same(index.columns, key))) {
|
|
137
|
+
violations.push(`${name}: unique key (${key.join(',')}) required`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
for (const key of expected.foreignKeys ?? []) {
|
|
141
|
+
if (!foreignKeys.some((c) => c.table === name &&
|
|
142
|
+
c.valid &&
|
|
143
|
+
same(c.columns, key.columns) &&
|
|
144
|
+
c.target_schema === namespace.schema &&
|
|
145
|
+
c.target_table === key.table &&
|
|
146
|
+
same(c.targets, key.references) &&
|
|
147
|
+
c.delete_action === actions[key.onDelete ?? 'no action'] &&
|
|
148
|
+
c.update_action === actions[key.onUpdate ?? 'no action'])) {
|
|
149
|
+
violations.push(`${name}: foreign key (${key.columns.join(',')}) required`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
for (const expectedTrigger of [
|
|
153
|
+
...(expected.triggers ?? []),
|
|
154
|
+
...(expected.immutable ? [{ ...expected.immutable, type: 27 }] : []),
|
|
155
|
+
]) {
|
|
156
|
+
if (!triggers.some((t) => t.table === name &&
|
|
157
|
+
(t.enabled === 'O' || t.enabled === 'A') &&
|
|
158
|
+
t.type === expectedTrigger.type &&
|
|
159
|
+
!t.qualified &&
|
|
160
|
+
t.args === 0 &&
|
|
161
|
+
t.columns === '' &&
|
|
162
|
+
t.function_schema === namespace.schema &&
|
|
163
|
+
t.language === 'plpgsql' &&
|
|
164
|
+
t.return_type === 'trigger' &&
|
|
165
|
+
!t.security &&
|
|
166
|
+
sameSettings(t.configuration, expectedTrigger.configuration, expectedTrigger.schemaSearchPath) &&
|
|
167
|
+
t.function === expectedTrigger.function &&
|
|
168
|
+
createHash('sha256').update(t.body).digest('hex') === expectedTrigger.bodySha256)) {
|
|
169
|
+
violations.push(expected.immutable && expectedTrigger.type === 27
|
|
170
|
+
? `${name}: immutable evidence trigger required`
|
|
171
|
+
: `${name}: ${expectedTrigger.function} trigger required`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (violations.length)
|
|
176
|
+
throw new SchemaReadinessError(contract.name, violations);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
await db.destroy();
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
//# sourceMappingURL=postgres.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres.js","sourceRoot":"","sources":["../../src/readiness/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,GAAG,EAAqB,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,+BAA+B,EAAE,MAAM,0BAA0B,CAAC;AAsD3E,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,IAAY,EAA6B,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;AACvG,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,IAAY,EAA6B,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;AAEtG,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAE7C,YACW,SAAiB,EACjB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,CAAC;YACD,IAAI,UAAU,CAAC,MAAM;gBAAE,MAAM,IAAI,oBAAoB,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACnF,CAAC,CAAC,CAAC;IACP,CAAC;YAAS,CAAC;QACT,MAAM,EAAE,CAAC,OAAO,EAAE,CAAC;IACrB,CAAC;AACH,CAAC"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Transaction, Kysely } from 'kysely';
|
|
2
2
|
export interface TransactionContextData {
|
|
3
3
|
transaction: Transaction<unknown>;
|
|
4
|
+
database?: Kysely<unknown>;
|
|
5
|
+
parent?: TransactionContextData;
|
|
4
6
|
connectionName: string;
|
|
5
7
|
depth: number;
|
|
6
8
|
startedAt: Date;
|
|
@@ -19,6 +21,7 @@ export declare function runInTransaction<DB, T>(db: Kysely<DB>, fn: () => Promis
|
|
|
19
21
|
export declare function runWithTransaction<DB, T>(trx: Transaction<DB>, fn: () => Promise<T>, options?: {
|
|
20
22
|
name?: string;
|
|
21
23
|
connectionName?: string;
|
|
24
|
+
database?: Kysely<DB>;
|
|
22
25
|
}): Promise<T>;
|
|
23
26
|
export declare function AutoTransactional(options?: {
|
|
24
27
|
name?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.context.d.ts","sourceRoot":"","sources":["../../src/transaction/transaction.context.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"transaction.context.d.ts","sourceRoot":"","sources":["../../src/transaction/transaction.context.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAKlD,MAAM,WAAW,sBAAsB;IACrC,WAAW,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IAC3B,MAAM,CAAC,EAAE,sBAAsB,CAAC;IAChC,cAAc,EAAE,MAAM,CAAC;IACvB,KAAK,E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IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,eAAe,CA0BvG"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
-
import { sql } from 'kysely';
|
|
3
2
|
const globalStore = globalThis;
|
|
4
3
|
const TXN_STORAGE_KEY = Symbol.for('titan:database:transaction-storage');
|
|
5
4
|
const transactionStorage = globalStore[TXN_STORAGE_KEY] ??=
|
|
@@ -14,61 +13,76 @@ export function getCurrentTransaction() {
|
|
|
14
13
|
const ctx = transactionStorage.getStore();
|
|
15
14
|
return ctx?.transaction;
|
|
16
15
|
}
|
|
16
|
+
function ownsConnection(db, ctx) {
|
|
17
|
+
if (db === ctx.database || db === ctx.transaction)
|
|
18
|
+
return true;
|
|
19
|
+
if (typeof db.getExecutor !== 'function' || typeof ctx.transaction.getExecutor !== 'function')
|
|
20
|
+
return false;
|
|
21
|
+
const adapter = db.getExecutor().adapter;
|
|
22
|
+
return adapter !== undefined && adapter === ctx.transaction.getExecutor().adapter;
|
|
23
|
+
}
|
|
24
|
+
function contextFor(db) {
|
|
25
|
+
for (let ctx = transactionStorage.getStore(); ctx; ctx = ctx.parent) {
|
|
26
|
+
if (ownsConnection(db, ctx))
|
|
27
|
+
return ctx;
|
|
28
|
+
}
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
17
31
|
export function getExecutor(db) {
|
|
18
|
-
const ctx =
|
|
32
|
+
const ctx = contextFor(db);
|
|
19
33
|
if (ctx) {
|
|
20
34
|
return ctx.transaction;
|
|
21
35
|
}
|
|
22
36
|
return db;
|
|
23
37
|
}
|
|
24
|
-
let savepointSequence = 0;
|
|
25
38
|
export async function runInTransaction(db, fn, options) {
|
|
26
|
-
const
|
|
39
|
+
const parent = transactionStorage.getStore();
|
|
40
|
+
const existingCtx = contextFor(db);
|
|
27
41
|
if (existingCtx) {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
await sql.raw(`SAVEPOINT ${savepoint}`).execute(trx);
|
|
31
|
-
try {
|
|
32
|
-
const result = await fn();
|
|
33
|
-
await sql.raw(`RELEASE SAVEPOINT ${savepoint}`).execute(trx);
|
|
34
|
-
return result;
|
|
35
|
-
}
|
|
36
|
-
catch (error) {
|
|
37
|
-
try {
|
|
38
|
-
await sql.raw(`ROLLBACK TO SAVEPOINT ${savepoint}`).execute(trx);
|
|
39
|
-
}
|
|
40
|
-
catch {
|
|
41
|
-
}
|
|
42
|
-
throw error;
|
|
42
|
+
if (options?.connectionName && options.connectionName !== existingCtx.connectionName) {
|
|
43
|
+
throw new Error('The same database was requested under a different transaction connection name');
|
|
43
44
|
}
|
|
45
|
+
const { withTransaction } = await import('@kysera/dal');
|
|
46
|
+
return withTransaction(existingCtx.transaction, () => transactionStorage.run({
|
|
47
|
+
...existingCtx,
|
|
48
|
+
depth: existingCtx.depth + 1,
|
|
49
|
+
parent,
|
|
50
|
+
name: options?.name ?? existingCtx.name,
|
|
51
|
+
}, fn), {
|
|
52
|
+
rollbackErrorMode: 'callback',
|
|
53
|
+
onRollbackError: (originalError, rollbackError) => {
|
|
54
|
+
throw new AggregateError([originalError, rollbackError], 'Nested transaction failed and savepoint rollback could not be confirmed');
|
|
55
|
+
},
|
|
56
|
+
});
|
|
44
57
|
}
|
|
45
|
-
const
|
|
58
|
+
const inContext = async (trx) => {
|
|
46
59
|
const ctx = {
|
|
47
60
|
transaction: trx,
|
|
61
|
+
database: db,
|
|
62
|
+
parent,
|
|
48
63
|
connectionName: options?.connectionName ?? 'default',
|
|
49
64
|
depth: 1,
|
|
50
65
|
startedAt: new Date(),
|
|
51
66
|
name: options?.name,
|
|
52
67
|
};
|
|
53
68
|
return transactionStorage.run(ctx, fn);
|
|
54
|
-
}
|
|
69
|
+
};
|
|
55
70
|
if (options?.retry) {
|
|
56
|
-
const {
|
|
71
|
+
const { withTransactionRetry } = await import('@kysera/infra');
|
|
57
72
|
const maxAttempts = typeof options.retry === 'number' ? options.retry : 3;
|
|
58
|
-
return
|
|
73
|
+
return withTransactionRetry(db, inContext, {
|
|
59
74
|
maxAttempts,
|
|
60
|
-
delayMs: 100,
|
|
61
|
-
maxDelayMs: 2000,
|
|
62
|
-
shouldRetry: isSerializationError,
|
|
63
75
|
});
|
|
64
76
|
}
|
|
65
|
-
return
|
|
77
|
+
return db.transaction().execute(inContext);
|
|
66
78
|
}
|
|
67
79
|
export async function runWithTransaction(trx, fn, options) {
|
|
68
80
|
const existingCtx = transactionStorage.getStore();
|
|
69
81
|
const depth = existingCtx ? existingCtx.depth + 1 : 1;
|
|
70
82
|
const ctx = {
|
|
71
83
|
transaction: trx,
|
|
84
|
+
database: options?.database,
|
|
85
|
+
parent: existingCtx,
|
|
72
86
|
connectionName: options?.connectionName ?? existingCtx?.connectionName ?? 'default',
|
|
73
87
|
depth,
|
|
74
88
|
startedAt: new Date(),
|
|
@@ -85,9 +99,6 @@ export function AutoTransactional(options) {
|
|
|
85
99
|
throw new Error(`@AutoTransactional requires 'db' property on class ${target.constructor.name}. ` +
|
|
86
100
|
`Ensure the service has Kysely database injected.`);
|
|
87
101
|
}
|
|
88
|
-
if (isInTransactionContext()) {
|
|
89
|
-
return originalMethod.apply(this, args);
|
|
90
|
-
}
|
|
91
102
|
return runInTransaction(db, () => originalMethod.apply(this, args), {
|
|
92
103
|
name: options?.name ?? `${target.constructor.name}.${String(propertyKey)}`,
|
|
93
104
|
connectionName: options?.connectionName,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.context.js","sourceRoot":"","sources":["../../src/transaction/transaction.context.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"transaction.context.js","sourceRoot":"","sources":["../../src/transaction/transaction.context.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAqBrD,MAAM,WAAW,GAAG,UAAgD,CAAC;AAErE,MAAM,e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,CAAC,CAAC;AACzC,CAAC;AAUD,MAAM,UAAU,iBAAiB,CAAC,OAAoD;IACpF,OAAO,SAAS,0BAA0B,CACxC,MAAc,EACd,WAA4B,EAC5B,UAA8B;QAE9B,MAAM,cAAc,GAAG,UAAU,CAAC,KAAK,CAAC;QAExC,UAAU,CAAC,KAAK,GAAG,KAAK,UAAU,wBAAwB,CAAiC,GAAG,IAAe;YAC3G,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAEnB,IAAI,CAAC,EAAE,EAAE,CAAC;gBACR,MAAM,IAAI,KAAK,CACb,sDAAsD,MAAM,CAAC,WAAW,CAAC,IAAI,IAAI;oBAC/E,kDAAkD,CACrD,CAAC;YACJ,CAAC;YAED,OAAO,gBAAgB,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,cAAc,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE;gBAClE,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,IAAI,MAAM,CAAC,WAAW,CAAC,EAAE;gBAC1E,cAAc,EAAE,OAAO,EAAE,cAAc;aACxC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export
|
|
1
|
+
export { describeError } from '@omnitron-dev/titan/diagnostics';
|
|
2
2
|
//# sourceMappingURL=describe-error.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"describe-error.d.ts","sourceRoot":"","sources":["../../src/utils/describe-error.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"describe-error.d.ts","sourceRoot":"","sources":["../../src/utils/describe-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC"}
|
|
@@ -1,37 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
if (error == null)
|
|
3
|
-
return 'unknown error';
|
|
4
|
-
if (typeof error === 'string')
|
|
5
|
-
return error.trim() || 'unknown error';
|
|
6
|
-
if (!(error instanceof Error)) {
|
|
7
|
-
const described = String(error).trim();
|
|
8
|
-
return described && described !== '[object Object]' ? described : 'unknown error';
|
|
9
|
-
}
|
|
10
|
-
const message = error.message.trim();
|
|
11
|
-
if (message) {
|
|
12
|
-
const code = codeOf(error);
|
|
13
|
-
return code && !message.includes(code) ? `${message} (${code})` : message;
|
|
14
|
-
}
|
|
15
|
-
const causes = error.errors;
|
|
16
|
-
if (Array.isArray(causes) && causes.length > 0 && depth < 3) {
|
|
17
|
-
const described = causes.map((c) => describeError(c, depth + 1));
|
|
18
|
-
const unique = [...new Set(described)].filter((d) => d !== 'unknown error');
|
|
19
|
-
if (unique.length > 0)
|
|
20
|
-
return unique.join('; ');
|
|
21
|
-
}
|
|
22
|
-
const cause = error.cause;
|
|
23
|
-
if (cause != null && depth < 3) {
|
|
24
|
-
const described = describeError(cause, depth + 1);
|
|
25
|
-
if (described !== 'unknown error')
|
|
26
|
-
return described;
|
|
27
|
-
}
|
|
28
|
-
const code = codeOf(error);
|
|
29
|
-
if (code)
|
|
30
|
-
return `${error.name || 'Error'} (${code})`;
|
|
31
|
-
return error.name || 'unknown error';
|
|
32
|
-
}
|
|
33
|
-
function codeOf(error) {
|
|
34
|
-
const code = error.code;
|
|
35
|
-
return typeof code === 'string' && code.trim() ? code.trim() : undefined;
|
|
36
|
-
}
|
|
1
|
+
export { describeError } from '@omnitron-dev/titan/diagnostics';
|
|
37
2
|
//# sourceMappingURL=describe-error.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"describe-error.js","sourceRoot":"","sources":["../../src/utils/describe-error.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"describe-error.js","sourceRoot":"","sources":["../../src/utils/describe-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@omnitron-dev/titan-database",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "Database module for Titan framework with Kysely, migrations, RLS, and multi-dialect support",
|
|
5
5
|
"author": "LuxQuant",
|
|
6
6
|
"license": "MIT",
|
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
"types": "./dist/exports/plugins.d.ts",
|
|
17
17
|
"default": "./dist/exports/plugins.js"
|
|
18
18
|
},
|
|
19
|
+
"./coordination": {
|
|
20
|
+
"types": "./dist/exports/coordination.d.ts",
|
|
21
|
+
"default": "./dist/exports/coordination.js"
|
|
22
|
+
},
|
|
19
23
|
"./transaction": {
|
|
20
24
|
"types": "./dist/exports/transaction.d.ts",
|
|
21
25
|
"default": "./dist/exports/transaction.js"
|
|
@@ -39,31 +43,41 @@
|
|
|
39
43
|
"./dialects": {
|
|
40
44
|
"types": "./dist/exports/dialects.d.ts",
|
|
41
45
|
"default": "./dist/exports/dialects.js"
|
|
46
|
+
},
|
|
47
|
+
"./sqlite": {
|
|
48
|
+
"types": "./dist/exports/sqlite.d.ts",
|
|
49
|
+
"default": "./dist/exports/sqlite.js"
|
|
50
|
+
},
|
|
51
|
+
"./readiness": {
|
|
52
|
+
"types": "./dist/exports/readiness.d.ts",
|
|
53
|
+
"default": "./dist/exports/readiness.js"
|
|
42
54
|
}
|
|
43
55
|
},
|
|
44
56
|
"files": [
|
|
45
57
|
"dist"
|
|
46
58
|
],
|
|
47
59
|
"dependencies": {
|
|
48
|
-
"@kysera/audit": "^0.10.
|
|
49
|
-
"@kysera/core": "^0.10.
|
|
50
|
-
"@kysera/dialects": "^0.10.
|
|
51
|
-
"@kysera/executor": "^0.10.
|
|
52
|
-
"@kysera/infra": "^0.10.
|
|
53
|
-
"@kysera/migrations": "^0.10.
|
|
54
|
-
"@kysera/repository": "^0.10.
|
|
55
|
-
"@kysera/rls": "^0.10.
|
|
56
|
-
"@kysera/soft-delete": "^0.10.
|
|
57
|
-
"@kysera/timestamps": "^0.10.
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
"
|
|
60
|
+
"@kysera/audit": "^0.10.2",
|
|
61
|
+
"@kysera/core": "^0.10.2",
|
|
62
|
+
"@kysera/dialects": "^0.10.2",
|
|
63
|
+
"@kysera/executor": "^0.10.2",
|
|
64
|
+
"@kysera/infra": "^0.10.2",
|
|
65
|
+
"@kysera/migrations": "^0.10.2",
|
|
66
|
+
"@kysera/repository": "^0.10.2",
|
|
67
|
+
"@kysera/rls": "^0.10.2",
|
|
68
|
+
"@kysera/soft-delete": "^0.10.2",
|
|
69
|
+
"@kysera/timestamps": "^0.10.2",
|
|
70
|
+
"@omnitron-dev/eventemitter": "0.3.2",
|
|
71
|
+
"@types/better-sqlite3": "^9.6.0",
|
|
72
|
+
"kysely": "^0.29.8",
|
|
73
|
+
"zod": "^4.6.7",
|
|
74
|
+
"@kysera/dal": "^0.10.2"
|
|
61
75
|
},
|
|
62
76
|
"peerDependencies": {
|
|
77
|
+
"@omnitron-dev/titan": "0.3.2",
|
|
63
78
|
"better-sqlite3": "^13.0.3",
|
|
64
79
|
"mysql2": "^3.20.0",
|
|
65
|
-
"pg": "^8.20.0"
|
|
66
|
-
"@omnitron-dev/titan": "0.3.0"
|
|
80
|
+
"pg": "^8.20.0"
|
|
67
81
|
},
|
|
68
82
|
"peerDependenciesMeta": {
|
|
69
83
|
"pg": {
|
|
@@ -77,12 +91,19 @@
|
|
|
77
91
|
}
|
|
78
92
|
},
|
|
79
93
|
"devDependencies": {
|
|
80
|
-
"@
|
|
94
|
+
"@omnitron-dev/titan": "0.3.2",
|
|
95
|
+
"@types/node": "^26.6.6",
|
|
81
96
|
"reflect-metadata": "^0.2.2",
|
|
82
|
-
"typescript": "
|
|
83
|
-
"vitest": "^5.0.
|
|
84
|
-
"@
|
|
97
|
+
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
98
|
+
"vitest": "^5.0.5",
|
|
99
|
+
"@typescript/native": "npm:typescript@^7.0.2"
|
|
100
|
+
},
|
|
101
|
+
"repository": {
|
|
102
|
+
"type": "git",
|
|
103
|
+
"url": "git+https://github.com/omnitron-dev/omni.git",
|
|
104
|
+
"directory": "packages/titan-database"
|
|
85
105
|
},
|
|
106
|
+
"gitHead": "ecf537907f8e7efa75a56012a96c84c451ced77b",
|
|
86
107
|
"scripts": {
|
|
87
108
|
"build": "../../scripts/build-package.sh -p ./tsconfig.json",
|
|
88
109
|
"test": "vitest run",
|