@venizia/ignis-connectors 0.4.8-5 → 0.4.8-6
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/dist/esm/common/driver-data-source.d.ts +13 -6
- package/dist/esm/common/driver-data-source.js +71 -10
- package/dist/esm/common/driver-data-source.js.map +1 -1
- package/dist/esm/relational/core/datasources/abstract.d.ts +2 -0
- package/dist/esm/relational/core/datasources/abstract.js +4 -0
- package/dist/esm/relational/core/datasources/abstract.js.map +1 -1
- package/dist/esm/relational/core/datasources/base.d.ts +5 -1
- package/dist/esm/relational/core/datasources/base.js +12 -0
- package/dist/esm/relational/core/datasources/base.js.map +1 -1
- package/dist/esm/relational/core/datasources/common/types.d.ts +18 -2
- package/dist/esm/relational/core/datasources/common/types.js.map +1 -1
- package/dist/esm/relational/core/drivers/driver.d.ts +12 -0
- package/dist/esm/relational/core/drivers/driver.js +9 -1
- package/dist/esm/relational/core/drivers/driver.js.map +1 -1
- package/dist/esm/relational/core/migrations/runner.d.ts +29 -4
- package/dist/esm/relational/core/migrations/runner.js +114 -23
- package/dist/esm/relational/core/migrations/runner.js.map +1 -1
- package/dist/esm/relational/core/models/common/types.d.ts +20 -1
- package/dist/esm/relational/core/models/common/types.js.map +1 -1
- package/dist/esm/relational/core/models/common/unique-key-reader.d.ts +32 -0
- package/dist/esm/relational/core/models/common/unique-key-reader.js +140 -0
- package/dist/esm/relational/core/models/common/unique-key-reader.js.map +1 -0
- package/dist/esm/relational/core/models/index.d.ts +1 -0
- package/dist/esm/relational/core/models/index.js +1 -0
- package/dist/esm/relational/core/models/index.js.map +1 -1
- package/dist/esm/relational/core/models/unique-keys.d.ts +42 -0
- package/dist/esm/relational/core/models/unique-keys.js +41 -0
- package/dist/esm/relational/core/models/unique-keys.js.map +1 -0
- package/dist/esm/relational/core/repositories/common/executor.d.ts +14 -1
- package/dist/esm/relational/core/repositories/common/executor.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/scope-write-guard.d.ts +7 -0
- package/dist/esm/relational/core/repositories/common/scope-write-guard.js +11 -0
- package/dist/esm/relational/core/repositories/common/scope-write-guard.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/types.d.ts +10 -0
- package/dist/esm/relational/core/repositories/common/types.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/upsert-plan.d.ts +37 -0
- package/dist/esm/relational/core/repositories/common/upsert-plan.js +98 -0
- package/dist/esm/relational/core/repositories/common/upsert-plan.js.map +1 -0
- package/dist/esm/relational/core/repositories/core/base.d.ts +12 -1
- package/dist/esm/relational/core/repositories/core/base.js +58 -3
- package/dist/esm/relational/core/repositories/core/base.js.map +1 -1
- package/dist/esm/relational/core/repositories/core/persistable.d.ts +69 -2
- package/dist/esm/relational/core/repositories/core/persistable.js +95 -3
- package/dist/esm/relational/core/repositories/core/persistable.js.map +1 -1
- package/dist/esm/relational/core/repositories/core/readable.d.ts +28 -1
- package/dist/esm/relational/core/repositories/core/readable.js +115 -6
- package/dist/esm/relational/core/repositories/core/readable.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/filter.d.ts +21 -0
- package/dist/esm/relational/core/repositories/dialect/filter.js +107 -19
- package/dist/esm/relational/core/repositories/dialect/filter.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/internal/date-operand.d.ts +19 -0
- package/dist/esm/relational/core/repositories/dialect/internal/date-operand.js +79 -0
- package/dist/esm/relational/core/repositories/dialect/internal/date-operand.js.map +1 -0
- package/dist/esm/relational/core/repositories/dialect/internal/index.d.ts +1 -0
- package/dist/esm/relational/core/repositories/dialect/internal/index.js +1 -0
- package/dist/esm/relational/core/repositories/dialect/internal/index.js.map +1 -1
- package/dist/esm/relational/postgres/drivers/node-postgres.d.ts +2 -0
- package/dist/esm/relational/postgres/drivers/node-postgres.js +3 -0
- package/dist/esm/relational/postgres/drivers/node-postgres.js.map +1 -1
- package/dist/esm/relational/postgres/drivers/pglite.d.ts +2 -0
- package/dist/esm/relational/postgres/drivers/pglite.js +3 -0
- package/dist/esm/relational/postgres/drivers/pglite.js.map +1 -1
- package/dist/esm/relational/postgres/drivers/postgres-js.d.ts +2 -0
- package/dist/esm/relational/postgres/drivers/postgres-js.js +3 -0
- package/dist/esm/relational/postgres/drivers/postgres-js.js.map +1 -1
- package/dist/esm/relational/postgres/repositories/executor.d.ts +2 -0
- package/dist/esm/relational/postgres/repositories/executor.js +23 -2
- package/dist/esm/relational/postgres/repositories/executor.js.map +1 -1
- package/dist/esm/relational/sqlite/drivers/libsql.d.ts +2 -0
- package/dist/esm/relational/sqlite/drivers/libsql.js +3 -0
- package/dist/esm/relational/sqlite/drivers/libsql.js.map +1 -1
- package/dist/esm/relational/sqlite/repositories/executor.d.ts +2 -0
- package/dist/esm/relational/sqlite/repositories/executor.js +22 -2
- package/dist/esm/relational/sqlite/repositories/executor.js.map +1 -1
- package/dist/esm/search/core/repositories/common/types.d.ts +6 -3
- package/dist/esm/search/core/repositories/common/types.js.map +1 -1
- package/dist/esm/search/core/repositories/core/base.d.ts +7 -1
- package/dist/esm/search/core/repositories/core/base.js +41 -1
- package/dist/esm/search/core/repositories/core/base.js.map +1 -1
- package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.d.ts +2 -0
- package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.js +16 -5
- package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.js.map +1 -1
- package/dist/esm/search/typesense/repositories/dialect/query-dialect.d.ts +1 -0
- package/dist/esm/search/typesense/repositories/dialect/query-dialect.js +6 -3
- package/dist/esm/search/typesense/repositories/dialect/query-dialect.js.map +1 -1
- package/package.json +6 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';
|
|
1
|
+
import type { IDataSourceOpening, TAnyDataSourceSchema } from '@venizia/ignis-kernel';
|
|
2
2
|
import { AbstractDataSource } from '@venizia/ignis-kernel/repository';
|
|
3
3
|
import type { AnyObject, AnyType, TClass } from '@venizia/ignis-helpers/common';
|
|
4
4
|
import type { IConnectorDriver } from './driver.js';
|
|
@@ -14,15 +14,15 @@ import type { IConnectorDriver } from './driver.js';
|
|
|
14
14
|
* neutral base - do not move it down into a family.
|
|
15
15
|
*/
|
|
16
16
|
export declare abstract class AbstractDriverDataSource<Settings extends object = {}, Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema, ConfigurableOptions extends object = {}, Client = unknown, TConnector = unknown, TDriver extends IConnectorDriver<TConnector, AnyType> = IConnectorDriver<TConnector, Client>> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {
|
|
17
|
-
connector
|
|
17
|
+
connector?: TConnector;
|
|
18
18
|
protected client?: Client;
|
|
19
19
|
protected driver?: TDriver;
|
|
20
20
|
private closePromise?;
|
|
21
21
|
/**
|
|
22
22
|
* Lazy and idempotent: builds the driver named by `@datasource({ driver })` over the client
|
|
23
|
-
* `configure()` assigned, then the connector from it.
|
|
23
|
+
* `configure()` assigned, then the connector from it. Returns the connector.
|
|
24
24
|
*/
|
|
25
|
-
protected wireDriverFromMetadata():
|
|
25
|
+
protected wireDriverFromMetadata(): TConnector;
|
|
26
26
|
/**
|
|
27
27
|
* Rejects a driver-name string from untyped JS
|
|
28
28
|
* callers: a string carries no module into the bundle.
|
|
@@ -31,12 +31,16 @@ export declare abstract class AbstractDriverDataSource<Settings extends object =
|
|
|
31
31
|
protected resolveDriver(): TDriver;
|
|
32
32
|
/**
|
|
33
33
|
* Assigns `this.driver` AND builds `this.connector` in one step - a
|
|
34
|
-
* driver without its connector is silently bypassed on pooled queries.
|
|
34
|
+
* driver without its connector is silently bypassed on pooled queries. Returns the connector.
|
|
35
35
|
*/
|
|
36
36
|
protected useDriver(opts: {
|
|
37
37
|
driver: TDriver;
|
|
38
38
|
schema?: Schema;
|
|
39
|
-
}):
|
|
39
|
+
}): TConnector;
|
|
40
|
+
/** A datasource that opens on first use has no client, driver or connector until the first call that needs it has awaited `ensureOpen()`. */
|
|
41
|
+
private assertOpenForSyncUse;
|
|
42
|
+
/** The handles `configure()` is given: the connector and the client through the ungated internals, so its own database work (migrations, seeding) needs no gate. */
|
|
43
|
+
protected createOpening(): IDataSourceOpening<TConnector, Client>;
|
|
40
44
|
/** Wires the driver on first use, so a `configure()` that only builds `this.client` is enough. */
|
|
41
45
|
getConnector(): TConnector;
|
|
42
46
|
/**
|
|
@@ -44,12 +48,15 @@ export declare abstract class AbstractDriverDataSource<Settings extends object =
|
|
|
44
48
|
* than handing back an `undefined` typed as `Client`.
|
|
45
49
|
*/
|
|
46
50
|
getClient(): Client;
|
|
51
|
+
private readClient;
|
|
47
52
|
/**
|
|
48
53
|
* Ends the connection `configure()` opened. Runs once: every later call returns the first call's
|
|
49
54
|
* promise. Goes through the driver, wired now if nothing queried yet, because its `end()` is the
|
|
50
55
|
* engine's whole teardown - PGlite also clears the exit status it plants on the host process.
|
|
51
56
|
*/
|
|
52
57
|
close(): Promise<void>;
|
|
58
|
+
/** Ends a client that a failed open left half-built and forgets the driver and connector, so the next open starts from nothing. */
|
|
59
|
+
protected discardPartialOpen(): Promise<void>;
|
|
53
60
|
private endConnection;
|
|
54
61
|
/**
|
|
55
62
|
* Soft-evicts the pool after a secret rotation: rebuilds against the rotated credentials without
|
|
@@ -15,15 +15,16 @@ import { getError } from '@venizia/ignis-helpers/core';
|
|
|
15
15
|
export class AbstractDriverDataSource extends AbstractDataSource {
|
|
16
16
|
/**
|
|
17
17
|
* Lazy and idempotent: builds the driver named by `@datasource({ driver })` over the client
|
|
18
|
-
* `configure()` assigned, then the connector from it.
|
|
18
|
+
* `configure()` assigned, then the connector from it. Returns the connector.
|
|
19
19
|
*/
|
|
20
20
|
wireDriverFromMetadata() {
|
|
21
21
|
if (this.connector) {
|
|
22
|
-
return;
|
|
22
|
+
return this.connector;
|
|
23
23
|
}
|
|
24
24
|
if (this.driver) {
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
const connector = this.driver.createConnector({ schema: this.getSchema() });
|
|
26
|
+
this.connector = connector;
|
|
27
|
+
return connector;
|
|
27
28
|
}
|
|
28
29
|
if (!this.client) {
|
|
29
30
|
throw getError({
|
|
@@ -31,7 +32,7 @@ export class AbstractDriverDataSource extends AbstractDataSource {
|
|
|
31
32
|
});
|
|
32
33
|
}
|
|
33
34
|
const DriverClass = this.resolveDriverClass();
|
|
34
|
-
this.useDriver({ driver: new DriverClass({ client: this.client }) });
|
|
35
|
+
return this.useDriver({ driver: new DriverClass({ client: this.client }) });
|
|
35
36
|
}
|
|
36
37
|
/**
|
|
37
38
|
* Rejects a driver-name string from untyped JS
|
|
@@ -55,22 +56,57 @@ export class AbstractDriverDataSource extends AbstractDataSource {
|
|
|
55
56
|
}
|
|
56
57
|
/**
|
|
57
58
|
* Assigns `this.driver` AND builds `this.connector` in one step - a
|
|
58
|
-
* driver without its connector is silently bypassed on pooled queries.
|
|
59
|
+
* driver without its connector is silently bypassed on pooled queries. Returns the connector.
|
|
59
60
|
*/
|
|
60
61
|
useDriver(opts) {
|
|
61
62
|
this.driver = opts.driver;
|
|
62
|
-
|
|
63
|
+
const connector = opts.driver.createConnector({ schema: opts.schema ?? this.getSchema() });
|
|
64
|
+
this.connector = connector;
|
|
65
|
+
return connector;
|
|
66
|
+
}
|
|
67
|
+
/** A datasource that opens on first use has no client, driver or connector until the first call that needs it has awaited `ensureOpen()`. */
|
|
68
|
+
assertOpenForSyncUse(opts) {
|
|
69
|
+
if (!this.isOpenDeferred()) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (this.isClosed()) {
|
|
73
|
+
throw getError({
|
|
74
|
+
message: `[${this.constructor.name}][${opts.member}] The datasource is closed | It opens on first use only before close()`,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (this.isOpening()) {
|
|
78
|
+
throw getError({
|
|
79
|
+
message: `[${this.constructor.name}][${opts.member}] The datasource is still opening | Inside configure() use the opening argument (opening.${opts.member}()); outside it, await ensureOpen()`,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (!this.isOpen()) {
|
|
83
|
+
throw getError({
|
|
84
|
+
message: `[${this.constructor.name}][${opts.member}] The datasource opens on first use and is not open | Await ensureOpen() first; repository calls do it for you`,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** The handles `configure()` is given: the connector and the client through the ungated internals, so its own database work (migrations, seeding) needs no gate. */
|
|
89
|
+
createOpening() {
|
|
90
|
+
return {
|
|
91
|
+
...super.createOpening(),
|
|
92
|
+
getConnector: () => this.wireDriverFromMetadata(),
|
|
93
|
+
getClient: () => this.readClient(),
|
|
94
|
+
};
|
|
63
95
|
}
|
|
64
96
|
/** Wires the driver on first use, so a `configure()` that only builds `this.client` is enough. */
|
|
65
97
|
getConnector() {
|
|
66
|
-
this.
|
|
67
|
-
return this.
|
|
98
|
+
this.assertOpenForSyncUse({ member: this.getConnector.name });
|
|
99
|
+
return this.wireDriverFromMetadata();
|
|
68
100
|
}
|
|
69
101
|
/**
|
|
70
102
|
* Raw driver client (`pg.Pool` / `Sql`). Throws rather
|
|
71
103
|
* than handing back an `undefined` typed as `Client`.
|
|
72
104
|
*/
|
|
73
105
|
getClient() {
|
|
106
|
+
this.assertOpenForSyncUse({ member: this.getClient.name });
|
|
107
|
+
return this.readClient();
|
|
108
|
+
}
|
|
109
|
+
readClient() {
|
|
74
110
|
if (this.driver) {
|
|
75
111
|
return this.driver.getClient();
|
|
76
112
|
}
|
|
@@ -87,9 +123,28 @@ export class AbstractDriverDataSource extends AbstractDataSource {
|
|
|
87
123
|
* engine's whole teardown - PGlite also clears the exit status it plants on the host process.
|
|
88
124
|
*/
|
|
89
125
|
close() {
|
|
90
|
-
|
|
126
|
+
// A stop that arrives while the first use is still opening waits for that open, then closes what it built.
|
|
127
|
+
this.closePromise ??= this.settleOpening().then(() => this.endConnection());
|
|
91
128
|
return this.closePromise;
|
|
92
129
|
}
|
|
130
|
+
/** Ends a client that a failed open left half-built and forgets the driver and connector, so the next open starts from nothing. */
|
|
131
|
+
async discardPartialOpen() {
|
|
132
|
+
const { client, driver } = this;
|
|
133
|
+
this.client = undefined;
|
|
134
|
+
this.driver = undefined;
|
|
135
|
+
this.connector = undefined;
|
|
136
|
+
// A close() that is waiting for this open owns the slot: clearing it would let a second close end the connection twice.
|
|
137
|
+
if (!this.isClosed()) {
|
|
138
|
+
this.closePromise = undefined;
|
|
139
|
+
}
|
|
140
|
+
if (driver && typeof driver.end === 'function') {
|
|
141
|
+
await driver.end();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (client !== undefined) {
|
|
145
|
+
await this.drainClient({ client });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
93
148
|
async endConnection() {
|
|
94
149
|
if (!this.driver && this.client === undefined) {
|
|
95
150
|
return;
|
|
@@ -120,6 +175,12 @@ export class AbstractDriverDataSource extends AbstractDataSource {
|
|
|
120
175
|
*/
|
|
121
176
|
async onSecretRotated(opts) {
|
|
122
177
|
const logger = this.logger.for(this.onSecretRotated.name);
|
|
178
|
+
// Nothing is open yet, so there is no pool to swap: the rotated credentials wait in the settings for the first use.
|
|
179
|
+
if (this.isOpenDeferred() && !this.isOpen()) {
|
|
180
|
+
Object.assign(this.settings, this.mapSecretToSettings({ secret: opts.secret }));
|
|
181
|
+
logger.info('Datasource not open yet; credentials kept for its first use | key: %s', opts.key);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
123
184
|
const oldClient = this.getClient();
|
|
124
185
|
// Snapshot so a failed rebuild restores the datasource verbatim;
|
|
125
186
|
// `settings` is copied because rotation mutates it in place.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"driver-data-source.js","sourceRoot":"","sources":["../../../src/common/driver-data-source.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAElE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD;;;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E,QAAQ,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3C,MAAM,MAAM,GAAc,EAAE,CAAC;QAE7B,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;QACzB,CAAC;QAED,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC7B,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';\nimport { AbstractDataSource } from '@venizia/ignis-kernel/repository';\nimport { MetadataRegistry } from '@venizia/ignis-kernel/metadata';\nimport type { AnyObject, AnyType, TClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IConnectorDriver } from './driver';\n\n/**\n * A datasource that holds one client and a connector built over it through a driver: the lifecycle\n * every connector family that talks to an external engine shares - wiring the driver named by\n * `@datasource({ driver })`, closing once, soft-evicting the client after a secret rotation, draining\n * a client by whichever verb its engine spells it with. No SQL members: the relational family adds\n * its dialect, executor and transactions in `AbstractRelationalDataSource`, a raw-SQL engine adds\n * nothing (`BaseRawSqlDataSource`). Transactions stay NotSupported, as in `AbstractDataSource`.\n *\n * `mapSecretToSettings` is a driver-config convention, not Postgres SQL, so it belongs on this\n * neutral base - do not move it down into a family.\n */\nexport abstract class AbstractDriverDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n TDriver extends IConnectorDriver<TConnector, AnyType> = IConnectorDriver<TConnector, Client>,\n> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {\n connector: TConnector;\n\n protected client?: Client;\n protected driver?: TDriver;\n\n private closePromise?: Promise<void>;\n\n /**\n * Lazy and idempotent: builds the driver named by `@datasource({ driver })` over the client\n * `configure()` assigned, then the connector from it.\n */\n protected wireDriverFromMetadata(): void {\n if (this.connector) {\n return;\n }\n\n if (this.driver) {\n this.connector = this.driver.createConnector({ schema: this.getSchema() });\n\n return;\n }\n\n if (!this.client) {\n throw getError({\n message: `[${this.constructor.name}][wireDriverFromMetadata] No driver and no client | Assign this.client in configure(), or wire a custom driver with useDriver()`,\n });\n }\n\n const DriverClass = this.resolveDriverClass();\n this.useDriver({ driver: new DriverClass({ client: this.client }) });\n }\n\n /**\n * Rejects a driver-name string from untyped JS\n * callers: a string carries no module into the bundle.\n */\n protected resolveDriverClass(): TClass<TDriver> {\n const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({\n target: this.constructor,\n });\n const driver = metadata?.driver;\n\n if (typeof driver !== 'function') {\n throw getError({\n message: `[${this.constructor.name}][resolveDriverClass] @datasource({ driver }) must name a driver CLASS | Got: ${String(driver)} | Use \\`@datasource({ driver: NodePostgresDriver })\\` with \\`import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres'\\`, or wire a custom driver with useDriver()`,\n });\n }\n\n return driver as TClass<TDriver>;\n }\n\n protected resolveDriver(): TDriver {\n this.wireDriverFromMetadata();\n\n return this.driver as TDriver;\n }\n\n /**\n * Assigns `this.driver` AND builds `this.connector` in one step - a\n * driver without its connector is silently bypassed on pooled queries.\n */\n protected useDriver(opts: { driver: TDriver; schema?: Schema }): void {\n this.driver = opts.driver;\n this.connector = opts.driver.createConnector({ schema: opts.schema ?? this.getSchema() });\n }\n\n /** Wires the driver on first use, so a `configure()` that only builds `this.client` is enough. */\n getConnector(): TConnector {\n this.wireDriverFromMetadata();\n\n return this.connector;\n }\n\n /**\n * Raw driver client (`pg.Pool` / `Sql`). Throws rather\n * than handing back an `undefined` typed as `Client`.\n */\n getClient(): Client {\n if (this.driver) {\n return this.driver.getClient() as Client;\n }\n\n if (!this.client) {\n throw getError({\n message: `[${this.constructor.name}][getClient] No driver and no client | Assign this.driver in configure()`,\n });\n }\n\n return this.client;\n }\n\n /**\n * Ends the connection `configure()` opened. Runs once: every later call returns the first call's\n * promise. Goes through the driver, wired now if nothing queried yet, because its `end()` is the\n * engine's whole teardown - PGlite also clears the exit status it plants on the host process.\n */\n override close(): Promise<void> {\n this.closePromise ??= this.endConnection();\n\n return this.closePromise;\n }\n\n private async endConnection(): Promise<void> {\n if (!this.driver && this.client === undefined) {\n return;\n }\n\n let driver: TDriver;\n\n try {\n driver = this.resolveDriver();\n } catch (error) {\n this.logger\n .for(this.close.name)\n .warn('No driver to end the connection with | draining the client | error: %s', error);\n await this.drainClient({ client: this.client });\n\n return;\n }\n\n // A hand-made driver cast past `IConnectorDriver` can lack the `end()` its type promises.\n if (typeof driver.end !== 'function') {\n this.logger.for(this.close.name).warn('The driver has no end() | draining the client');\n await this.drainClient({ client: this.client });\n\n return;\n }\n\n await driver.end();\n }\n\n /**\n * Soft-evicts the pool after a secret rotation: rebuilds against the rotated credentials without\n * touching live fields, swaps atomically, then drains the old pool. On failure live state is\n * restored, any half-built pool drained, and the error rethrown.\n */\n async onSecretRotated(opts: { key: string; secret: Record<string, string> }): Promise<void> {\n const logger = this.logger.for(this.onSecretRotated.name);\n const oldClient = this.getClient() as AnyType;\n\n // Snapshot so a failed rebuild restores the datasource verbatim;\n // `settings` is copied because rotation mutates it in place.\n const savedClient = this.client;\n const savedSettings = { ...(this.settings as AnyObject) };\n\n // Rotation only takes effect through this.settings + configure(); a configure() that\n // hard-codes its connection string or reads the environment directly rebuilds with stale credentials.\n Object.assign(this.settings as AnyObject, this.mapSecretToSettings({ secret: opts.secret }));\n\n // configure() overwrites this.client, so the new pool is captured\n // into a local and the old client restored at once - live fields\n // are never nulled and the old pool keeps serving until the swap.\n let newClient: Client;\n\n try {\n await this.configure();\n newClient = this.client as Client;\n } catch (error) {\n const halfBuilt = this.client as AnyType;\n this.client = savedClient;\n this.restoreSettings({ saved: savedSettings });\n\n if (halfBuilt && halfBuilt !== savedClient) {\n await this.drainClient({ client: halfBuilt });\n }\n\n logger.error('Secret rotation failed in configure(); kept old pool | key: %s', opts.key);\n throw error;\n }\n\n this.client = savedClient;\n\n // Wired into locals: live state must stay on the old pool until the swap below.\n let newDriver: TDriver;\n let newConnector: TConnector;\n\n try {\n const DriverClass = this.resolveDriverClass();\n newDriver = new DriverClass({ client: newClient as AnyType });\n newConnector = newDriver.createConnector({ schema: this.getSchema() });\n } catch (error) {\n this.restoreSettings({ saved: savedSettings });\n await this.drainClient({ client: newClient });\n\n logger.error('Secret rotation failed while wiring driver; kept old pool | key: %s', opts.key);\n throw error;\n }\n\n // Commit the live fields in one synchronous step so there is no null window,\n // then soft-evict the old pool so its in-flight transactions can finish.\n this.client = newClient as AnyType;\n this.driver = newDriver;\n this.connector = newConnector as AnyType;\n\n const isDrained = await this.drainClient({ client: oldClient });\n\n if (isDrained) {\n logger.info('Old pool drained after secret rotation | key: %s', opts.key);\n }\n }\n\n /** Puts `settings` back to the snapshot: a key the failed rotation added (the rotated `password`) is removed, not left behind. */\n private restoreSettings(opts: { saved: AnyObject }): void {\n const settings = this.settings as AnyObject;\n\n for (const key of Object.keys(settings)) {\n if (!(key in opts.saved)) {\n delete settings[key];\n }\n }\n\n Object.assign(settings, opts.saved);\n }\n\n /**\n * Shuts a client down by whichever verb its engine spells it with -\n * `pg.Pool` and postgres.js have `end()`, PGlite and libsql only `close()`.\n * Probed rather than type-tested: this tier must not name an engine, and a\n * client left undrained keeps a WASM instance or file handle alive forever.\n */\n protected async drainClient(opts: { client: unknown }): Promise<boolean> {\n const client = opts.client as AnyType;\n\n const drain = typeof client?.end === 'function' ? client.end : client?.close;\n\n if (typeof drain !== 'function') {\n this.logger\n .for(this.drainClient.name)\n .warn('Client exposes neither end() nor close(); nothing to drain');\n\n return false;\n }\n\n await drain.call(client);\n\n return true;\n }\n\n /** Vault's database engine returns `{ username, password }`; pg expects `{ user, password }`. */\n protected mapSecretToSettings(opts: { secret: Record<string, string> }): AnyObject {\n const { username, password } = opts.secret;\n const mapped: AnyObject = {};\n\n if (username !== undefined) {\n mapped.user = username;\n }\n\n if (password !== undefined) {\n mapped.password = password;\n }\n\n return mapped;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"driver-data-source.js","sourceRoot":"","sources":["../../../src/common/driver-data-source.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAElE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD;;;;;;;;;;GAUG;AACH,MAAM,OAAgB,wBAOpB,SAAQ,kBAAyD;IAQjE;;;OAGG;IACO,sBAAsB;QAC9B,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,OAAO,IAAI,CAAC,SAAS,CAAC;QACxB,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;YAC5E,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;YAE3B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,iIAAiI;aACpK,CAAC,CAAC;QACL,CAAC;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAAC;QAE9C,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,IAAI,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED;;;OAGG;IACO,kBAAkB;QAC1B,MAAM,QAAQ,GAAG,gBAAgB,CAAC,WAAW,EAAE,CAAC,qBAAqB,CAAC;YACpE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,CAAC,IAAI,CAAC;iBAC1B,IAAI,CAAC,4DAA4D,CAAC,CAAC;YAEtE,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,iGAAiG;IACvF,mBAAmB,CAAC,IAAwC;QACpE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3C,MAAM,MAAM,GAAc,EAAE,CAAC;QAE7B,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;QACzB,CAAC;QAED,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC7B,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import type { IDataSourceOpening, TAnyDataSourceSchema } from '@venizia/ignis-kernel';\nimport { AbstractDataSource } from '@venizia/ignis-kernel/repository';\nimport { MetadataRegistry } from '@venizia/ignis-kernel/metadata';\nimport type { AnyObject, AnyType, TClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IConnectorDriver } from './driver';\n\n/**\n * A datasource that holds one client and a connector built over it through a driver: the lifecycle\n * every connector family that talks to an external engine shares - wiring the driver named by\n * `@datasource({ driver })`, closing once, soft-evicting the client after a secret rotation, draining\n * a client by whichever verb its engine spells it with. No SQL members: the relational family adds\n * its dialect, executor and transactions in `AbstractRelationalDataSource`, a raw-SQL engine adds\n * nothing (`BaseRawSqlDataSource`). Transactions stay NotSupported, as in `AbstractDataSource`.\n *\n * `mapSecretToSettings` is a driver-config convention, not Postgres SQL, so it belongs on this\n * neutral base - do not move it down into a family.\n */\nexport abstract class AbstractDriverDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n TDriver extends IConnectorDriver<TConnector, AnyType> = IConnectorDriver<TConnector, Client>,\n> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {\n connector?: TConnector;\n\n protected client?: Client;\n protected driver?: TDriver;\n\n private closePromise?: Promise<void>;\n\n /**\n * Lazy and idempotent: builds the driver named by `@datasource({ driver })` over the client\n * `configure()` assigned, then the connector from it. Returns the connector.\n */\n protected wireDriverFromMetadata(): TConnector {\n if (this.connector) {\n return this.connector;\n }\n\n if (this.driver) {\n const connector = this.driver.createConnector({ schema: this.getSchema() });\n this.connector = connector;\n\n return connector;\n }\n\n if (!this.client) {\n throw getError({\n message: `[${this.constructor.name}][wireDriverFromMetadata] No driver and no client | Assign this.client in configure(), or wire a custom driver with useDriver()`,\n });\n }\n\n const DriverClass = this.resolveDriverClass();\n\n return this.useDriver({ driver: new DriverClass({ client: this.client }) });\n }\n\n /**\n * Rejects a driver-name string from untyped JS\n * callers: a string carries no module into the bundle.\n */\n protected resolveDriverClass(): TClass<TDriver> {\n const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({\n target: this.constructor,\n });\n const driver = metadata?.driver;\n\n if (typeof driver !== 'function') {\n throw getError({\n message: `[${this.constructor.name}][resolveDriverClass] @datasource({ driver }) must name a driver CLASS | Got: ${String(driver)} | Use \\`@datasource({ driver: NodePostgresDriver })\\` with \\`import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres'\\`, or wire a custom driver with useDriver()`,\n });\n }\n\n return driver as TClass<TDriver>;\n }\n\n protected resolveDriver(): TDriver {\n this.wireDriverFromMetadata();\n\n return this.driver as TDriver;\n }\n\n /**\n * Assigns `this.driver` AND builds `this.connector` in one step - a\n * driver without its connector is silently bypassed on pooled queries. Returns the connector.\n */\n protected useDriver(opts: { driver: TDriver; schema?: Schema }): TConnector {\n this.driver = opts.driver;\n const connector = opts.driver.createConnector({ schema: opts.schema ?? this.getSchema() });\n this.connector = connector;\n\n return connector;\n }\n\n /** A datasource that opens on first use has no client, driver or connector until the first call that needs it has awaited `ensureOpen()`. */\n private assertOpenForSyncUse(opts: { member: string }): void {\n if (!this.isOpenDeferred()) {\n return;\n }\n\n if (this.isClosed()) {\n throw getError({\n message: `[${this.constructor.name}][${opts.member}] The datasource is closed | It opens on first use only before close()`,\n });\n }\n\n if (this.isOpening()) {\n throw getError({\n message: `[${this.constructor.name}][${opts.member}] The datasource is still opening | Inside configure() use the opening argument (opening.${opts.member}()); outside it, await ensureOpen()`,\n });\n }\n\n if (!this.isOpen()) {\n throw getError({\n message: `[${this.constructor.name}][${opts.member}] The datasource opens on first use and is not open | Await ensureOpen() first; repository calls do it for you`,\n });\n }\n }\n\n /** The handles `configure()` is given: the connector and the client through the ungated internals, so its own database work (migrations, seeding) needs no gate. */\n protected override createOpening(): IDataSourceOpening<TConnector, Client> {\n return {\n ...super.createOpening(),\n getConnector: () => this.wireDriverFromMetadata(),\n getClient: () => this.readClient(),\n };\n }\n\n /** Wires the driver on first use, so a `configure()` that only builds `this.client` is enough. */\n getConnector(): TConnector {\n this.assertOpenForSyncUse({ member: this.getConnector.name });\n\n return this.wireDriverFromMetadata();\n }\n\n /**\n * Raw driver client (`pg.Pool` / `Sql`). Throws rather\n * than handing back an `undefined` typed as `Client`.\n */\n getClient(): Client {\n this.assertOpenForSyncUse({ member: this.getClient.name });\n\n return this.readClient();\n }\n\n private readClient(): Client {\n if (this.driver) {\n return this.driver.getClient() as Client;\n }\n\n if (!this.client) {\n throw getError({\n message: `[${this.constructor.name}][getClient] No driver and no client | Assign this.driver in configure()`,\n });\n }\n\n return this.client;\n }\n\n /**\n * Ends the connection `configure()` opened. Runs once: every later call returns the first call's\n * promise. Goes through the driver, wired now if nothing queried yet, because its `end()` is the\n * engine's whole teardown - PGlite also clears the exit status it plants on the host process.\n */\n override close(): Promise<void> {\n // A stop that arrives while the first use is still opening waits for that open, then closes what it built.\n this.closePromise ??= this.settleOpening().then(() => this.endConnection());\n\n return this.closePromise;\n }\n\n /** Ends a client that a failed open left half-built and forgets the driver and connector, so the next open starts from nothing. */\n protected override async discardPartialOpen(): Promise<void> {\n const { client, driver } = this;\n\n this.client = undefined;\n this.driver = undefined;\n this.connector = undefined;\n\n // A close() that is waiting for this open owns the slot: clearing it would let a second close end the connection twice.\n if (!this.isClosed()) {\n this.closePromise = undefined;\n }\n\n if (driver && typeof driver.end === 'function') {\n await driver.end();\n\n return;\n }\n\n if (client !== undefined) {\n await this.drainClient({ client });\n }\n }\n\n private async endConnection(): Promise<void> {\n if (!this.driver && this.client === undefined) {\n return;\n }\n\n let driver: TDriver;\n\n try {\n driver = this.resolveDriver();\n } catch (error) {\n this.logger\n .for(this.close.name)\n .warn('No driver to end the connection with | draining the client | error: %s', error);\n await this.drainClient({ client: this.client });\n\n return;\n }\n\n // A hand-made driver cast past `IConnectorDriver` can lack the `end()` its type promises.\n if (typeof driver.end !== 'function') {\n this.logger.for(this.close.name).warn('The driver has no end() | draining the client');\n await this.drainClient({ client: this.client });\n\n return;\n }\n\n await driver.end();\n }\n\n /**\n * Soft-evicts the pool after a secret rotation: rebuilds against the rotated credentials without\n * touching live fields, swaps atomically, then drains the old pool. On failure live state is\n * restored, any half-built pool drained, and the error rethrown.\n */\n async onSecretRotated(opts: { key: string; secret: Record<string, string> }): Promise<void> {\n const logger = this.logger.for(this.onSecretRotated.name);\n\n // Nothing is open yet, so there is no pool to swap: the rotated credentials wait in the settings for the first use.\n if (this.isOpenDeferred() && !this.isOpen()) {\n Object.assign(this.settings, this.mapSecretToSettings({ secret: opts.secret }));\n logger.info(\n 'Datasource not open yet; credentials kept for its first use | key: %s',\n opts.key,\n );\n\n return;\n }\n\n const oldClient = this.getClient() as AnyType;\n\n // Snapshot so a failed rebuild restores the datasource verbatim;\n // `settings` is copied because rotation mutates it in place.\n const savedClient = this.client;\n const savedSettings = { ...(this.settings as AnyObject) };\n\n // Rotation only takes effect through this.settings + configure(); a configure() that\n // hard-codes its connection string or reads the environment directly rebuilds with stale credentials.\n Object.assign(this.settings as AnyObject, this.mapSecretToSettings({ secret: opts.secret }));\n\n // configure() overwrites this.client, so the new pool is captured\n // into a local and the old client restored at once - live fields\n // are never nulled and the old pool keeps serving until the swap.\n let newClient: Client;\n\n try {\n await this.configure();\n newClient = this.client as Client;\n } catch (error) {\n const halfBuilt = this.client as AnyType;\n this.client = savedClient;\n this.restoreSettings({ saved: savedSettings });\n\n if (halfBuilt && halfBuilt !== savedClient) {\n await this.drainClient({ client: halfBuilt });\n }\n\n logger.error('Secret rotation failed in configure(); kept old pool | key: %s', opts.key);\n throw error;\n }\n\n this.client = savedClient;\n\n // Wired into locals: live state must stay on the old pool until the swap below.\n let newDriver: TDriver;\n let newConnector: TConnector;\n\n try {\n const DriverClass = this.resolveDriverClass();\n newDriver = new DriverClass({ client: newClient as AnyType });\n newConnector = newDriver.createConnector({ schema: this.getSchema() });\n } catch (error) {\n this.restoreSettings({ saved: savedSettings });\n await this.drainClient({ client: newClient });\n\n logger.error('Secret rotation failed while wiring driver; kept old pool | key: %s', opts.key);\n throw error;\n }\n\n // Commit the live fields in one synchronous step so there is no null window,\n // then soft-evict the old pool so its in-flight transactions can finish.\n this.client = newClient as AnyType;\n this.driver = newDriver;\n this.connector = newConnector as AnyType;\n\n const isDrained = await this.drainClient({ client: oldClient });\n\n if (isDrained) {\n logger.info('Old pool drained after secret rotation | key: %s', opts.key);\n }\n }\n\n /** Puts `settings` back to the snapshot: a key the failed rotation added (the rotated `password`) is removed, not left behind. */\n private restoreSettings(opts: { saved: AnyObject }): void {\n const settings = this.settings as AnyObject;\n\n for (const key of Object.keys(settings)) {\n if (!(key in opts.saved)) {\n delete settings[key];\n }\n }\n\n Object.assign(settings, opts.saved);\n }\n\n /**\n * Shuts a client down by whichever verb its engine spells it with -\n * `pg.Pool` and postgres.js have `end()`, PGlite and libsql only `close()`.\n * Probed rather than type-tested: this tier must not name an engine, and a\n * client left undrained keeps a WASM instance or file handle alive forever.\n */\n protected async drainClient(opts: { client: unknown }): Promise<boolean> {\n const client = opts.client as AnyType;\n\n const drain = typeof client?.end === 'function' ? client.end : client?.close;\n\n if (typeof drain !== 'function') {\n this.logger\n .for(this.drainClient.name)\n .warn('Client exposes neither end() nor close(); nothing to drain');\n\n return false;\n }\n\n await drain.call(client);\n\n return true;\n }\n\n /** Vault's database engine returns `{ username, password }`; pg expects `{ user, password }`. */\n protected mapSecretToSettings(opts: { secret: Record<string, string> }): AnyObject {\n const { username, password } = opts.secret;\n const mapped: AnyObject = {};\n\n if (username !== undefined) {\n mapped.user = username;\n }\n\n if (password !== undefined) {\n mapped.password = password;\n }\n\n return mapped;\n }\n}\n"]}
|
|
@@ -12,6 +12,8 @@ import type { IRelationalQueryDialect, IRelationalQueryExecutor } from '../repos
|
|
|
12
12
|
* query executor.
|
|
13
13
|
*/
|
|
14
14
|
export declare abstract class AbstractRelationalDataSource<Settings extends object = {}, Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema, ConfigurableOptions extends object = {}, Client = unknown, TConnector = unknown> extends AbstractDriverDataSource<Settings, Schema, ConfigurableOptions, Client, TConnector, IRelationalDriver<TConnector>> implements IRelationalDataSource<Settings, Schema, ConfigurableOptions, Client, TConnector> {
|
|
15
|
+
/** Every repository verb and `beginTransaction()` awaits `ensureOpen()` first, so a relational datasource can open on first use. */
|
|
16
|
+
protected supportsDeferredOpen(): boolean;
|
|
15
17
|
abstract getConnectionString(): ValueOrPromise<string>;
|
|
16
18
|
abstract beginTransaction(opts?: TRelationalTransactionOptions): Promise<IRelationalTransaction<TConnector>>;
|
|
17
19
|
abstract getQueryDialect(): IRelationalQueryDialect;
|
|
@@ -7,5 +7,9 @@ import { AbstractDriverDataSource } from '../../../common/driver-data-source.js'
|
|
|
7
7
|
* query executor.
|
|
8
8
|
*/
|
|
9
9
|
export class AbstractRelationalDataSource extends AbstractDriverDataSource {
|
|
10
|
+
/** Every repository verb and `beginTransaction()` awaits `ensureOpen()` first, so a relational datasource can open on first use. */
|
|
11
|
+
supportsDeferredOpen() {
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
10
14
|
}
|
|
11
15
|
//# sourceMappingURL=abstract.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/relational/core/datasources/abstract.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAYvE;;;;;;GAMG;AACH,MAAM,OAAgB,4BAOpB,SAAQ,wBAOP;
|
|
1
|
+
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/relational/core/datasources/abstract.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAYvE;;;;;;GAMG;AACH,MAAM,OAAgB,4BAOpB,SAAQ,wBAOP;IAGD,oIAAoI;IACjH,oBAAoB;QACrC,OAAO,IAAI,CAAC;IACd,CAAC;CASF","sourcesContent":["import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { AbstractDriverDataSource } from '@/common/driver-data-source';\nimport type { IRelationalDriver } from '@/relational/core/drivers';\nimport type {\n IRelationalDataSource,\n IRelationalTransaction,\n TRelationalTransactionOptions,\n} from '@/relational/core/datasources/common';\nimport type {\n IRelationalQueryDialect,\n IRelationalQueryExecutor,\n} from '@/relational/core/repositories/common';\n\n/**\n * SQL branch root: connector, pool, transactions. Engine-neutral - dialect and executor are\n * declared abstract here and supplied by each engine branch. The driver lifecycle (wiring, close,\n * secret rotation, drain) is `AbstractDriverDataSource`, shared with the raw-SQL family; this class\n * adds what only a relational engine has: a connection string, transactions, a query dialect and a\n * query executor.\n */\nexport abstract class AbstractRelationalDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n>\n extends AbstractDriverDataSource<\n Settings,\n Schema,\n ConfigurableOptions,\n Client,\n TConnector,\n IRelationalDriver<TConnector>\n >\n implements IRelationalDataSource<Settings, Schema, ConfigurableOptions, Client, TConnector>\n{\n /** Every repository verb and `beginTransaction()` awaits `ensureOpen()` first, so a relational datasource can open on first use. */\n protected override supportsDeferredOpen(): boolean {\n return true;\n }\n\n abstract getConnectionString(): ValueOrPromise<string>;\n abstract override beginTransaction(\n opts?: TRelationalTransactionOptions,\n ): Promise<IRelationalTransaction<TConnector>>;\n\n abstract getQueryDialect(): IRelationalQueryDialect;\n abstract getQueryExecutor(): IRelationalQueryExecutor<TConnector>;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';
|
|
2
2
|
import { AbstractRelationalDataSource } from './abstract.js';
|
|
3
|
-
import type { IRelationalTransaction, TRelationalTransactionOptions } from './common/index.js';
|
|
3
|
+
import type { IRelationalDataSourceOpening, IRelationalTransaction, TRelationalTransactionOptions } from './common/index.js';
|
|
4
4
|
/** Base DataSource with schema auto-discovery from registered repositories. */
|
|
5
5
|
export declare abstract class BaseRelationalDataSource<Settings extends object = {}, Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema, ConfigurableOptions extends object = {}, Client = unknown, TConnector = unknown> extends AbstractRelationalDataSource<Settings, Schema, ConfigurableOptions, Client, TConnector> {
|
|
6
6
|
constructor(opts: {
|
|
@@ -16,6 +16,10 @@ export declare abstract class BaseRelationalDataSource<Settings extends object =
|
|
|
16
16
|
transactions: boolean;
|
|
17
17
|
};
|
|
18
18
|
beginTransaction(opts?: TRelationalTransactionOptions): Promise<IRelationalTransaction<TConnector>>;
|
|
19
|
+
/** Adds the transaction to the handles of the open: `configure()` can run its migrations in one, through the ungated internals. */
|
|
20
|
+
protected createOpening(): IRelationalDataSourceOpening<TConnector, Client>;
|
|
21
|
+
/** A transaction on a connection of its own, with no gate: for `beginTransaction()` (after the open) and for the open itself. */
|
|
22
|
+
private openTransaction;
|
|
19
23
|
/** The engine's own BEGIN. Postgres interpolates an isolation level; SQLite has none and uses `BEGIN IMMEDIATE`. Never parameterized - `BEGIN ... ISOLATION LEVEL $1` is not valid SQL. */
|
|
20
24
|
protected abstract buildBeginStatement(opts?: TRelationalTransactionOptions): string;
|
|
21
25
|
}
|
|
@@ -98,6 +98,18 @@ export class BaseRelationalDataSource extends AbstractRelationalDataSource {
|
|
|
98
98
|
return { transactions: true };
|
|
99
99
|
}
|
|
100
100
|
async beginTransaction(opts) {
|
|
101
|
+
await this.ensureOpen();
|
|
102
|
+
return this.openTransaction(opts);
|
|
103
|
+
}
|
|
104
|
+
/** Adds the transaction to the handles of the open: `configure()` can run its migrations in one, through the ungated internals. */
|
|
105
|
+
createOpening() {
|
|
106
|
+
return {
|
|
107
|
+
...super.createOpening(),
|
|
108
|
+
beginTransaction: (opts) => this.openTransaction(opts),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** A transaction on a connection of its own, with no gate: for `beginTransaction()` (after the open) and for the open itself. */
|
|
112
|
+
async openTransaction(opts) {
|
|
101
113
|
const driver = this.resolveDriver();
|
|
102
114
|
const connection = await driver.acquire({ schema: this.getSchema() });
|
|
103
115
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/relational/core/datasources/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAyB,MAAM,uBAAuB,CAAC;AAGvF,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,kGAAkG;AAClG,oHAAoH;AACpH,mGAAmG;AACnG,oGAAoG;AACpG,mEAAmE;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,yDAAyD,CAAC;AAE3F,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EAAE,eAAe,EAAE,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,MAAM,MAAM,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QACpC,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;QAEtE,IAAI,CAAC;YACH,MAAM,UAAU,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC1E,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,KAAK,CAAC,yCAAyC,EAAE,KAAK,CAAC,CAAC;YAE5F,oLAAoL;YACpL,UAAU,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;YACtC,MAAM,KAAK,CAAC;QACd,CAAC;QAED,OAAO,IAAI,qBAAqB,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;IACrE,CAAC;CAIF;AAED,mGAAmG;AACnG,mGAAmG;AACnG,0EAA0E;AAC1E,uBAAuB,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,gBAAgB,CAAC,MAA0B,EAAE,CAAC,CAAC","sourcesContent":["import { MetadataRegistry } from '@venizia/ignis-kernel';\nimport { RelationBuilderRegistry, type TRelationBuilder } from '@venizia/ignis-kernel';\nimport type { TClass } from '@venizia/ignis-helpers/common';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IDataSource, TAnyDataSourceSchema } from '@venizia/ignis-kernel';\n// Deep import, not a barrel: `discoverSchema()` below is the only production call site that needs\n// `RelationsFactory.create`, so the install runs from here rather than `dialect/relations/create.ts` - nothing else\n// value-imports that file's `RelationsFactory` export, and a `sideEffects: false` bundler drops an\n// unused export's module body even when it is reachable through a barrel `export *` chain (verified\n// with `bun build --target=browser`, the tool `make purity` uses).\nimport { RelationsFactory } from '@/relational/core/repositories/dialect/relations/create';\nimport type { IRelationalConnection } from '@/relational/core/drivers';\nimport { AbstractRelationalDataSource } from './abstract';\nimport type { IRelationalTransaction, TRelationalTransactionOptions } from './common';\nimport { RelationPairing } from './relation-pairing';\nimport type { ITransactionEnd } from './transaction-lifecycle';\nimport { TransactionLifecycle } from './transaction-lifecycle';\n\n/** The handle `beginTransaction()` returns: the shared end rules over one acquired connection. On a failed end the connection is discarded rather than pooled - the next borrower would inherit an open transaction - and the error rethrown: a caller must never believe a failed COMMIT succeeded. */\nclass ConnectionTransaction<TConnector>\n extends TransactionLifecycle\n implements IRelationalTransaction<TConnector>\n{\n readonly connector: TConnector;\n\n // ES-private so a logged, spread or serialised handle never reaches the datasource settings. The datasource, not its logger: the logger is read only when an end fails or is a no-op.\n readonly #dataSource: { readonly logger: ILogger };\n readonly #connection: IRelationalConnection<TConnector>;\n\n constructor(opts: {\n dataSource: { readonly logger: ILogger };\n connection: IRelationalConnection<TConnector>;\n }) {\n super();\n\n this.#dataSource = opts.dataSource;\n this.#connection = opts.connection;\n this.connector = opts.connection.connector;\n }\n\n protected override executeEnd(opts: { end: ITransactionEnd }): Promise<unknown> {\n return this.#connection.execute({ statement: opts.end.statement });\n }\n\n protected override onEnded(): void {\n this.#connection.release();\n }\n\n protected override onEndFailed(opts: { end: ITransactionEnd; error: unknown }): void {\n const { end, error } = opts;\n\n this.#dataSource.logger\n .for(end.verb)\n .error('Failed to %s transaction | Error: %s', end.statement, error);\n this.#connection.release({ destroy: true });\n }\n\n protected override onRollbackAfterFailure(): void {\n this.#dataSource.logger\n .for('rollback')\n .debug('Rollback after a failure-ended transaction - no-op, already torn down');\n }\n}\n\n/** Base DataSource with schema auto-discovery from registered repositories. */\nexport abstract class BaseRelationalDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n> extends AbstractRelationalDataSource<Settings, Schema, ConfigurableOptions, Client, TConnector> {\n constructor(opts: { name: string; config: Settings; schema?: Schema }) {\n super({ scope: opts.name });\n\n this.name = opts.name;\n this.settings = opts.config;\n\n if (opts.schema) {\n this.schema = opts.schema;\n }\n }\n\n /** Auto-discovers schema from repositories if not manually provided. */\n override getSchema(): Schema {\n this.schema ??= this.discoverSchema();\n\n return this.schema;\n }\n\n protected discoverSchema(): Schema {\n const registry = MetadataRegistry.getInstance();\n const metadata = registry.getDataSourceMetadata({ target: this.constructor });\n\n if (metadata?.autoDiscovery === false) {\n this.logger.for(this.discoverSchema.name).debug('Auto-discovery disabled for %s', this.name);\n\n return {} as Schema;\n }\n\n const { schema, relations } = registry.buildSchema({\n dataSource: this.constructor as TClass<IDataSource>,\n });\n\n const models = Object.keys(schema);\n this.logger\n .for(this.discoverSchema.name)\n .debug(\n 'Detected model(s) | Name: %s | Count: %s | Models: %j',\n this.name,\n models.length,\n models,\n );\n\n const discovered = { ...schema, ...relations };\n\n // An inverse one() nothing pairs fails here; any other relation drizzle cannot pair is only\n // reported, so a model set that boots today keeps booting, and its first query still throws.\n const { unpaired, outside } = RelationPairing.inspect({\n dataSource: this.constructor.name,\n schema: discovered,\n });\n const fatal = unpaired.find((item) =>\n RelationPairing.isInverseOne({ relation: item.relation }),\n );\n\n if (fatal) {\n throw getError({ message: fatal.message });\n }\n\n const logger = this.logger.for(this.discoverSchema.name);\n\n for (const item of unpaired) {\n logger.warn(item.message);\n }\n\n if (outside.length > 0) {\n logger.debug(RelationPairing.describeOutside({ outside }));\n }\n\n // buildSchema() is shared by every connector so it returns Record<string, unknown>; the cast narrows back to the Drizzle schema shape.\n return discovered as Schema;\n }\n\n hasDiscoverableModels(): boolean {\n const registry = MetadataRegistry.getInstance();\n\n return registry.hasModels({ dataSource: this.constructor as TClass<IDataSource> });\n }\n\n override getCapabilities() {\n return { transactions: true };\n }\n\n override async beginTransaction(\n opts?: TRelationalTransactionOptions,\n ): Promise<IRelationalTransaction<TConnector>> {\n const driver = this.resolveDriver();\n const connection = await driver.acquire({ schema: this.getSchema() });\n\n try {\n await connection.execute({ statement: this.buildBeginStatement(opts) });\n } catch (error) {\n this.logger.for('beginTransaction').error('Failed to BEGIN transaction | Error: %s', error);\n\n // No caller ever receives a handle to release this connection, so leaking it exhausts the pool; destroyed rather than pooled because session state after a failed BEGIN is unknown.\n connection.release({ destroy: true });\n throw error;\n }\n\n return new ConnectionTransaction({ dataSource: this, connection });\n }\n\n /** The engine's own BEGIN. Postgres interpolates an isolation level; SQLite has none and uses `BEGIN IMMEDIATE`. Never parameterized - `BEGIN ... ISOLATION LEVEL $1` is not valid SQL. */\n protected abstract buildBeginStatement(opts?: TRelationalTransactionOptions): string;\n}\n\n// Runs once this module loads. Every engine (postgres, sqlite) extends `BaseRelationalDataSource`,\n// and `discoverSchema()` above is the sole caller of `resolveModelRelations()`, so this is the one\n// place guaranteed to load whenever relation building is actually needed.\nRelationBuilderRegistry.set({ builder: RelationsFactory.create as TRelationBuilder });\n"]}
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/relational/core/datasources/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAyB,MAAM,uBAAuB,CAAC;AAGvF,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,kGAAkG;AAClG,oHAAoH;AACpH,mGAAmG;AACnG,oGAAoG;AACpG,mEAAmE;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,yDAAyD,CAAC;AAE3F,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAM1D,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE/D,wSAAwS;AACxS,MAAM,qBACJ,SAAQ,oBAAoB;IAK5B,sLAAsL;IAC7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L,GAAG,KAAK,CAAC,aAAa,EAAE;YACxB,gBAAgB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC;SACvD,CAAC;IACJ,CAAC;IAED,iIAAiI;IACzH,KAAK,CAAC,eAAe,CAC3B,IAAoC;QAEpC,MAAM,MAAM,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QACpC,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;QAEtE,IAAI,CAAC;YACH,MAAM,UAAU,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC1E,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,KAAK,CAAC,yCAAyC,EAAE,KAAK,CAAC,CAAC;YAE5F,oLAAoL;YACpL,UAAU,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;YACtC,MAAM,KAAK,CAAC;QACd,CAAC;QAED,OAAO,IAAI,qBAAqB,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;IACrE,CAAC;CAIF;AAED,mGAAmG;AACnG,mGAAmG;AACnG,0EAA0E;AAC1E,uBAAuB,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,gBAAgB,CAAC,MAA0B,EAAE,CAAC,CAAC","sourcesContent":["import { MetadataRegistry } from '@venizia/ignis-kernel';\nimport { RelationBuilderRegistry, type TRelationBuilder } from '@venizia/ignis-kernel';\nimport type { TClass } from '@venizia/ignis-helpers/common';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IDataSource, TAnyDataSourceSchema } from '@venizia/ignis-kernel';\n// Deep import, not a barrel: `discoverSchema()` below is the only production call site that needs\n// `RelationsFactory.create`, so the install runs from here rather than `dialect/relations/create.ts` - nothing else\n// value-imports that file's `RelationsFactory` export, and a `sideEffects: false` bundler drops an\n// unused export's module body even when it is reachable through a barrel `export *` chain (verified\n// with `bun build --target=browser`, the tool `make purity` uses).\nimport { RelationsFactory } from '@/relational/core/repositories/dialect/relations/create';\nimport type { IRelationalConnection } from '@/relational/core/drivers';\nimport { AbstractRelationalDataSource } from './abstract';\nimport type {\n IRelationalDataSourceOpening,\n IRelationalTransaction,\n TRelationalTransactionOptions,\n} from './common';\nimport { RelationPairing } from './relation-pairing';\nimport type { ITransactionEnd } from './transaction-lifecycle';\nimport { TransactionLifecycle } from './transaction-lifecycle';\n\n/** The handle `beginTransaction()` returns: the shared end rules over one acquired connection. On a failed end the connection is discarded rather than pooled - the next borrower would inherit an open transaction - and the error rethrown: a caller must never believe a failed COMMIT succeeded. */\nclass ConnectionTransaction<TConnector>\n extends TransactionLifecycle\n implements IRelationalTransaction<TConnector>\n{\n readonly connector: TConnector;\n\n // ES-private so a logged, spread or serialised handle never reaches the datasource settings. The datasource, not its logger: the logger is read only when an end fails or is a no-op.\n readonly #dataSource: { readonly logger: ILogger };\n readonly #connection: IRelationalConnection<TConnector>;\n\n constructor(opts: {\n dataSource: { readonly logger: ILogger };\n connection: IRelationalConnection<TConnector>;\n }) {\n super();\n\n this.#dataSource = opts.dataSource;\n this.#connection = opts.connection;\n this.connector = opts.connection.connector;\n }\n\n protected override executeEnd(opts: { end: ITransactionEnd }): Promise<unknown> {\n return this.#connection.execute({ statement: opts.end.statement });\n }\n\n protected override onEnded(): void {\n this.#connection.release();\n }\n\n protected override onEndFailed(opts: { end: ITransactionEnd; error: unknown }): void {\n const { end, error } = opts;\n\n this.#dataSource.logger\n .for(end.verb)\n .error('Failed to %s transaction | Error: %s', end.statement, error);\n this.#connection.release({ destroy: true });\n }\n\n protected override onRollbackAfterFailure(): void {\n this.#dataSource.logger\n .for('rollback')\n .debug('Rollback after a failure-ended transaction - no-op, already torn down');\n }\n}\n\n/** Base DataSource with schema auto-discovery from registered repositories. */\nexport abstract class BaseRelationalDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n> extends AbstractRelationalDataSource<Settings, Schema, ConfigurableOptions, Client, TConnector> {\n constructor(opts: { name: string; config: Settings; schema?: Schema }) {\n super({ scope: opts.name });\n\n this.name = opts.name;\n this.settings = opts.config;\n\n if (opts.schema) {\n this.schema = opts.schema;\n }\n }\n\n /** Auto-discovers schema from repositories if not manually provided. */\n override getSchema(): Schema {\n this.schema ??= this.discoverSchema();\n\n return this.schema;\n }\n\n protected discoverSchema(): Schema {\n const registry = MetadataRegistry.getInstance();\n const metadata = registry.getDataSourceMetadata({ target: this.constructor });\n\n if (metadata?.autoDiscovery === false) {\n this.logger.for(this.discoverSchema.name).debug('Auto-discovery disabled for %s', this.name);\n\n return {} as Schema;\n }\n\n const { schema, relations } = registry.buildSchema({\n dataSource: this.constructor as TClass<IDataSource>,\n });\n\n const models = Object.keys(schema);\n this.logger\n .for(this.discoverSchema.name)\n .debug(\n 'Detected model(s) | Name: %s | Count: %s | Models: %j',\n this.name,\n models.length,\n models,\n );\n\n const discovered = { ...schema, ...relations };\n\n // An inverse one() nothing pairs fails here; any other relation drizzle cannot pair is only\n // reported, so a model set that boots today keeps booting, and its first query still throws.\n const { unpaired, outside } = RelationPairing.inspect({\n dataSource: this.constructor.name,\n schema: discovered,\n });\n const fatal = unpaired.find((item) =>\n RelationPairing.isInverseOne({ relation: item.relation }),\n );\n\n if (fatal) {\n throw getError({ message: fatal.message });\n }\n\n const logger = this.logger.for(this.discoverSchema.name);\n\n for (const item of unpaired) {\n logger.warn(item.message);\n }\n\n if (outside.length > 0) {\n logger.debug(RelationPairing.describeOutside({ outside }));\n }\n\n // buildSchema() is shared by every connector so it returns Record<string, unknown>; the cast narrows back to the Drizzle schema shape.\n return discovered as Schema;\n }\n\n hasDiscoverableModels(): boolean {\n const registry = MetadataRegistry.getInstance();\n\n return registry.hasModels({ dataSource: this.constructor as TClass<IDataSource> });\n }\n\n override getCapabilities() {\n return { transactions: true };\n }\n\n override async beginTransaction(\n opts?: TRelationalTransactionOptions,\n ): Promise<IRelationalTransaction<TConnector>> {\n await this.ensureOpen();\n\n return this.openTransaction(opts);\n }\n\n /** Adds the transaction to the handles of the open: `configure()` can run its migrations in one, through the ungated internals. */\n protected override createOpening(): IRelationalDataSourceOpening<TConnector, Client> {\n return {\n ...super.createOpening(),\n beginTransaction: (opts) => this.openTransaction(opts),\n };\n }\n\n /** A transaction on a connection of its own, with no gate: for `beginTransaction()` (after the open) and for the open itself. */\n private async openTransaction(\n opts?: TRelationalTransactionOptions,\n ): Promise<IRelationalTransaction<TConnector>> {\n const driver = this.resolveDriver();\n const connection = await driver.acquire({ schema: this.getSchema() });\n\n try {\n await connection.execute({ statement: this.buildBeginStatement(opts) });\n } catch (error) {\n this.logger.for('beginTransaction').error('Failed to BEGIN transaction | Error: %s', error);\n\n // No caller ever receives a handle to release this connection, so leaking it exhausts the pool; destroyed rather than pooled because session state after a failed BEGIN is unknown.\n connection.release({ destroy: true });\n throw error;\n }\n\n return new ConnectionTransaction({ dataSource: this, connection });\n }\n\n /** The engine's own BEGIN. Postgres interpolates an isolation level; SQLite has none and uses `BEGIN IMMEDIATE`. Never parameterized - `BEGIN ... ISOLATION LEVEL $1` is not valid SQL. */\n protected abstract buildBeginStatement(opts?: TRelationalTransactionOptions): string;\n}\n\n// Runs once this module loads. Every engine (postgres, sqlite) extends `BaseRelationalDataSource`,\n// and `discoverSchema()` above is the sole caller of `resolveModelRelations()`, so this is the one\n// place guaranteed to load whenever relation building is actually needed.\nRelationBuilderRegistry.set({ builder: RelationsFactory.create as TRelationBuilder });\n"]}
|
|
@@ -1,8 +1,24 @@
|
|
|
1
|
-
import type { AbstractDataSource, ITransaction, ITransactionOptions, TAnyDataSourceSchema } from '@venizia/ignis-kernel';
|
|
1
|
+
import type { AbstractDataSource, IDataSourceOpening, ITransaction, ITransactionOptions, TAnyDataSourceSchema } from '@venizia/ignis-kernel';
|
|
2
2
|
import type { IRelationalQueryDialect, IRelationalQueryExecutor } from '../../repositories/common/index.js';
|
|
3
3
|
import type { ValueOrPromise } from '@venizia/ignis-helpers/common';
|
|
4
4
|
/** Neutral SQL transaction options; each engine adds its own knobs. An alias, not an empty `interface ... extends`, which `@typescript-eslint/no-empty-object-type` rejects. */
|
|
5
5
|
export type TRelationalTransactionOptions = ITransactionOptions;
|
|
6
|
+
/**
|
|
7
|
+
* The handles a relational datasource's `configure()` is given as its second argument, typed by the datasource's own
|
|
8
|
+
* connector and client: `opening.getClient()` of a PGlite datasource is a `PGlite`.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* override async configure(
|
|
13
|
+
* _options?: object,
|
|
14
|
+
* opening?: IRelationalDataSourceOpening<TRelationalConnector, PGlite>,
|
|
15
|
+
* ): Promise<void> {
|
|
16
|
+
* this.client = new PGlite(this.settings.dataDir);
|
|
17
|
+
* const transaction = await opening!.beginTransaction(); // migrations, seeding
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export type IRelationalDataSourceOpening<TConnector, Client> = IDataSourceOpening<TConnector, Client, IRelationalTransaction<TConnector>, TRelationalTransactionOptions>;
|
|
6
22
|
/** Transaction handle for a SQL datasource: `connector` runs queries inside the transaction, `commit()` and `rollback()` end it. */
|
|
7
23
|
export interface IRelationalTransaction<TConnector> extends ITransaction {
|
|
8
24
|
/** Bound to the transaction's own connection, whichever driver acquired it. */
|
|
@@ -14,7 +30,7 @@ export interface IRelationalTransaction<TConnector> extends ITransaction {
|
|
|
14
30
|
}
|
|
15
31
|
/** SQL-branch contract, engine-free. Extends `AbstractDataSource` itself, not just `IDataSource`, so repositories can narrow safely. `getConnectionString()` is app-implemented and never called by the framework - an embedded engine with no URL returns its data directory. */
|
|
16
32
|
export interface IRelationalDataSource<Settings extends object = {}, Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema, ConfigurableOptions extends object = {}, Client = unknown, TConnector = unknown> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {
|
|
17
|
-
connector
|
|
33
|
+
connector?: TConnector;
|
|
18
34
|
getConnectionString(): ValueOrPromise<string>;
|
|
19
35
|
getConnector(): TConnector;
|
|
20
36
|
getClient(): Client;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/relational/core/datasources/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AbstractDataSource,\n ITransaction,\n ITransactionOptions,\n TAnyDataSourceSchema,\n} from '@venizia/ignis-kernel';\nimport type {\n IRelationalQueryDialect,\n IRelationalQueryExecutor,\n} from '@/relational/core/repositories/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\n\n/** Neutral SQL transaction options; each engine adds its own knobs. An alias, not an empty `interface ... extends`, which `@typescript-eslint/no-empty-object-type` rejects. */\nexport type TRelationalTransactionOptions = ITransactionOptions;\n\n/** Transaction handle for a SQL datasource: `connector` runs queries inside the transaction, `commit()` and `rollback()` end it. */\nexport interface IRelationalTransaction<TConnector> extends ITransaction {\n /** Bound to the transaction's own connection, whichever driver acquired it. */\n connector: TConnector;\n\n /** Throws if COMMIT fails, per {@link ITransaction.commit}. The connection is discarded where the driver supports it (node-postgres `release(error)`); postgres-js has no destroy semantics, so a poisoned connection returns to its pool. */\n commit(): Promise<void>;\n\n /** Throws if ROLLBACK fails (same connection-discard caveat as {@link commit}) - but is a silent no-op after the transaction already ended BY FAILURE, keeping `catch (error) { await transaction.rollback(); throw error; }` safe. */\n rollback(): Promise<void>;\n}\n\n/** SQL-branch contract, engine-free. Extends `AbstractDataSource` itself, not just `IDataSource`, so repositories can narrow safely. `getConnectionString()` is app-implemented and never called by the framework - an embedded engine with no URL returns its data directory. */\nexport interface IRelationalDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {\n connector
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/relational/core/datasources/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AbstractDataSource,\n IDataSourceOpening,\n ITransaction,\n ITransactionOptions,\n TAnyDataSourceSchema,\n} from '@venizia/ignis-kernel';\nimport type {\n IRelationalQueryDialect,\n IRelationalQueryExecutor,\n} from '@/relational/core/repositories/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\n\n/** Neutral SQL transaction options; each engine adds its own knobs. An alias, not an empty `interface ... extends`, which `@typescript-eslint/no-empty-object-type` rejects. */\nexport type TRelationalTransactionOptions = ITransactionOptions;\n\n/**\n * The handles a relational datasource's `configure()` is given as its second argument, typed by the datasource's own\n * connector and client: `opening.getClient()` of a PGlite datasource is a `PGlite`.\n *\n * @example\n * ```typescript\n * override async configure(\n * _options?: object,\n * opening?: IRelationalDataSourceOpening<TRelationalConnector, PGlite>,\n * ): Promise<void> {\n * this.client = new PGlite(this.settings.dataDir);\n * const transaction = await opening!.beginTransaction(); // migrations, seeding\n * }\n * ```\n */\nexport type IRelationalDataSourceOpening<TConnector, Client> = IDataSourceOpening<\n TConnector,\n Client,\n IRelationalTransaction<TConnector>,\n TRelationalTransactionOptions\n>;\n\n/** Transaction handle for a SQL datasource: `connector` runs queries inside the transaction, `commit()` and `rollback()` end it. */\nexport interface IRelationalTransaction<TConnector> extends ITransaction {\n /** Bound to the transaction's own connection, whichever driver acquired it. */\n connector: TConnector;\n\n /** Throws if COMMIT fails, per {@link ITransaction.commit}. The connection is discarded where the driver supports it (node-postgres `release(error)`); postgres-js has no destroy semantics, so a poisoned connection returns to its pool. */\n commit(): Promise<void>;\n\n /** Throws if ROLLBACK fails (same connection-discard caveat as {@link commit}) - but is a silent no-op after the transaction already ended BY FAILURE, keeping `catch (error) { await transaction.rollback(); throw error; }` safe. */\n rollback(): Promise<void>;\n}\n\n/** SQL-branch contract, engine-free. Extends `AbstractDataSource` itself, not just `IDataSource`, so repositories can narrow safely. `getConnectionString()` is app-implemented and never called by the framework - an embedded engine with no URL returns its data directory. */\nexport interface IRelationalDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {\n connector?: TConnector;\n\n getConnectionString(): ValueOrPromise<string>;\n getConnector(): TConnector;\n getClient(): Client;\n getQueryDialect(): IRelationalQueryDialect;\n getQueryExecutor(): IRelationalQueryExecutor<TConnector>;\n beginTransaction(\n opts?: TRelationalTransactionOptions,\n ): Promise<IRelationalTransaction<TConnector>>;\n}\n"]}
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';
|
|
2
|
+
import type { TConstValue } from '@venizia/ignis-helpers/common';
|
|
2
3
|
import type { IConnectorDriver } from '../../../common/driver.js';
|
|
4
|
+
/** The SQL engines a relational driver can speak. Only the migration ledger reads it today: Postgres has schemas to create, SQLite has only `main`. */
|
|
5
|
+
export declare class RelationalDialects {
|
|
6
|
+
static readonly POSTGRES = "postgres";
|
|
7
|
+
static readonly SQLITE = "sqlite";
|
|
8
|
+
static readonly SCHEME_SET: Set<string>;
|
|
9
|
+
static isValid(input: string): input is TRelationalDialect;
|
|
10
|
+
}
|
|
11
|
+
/** Union of the `RelationalDialects` values. */
|
|
12
|
+
export type TRelationalDialect = TConstValue<typeof RelationalDialects>;
|
|
3
13
|
/** Neutral result of a raw statement. Each driver maps its native shape (pg `rowCount`, postgres-js `count`) at its own boundary - callers never sniff shapes at runtime. */
|
|
4
14
|
export interface IStatementResult {
|
|
5
15
|
/** Rows affected - the same `count` the repository verbs return; `0` for control statements (BEGIN / COMMIT / SET LOCAL). */
|
|
@@ -24,6 +34,8 @@ export interface IRelationalConnection<TConnector> {
|
|
|
24
34
|
}
|
|
25
35
|
/** The common driver (connector, client, end) plus connection acquisition and raw control statements - the only places hard-wired to a client library. `configure()` stays app-written: the framework never builds the driver for you. */
|
|
26
36
|
export interface IRelationalDriver<TConnector, Client = unknown> extends IConnectorDriver<TConnector, Client> {
|
|
37
|
+
/** The engine this driver speaks. The built-in drivers declare it; a hand-made driver may omit it, and the migration ledger then accepts no `ledger.schema` (it cannot know whether the engine has schemas). */
|
|
38
|
+
readonly dialect?: TRelationalDialect;
|
|
27
39
|
acquire(opts: {
|
|
28
40
|
schema: TAnyDataSourceSchema;
|
|
29
41
|
}): Promise<IRelationalConnection<TConnector>>;
|
|
@@ -1,2 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
/** The SQL engines a relational driver can speak. Only the migration ledger reads it today: Postgres has schemas to create, SQLite has only `main`. */
|
|
2
|
+
export class RelationalDialects {
|
|
3
|
+
static { this.POSTGRES = 'postgres'; }
|
|
4
|
+
static { this.SQLITE = 'sqlite'; }
|
|
5
|
+
static { this.SCHEME_SET = new Set([this.POSTGRES, this.SQLITE]); }
|
|
6
|
+
static isValid(input) {
|
|
7
|
+
return this.SCHEME_SET.has(input);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
2
10
|
//# sourceMappingURL=driver.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"driver.js","sourceRoot":"","sources":["../../../../../src/relational/core/drivers/driver.ts"],"names":[],"mappings":"","sourcesContent":["import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';\nimport type { IConnectorDriver } from '@/common/driver';\n\n/** Neutral result of a raw statement. Each driver maps its native shape (pg `rowCount`, postgres-js `count`) at its own boundary - callers never sniff shapes at runtime. */\nexport interface IStatementResult {\n /** Rows affected - the same `count` the repository verbs return; `0` for control statements (BEGIN / COMMIT / SET LOCAL). */\n count: number;\n}\n\n/** One dedicated physical connection, held for the lifetime of a single explicit transaction. */\nexport interface IRelationalConnection<TConnector> {\n /** Drizzle bound to THIS connection, not to the pool. */\n connector: TConnector;\n\n /** Runs a control statement verbatim (BEGIN / COMMIT / ROLLBACK / SET LOCAL) - never parameterized, `BEGIN ... ISOLATION LEVEL $1` is not valid SQL. Use `connector` for rows. */\n execute(opts: { statement: string }): Promise<IStatementResult>;\n\n /** Rows from a verbatim statement, for the few callers that have no Drizzle schema to query through - the migration ledger is the one in-tree case. Also unparameterized: placeholder syntax is not portable (`$1` on Postgres, `?` on SQLite), so a caller needing a value must prove it is a literal. */\n query<R>(opts: { statement: string }): Promise<Array<R>>;\n\n /** Returns the connection; `destroy` discards instead of pooling - required after a failed COMMIT/ROLLBACK, where the next borrower would inherit an open transaction. A driver that cannot destroy must say so in its own docs. */\n release(opts?: { destroy?: boolean }): void;\n}\n\n/** The common driver (connector, client, end) plus connection acquisition and raw control statements - the only places hard-wired to a client library. `configure()` stays app-written: the framework never builds the driver for you. */\nexport interface IRelationalDriver<TConnector, Client = unknown> extends IConnectorDriver<\n TConnector,\n Client\n> {\n acquire(opts: { schema: TAnyDataSourceSchema }): Promise<IRelationalConnection<TConnector>>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"driver.js","sourceRoot":"","sources":["../../../../../src/relational/core/drivers/driver.ts"],"names":[],"mappings":"AAIA,uJAAuJ;AACvJ,MAAM,OAAO,kBAAkB;aACb,aAAQ,GAAG,UAAU,CAAC;aACtB,WAAM,GAAG,QAAQ,CAAC;aAElB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAEnE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC","sourcesContent":["import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\nimport type { IConnectorDriver } from '@/common/driver';\n\n/** The SQL engines a relational driver can speak. Only the migration ledger reads it today: Postgres has schemas to create, SQLite has only `main`. */\nexport class RelationalDialects {\n static readonly POSTGRES = 'postgres';\n static readonly SQLITE = 'sqlite';\n\n static readonly SCHEME_SET = new Set([this.POSTGRES, this.SQLITE]);\n\n static isValid(input: string): input is TRelationalDialect {\n return this.SCHEME_SET.has(input);\n }\n}\n/** Union of the `RelationalDialects` values. */\nexport type TRelationalDialect = TConstValue<typeof RelationalDialects>;\n\n/** Neutral result of a raw statement. Each driver maps its native shape (pg `rowCount`, postgres-js `count`) at its own boundary - callers never sniff shapes at runtime. */\nexport interface IStatementResult {\n /** Rows affected - the same `count` the repository verbs return; `0` for control statements (BEGIN / COMMIT / SET LOCAL). */\n count: number;\n}\n\n/** One dedicated physical connection, held for the lifetime of a single explicit transaction. */\nexport interface IRelationalConnection<TConnector> {\n /** Drizzle bound to THIS connection, not to the pool. */\n connector: TConnector;\n\n /** Runs a control statement verbatim (BEGIN / COMMIT / ROLLBACK / SET LOCAL) - never parameterized, `BEGIN ... ISOLATION LEVEL $1` is not valid SQL. Use `connector` for rows. */\n execute(opts: { statement: string }): Promise<IStatementResult>;\n\n /** Rows from a verbatim statement, for the few callers that have no Drizzle schema to query through - the migration ledger is the one in-tree case. Also unparameterized: placeholder syntax is not portable (`$1` on Postgres, `?` on SQLite), so a caller needing a value must prove it is a literal. */\n query<R>(opts: { statement: string }): Promise<Array<R>>;\n\n /** Returns the connection; `destroy` discards instead of pooling - required after a failed COMMIT/ROLLBACK, where the next borrower would inherit an open transaction. A driver that cannot destroy must say so in its own docs. */\n release(opts?: { destroy?: boolean }): void;\n}\n\n/** The common driver (connector, client, end) plus connection acquisition and raw control statements - the only places hard-wired to a client library. `configure()` stays app-written: the framework never builds the driver for you. */\nexport interface IRelationalDriver<TConnector, Client = unknown> extends IConnectorDriver<\n TConnector,\n Client\n> {\n /** The engine this driver speaks. The built-in drivers declare it; a hand-made driver may omit it, and the migration ledger then accepts no `ledger.schema` (it cannot know whether the engine has schemas). */\n readonly dialect?: TRelationalDialect;\n\n acquire(opts: { schema: TAnyDataSourceSchema }): Promise<IRelationalConnection<TConnector>>;\n}\n"]}
|
|
@@ -33,16 +33,26 @@ export interface IMigration {
|
|
|
33
33
|
export declare class RelationalMigrationRunner extends BaseHelper {
|
|
34
34
|
private readonly driver;
|
|
35
35
|
private readonly ledgerTable;
|
|
36
|
+
/** `undefined` is the engine's default schema: the table is then written unqualified, as it always was. */
|
|
37
|
+
private readonly ledgerSchema;
|
|
36
38
|
/** Set when a ROLLBACK itself fails, so the connection is destroyed rather than pooled. */
|
|
37
39
|
private isSessionPoisoned;
|
|
38
40
|
constructor(opts: {
|
|
39
41
|
driver: IRelationalDriver<unknown>;
|
|
40
42
|
/**
|
|
41
|
-
*
|
|
43
|
+
* Where the applied migrations are recorded. Both names are validated like a migration name and
|
|
44
|
+
* written quoted.
|
|
42
45
|
*
|
|
43
|
-
*
|
|
46
|
+
* - `table` defaults to `'ignis_migrations'`.
|
|
47
|
+
* - `schema` defaults to the engine's default schema. On Postgres a `schema` is created when it
|
|
48
|
+
* is missing (checked first, so an existing one needs no `CREATE` privilege), in the same
|
|
49
|
+
* transaction as the ledger table. SQLite has only `main`: any other
|
|
50
|
+
* schema is refused here, and so is any schema on a driver that declares no `dialect`.
|
|
44
51
|
*/
|
|
45
|
-
|
|
52
|
+
ledger?: {
|
|
53
|
+
schema?: string;
|
|
54
|
+
table?: string;
|
|
55
|
+
};
|
|
46
56
|
scope?: string;
|
|
47
57
|
});
|
|
48
58
|
/**
|
|
@@ -52,6 +62,10 @@ export declare class RelationalMigrationRunner extends BaseHelper {
|
|
|
52
62
|
* is refused rather than escaped. Escaping is what gets this wrong; refusing cannot.
|
|
53
63
|
*/
|
|
54
64
|
private static assertSafeName;
|
|
65
|
+
/** A schema is accepted only on an engine known to have it: Postgres, or SQLite's `main`. A driver that names no dialect cannot be asked, so it gets none. Never ignored, never guessed. */
|
|
66
|
+
private assertSchemaSupported;
|
|
67
|
+
/** The ledger table as SQL: `"schema"."table"`, or `"table"` when the engine's default schema is used. */
|
|
68
|
+
private get ledgerName();
|
|
55
69
|
/** Splits on `drizzle-kit`'s own breakpoint marker; a hand-written single-statement migration has none and comes back whole. */
|
|
56
70
|
static splitStatements(opts: {
|
|
57
71
|
sql: string;
|
|
@@ -59,7 +73,18 @@ export declare class RelationalMigrationRunner extends BaseHelper {
|
|
|
59
73
|
run(opts: {
|
|
60
74
|
migrations: ReadonlyArray<IMigration>;
|
|
61
75
|
}): Promise<void>;
|
|
62
|
-
/**
|
|
76
|
+
/** The ledger's schema (Postgres only, and only when one is named, and only when it is missing) and its table. */
|
|
77
|
+
private createLedger;
|
|
78
|
+
/**
|
|
79
|
+
* Creates the schema only when it is missing. `CREATE SCHEMA IF NOT EXISTS` is not enough: Postgres checks the
|
|
80
|
+
* `CREATE` privilege on the database before it looks at `IF NOT EXISTS`, so a role without it would fail even for
|
|
81
|
+
* `public`. Asking `pg_namespace` first lets such a role use an existing schema; it fails only when it must create one.
|
|
82
|
+
* The name passed the safe-name check, so it is embedded as a literal like the others.
|
|
83
|
+
*/
|
|
84
|
+
private ensureSchema;
|
|
85
|
+
/** One migration and its ledger row, in one transaction. */
|
|
63
86
|
private applyOne;
|
|
87
|
+
/** BEGIN/COMMIT written here rather than through `beginTransaction()`: that acquires its OWN connection, and the ledger read has to see the same session on a single-connection engine. */
|
|
88
|
+
private transact;
|
|
64
89
|
}
|
|
65
90
|
//# sourceMappingURL=runner.d.ts.map
|