@nage-api/data-sql 1.0.0-beta.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,150 @@
1
+ # @nage-api/data-sql
2
+
3
+ The SQL driver for `@nage-api/data` (PLAN.md §14.1), built on Sequelize.
4
+
5
+ Install one driver, never two: the engine is chosen when the workspace is
6
+ scaffolded, so no dead branch of the other stack is compiled in. Today this is
7
+ the only driver there is — `@nage-api/data-mongo` (§8) has not been written.
8
+
9
+ `sequelize` is a **peer** dependency, so the dialect package is yours to choose:
10
+ `pg`, `mysql2`, `mariadb` or `sqlite3` alongside it.
11
+
12
+ ```ts
13
+ import { Module } from '@nestjs/common';
14
+ import { resolveTlsOptions } from '@nage-api/core';
15
+ import { NageSqlModule } from '@nage-api/data-sql';
16
+ import type { NageConfig } from '@nage-api/contracts';
17
+ import { Sequelize } from 'sequelize';
18
+
19
+ import type { Env } from './config/env.schema.js';
20
+
21
+ /** Both come from the application: validated env, and the config it built. */
22
+ declare const env: Env;
23
+ declare const config: NageConfig;
24
+
25
+ const sequelize = new Sequelize(env.DATABASE_URL, {
26
+ // `verify-full` unless the config says otherwise; the legacy pair of
27
+ // `rejectUnauthorized: false` literals is what this replaces (§12).
28
+ dialectOptions: { ssl: resolveTlsOptions(config.database?.ssl) },
29
+ logging: false,
30
+ });
31
+
32
+ @Module({ imports: [NageSqlModule.forRoot({ sequelize })] })
33
+ export class AppModule {}
34
+ ```
35
+
36
+ A model declares the framework's audit columns and leaves Sequelize's own
37
+ bookkeeping off, because the driver stamps those columns itself:
38
+
39
+ ```ts
40
+ import { defineQueryPolicy } from '@nage-api/data';
41
+ import { SqlRepository } from '@nage-api/data-sql';
42
+ import { DataTypes, type Model, type ModelStatic, type Sequelize } from 'sequelize';
43
+
44
+ interface Product {
45
+ readonly id: number;
46
+ name: string;
47
+ price: number;
48
+ }
49
+
50
+ /** The row type the driver expects: attributes stay opaque to it. */
51
+ type Row = Model<Record<string, unknown>, Record<string, unknown>>;
52
+
53
+ declare const sequelize: Sequelize;
54
+
55
+ const ProductModel: ModelStatic<Row> = sequelize.define<Row>(
56
+ 'Product',
57
+ {
58
+ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
59
+ name: { type: DataTypes.STRING, allowNull: false },
60
+ price: { type: DataTypes.INTEGER, allowNull: false },
61
+ // Stamped by `@nage-api/data`, so they are ordinary columns here.
62
+ created_at: DataTypes.STRING,
63
+ updated_at: DataTypes.STRING,
64
+ created_by: DataTypes.INTEGER,
65
+ updated_by: DataTypes.INTEGER,
66
+ deleted_at: DataTypes.STRING,
67
+ deleted_by: DataTypes.INTEGER,
68
+ },
69
+ // `timestamps: false` and no `paranoid`: two mechanisms writing the same
70
+ // columns disagree about their format and their meaning.
71
+ { tableName: 'products', timestamps: false, freezeTableName: true },
72
+ );
73
+
74
+ const productPolicy = defineQueryPolicy<Product>({
75
+ filterable: ['name', 'price'],
76
+ sortable: ['name', 'price'],
77
+ selectable: ['id', 'name', 'price'],
78
+ searchable: ['name'],
79
+ });
80
+
81
+ const products = new SqlRepository<Product>(ProductModel, { policy: productPolicy });
82
+ ```
83
+
84
+ ## What it provides
85
+
86
+ | Export | Purpose |
87
+ | --------------------- | ----------------------------------------------------------------- |
88
+ | `SqlRepository` | `RepositoryPort` over a Sequelize model |
89
+ | `SqlUnitOfWork` | `UnitOfWork` over a managed Sequelize transaction |
90
+ | `SqlMigrationStore` | The migrations ledger, plus a best-effort lock |
91
+ | `SqlDataSourceHealth` | `authenticate()` probe for `/health/ready` |
92
+ | `translateWhere` | The DSL → `Op.*` translation |
93
+ | `NageSqlModule` | Publishes the unit of work and health probe against core's tokens |
94
+
95
+ ## Behaviour worth knowing
96
+
97
+ **A client-supplied key never reaches Sequelize.** `translateWhere` maps each
98
+ DSL operator to an `Op.*` symbol and throws on anything else, so the emitted
99
+ clause contains only symbols this package owns. That is the second line of
100
+ defence; `parseQuery` in `@nage-api/data` is the first.
101
+
102
+ **Audit and soft delete are the framework's, not Sequelize's.** The driver uses
103
+ the shared `stamp*` helpers rather than Sequelize's `timestamps`/`paranoid`, so
104
+ the columns and semantics are identical across drivers — which is what lets one
105
+ conformance suite cover both.
106
+
107
+ **Transactions are the database's.** `SqlUnitOfWork.run` uses a managed
108
+ transaction: it commits on success, rolls back on failure, and re-raises the
109
+ original error — the same observable contract the in-memory driver gives.
110
+
111
+ **Migrations replace auto-sync.** `SqlMigrationStore` records each applied
112
+ migration in `nage_migrations`. Its lock is a row in that same table rather than
113
+ an advisory lock — SQLite has none — so it is best effort: it stops a second
114
+ process starting, and a process that dies mid-migration leaves the row behind
115
+ for an operator to delete. Migrating as one deploy step, not on every instance
116
+ boot, is what the design assumes. `nage db migrate` is the intended entry point
117
+ and is **not implemented yet** (see `@nage-api/cli`'s "Not yet implemented"), so
118
+ today the runner is called from a script of your own.
119
+
120
+ ## Testing
121
+
122
+ The driver runs the shared conformance suite from `@nage-api/data` against SQLite
123
+ in-process — real SQL generation, real transactions, no container required, and
124
+ the same suite the in-memory driver runs, which is what makes parity checkable.
125
+
126
+ Against Postgres and MySQL it is untested. `@nage-api/testing` ships the
127
+ `ContainerHarness` the matrix needs and pins the images, but no suite here uses
128
+ it and the adapter has never run against Docker, so dialect-specific behaviour —
129
+ `ILIKE`, the `LIKE` escape character, `findAndCountAll` with a join — rests on
130
+ Sequelize rather than on a test in this repository.
131
+
132
+ ## Not yet implemented
133
+
134
+ - **The module does not open the connection.** `forRoot` takes an already-built
135
+ `Sequelize`; there is no `forRootAsync` and nothing reads `database.pool`, so
136
+ pool sizing, `acquireTimeoutMs` and connect-retry backoff are the application's
137
+ to arrange (§14.2). It does close the pool: `onApplicationShutdown` calls
138
+ `sequelize.close()`, and `installShutdown` runs that **after** the HTTP drain,
139
+ so nothing is still querying when it happens.
140
+ - **Named scopes.** `Query.scope` reaches the driver and is ignored.
141
+ - **Optimistic locking.** `descriptor.versioned` is accepted and unused.
142
+ - **`bulkUpdate` and `bulkDelete` are row-by-row.** Each matching row is fetched
143
+ and written individually so that the audit stamps and soft-delete semantics
144
+ match the other driver exactly; a wide bulk write is N statements, not one.
145
+ - **`populate` is thin.** It becomes a Sequelize `include` by association name.
146
+ Only a `belongsTo` case is tested, and the driver does not set `distinct`, so
147
+ eager-loading a to-many association can inflate `pagination.count`.
148
+
149
+ `docs/packages/data-sql.md` is the longer guide: every option and its default, the
150
+ model definition this driver expects, and the mistakes worth knowing about.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@nage-api/data-sql` — the SQL driver (PLAN.md §14.1).
3
+ *
4
+ * Implements the ports declared by `@nage-api/data` on top of Sequelize. A project
5
+ * installs this **or** `@nage-api/data-mongo`, never both: the engine is chosen at
6
+ * scaffold time, so no dead branch of the other stack is compiled in — the
7
+ * problem that made every legacy deployment boot a Mongo connection it did not
8
+ * use.
9
+ */
10
+ export { SqlRepository, type SqlRepositoryOptions } from './sql.repository.js';
11
+ export { SqlUnitOfWork, transactionOf, type SqlTxContext } from './sql.unit-of-work.js';
12
+ export { SqlMigrationStore, type SqlMigrationStoreOptions } from './sql.migration-store.js';
13
+ export { SqlDataSourceHealth } from './sql.health.js';
14
+ export { translateWhere } from './where-translator.js';
15
+ export { NageSqlModule, type SqlModuleOptions } from './sql.module.js';
16
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ /**
3
+ * `@nage-api/data-sql` — the SQL driver (PLAN.md §14.1).
4
+ *
5
+ * Implements the ports declared by `@nage-api/data` on top of Sequelize. A project
6
+ * installs this **or** `@nage-api/data-mongo`, never both: the engine is chosen at
7
+ * scaffold time, so no dead branch of the other stack is compiled in — the
8
+ * problem that made every legacy deployment boot a Mongo connection it did not
9
+ * use.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.NageSqlModule = exports.translateWhere = exports.SqlDataSourceHealth = exports.SqlMigrationStore = exports.transactionOf = exports.SqlUnitOfWork = exports.SqlRepository = void 0;
13
+ var sql_repository_js_1 = require("./sql.repository.js");
14
+ Object.defineProperty(exports, "SqlRepository", { enumerable: true, get: function () { return sql_repository_js_1.SqlRepository; } });
15
+ var sql_unit_of_work_js_1 = require("./sql.unit-of-work.js");
16
+ Object.defineProperty(exports, "SqlUnitOfWork", { enumerable: true, get: function () { return sql_unit_of_work_js_1.SqlUnitOfWork; } });
17
+ Object.defineProperty(exports, "transactionOf", { enumerable: true, get: function () { return sql_unit_of_work_js_1.transactionOf; } });
18
+ var sql_migration_store_js_1 = require("./sql.migration-store.js");
19
+ Object.defineProperty(exports, "SqlMigrationStore", { enumerable: true, get: function () { return sql_migration_store_js_1.SqlMigrationStore; } });
20
+ var sql_health_js_1 = require("./sql.health.js");
21
+ Object.defineProperty(exports, "SqlDataSourceHealth", { enumerable: true, get: function () { return sql_health_js_1.SqlDataSourceHealth; } });
22
+ var where_translator_js_1 = require("./where-translator.js");
23
+ Object.defineProperty(exports, "translateWhere", { enumerable: true, get: function () { return where_translator_js_1.translateWhere; } });
24
+ var sql_module_js_1 = require("./sql.module.js");
25
+ Object.defineProperty(exports, "NageSqlModule", { enumerable: true, get: function () { return sql_module_js_1.NageSqlModule; } });
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Connection probe for `/health/ready` (PLAN.md §21).
3
+ *
4
+ * `authenticate()` issues a trivial query, so a pool that has lost its
5
+ * connection reports down instead of the instance discovering it on the next
6
+ * request.
7
+ */
8
+ import type { DataSourceHealth } from '@nage-api/contracts';
9
+ import type { Sequelize } from 'sequelize';
10
+ export declare class SqlDataSourceHealth implements DataSourceHealth {
11
+ private readonly sequelize;
12
+ readonly driver: string;
13
+ constructor(sequelize: Sequelize);
14
+ ping(): Promise<boolean>;
15
+ }
16
+ //# sourceMappingURL=sql.health.d.ts.map
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ /**
3
+ * Connection probe for `/health/ready` (PLAN.md §21).
4
+ *
5
+ * `authenticate()` issues a trivial query, so a pool that has lost its
6
+ * connection reports down instead of the instance discovering it on the next
7
+ * request.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.SqlDataSourceHealth = void 0;
11
+ class SqlDataSourceHealth {
12
+ sequelize;
13
+ driver;
14
+ constructor(sequelize) {
15
+ this.sequelize = sequelize;
16
+ this.driver = `sql:${sequelize.getDialect()}`;
17
+ }
18
+ async ping() {
19
+ try {
20
+ await this.sequelize.authenticate();
21
+ return true;
22
+ }
23
+ catch {
24
+ // The reason is the caller's to log; readiness only needs the verdict.
25
+ return false;
26
+ }
27
+ }
28
+ }
29
+ exports.SqlDataSourceHealth = SqlDataSourceHealth;
30
+ //# sourceMappingURL=sql.health.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The migrations ledger, in SQL (PLAN.md §14.2).
3
+ *
4
+ * One row per applied migration, plus an advisory lock so that four instances
5
+ * booting together do not all try to migrate — the failure mode `synchronize`
6
+ * had, at a worse moment.
7
+ */
8
+ import type { AppliedMigration, MigrationStore } from '@nage-api/data';
9
+ import { type Sequelize } from 'sequelize';
10
+ export interface SqlMigrationStoreOptions {
11
+ /** Ledger table name; `nage_migrations` by default. */
12
+ readonly tableName?: string;
13
+ }
14
+ export declare class SqlMigrationStore implements MigrationStore {
15
+ #private;
16
+ constructor(sequelize: Sequelize, options?: SqlMigrationStoreOptions);
17
+ initialize(): Promise<void>;
18
+ applied(): Promise<readonly AppliedMigration[]>;
19
+ record(migration: AppliedMigration): Promise<void>;
20
+ remove(id: string): Promise<void>;
21
+ /**
22
+ * Best-effort lock.
23
+ *
24
+ * A row in the ledger stands in for a lock the dialect may not have; SQLite in
25
+ * particular has no advisory locks. It is honest about being best effort:
26
+ * `nage db migrate` as a deploy step remains the supported path.
27
+ */
28
+ lock(): Promise<boolean>;
29
+ unlock(): Promise<void>;
30
+ }
31
+ //# sourceMappingURL=sql.migration-store.d.ts.map
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ /**
3
+ * The migrations ledger, in SQL (PLAN.md §14.2).
4
+ *
5
+ * One row per applied migration, plus an advisory lock so that four instances
6
+ * booting together do not all try to migrate — the failure mode `synchronize`
7
+ * had, at a worse moment.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.SqlMigrationStore = void 0;
11
+ const core_1 = require("@nage-api/core");
12
+ const sequelize_1 = require("sequelize");
13
+ class SqlMigrationStore {
14
+ #sequelize;
15
+ #tableName;
16
+ #model;
17
+ #locked = false;
18
+ constructor(sequelize, options = {}) {
19
+ this.#sequelize = sequelize;
20
+ this.#tableName = options.tableName ?? 'nage_migrations';
21
+ }
22
+ async initialize() {
23
+ if (this.#model !== undefined)
24
+ return;
25
+ this.#model = this.#sequelize.define(this.#tableName, {
26
+ id: { type: sequelize_1.DataTypes.STRING(255), primaryKey: true },
27
+ name: { type: sequelize_1.DataTypes.STRING(255), allowNull: false },
28
+ applied_at: { type: sequelize_1.DataTypes.STRING(64), allowNull: false },
29
+ checksum: { type: sequelize_1.DataTypes.STRING(128), allowNull: true },
30
+ }, { tableName: this.#tableName, timestamps: false, freezeTableName: true });
31
+ await this.#model.sync();
32
+ }
33
+ async applied() {
34
+ const rows = await this.#require().findAll({ order: [['id', 'ASC']] });
35
+ return (rows
36
+ // The lock lives in the same table; it is not a migration.
37
+ .filter((row) => String(row.get({ plain: true })['id']) !== LOCK_ID)
38
+ .map((row) => {
39
+ const plain = row.get({ plain: true });
40
+ const checksum = plain['checksum'];
41
+ return {
42
+ id: String(plain['id']),
43
+ name: String(plain['name']),
44
+ appliedAt: String(plain['applied_at']),
45
+ ...(typeof checksum === 'string' ? { checksum } : {}),
46
+ };
47
+ }));
48
+ }
49
+ async record(migration) {
50
+ await this.#require().create({
51
+ id: migration.id,
52
+ name: migration.name,
53
+ applied_at: migration.appliedAt,
54
+ checksum: migration.checksum ?? null,
55
+ });
56
+ }
57
+ async remove(id) {
58
+ await this.#require().destroy({ where: { id } });
59
+ }
60
+ /**
61
+ * Best-effort lock.
62
+ *
63
+ * A row in the ledger stands in for a lock the dialect may not have; SQLite in
64
+ * particular has no advisory locks. It is honest about being best effort:
65
+ * `nage db migrate` as a deploy step remains the supported path.
66
+ */
67
+ async lock() {
68
+ const model = this.#require();
69
+ const existing = await model.findByPk(LOCK_ID);
70
+ if (existing !== null)
71
+ return false;
72
+ await model.create({
73
+ id: LOCK_ID,
74
+ name: 'lock',
75
+ applied_at: new Date().toISOString(),
76
+ checksum: null,
77
+ });
78
+ this.#locked = true;
79
+ return true;
80
+ }
81
+ async unlock() {
82
+ if (!this.#locked)
83
+ return;
84
+ await this.#require().destroy({ where: { id: LOCK_ID } });
85
+ this.#locked = false;
86
+ }
87
+ #require() {
88
+ if (this.#model === undefined) {
89
+ throw new core_1.DatabaseError({ detail: 'The migration store has not been initialised' });
90
+ }
91
+ return this.#model;
92
+ }
93
+ }
94
+ exports.SqlMigrationStore = SqlMigrationStore;
95
+ /** Sorts before any timestamp id, and is filtered out of `applied()` by name. */
96
+ const LOCK_ID = '__lock__';
97
+ //# sourceMappingURL=sql.migration-store.js.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `NageSqlModule.forRoot()` — wires the SQL driver into an application
3
+ * (PLAN.md §7.3).
4
+ *
5
+ * Publishes the unit of work and the health probe against the tokens declared
6
+ * by `@nage-api/core`, so application code and feature packages inject ports and
7
+ * never this module.
8
+ *
9
+ * It also closes the pool on shutdown (§21, "DB lifecycle … close on
10
+ * shutdown"), which nothing did before: the connections were left to the process
11
+ * exit. On a rolling deploy that leaves the server holding sessions for an
12
+ * instance that has gone, and any statement still open is torn down rather than
13
+ * ended. The hook runs after the HTTP drain — see `installShutdown` in
14
+ * `@nage-api/core`, which is what puts the two in that order.
15
+ */
16
+ import { type DynamicModule } from '@nestjs/common';
17
+ import type { LoggerPort } from '@nage-api/contracts';
18
+ import type { Sequelize } from 'sequelize';
19
+ /** Token for the connection itself, for code that needs raw SQL. */
20
+ export declare const NAGE_SEQUELIZE: unique symbol;
21
+ export interface SqlModuleOptions {
22
+ /** An already-configured connection. TLS comes from `resolveTlsOptions` (§12). */
23
+ readonly sequelize: Sequelize;
24
+ }
25
+ export declare class NageSqlModule {
26
+ private readonly sequelize;
27
+ private readonly logger?;
28
+ constructor(sequelize: Sequelize, logger?: LoggerPort | undefined);
29
+ static forRoot(options: SqlModuleOptions): DynamicModule;
30
+ onApplicationShutdown(): Promise<void>;
31
+ }
32
+ //# sourceMappingURL=sql.module.d.ts.map
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /**
3
+ * `NageSqlModule.forRoot()` — wires the SQL driver into an application
4
+ * (PLAN.md §7.3).
5
+ *
6
+ * Publishes the unit of work and the health probe against the tokens declared
7
+ * by `@nage-api/core`, so application code and feature packages inject ports and
8
+ * never this module.
9
+ *
10
+ * It also closes the pool on shutdown (§21, "DB lifecycle … close on
11
+ * shutdown"), which nothing did before: the connections were left to the process
12
+ * exit. On a rolling deploy that leaves the server holding sessions for an
13
+ * instance that has gone, and any statement still open is torn down rather than
14
+ * ended. The hook runs after the HTTP drain — see `installShutdown` in
15
+ * `@nage-api/core`, which is what puts the two in that order.
16
+ */
17
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
18
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
20
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
21
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22
+ };
23
+ var __metadata = (this && this.__metadata) || function (k, v) {
24
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
25
+ };
26
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
27
+ return function (target, key) { decorator(target, key, paramIndex); }
28
+ };
29
+ var NageSqlModule_1;
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.NageSqlModule = exports.NAGE_SEQUELIZE = void 0;
32
+ const common_1 = require("@nestjs/common");
33
+ const core_1 = require("@nage-api/core");
34
+ const data_1 = require("@nage-api/data");
35
+ const sql_health_js_1 = require("./sql.health.js");
36
+ const sql_unit_of_work_js_1 = require("./sql.unit-of-work.js");
37
+ /** Token for the connection itself, for code that needs raw SQL. */
38
+ exports.NAGE_SEQUELIZE = Symbol('NAGE_SEQUELIZE');
39
+ let NageSqlModule = NageSqlModule_1 = class NageSqlModule {
40
+ sequelize;
41
+ logger;
42
+ constructor(sequelize, logger) {
43
+ this.sequelize = sequelize;
44
+ this.logger = logger;
45
+ }
46
+ static forRoot(options) {
47
+ return {
48
+ module: NageSqlModule_1,
49
+ providers: [
50
+ { provide: exports.NAGE_SEQUELIZE, useValue: options.sequelize },
51
+ { provide: core_1.NAGE_UNIT_OF_WORK, useValue: new sql_unit_of_work_js_1.SqlUnitOfWork(options.sequelize) },
52
+ { provide: data_1.NAGE_DATA_HEALTH, useValue: new sql_health_js_1.SqlDataSourceHealth(options.sequelize) },
53
+ ],
54
+ exports: [exports.NAGE_SEQUELIZE, core_1.NAGE_UNIT_OF_WORK, data_1.NAGE_DATA_HEALTH],
55
+ };
56
+ }
57
+ async onApplicationShutdown() {
58
+ try {
59
+ await this.sequelize.close();
60
+ }
61
+ catch (error) {
62
+ // Reported, not rethrown: a driver that cannot close is not a reason to
63
+ // fail the shutdown that is already under way, and the shutdown sequence
64
+ // would otherwise turn this into a non-zero exit on every deploy.
65
+ this.logger?.warn('Closing the database connection failed', {
66
+ error: error instanceof Error ? error.message : String(error),
67
+ });
68
+ }
69
+ }
70
+ };
71
+ exports.NageSqlModule = NageSqlModule;
72
+ exports.NageSqlModule = NageSqlModule = NageSqlModule_1 = __decorate([
73
+ (0, common_1.Global)(),
74
+ (0, common_1.Module)({}),
75
+ __param(0, (0, common_1.Inject)(exports.NAGE_SEQUELIZE)),
76
+ __param(1, (0, common_1.Optional)()),
77
+ __param(1, (0, common_1.Inject)(core_1.NAGE_LOGGER)),
78
+ __metadata("design:paramtypes", [Function, Object])
79
+ ], NageSqlModule);
80
+ //# sourceMappingURL=sql.module.js.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Sequelize-backed `RepositoryPort` (PLAN.md §14.1).
3
+ *
4
+ * The same contract the in-memory driver implements, over a real database. It
5
+ * shares the DSL, the audit stamping and the soft-delete semantics with
6
+ * `@nage-api/data` rather than reimplementing them, so behaviour that the
7
+ * conformance suite pins down cannot drift between drivers.
8
+ */
9
+ import type { BulkResult, ByIdQuery, CursorPaginated, DeepPartial, DeleteOptions, Id, ModelDescriptor, Paginated, Query, QueryPolicy, RepositoryPort, UnknownRecord, WriteOptions } from '@nage-api/contracts';
10
+ import type { Model, ModelStatic } from 'sequelize';
11
+ /** A Sequelize model instance carrying arbitrary attributes. */
12
+ type AnyModel = Model<UnknownRecord, UnknownRecord>;
13
+ export interface SqlRepositoryOptions<TEntity> {
14
+ readonly descriptor?: Partial<ModelDescriptor<TEntity>>;
15
+ readonly policy?: QueryPolicy<TEntity>;
16
+ readonly now?: () => Date;
17
+ }
18
+ export declare class SqlRepository<TEntity extends {
19
+ id: Id;
20
+ }> implements RepositoryPort<TEntity> {
21
+ #private;
22
+ readonly descriptor: ModelDescriptor<TEntity>;
23
+ constructor(model: ModelStatic<AnyModel>, options?: SqlRepositoryOptions<TEntity>);
24
+ findAll(query?: Query<TEntity>): Promise<Paginated<TEntity>>;
25
+ findByCursor(query?: Query<TEntity>): Promise<CursorPaginated<TEntity>>;
26
+ findOne(query?: Query<TEntity>): Promise<TEntity | null>;
27
+ findById(id: Id, query?: Omit<ByIdQuery<TEntity>, 'id'>): Promise<TEntity | null>;
28
+ exists(query?: Query<TEntity>): Promise<boolean>;
29
+ count(query?: Query<TEntity>): Promise<number>;
30
+ create(data: DeepPartial<TEntity>, options?: WriteOptions): Promise<TEntity>;
31
+ update(id: Id, data: DeepPartial<TEntity>, options?: WriteOptions): Promise<TEntity>;
32
+ delete(id: Id, options?: DeleteOptions): Promise<void>;
33
+ restore(id: Id, options?: WriteOptions): Promise<TEntity>;
34
+ bulkCreate(data: readonly DeepPartial<TEntity>[], options?: WriteOptions): Promise<BulkResult<TEntity>>;
35
+ bulkUpdate(query: Query<TEntity>, data: DeepPartial<TEntity>, options?: WriteOptions): Promise<BulkResult<TEntity>>;
36
+ bulkDelete(query: Query<TEntity>, options?: DeleteOptions): Promise<number>;
37
+ }
38
+ export {};
39
+ //# sourceMappingURL=sql.repository.d.ts.map
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ /**
3
+ * Sequelize-backed `RepositoryPort` (PLAN.md §14.1).
4
+ *
5
+ * The same contract the in-memory driver implements, over a real database. It
6
+ * shares the DSL, the audit stamping and the soft-delete semantics with
7
+ * `@nage-api/data` rather than reimplementing them, so behaviour that the
8
+ * conformance suite pins down cannot drift between drivers.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.SqlRepository = void 0;
12
+ const core_1 = require("@nage-api/core");
13
+ const data_1 = require("@nage-api/data");
14
+ const where_translator_js_1 = require("./where-translator.js");
15
+ const sql_unit_of_work_js_1 = require("./sql.unit-of-work.js");
16
+ class SqlRepository {
17
+ descriptor;
18
+ #model;
19
+ #policy;
20
+ #now;
21
+ constructor(model, options = {}) {
22
+ this.#model = model;
23
+ this.descriptor = {
24
+ name: model.name,
25
+ primaryKey: 'id',
26
+ softDelete: true,
27
+ timestamps: true,
28
+ versioned: false,
29
+ ...options.descriptor,
30
+ };
31
+ this.#policy = options.policy ?? (0, data_1.defineQueryPolicy)();
32
+ this.#now = options.now ?? (() => new Date());
33
+ }
34
+ // ── Reads ─────────────────────────────────────────────────────────────────
35
+ async findAll(query = {}) {
36
+ const { offset, limit } = (0, data_1.resolvePagination)(query, this.#policy);
37
+ const { rows, count } = await this.#model.findAndCountAll({
38
+ ...this.#findOptions(query),
39
+ offset,
40
+ limit,
41
+ });
42
+ return {
43
+ records: rows.map((row) => this.#toEntity(row, query)),
44
+ pagination: { offset, limit, count },
45
+ };
46
+ }
47
+ async findByCursor(query = {}) {
48
+ const { limit } = (0, data_1.resolvePagination)(query, this.#policy);
49
+ const offset = query.cursor === undefined ? 0 : Number(decodeCursor(query.cursor));
50
+ // One extra row answers "is there more?" without a second count query.
51
+ const rows = await this.#model.findAll({
52
+ ...this.#findOptions(query),
53
+ offset,
54
+ limit: limit + 1,
55
+ });
56
+ const hasMore = rows.length > limit;
57
+ const page = hasMore ? rows.slice(0, limit) : rows;
58
+ return {
59
+ records: page.map((row) => this.#toEntity(row, query)),
60
+ pagination: {
61
+ nextCursor: hasMore ? encodeCursor(String(offset + limit)) : null,
62
+ limit,
63
+ hasMore,
64
+ },
65
+ };
66
+ }
67
+ async findOne(query = {}) {
68
+ const row = await this.#model.findOne(this.#findOptions(query));
69
+ return row === null ? null : this.#toEntity(row, query);
70
+ }
71
+ async findById(id, query = {}) {
72
+ const row = await this.#findRow(id, query.withDeleted === true);
73
+ return row === null ? null : this.#toEntity(row, query);
74
+ }
75
+ async exists(query = {}) {
76
+ return (await this.count(query)) > 0;
77
+ }
78
+ count(query = {}) {
79
+ return this.#model.count({ where: this.#whereFor(query) });
80
+ }
81
+ // ── Writes ────────────────────────────────────────────────────────────────
82
+ async create(data, options = {}) {
83
+ const row = await this.#model.create((0, data_1.stampCreate)(data, { now: this.#now }), {
84
+ ...this.#transaction(options),
85
+ });
86
+ return this.#toEntity(row);
87
+ }
88
+ async update(id, data, options = {}) {
89
+ const row = await this.#findRow(id, false);
90
+ if (row === null)
91
+ throw this.#notFound(id);
92
+ await row.update((0, data_1.stampUpdate)(data, { now: this.#now }), {
93
+ ...this.#transaction(options),
94
+ });
95
+ return this.#toEntity(row);
96
+ }
97
+ async delete(id, options = {}) {
98
+ const row = await this.#findRow(id, false);
99
+ if (row === null)
100
+ throw this.#notFound(id);
101
+ const mode = options.mode ?? (this.descriptor.softDelete ? 'soft' : 'hard');
102
+ if (mode === 'hard' || !this.descriptor.softDelete) {
103
+ await row.destroy({ ...this.#transaction(options) });
104
+ return;
105
+ }
106
+ await row.update((0, data_1.stampSoftDelete)({ now: this.#now }), { ...this.#transaction(options) });
107
+ }
108
+ async restore(id, options = {}) {
109
+ const row = await this.#findRow(id, true);
110
+ if (row === null)
111
+ throw this.#notFound(id);
112
+ await row.update((0, data_1.stampRestore)({ now: this.#now }), { ...this.#transaction(options) });
113
+ return this.#toEntity(row);
114
+ }
115
+ async bulkCreate(data, options = {}) {
116
+ const rows = await this.#model.bulkCreate(data.map((entry) => (0, data_1.stampCreate)(entry, { now: this.#now })), { ...this.#transaction(options) });
117
+ return { affected: rows.length, records: rows.map((row) => this.#toEntity(row)) };
118
+ }
119
+ async bulkUpdate(query, data, options = {}) {
120
+ const rows = await this.#model.findAll({ where: this.#whereFor(query) });
121
+ const patch = (0, data_1.stampUpdate)(data, { now: this.#now });
122
+ for (const row of rows)
123
+ await row.update(patch, { ...this.#transaction(options) });
124
+ return { affected: rows.length, records: rows.map((row) => this.#toEntity(row)) };
125
+ }
126
+ async bulkDelete(query, options = {}) {
127
+ const rows = await this.#model.findAll({ where: this.#whereFor(query) });
128
+ const mode = options.mode ?? (this.descriptor.softDelete ? 'soft' : 'hard');
129
+ for (const row of rows) {
130
+ if (mode === 'hard' || !this.descriptor.softDelete) {
131
+ await row.destroy({ ...this.#transaction(options) });
132
+ }
133
+ else {
134
+ await row.update((0, data_1.stampSoftDelete)({ now: this.#now }), { ...this.#transaction(options) });
135
+ }
136
+ }
137
+ return rows.length;
138
+ }
139
+ // ── Internals ─────────────────────────────────────────────────────────────
140
+ #findOptions(query) {
141
+ const options = { where: this.#whereFor(query) };
142
+ if (query.sort !== undefined && query.sort.length > 0) {
143
+ options.order = query.sort.map(([field, direction]) => [
144
+ field,
145
+ direction.toUpperCase(),
146
+ ]);
147
+ }
148
+ if (query.select !== undefined && query.select.length > 0) {
149
+ // The primary key is always fetched: a record the caller cannot identify
150
+ // is of little use, and soft-delete checks need it.
151
+ options.attributes = [...new Set([this.descriptor.primaryKey, ...query.select])];
152
+ }
153
+ if (query.populate !== undefined && query.populate.length > 0) {
154
+ options.include = query.populate.map((relation) => ({ association: relation }));
155
+ }
156
+ return options;
157
+ }
158
+ /**
159
+ * Build the `where` clause, layering soft delete and search on top of the
160
+ * translated DSL.
161
+ */
162
+ #whereFor(query) {
163
+ const clauses = [
164
+ (0, where_translator_js_1.translateWhere)(query.where, this.#dialect()),
165
+ ];
166
+ if (this.descriptor.softDelete && query.withDeleted !== true) {
167
+ clauses.push({ deleted_at: null });
168
+ }
169
+ if (query.search !== undefined) {
170
+ const fields = query.search.fields ?? this.#policy.searchable;
171
+ const term = `%${escapeLike(query.search.term)}%`;
172
+ const searchClause = (0, where_translator_js_1.translateWhere)({ or: fields.map((field) => ({ [field]: { ilike: term } })) }, this.#dialect());
173
+ clauses.push(searchClause);
174
+ }
175
+ return Object.assign({}, ...clauses);
176
+ }
177
+ async #findRow(id, withDeleted) {
178
+ const row = await this.#model.findByPk(id);
179
+ if (row === null)
180
+ return null;
181
+ if (!withDeleted && this.descriptor.softDelete && (0, data_1.isSoftDeleted)(row.get())) {
182
+ return null;
183
+ }
184
+ return row;
185
+ }
186
+ /**
187
+ * Narrow a row back to the fields the caller selected.
188
+ *
189
+ * `#findOptions` widens the SQL attribute list with the primary key, so the
190
+ * row carries a column the caller did not ask for; every read has to project
191
+ * it away. Skipping this on the list reads is what let the SQL driver return
192
+ * `id` while the in-memory driver did not, and a projection that differs by
193
+ * driver is a response shape that changes with the engine.
194
+ */
195
+ #toEntity(row, query = {}) {
196
+ const plain = row.get({ plain: true });
197
+ if (query.select === undefined || query.select.length === 0)
198
+ return plain;
199
+ const projected = {};
200
+ for (const field of query.select)
201
+ projected[field] = plain[field];
202
+ return projected;
203
+ }
204
+ #transaction(options) {
205
+ const transaction = (0, sql_unit_of_work_js_1.transactionOf)(options.tx);
206
+ return transaction === undefined ? {} : { transaction };
207
+ }
208
+ #dialect() {
209
+ return this.#model.sequelize?.getDialect() ?? 'postgres';
210
+ }
211
+ #notFound(id) {
212
+ return new core_1.NotFoundError({
213
+ detail: `${this.descriptor.name} ${String(id)} was not found`,
214
+ meta: { model: this.descriptor.name, id },
215
+ });
216
+ }
217
+ }
218
+ exports.SqlRepository = SqlRepository;
219
+ /**
220
+ * `%` and `_` are wildcards in LIKE; a searched term must not carry them.
221
+ *
222
+ * The backslash is the default LIKE escape character on Postgres and MySQL, so
223
+ * no `ESCAPE` clause is emitted. SQLite has no default escape character, so
224
+ * there a term containing `%`, `_` or `\` matches nothing instead of matching
225
+ * the literal — a false negative, and the safe direction to be wrong in: the
226
+ * alternative, leaving the term unescaped, turns one keystroke into a
227
+ * full-table read.
228
+ */
229
+ function escapeLike(term) {
230
+ return term.replace(/[%_\\]/g, '\\$&');
231
+ }
232
+ function encodeCursor(value) {
233
+ return Buffer.from(value, 'utf8').toString('base64url');
234
+ }
235
+ function decodeCursor(cursor) {
236
+ return Buffer.from(cursor, 'base64url').toString('utf8');
237
+ }
238
+ //# sourceMappingURL=sql.repository.js.map
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Sequelize transactions behind the `UnitOfWork` port (PLAN.md §14.2).
3
+ *
4
+ * The legacy framework had no transaction abstraction at all: a bulk operation
5
+ * that failed halfway left the rows it had already written. Here a unit commits
6
+ * or rolls back as a whole, and the lifecycle hooks of `ModelService` run inside
7
+ * it, so a failing `doAfterCreate` undoes the create.
8
+ */
9
+ import type { TxContext, UnitOfWork } from '@nage-api/contracts';
10
+ import type { Sequelize, Transaction } from 'sequelize';
11
+ /**
12
+ * The driver's transaction handle.
13
+ *
14
+ * `TxContext` is deliberately opaque in the contract — its shape is the driver's
15
+ * business — so the Sequelize transaction rides along here and repositories
16
+ * read it back out.
17
+ */
18
+ export interface SqlTxContext extends TxContext {
19
+ readonly transaction: Transaction;
20
+ }
21
+ export declare class SqlUnitOfWork implements UnitOfWork {
22
+ private readonly sequelize;
23
+ constructor(sequelize: Sequelize);
24
+ /**
25
+ * Run `fn` inside a managed transaction.
26
+ *
27
+ * Sequelize commits when the callback resolves and rolls back when it throws,
28
+ * re-raising the original error — the same observable behaviour the in-memory
29
+ * driver gives, which is what lets one conformance suite cover both.
30
+ */
31
+ run<TResult>(fn: (tx: TxContext) => Promise<TResult>): Promise<TResult>;
32
+ }
33
+ /** Read the Sequelize transaction out of an opaque context, if there is one. */
34
+ export declare function transactionOf(tx: TxContext | undefined): Transaction | undefined;
35
+ //# sourceMappingURL=sql.unit-of-work.d.ts.map
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ /**
3
+ * Sequelize transactions behind the `UnitOfWork` port (PLAN.md §14.2).
4
+ *
5
+ * The legacy framework had no transaction abstraction at all: a bulk operation
6
+ * that failed halfway left the rows it had already written. Here a unit commits
7
+ * or rolls back as a whole, and the lifecycle hooks of `ModelService` run inside
8
+ * it, so a failing `doAfterCreate` undoes the create.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.SqlUnitOfWork = void 0;
12
+ exports.transactionOf = transactionOf;
13
+ const core_1 = require("@nage-api/core");
14
+ class SqlUnitOfWork {
15
+ sequelize;
16
+ constructor(sequelize) {
17
+ this.sequelize = sequelize;
18
+ }
19
+ /**
20
+ * Run `fn` inside a managed transaction.
21
+ *
22
+ * Sequelize commits when the callback resolves and rolls back when it throws,
23
+ * re-raising the original error — the same observable behaviour the in-memory
24
+ * driver gives, which is what lets one conformance suite cover both.
25
+ */
26
+ run(fn) {
27
+ return this.sequelize.transaction(async (transaction) => {
28
+ const context = { id: (0, core_1.randomId)(), driver: 'sql', transaction };
29
+ return fn(context);
30
+ });
31
+ }
32
+ }
33
+ exports.SqlUnitOfWork = SqlUnitOfWork;
34
+ /** Read the Sequelize transaction out of an opaque context, if there is one. */
35
+ function transactionOf(tx) {
36
+ return tx?.transaction;
37
+ }
38
+ //# sourceMappingURL=sql.unit-of-work.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Translate the typed `Where` DSL into Sequelize's operator symbols
3
+ * (PLAN.md §12, §14.1).
4
+ *
5
+ * The translation is total and closed: every operator the DSL defines maps to a
6
+ * `Op.*` symbol, and anything else throws. The legacy driver passed
7
+ * client-supplied `$`-keys through to the ORM, which is how a query language
8
+ * became an injection surface — here a client-supplied key never reaches
9
+ * Sequelize, because only names this function knows are emitted.
10
+ */
11
+ import type { Where } from '@nage-api/contracts';
12
+ type SequelizeWhere = Record<string | symbol, unknown>;
13
+ /** Convert a validated `Where` clause into a Sequelize `where` object. */
14
+ export declare function translateWhere<TEntity>(where: Where<TEntity> | undefined, dialect?: string): SequelizeWhere;
15
+ export {};
16
+ //# sourceMappingURL=where-translator.d.ts.map
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ /**
3
+ * Translate the typed `Where` DSL into Sequelize's operator symbols
4
+ * (PLAN.md §12, §14.1).
5
+ *
6
+ * The translation is total and closed: every operator the DSL defines maps to a
7
+ * `Op.*` symbol, and anything else throws. The legacy driver passed
8
+ * client-supplied `$`-keys through to the ORM, which is how a query language
9
+ * became an injection surface — here a client-supplied key never reaches
10
+ * Sequelize, because only names this function knows are emitted.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.translateWhere = translateWhere;
14
+ const sequelize_1 = require("sequelize");
15
+ const core_1 = require("@nage-api/core");
16
+ /**
17
+ * A `Map` rather than an object: a lookup miss is `undefined`, which is the
18
+ * case that matters here — an unknown key must fall through to the rejection
19
+ * below rather than quietly producing `undefined` as an operator.
20
+ */
21
+ const OPERATOR_MAP = new Map([
22
+ ['eq', sequelize_1.Op.eq],
23
+ ['ne', sequelize_1.Op.ne],
24
+ ['gt', sequelize_1.Op.gt],
25
+ ['gte', sequelize_1.Op.gte],
26
+ ['lt', sequelize_1.Op.lt],
27
+ ['lte', sequelize_1.Op.lte],
28
+ ['in', sequelize_1.Op.in],
29
+ ['nin', sequelize_1.Op.notIn],
30
+ ['like', sequelize_1.Op.like],
31
+ // Only Postgres implements ILIKE; elsewhere it is folded to LIKE below.
32
+ ['ilike', sequelize_1.Op.iLike],
33
+ ['between', sequelize_1.Op.between],
34
+ ]);
35
+ const LOGICAL_MAP = new Map([
36
+ ['and', sequelize_1.Op.and],
37
+ ['or', sequelize_1.Op.or],
38
+ ['not', sequelize_1.Op.not],
39
+ ]);
40
+ function isPlainObject(value) {
41
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
42
+ }
43
+ /** Convert a validated `Where` clause into a Sequelize `where` object. */
44
+ function translateWhere(where, dialect = 'postgres') {
45
+ if (where === undefined)
46
+ return {};
47
+ const result = {};
48
+ // Entries are typed `unknown` deliberately: the clause is validated data from
49
+ // `parseQuery`, but at runtime it is still a plain object a caller built.
50
+ for (const [key, value] of Object.entries(where)) {
51
+ if (value === undefined)
52
+ continue;
53
+ const logical = LOGICAL_MAP.get(key);
54
+ if (logical !== undefined) {
55
+ result[logical] = Array.isArray(value)
56
+ ? value.map((clause) => translateWhere(clause, dialect))
57
+ : translateWhere(value, dialect);
58
+ continue;
59
+ }
60
+ if (!isPlainObject(value)) {
61
+ // A bare value is equality.
62
+ result[key] = value;
63
+ continue;
64
+ }
65
+ result[key] = translateCondition(key, value, dialect);
66
+ }
67
+ return result;
68
+ }
69
+ function translateCondition(field, condition, dialect) {
70
+ const translated = {};
71
+ for (const [operator, operand] of Object.entries(condition)) {
72
+ if (operator === 'isNull') {
73
+ translated[operand === true ? sequelize_1.Op.is : sequelize_1.Op.not] = null;
74
+ continue;
75
+ }
76
+ const symbol = OPERATOR_MAP.get(operator);
77
+ if (symbol === undefined) {
78
+ // Unreachable through `parseQuery`, which allow-lists operators; this is
79
+ // the second line of defence for code that builds a clause by hand.
80
+ throw new core_1.InvalidQueryError({
81
+ message: `Operator "${operator}" is not supported by the SQL driver`,
82
+ meta: { field, operator },
83
+ });
84
+ }
85
+ // Only Postgres implements ILIKE; elsewhere the comparison is folded to
86
+ // LIKE, which most other dialects treat case-insensitively by collation.
87
+ if (operator === 'ilike' && dialect !== 'postgres') {
88
+ translated[sequelize_1.Op.like] = operand;
89
+ continue;
90
+ }
91
+ translated[symbol] = operand;
92
+ }
93
+ return translated;
94
+ }
95
+ //# sourceMappingURL=where-translator.js.map
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@nage-api/data-sql",
3
+ "version": "1.0.0-beta.2",
4
+ "description": "SQL driver for @nage-api/data — Sequelize-backed repository, unit of work and migration store",
5
+ "license": "Apache-2.0",
6
+ "type": "commonjs",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "!dist/.tsbuildinfo",
20
+ "!dist/**/*.map",
21
+ "README.md"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "dependencies": {
27
+ "@nage-api/contracts": "1.0.0-beta.2",
28
+ "@nage-api/core": "1.0.0-beta.2",
29
+ "@nage-api/data": "1.0.0-beta.2"
30
+ },
31
+ "peerDependencies": {
32
+ "@nestjs/common": "^11.0.0",
33
+ "reflect-metadata": "^0.2.0",
34
+ "sequelize": "^6.37.0"
35
+ },
36
+ "devDependencies": {
37
+ "@nestjs/common": "11.1.29",
38
+ "@swc/core": "1.15.47",
39
+ "@types/node": "22.20.1",
40
+ "@vitest/coverage-v8": "4.1.10",
41
+ "reflect-metadata": "0.2.2",
42
+ "rimraf": "6.1.3",
43
+ "sequelize": "6.37.8",
44
+ "sqlite3": "6.0.1",
45
+ "typescript": "5.9.3",
46
+ "unplugin-swc": "1.5.11",
47
+ "vitest": "4.1.10",
48
+ "@nage-api/testing": "1.0.0-beta.2"
49
+ },
50
+ "engines": {
51
+ "node": ">=22.0.0"
52
+ },
53
+ "scripts": {
54
+ "build": "tsc -b tsconfig.build.json",
55
+ "clean": "rimraf dist .turbo",
56
+ "typecheck": "tsc -p tsconfig.json --noEmit",
57
+ "test": "vitest run"
58
+ }
59
+ }