@kiri-orm/core 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -3
- package/dist/types/client/create-client.d.ts +32 -0
- package/dist/types/client/index.d.ts +4 -0
- package/dist/types/client/model-handle.d.ts +148 -0
- package/dist/types/client/module.d.ts +54 -0
- package/dist/types/client/orm-client.d.ts +107 -0
- package/dist/types/connection.d.ts +40 -0
- package/dist/types/crud/aggregate-filter.d.ts +36 -0
- package/dist/types/crud/aggregate-paths.d.ts +74 -0
- package/dist/types/crud/aggregate-spec.d.ts +36 -0
- package/dist/types/crud/aggregate.d.ts +59 -0
- package/dist/types/crud/create-many.d.ts +42 -0
- package/dist/types/crud/errors.d.ts +16 -0
- package/dist/types/crud/index.d.ts +12 -0
- package/dist/types/crud/insert-many.d.ts +63 -0
- package/dist/types/crud/map-filter.d.ts +18 -0
- package/dist/types/crud/order.d.ts +58 -0
- package/dist/types/crud/paginate.d.ts +55 -0
- package/dist/types/crud/prepare-write.d.ts +55 -0
- package/dist/types/crud/repository-factory.d.ts +27 -0
- package/dist/types/crud/repository.d.ts +297 -0
- package/dist/types/crud/resolve-where.d.ts +24 -0
- package/dist/types/crud/row-mapping.d.ts +45 -0
- package/dist/types/crud/select.d.ts +74 -0
- package/dist/types/crud/sequence.d.ts +56 -0
- package/dist/types/crud/transaction.d.ts +19 -0
- package/dist/types/diagnostics/index.d.ts +1 -0
- package/dist/types/diagnostics/n-plus-one.d.ts +108 -0
- package/dist/types/dialect/date-bucket.d.ts +46 -0
- package/dist/types/dialect/index.d.ts +1 -0
- package/dist/types/domain/compile.d.ts +30 -0
- package/dist/types/domain/errors.d.ts +20 -0
- package/dist/types/domain/index.d.ts +4 -0
- package/dist/types/domain/parse.d.ts +30 -0
- package/dist/types/dto/field-schema.d.ts +12 -0
- package/dist/types/dto/index.d.ts +3 -0
- package/dist/types/dto/jsdoc-generator.d.ts +29 -0
- package/dist/types/dto/schema-generator.d.ts +59 -0
- package/dist/types/fields/auto-id.d.ts +27 -0
- package/dist/types/fields/cast-value.d.ts +19 -0
- package/dist/types/fields/computed-access.d.ts +22 -0
- package/dist/types/fields/default-for.d.ts +11 -0
- package/dist/types/fields/default-registry.d.ts +9 -0
- package/dist/types/fields/define-computed-field.d.ts +57 -0
- package/dist/types/fields/define-field.d.ts +35 -0
- package/dist/types/fields/errors.d.ts +30 -0
- package/dist/types/fields/index.d.ts +7 -0
- package/dist/types/fields/registry.d.ts +55 -0
- package/dist/types/fields/types/boolean.d.ts +5 -0
- package/dist/types/fields/types/char.d.ts +12 -0
- package/dist/types/fields/types/date.d.ts +10 -0
- package/dist/types/fields/types/datetime.d.ts +11 -0
- package/dist/types/fields/types/enum.d.ts +11 -0
- package/dist/types/fields/types/float.d.ts +11 -0
- package/dist/types/fields/types/integer.d.ts +11 -0
- package/dist/types/fields/types/json.d.ts +9 -0
- package/dist/types/fields/types/text.d.ts +10 -0
- package/dist/types/fields/types/uuid.d.ts +14 -0
- package/dist/types/fields/validate-value.d.ts +14 -0
- package/dist/types/global/connect.d.ts +29 -0
- package/dist/types/global/create-model.d.ts +189 -0
- package/dist/types/global/create-report.d.ts +32 -0
- package/dist/types/global/dto.d.ts +31 -0
- package/dist/types/global/glob.d.ts +12 -0
- package/dist/types/global/identity-scope.d.ts +18 -0
- package/dist/types/global/index.d.ts +12 -0
- package/dist/types/global/load-models.d.ts +31 -0
- package/dist/types/global/migrate.d.ts +68 -0
- package/dist/types/global/n-plus-one.d.ts +42 -0
- package/dist/types/global/sequences.d.ts +19 -0
- package/dist/types/global/state.d.ts +38 -0
- package/dist/types/global/sync-models.d.ts +11 -0
- package/dist/types/global/transaction.d.ts +22 -0
- package/dist/types/index.d.ts +16 -0
- package/dist/types/meta/index.d.ts +5 -0
- package/dist/types/meta/query.d.ts +34 -0
- package/dist/types/meta/reserved-tables.d.ts +10 -0
- package/dist/types/meta/schema.d.ts +18 -0
- package/dist/types/meta/snapshot.d.ts +35 -0
- package/dist/types/meta/sync-meta.d.ts +42 -0
- package/dist/types/meta/upsert.d.ts +81 -0
- package/dist/types/migrations/apply.d.ts +18 -0
- package/dist/types/migrations/describe.d.ts +11 -0
- package/dist/types/migrations/diff.d.ts +141 -0
- package/dist/types/migrations/errors.d.ts +23 -0
- package/dist/types/migrations/foreign-keys-plan.d.ts +27 -0
- package/dist/types/migrations/generate.d.ts +51 -0
- package/dist/types/migrations/index.d.ts +7 -0
- package/dist/types/migrations/render.d.ts +45 -0
- package/dist/types/migrations/runner.d.ts +118 -0
- package/dist/types/models/define-model.d.ts +52 -0
- package/dist/types/models/errors.d.ts +23 -0
- package/dist/types/models/index.d.ts +4 -0
- package/dist/types/models/inheritance.d.ts +73 -0
- package/dist/types/models/naming.d.ts +44 -0
- package/dist/types/models/primary-key.d.ts +39 -0
- package/dist/types/models/registry.d.ts +112 -0
- package/dist/types/relations/attach-detach.d.ts +76 -0
- package/dist/types/relations/cascade-delete.d.ts +29 -0
- package/dist/types/relations/commands.d.ts +84 -0
- package/dist/types/relations/define-relation.d.ts +106 -0
- package/dist/types/relations/eager-load.d.ts +28 -0
- package/dist/types/relations/errors.d.ts +21 -0
- package/dist/types/relations/foreign-keys.d.ts +76 -0
- package/dist/types/relations/index.d.ts +7 -0
- package/dist/types/relations/keys.d.ts +14 -0
- package/dist/types/relations/pivot-schema.d.ts +24 -0
- package/dist/types/relations/with-spec.d.ts +33 -0
- package/dist/types/reports/define-report.d.ts +37 -0
- package/dist/types/reports/errors.d.ts +9 -0
- package/dist/types/reports/index.d.ts +3 -0
- package/dist/types/reports/report-handle.d.ts +58 -0
- package/dist/types/schema/build-column.d.ts +18 -0
- package/dist/types/schema/column-builder-registry.d.ts +30 -0
- package/dist/types/schema/default-column-builders.d.ts +9 -0
- package/dist/types/schema/errors.d.ts +9 -0
- package/dist/types/schema/foreign-keys.d.ts +33 -0
- package/dist/types/schema/index.d.ts +6 -0
- package/dist/types/schema/introspect-foreign-keys.d.ts +23 -0
- package/dist/types/schema/sync.d.ts +63 -0
- package/dist/types/uow/entity.d.ts +80 -0
- package/dist/types/uow/errors.d.ts +8 -0
- package/dist/types/uow/hooks.d.ts +35 -0
- package/dist/types/uow/index.d.ts +5 -0
- package/dist/types/uow/unit-of-work.d.ts +142 -0
- package/dist/types/uow/with-unit-of-work.d.ts +23 -0
- package/package.json +20 -3
- package/src/connection.js +1 -1
- package/src/crud/insert-many.js +1 -1
- package/src/crud/repository.js +9 -1
package/README.md
CHANGED
|
@@ -27,7 +27,6 @@ const post = await Post.create({ title: "Hello" });
|
|
|
27
27
|
`_meta_models` / `_meta_fields` (an idea borrowed from Odoo). Migrations diff against that
|
|
28
28
|
_recorded_ schema instead of guessing from live introspection, and the CLI and the DTO
|
|
29
29
|
generators read from it too.
|
|
30
|
-
- **Plain JavaScript.** No TypeScript type system involved, no generated client.
|
|
31
30
|
- **The database enforces your relations.** Every `belongsTo` becomes a real `FOREIGN KEY` with
|
|
32
31
|
its `ON DELETE` action, so deleting a row is one statement however many tables point at it.
|
|
33
32
|
- **Relations load without N+1.** `with: [...]` costs one extra query per relation, however many
|
|
@@ -212,6 +211,26 @@ const page = await Post.paginate(
|
|
|
212
211
|
|
|
213
212
|
`aggregate()` handles grouping and several figures at once, all in one statement in the database.
|
|
214
213
|
|
|
214
|
+
```js
|
|
215
|
+
await Order.aggregate(
|
|
216
|
+
[
|
|
217
|
+
["status", "!=", "cancelled"],
|
|
218
|
+
["revenue", ">", 1000],
|
|
219
|
+
],
|
|
220
|
+
{
|
|
221
|
+
groupBy: ["customerId", "placedAt:month"],
|
|
222
|
+
aggregates: {
|
|
223
|
+
orders: "count",
|
|
224
|
+
revenue: { sum: "total" },
|
|
225
|
+
biggest: { max: "total" },
|
|
226
|
+
},
|
|
227
|
+
orderBy: "-revenue",
|
|
228
|
+
limit: 10,
|
|
229
|
+
},
|
|
230
|
+
);
|
|
231
|
+
// [{ customerId: 7, placedAt_month: Date(2024-02-01), orders: 12, revenue: 5400, biggest: 900 }, …]
|
|
232
|
+
```
|
|
233
|
+
|
|
215
234
|
## Transactions
|
|
216
235
|
|
|
217
236
|
Every method accepts `{ trx }`. If the callback throws, nothing in it is committed.
|
|
@@ -331,6 +350,34 @@ different objects. Opt in with `withIdentityMap(fn)` when you want one.
|
|
|
331
350
|
## Also included
|
|
332
351
|
|
|
333
352
|
- **Reports:** `createReport()` defines a read-only, aggregated model for dashboards and exports.
|
|
353
|
+
|
|
354
|
+
```js
|
|
355
|
+
import { createReport } from "@kiri-orm/core";
|
|
356
|
+
|
|
357
|
+
export const SalesByCustomer = createReport("salesByCustomer", {
|
|
358
|
+
from: "order", // the model it reads
|
|
359
|
+
where: [["status", "!=", "cancelled"]], // always applied
|
|
360
|
+
fields: {
|
|
361
|
+
customerId: true, // a plain field of `order`
|
|
362
|
+
customerName: "customer.name", // a field through a to-one path
|
|
363
|
+
month: { from: "placedAt", bucket: "month" },
|
|
364
|
+
orders: { agg: "count" },
|
|
365
|
+
revenue: { agg: "sum", of: "total" },
|
|
366
|
+
itemsSold: { agg: "sum", of: "items.qty" }, // across a to-many relation
|
|
367
|
+
avgOrder: {
|
|
368
|
+
// plain JavaScript over the finished row
|
|
369
|
+
compute: (row) => row.revenue / row.orders,
|
|
370
|
+
depends: ["orders", "revenue"],
|
|
371
|
+
},
|
|
372
|
+
},
|
|
373
|
+
orderBy: "-revenue", // the default; override per call
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
await SalesByCustomer.find([["revenue", ">", 1000]], { limit: 10 });
|
|
377
|
+
await SalesByCustomer.findOne([["customerName", "=", "Ada"]]);
|
|
378
|
+
await SalesByCustomer.count();
|
|
379
|
+
```
|
|
380
|
+
|
|
334
381
|
- **DTO generation:** `generateModelDTOs("post")` returns create / update / read JSON Schemas
|
|
335
382
|
built from the same field definitions.
|
|
336
383
|
- **N+1 detection:** the ORM can flag a query that is repeated per row.
|
|
@@ -338,8 +385,6 @@ different objects. Opt in with `withIdentityMap(fn)` when you want one.
|
|
|
338
385
|
|
|
339
386
|
## Good to know
|
|
340
387
|
|
|
341
|
-
- **Plain JavaScript.** The package ships no `.d.ts` files. `orm generate:dto` produces JSDoc
|
|
342
|
-
typedefs and JSON Schemas from your models if you want editor hints.
|
|
343
388
|
- **No silent schema changes.** A field that disappears from your code is flagged in the
|
|
344
389
|
metadata rather than dropped, and changing a field's `type` is never auto-migrated.
|
|
345
390
|
- **SQLite and Postgres only.** Other databases are not supported.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { HookRegistry } from "../uow/hooks.js";
|
|
2
|
+
import { OrmClient } from "./orm-client.js";
|
|
3
|
+
/**
|
|
4
|
+
* Builds a single `OrmClient` from a connection config plus either a
|
|
5
|
+
* flat list of model descriptors (`options.models`) or a list of
|
|
6
|
+
* `defineModule()` results (`options.modules`), or both. This is the
|
|
7
|
+
* intended entry point for an app using this ORM - `ModelRegistry`,
|
|
8
|
+
* `Repository`/`RepositoryFactory`, and `HookRegistry` are still
|
|
9
|
+
* available directly for lower-level/advanced use, but a normal app
|
|
10
|
+
* should only need this.
|
|
11
|
+
*
|
|
12
|
+
* Deliberately does NOT sync automatically - call `client.sync()`
|
|
13
|
+
* once you're ready, so schema changes stay an explicit, visible step
|
|
14
|
+
* (matching every other phase of this ORM, where sync() is always
|
|
15
|
+
* something the caller chooses to run, never implicit).
|
|
16
|
+
*
|
|
17
|
+
* @param {import('../connection.js').ConnectionConfig} connectionConfig
|
|
18
|
+
* @param {Object} [options]
|
|
19
|
+
* @param {object[]} [options.models] - flat model descriptors
|
|
20
|
+
* @param {import('./module.js').OrmModule[]} [options.modules]
|
|
21
|
+
* @param {(hooks: HookRegistry) => void} [options.registerHooks] - for hooks not tied to a module
|
|
22
|
+
* @param {import('../models/naming.js').NamingStrategy} [options.namingStrategy]
|
|
23
|
+
* @param {import('../fields/registry.js').FieldTypeRegistry} [options.fieldTypeRegistry]
|
|
24
|
+
* @returns {OrmClient}
|
|
25
|
+
*/
|
|
26
|
+
export declare function createClient(connectionConfig: import('../connection.js').ConnectionConfig, options?: {
|
|
27
|
+
models?: object[];
|
|
28
|
+
modules?: import('./module.js').OrmModule[];
|
|
29
|
+
registerHooks?: (hooks: HookRegistry) => void;
|
|
30
|
+
namingStrategy?: import('../models/naming.js').NamingStrategy;
|
|
31
|
+
fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry;
|
|
32
|
+
}): OrmClient;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The object behind `client.models.<modelName>`. Wraps a shared
|
|
3
|
+
* UnitOfWork (for entity-returning, identity-mapped, dirty-tracked
|
|
4
|
+
* operations) and a Repository (for bulk operations that don't
|
|
5
|
+
* involve a single tracked instance) for one model.
|
|
6
|
+
*
|
|
7
|
+
* Deliberately always returns tracked entities from find/findOne/
|
|
8
|
+
* create - unlike the lower-level Repository (Phase 5, still
|
|
9
|
+
* available directly for advanced use), which returns plain objects.
|
|
10
|
+
* Mixing both return shapes in one app was a concrete source of
|
|
11
|
+
* confusion found while building a multi-file example; the client
|
|
12
|
+
* facade picks one shape and commits to it everywhere.
|
|
13
|
+
*/
|
|
14
|
+
export declare class ModelHandle {
|
|
15
|
+
#private;
|
|
16
|
+
unitOfWork: import("../uow/unit-of-work.js").UnitOfWork;
|
|
17
|
+
modelName: string;
|
|
18
|
+
/**
|
|
19
|
+
* @param {import('../uow/unit-of-work.js').UnitOfWork} unitOfWork
|
|
20
|
+
* @param {string} modelName
|
|
21
|
+
*/
|
|
22
|
+
constructor(unitOfWork: import('../uow/unit-of-work.js').UnitOfWork, modelName: string);
|
|
23
|
+
/** @param {Record<string, unknown>|unknown[]} [filter] @param {{limit?: number, with?: string[]}} [options] */
|
|
24
|
+
find(filter?: Record<string, unknown> | unknown[], options?: {
|
|
25
|
+
limit?: number;
|
|
26
|
+
with?: string[];
|
|
27
|
+
}): Promise<Record<string, unknown>[]>;
|
|
28
|
+
/** @param {Record<string, unknown>|unknown[]} [filter] @param {{with?: string[]}} [options] */
|
|
29
|
+
findOne(filter?: Record<string, unknown> | unknown[], options?: {
|
|
30
|
+
with?: string[];
|
|
31
|
+
}): Promise<Record<string, unknown> | null>;
|
|
32
|
+
/**
|
|
33
|
+
* @param {Record<string, unknown>} data - field values, plus optional `hasMany` /
|
|
34
|
+
* `belongsToMany` relation values as `Command.*()` entries or ids
|
|
35
|
+
*/
|
|
36
|
+
create(data: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
37
|
+
/**
|
|
38
|
+
* Creates many records at once, returning tracked entities in input
|
|
39
|
+
* order. Cost does not grow with the number of records: one
|
|
40
|
+
* multi-row INSERT per chunk, plus a fixed number of statements per
|
|
41
|
+
* relation written through `Command.*()` values - so this is the
|
|
42
|
+
* right call for imports, and the way to create related records
|
|
43
|
+
* without `attach()`-ing each parent afterwards.
|
|
44
|
+
*
|
|
45
|
+
* All-or-nothing. Every row is validated before anything is
|
|
46
|
+
* written; errors are keyed by row (`[3].title`). Per-row hooks
|
|
47
|
+
* still run. See `createRecords()` for the full contract.
|
|
48
|
+
*
|
|
49
|
+
* @param {Record<string, unknown>[]} dataList
|
|
50
|
+
* @param {{ chunkSize?: number }} [options]
|
|
51
|
+
*/
|
|
52
|
+
createMany(dataList: Record<string, unknown>[], options?: {
|
|
53
|
+
chunkSize?: number;
|
|
54
|
+
}): Promise<Record<string, unknown>[]>;
|
|
55
|
+
/**
|
|
56
|
+
* Bulk update, bypassing the identity map and per-row hooks - for
|
|
57
|
+
* "update every row matching this filter" operations where there's
|
|
58
|
+
* no single entity to track. Named distinctly from entity.save()
|
|
59
|
+
* so the different semantics (no hooks, no dirty-tracking) are
|
|
60
|
+
* visible at the call site rather than implicit.
|
|
61
|
+
*
|
|
62
|
+
* @param {Record<string, unknown>|unknown[]} filter
|
|
63
|
+
* @param {Record<string, unknown>} data
|
|
64
|
+
*/
|
|
65
|
+
updateMany(filter: Record<string, unknown> | unknown[], data: Record<string, unknown>): Promise<number>;
|
|
66
|
+
/**
|
|
67
|
+
* Loads relations onto entities you already hold, in one statement per relation - the batched
|
|
68
|
+
* alternative to calling `load()` once per entity (N+1). `spec` is a relation name with its
|
|
69
|
+
* constraints in `options` (`select`, `with`, `where`, `orderBy`, `limit`, `offset`), or a whole
|
|
70
|
+
* `with` value. The entities are changed in place and returned; the related rows are plain records.
|
|
71
|
+
*
|
|
72
|
+
* @param {Record<string, unknown>[]} entities
|
|
73
|
+
* @param {string|string[]|object} spec
|
|
74
|
+
* @param {object} [options]
|
|
75
|
+
*/
|
|
76
|
+
loadMany(entities: Record<string, unknown>[], spec: string | string[] | object, options?: object): Promise<Record<string, unknown>[]>;
|
|
77
|
+
/** Loads one relation onto one entity (use loadMany() for several - this is one statement per call). */
|
|
78
|
+
load(entity: any, relationName: any, options?: {}): Promise<unknown>;
|
|
79
|
+
/**
|
|
80
|
+
* One page of entities plus `{ page, perPage, total, pageCount, hasNext, hasPrevious }`.
|
|
81
|
+
* Takes `page`, `perPage`, `total: false`, and anything find() takes. See crud/paginate.js.
|
|
82
|
+
*
|
|
83
|
+
* @param {Record<string, unknown>|unknown[]} [filter]
|
|
84
|
+
* @param {object} [options]
|
|
85
|
+
* @returns {Promise<import('../crud/paginate.js').Page>}
|
|
86
|
+
*/
|
|
87
|
+
paginate(filter?: Record<string, unknown> | unknown[], options?: object): Promise<import('../crud/paginate.js').Page>;
|
|
88
|
+
/**
|
|
89
|
+
* Groups rows and computes count / sum / avg / min / max in one query. Plain result rows,
|
|
90
|
+
* nothing tracked. See `Repository.aggregate()` for the options.
|
|
91
|
+
*
|
|
92
|
+
* @param {Record<string, unknown>|unknown[]} [filter]
|
|
93
|
+
* @param {object} options - `{ groupBy, aggregates, orderBy, limit, offset }`
|
|
94
|
+
*/
|
|
95
|
+
aggregate(filter?: Record<string, unknown> | unknown[], options?: object): Promise<Record<string, unknown>[]>;
|
|
96
|
+
/** Number of matching rows. @param {Record<string, unknown>|unknown[]} [filter] */
|
|
97
|
+
count(filter?: Record<string, unknown> | unknown[]): Promise<number>;
|
|
98
|
+
/** Sum of a numeric field over the matching rows (null if none). */
|
|
99
|
+
sum(field: any, filter?: {}): Promise<unknown>;
|
|
100
|
+
/** Average of a numeric field over the matching rows (null if none). */
|
|
101
|
+
avg(field: any, filter?: {}): Promise<unknown>;
|
|
102
|
+
/** Smallest value of a field over the matching rows (null if none). */
|
|
103
|
+
min(field: any, filter?: {}): Promise<unknown>;
|
|
104
|
+
/** Largest value of a field over the matching rows (null if none). */
|
|
105
|
+
max(field: any, filter?: {}): Promise<unknown>;
|
|
106
|
+
/**
|
|
107
|
+
* Bulk delete, same rationale as updateMany() - no hooks run.
|
|
108
|
+
* @param {Record<string, unknown>|unknown[]} filter
|
|
109
|
+
*/
|
|
110
|
+
deleteMany(filter: Record<string, unknown> | unknown[]): Promise<number>;
|
|
111
|
+
/**
|
|
112
|
+
* Associates one or more related records via a `belongsToMany`
|
|
113
|
+
* relation's pivot table. Existing associations are left alone
|
|
114
|
+
* (not duplicated) rather than erroring on a repeat attach() of the
|
|
115
|
+
* same pair.
|
|
116
|
+
*
|
|
117
|
+
* @param {Record<string, unknown>|number|string} source - an entity or a raw id
|
|
118
|
+
* @param {string} relationName
|
|
119
|
+
* @param {number|string|Array<number|string>} targetIds
|
|
120
|
+
* @returns {Promise<number>} count of new associations actually inserted
|
|
121
|
+
*/
|
|
122
|
+
attach(source: Record<string, unknown> | number | string, relationName: string, targetIds: number | string | Array<number | string>): Promise<number>;
|
|
123
|
+
/**
|
|
124
|
+
* Bulk version of attach(): associates many sources with their
|
|
125
|
+
* targets at once. Use this instead of calling attach() in a loop -
|
|
126
|
+
* that costs a couple of queries per source, this costs a handful in
|
|
127
|
+
* total. (To attach relations to records you are *creating*, pass
|
|
128
|
+
* them in the create payload instead; see createMany().)
|
|
129
|
+
*
|
|
130
|
+
* @param {string} relationName
|
|
131
|
+
* @param {Array<{ source: Record<string, unknown>|number|string, targets: number|string|Array<number|string> }>} links
|
|
132
|
+
* @returns {Promise<number>} count of new associations actually inserted
|
|
133
|
+
*/
|
|
134
|
+
attachMany(relationName: string, links: Array<{
|
|
135
|
+
source: Record<string, unknown> | number | string;
|
|
136
|
+
targets: number | string | Array<number | string>;
|
|
137
|
+
}>): Promise<number>;
|
|
138
|
+
/**
|
|
139
|
+
* Removes one or more associations via a `belongsToMany` relation's
|
|
140
|
+
* pivot table.
|
|
141
|
+
*
|
|
142
|
+
* @param {Record<string, unknown>|number|string} source
|
|
143
|
+
* @param {string} relationName
|
|
144
|
+
* @param {number|string|Array<number|string>} targetIds
|
|
145
|
+
* @returns {Promise<number>} count of associations removed
|
|
146
|
+
*/
|
|
147
|
+
detach(source: Record<string, unknown> | number | string, relationName: string, targetIds: number | string | Array<number | string>): Promise<number>;
|
|
148
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {Object} OrmModule
|
|
3
|
+
* @property {string} name
|
|
4
|
+
* @property {object[]} models - raw model descriptors (what you'd pass to registry.define())
|
|
5
|
+
* @property {(hooks: import('../uow/hooks.js').HookRegistry) => void} registerHooks
|
|
6
|
+
* @property {((client: import('./orm-client.js').OrmClient) => Record<string, Function>)|null} createService
|
|
7
|
+
*/
|
|
8
|
+
export type OrmModule = {
|
|
9
|
+
name: string;
|
|
10
|
+
/**
|
|
11
|
+
* - raw model descriptors (what you'd pass to registry.define())
|
|
12
|
+
*/
|
|
13
|
+
models: object[];
|
|
14
|
+
registerHooks: (hooks: import('../uow/hooks.js').HookRegistry) => void;
|
|
15
|
+
createService: ((client: import('./orm-client.js').OrmClient) => Record<string, Function>) | null;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Packages one bounded-context's models, hooks, AND domain operations
|
|
19
|
+
* into a single unit a composition root can pass to
|
|
20
|
+
* `createClient({ modules: [...] })`. This is what makes a modular
|
|
21
|
+
* monolith actually modular in practice: each module (identity,
|
|
22
|
+
* billing, catalog, ...) owns and can unit-test its own model
|
|
23
|
+
* definitions, business-rule hooks, and use cases in isolation,
|
|
24
|
+
* without importing anything from the other modules - the
|
|
25
|
+
* composition root is the only place that needs to know every module
|
|
26
|
+
* exists, and app-level code (seeding, request handlers, whatever)
|
|
27
|
+
* should only ever call a module's `createService` functions, never
|
|
28
|
+
* reach into `client.models.<name>` for another module's models
|
|
29
|
+
* directly. `client.models.<name>` stays available for a module's OWN
|
|
30
|
+
* use within its own `createService` implementation, and for direct,
|
|
31
|
+
* single-module apps that don't need this structure at all.
|
|
32
|
+
*
|
|
33
|
+
* `createService`, if provided, is called once per `OrmClient`
|
|
34
|
+
* (including once per transaction-scoped client - see
|
|
35
|
+
* `OrmClient#transaction`) with that client, and should return a
|
|
36
|
+
* plain object of functions implementing the module's actual
|
|
37
|
+
* operations (e.g. `placeOrder`, `cancelOrder` - not just generic
|
|
38
|
+
* create/find). The returned object is exposed as `client.<name>`, so
|
|
39
|
+
* `client` never needs to be threaded through by hand at every call
|
|
40
|
+
* site the way it would calling an exported function directly.
|
|
41
|
+
*
|
|
42
|
+
* @param {Object} options
|
|
43
|
+
* @param {string} options.name
|
|
44
|
+
* @param {object[]} options.models
|
|
45
|
+
* @param {(hooks: import('../uow/hooks.js').HookRegistry) => void} [options.registerHooks]
|
|
46
|
+
* @param {(client: import('./orm-client.js').OrmClient) => Record<string, Function>} [options.createService]
|
|
47
|
+
* @returns {Readonly<OrmModule>}
|
|
48
|
+
*/
|
|
49
|
+
export declare function defineModule(options: {
|
|
50
|
+
name: string;
|
|
51
|
+
models: object[];
|
|
52
|
+
registerHooks?: (hooks: import('../uow/hooks.js').HookRegistry) => void;
|
|
53
|
+
createService?: (client: import('./orm-client.js').OrmClient) => Record<string, Function>;
|
|
54
|
+
}): Readonly<OrmModule>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { UnitOfWork } from "../uow/unit-of-work.js";
|
|
2
|
+
/**
|
|
3
|
+
* The single object an app built on this ORM actually holds onto.
|
|
4
|
+
* Wraps a `db` connection, a `ModelRegistry`, and a `HookRegistry`
|
|
5
|
+
* (which `createClient()` builds for you), and exposes:
|
|
6
|
+
*
|
|
7
|
+
* - `client.reports.<name>` - a `ReportHandle` per report registered with `createClient({ reports })`
|
|
8
|
+
* or a module's `reports`: read-only summary rows (see `defineReport()`), one SQL statement per call,
|
|
9
|
+
* following the client into transactions like `client.models` does.
|
|
10
|
+
* - `client.models.<name>` - a `ModelHandle` per registered model,
|
|
11
|
+
* built lazily and cached, validated eagerly (accessing an unknown
|
|
12
|
+
* model name throws immediately, not on the first method call).
|
|
13
|
+
* Generic CRUD - the right level for a module's OWN use within its
|
|
14
|
+
* own service, or for a small single-module app that doesn't need
|
|
15
|
+
* more structure than that.
|
|
16
|
+
* - `client.<moduleName>` - if a module was defined with
|
|
17
|
+
* `createService`, its result is exposed here: real domain
|
|
18
|
+
* operations (`client.orders.placeOrder(...)`), not just generic
|
|
19
|
+
* CRUD. This is the surface app-level code (seeding, request
|
|
20
|
+
* handlers) and OTHER modules should actually call - reaching into
|
|
21
|
+
* `client.models.<name>` for a model that belongs to a different
|
|
22
|
+
* module bypasses whatever validation/business rules that module's
|
|
23
|
+
* service enforces, defeating the point of having modules at all.
|
|
24
|
+
* - `client.sync()` - runs Phase 3-7's sync() (tables, meta, pivots).
|
|
25
|
+
* - `client.syncSequences()` - moves every auto-increment model's Postgres
|
|
26
|
+
* sequence past the ids already in its table; run it after inserting ids
|
|
27
|
+
* outside the ORM (raw SQL, seeds, a restored dump). No-op on SQLite.
|
|
28
|
+
* - `client.transaction(fn)` - runs `fn` against a transaction-scoped
|
|
29
|
+
* client with its own identity map, committing/rolling back with
|
|
30
|
+
* the transaction (built on `UnitOfWork` under the hood). Module
|
|
31
|
+
* services are rebuilt for the transaction-scoped client too, so
|
|
32
|
+
* `tx.orders.placeOrder(...)` works identically inside a
|
|
33
|
+
* transaction as outside one.
|
|
34
|
+
* - `client.db` - the raw Knex instance, an intentional escape hatch
|
|
35
|
+
* for anything not yet covered by the higher-level surface.
|
|
36
|
+
* - `client.close()` - closes the connection.
|
|
37
|
+
*/
|
|
38
|
+
export declare class OrmClient {
|
|
39
|
+
#private;
|
|
40
|
+
db: import("knex").Knex<any, any[]>;
|
|
41
|
+
modelRegistry: import("../models/registry.js").ModelRegistry;
|
|
42
|
+
hooks: import("../uow/hooks.js").HookRegistry;
|
|
43
|
+
unitOfWork: UnitOfWork;
|
|
44
|
+
models: {};
|
|
45
|
+
reportDescriptors: any[];
|
|
46
|
+
reports: {};
|
|
47
|
+
moduleServices: {
|
|
48
|
+
name: string;
|
|
49
|
+
createService: (client: OrmClient) => Record<string, Function>;
|
|
50
|
+
}[];
|
|
51
|
+
/**
|
|
52
|
+
* @param {import('knex').Knex} db
|
|
53
|
+
* @param {import('../models/registry.js').ModelRegistry} modelRegistry
|
|
54
|
+
* @param {import('../uow/hooks.js').HookRegistry} hooks
|
|
55
|
+
* @param {import('knex').Knex.Transaction} [trx]
|
|
56
|
+
* @param {{ name: string, createService: (client: OrmClient) => Record<string, Function> }[]} [moduleServices]
|
|
57
|
+
*/
|
|
58
|
+
constructor(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, hooks: import('../uow/hooks.js').HookRegistry, trx?: import('knex').Knex.Transaction, moduleServices?: {
|
|
59
|
+
name: string;
|
|
60
|
+
createService: (client: OrmClient) => Record<string, Function>;
|
|
61
|
+
}[], reports?: any[]);
|
|
62
|
+
/**
|
|
63
|
+
* Runs `fn` while watching this client's connection (its transaction, on a `tx` client) and returns
|
|
64
|
+
* what repeated: `{ result, findings }`. See `detectNPlusOne()` in global/n-plus-one.js.
|
|
65
|
+
*
|
|
66
|
+
* @template T
|
|
67
|
+
* @param {() => Promise<T>} fn
|
|
68
|
+
* @param {object} [options] - `threshold`, `windowMs`, `statements`
|
|
69
|
+
*/
|
|
70
|
+
detectNPlusOne<T>(fn: () => Promise<T>, options?: object): Promise<{
|
|
71
|
+
result: T;
|
|
72
|
+
findings: import("../diagnostics/n-plus-one.js").Finding[];
|
|
73
|
+
}>;
|
|
74
|
+
/** Like detectNPlusOne(), but throws an NPlusOneError (with `.findings`) if anything repeated. */
|
|
75
|
+
assertNoNPlusOne(fn: any, options?: {}): Promise<any>;
|
|
76
|
+
/** A live console watcher for development; returns the monitor (`.detach()` to stop). */
|
|
77
|
+
watchNPlusOne(options?: {}): import("../diagnostics/n-plus-one.js").QueryMonitor;
|
|
78
|
+
sync(): Promise<import("../schema/sync.js").SyncResult>;
|
|
79
|
+
/**
|
|
80
|
+
* Repairs every auto-increment model's sequence (Postgres) so the next
|
|
81
|
+
* generated id is past every id already stored. Idempotent; never moves a
|
|
82
|
+
* sequence backwards. See `syncSequence()` in crud/sequence.js.
|
|
83
|
+
*
|
|
84
|
+
* @returns {Promise<Array<{ model: string, table: string, synced: boolean }>>}
|
|
85
|
+
*/
|
|
86
|
+
syncSequences(): Promise<Array<{
|
|
87
|
+
model: string;
|
|
88
|
+
table: string;
|
|
89
|
+
synced: boolean;
|
|
90
|
+
}>>;
|
|
91
|
+
/**
|
|
92
|
+
* Runs `fn` with a transaction-scoped client: same models/hooks/
|
|
93
|
+
* module services, but its own identity map, and every operation
|
|
94
|
+
* inside runs as part of one Knex transaction. Commits on success,
|
|
95
|
+
* rolls back if `fn` throws - same semantics as `withUnitOfWork`,
|
|
96
|
+
* exposed through the same `client.models.<name>` /
|
|
97
|
+
* `client.<moduleName>` surface instead of `uow.find(name, ...)`
|
|
98
|
+
* calls, so code doesn't change shape between transactional and
|
|
99
|
+
* non-transactional use.
|
|
100
|
+
*
|
|
101
|
+
* @template T
|
|
102
|
+
* @param {(txClient: OrmClient) => Promise<T>} fn
|
|
103
|
+
* @returns {Promise<T>}
|
|
104
|
+
*/
|
|
105
|
+
transaction<T>(fn: (txClient: OrmClient) => Promise<T>): Promise<T>;
|
|
106
|
+
close(): Promise<void>;
|
|
107
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supported dialects for Phase 0. More can be added later without
|
|
3
|
+
* touching call sites, since everything routes through this factory.
|
|
4
|
+
*/
|
|
5
|
+
declare const DIALECTS: readonly ["sqlite", "postgres"];
|
|
6
|
+
export type ConnectionConfig = {
|
|
7
|
+
dialect: "sqlite" | "postgres";
|
|
8
|
+
/**
|
|
9
|
+
* - sqlite only, e.g. ":memory:" or a file path
|
|
10
|
+
*/
|
|
11
|
+
filename?: string;
|
|
12
|
+
/**
|
|
13
|
+
* - postgres only
|
|
14
|
+
*/
|
|
15
|
+
connectionString?: string;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {Object} ConnectionConfig
|
|
19
|
+
* @property {"sqlite"|"postgres"} dialect
|
|
20
|
+
* @property {string} [filename] - sqlite only, e.g. ":memory:" or a file path
|
|
21
|
+
* @property {string} [connectionString] - postgres only
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Creates a Knex instance for the given dialect. This is the single
|
|
25
|
+
* chokepoint all DB access should go through, so dialect quirks stay
|
|
26
|
+
* isolated here instead of leaking into model/query code.
|
|
27
|
+
*
|
|
28
|
+
* @param {ConnectionConfig} config
|
|
29
|
+
* @returns {import('knex').Knex}
|
|
30
|
+
*/
|
|
31
|
+
export declare function createConnection(config: ConnectionConfig): import('knex').Knex;
|
|
32
|
+
/**
|
|
33
|
+
* Gracefully closes a Knex connection. Wrapped so call sites (and tests)
|
|
34
|
+
* don't need to know about `.destroy()` vs other cleanup APIs if that
|
|
35
|
+
* ever changes per-dialect.
|
|
36
|
+
*
|
|
37
|
+
* @param {import('knex').Knex} db
|
|
38
|
+
*/
|
|
39
|
+
export declare function closeConnection(db: import('knex').Knex): Promise<void>;
|
|
40
|
+
export { DIALECTS };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns the filter into an AST (a plain-object filter becomes `[field = value]` terms).
|
|
3
|
+
* @param {Record<string, unknown>|unknown[]|undefined|null} filter
|
|
4
|
+
*/
|
|
5
|
+
export declare function filterToAst(filter: Record<string, unknown> | unknown[] | undefined | null): import("../domain/parse.js").DomainNode;
|
|
6
|
+
/** True if a plain-object filter names one of the result's own columns (so it can't be a simple column filter). */
|
|
7
|
+
export declare function mentionsResultColumn(filter: any, plan: any): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Splits a filter AST into the part for WHERE and the part for HAVING.
|
|
10
|
+
*
|
|
11
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
12
|
+
* @param {import('../domain/parse.js').DomainNode} ast
|
|
13
|
+
* @param {import('./aggregate-spec.js').AggregatePlan} plan
|
|
14
|
+
* @returns {{ where: import('../domain/parse.js').DomainNode, having: import('../domain/parse.js').DomainNode|null }}
|
|
15
|
+
*/
|
|
16
|
+
export declare function splitFilter(model: import('../models/define-model.js').ModelDescriptor, ast: import('../domain/parse.js').DomainNode, plan: import('./aggregate-spec.js').AggregatePlan): {
|
|
17
|
+
where: import('../domain/parse.js').DomainNode;
|
|
18
|
+
having: import('../domain/parse.js').DomainNode | null;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Compiles the HAVING half to one SQL string plus its bindings.
|
|
22
|
+
*
|
|
23
|
+
* @param {import('./aggregate-spec.js').AggregatePlan} plan
|
|
24
|
+
* @param {import('../domain/parse.js').DomainNode} ast
|
|
25
|
+
* @param {(entry: object) => { sql: string, bindings: unknown[] }} expressionFor - the aggregate's SQL expression
|
|
26
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
27
|
+
* @param {import('../fields/registry.js').FieldTypeRegistry} fieldTypeRegistry
|
|
28
|
+
* @returns {{ sql: string, bindings: unknown[] }}
|
|
29
|
+
*/
|
|
30
|
+
export declare function compileHaving(model: import('../models/define-model.js').ModelDescriptor, plan: import('./aggregate-spec.js').AggregatePlan, ast: import('../domain/parse.js').DomainNode, expressionFor: (entry: object) => {
|
|
31
|
+
sql: string;
|
|
32
|
+
bindings: unknown[];
|
|
33
|
+
}, fieldTypeRegistry: import('../fields/registry.js').FieldTypeRegistry): {
|
|
34
|
+
sql: string;
|
|
35
|
+
bindings: unknown[];
|
|
36
|
+
};
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export type ToOneHop = {
|
|
2
|
+
name: string;
|
|
3
|
+
relation: object;
|
|
4
|
+
from: object;
|
|
5
|
+
to: object;
|
|
6
|
+
parentField: string;
|
|
7
|
+
targetField: string;
|
|
8
|
+
};
|
|
9
|
+
export type ToManyPath = {
|
|
10
|
+
name: string;
|
|
11
|
+
relation: object;
|
|
12
|
+
kind: string;
|
|
13
|
+
from: object;
|
|
14
|
+
to: object;
|
|
15
|
+
localField: string;
|
|
16
|
+
childField?: string;
|
|
17
|
+
through?: string;
|
|
18
|
+
pivotKey?: string;
|
|
19
|
+
pivotOther?: string;
|
|
20
|
+
relatedKey?: string;
|
|
21
|
+
insideHops: ToOneHop[];
|
|
22
|
+
};
|
|
23
|
+
export type ResolvedPath = {
|
|
24
|
+
hops: ToOneHop[];
|
|
25
|
+
many: ToManyPath | null;
|
|
26
|
+
model: object;
|
|
27
|
+
field: string | null;
|
|
28
|
+
def: object | null;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Resolves a dotted path such as `customer.company.country` or `items.product.price`, starting
|
|
32
|
+
* at an aggregate's base model, into the pieces the SQL builder needs.
|
|
33
|
+
*
|
|
34
|
+
* The one distinction that matters is whether a relation can multiply rows:
|
|
35
|
+
*
|
|
36
|
+
* - **to-one** (`belongsTo` onto the related model's primary key): each row has at most one
|
|
37
|
+
* match, so a plain LEFT JOIN leaves the row count alone. These can be grouped by and
|
|
38
|
+
* aggregated freely, to any depth.
|
|
39
|
+
* - **to-many** (`hasMany`, `hasOne`, `belongsToMany`): joining would repeat the row once per
|
|
40
|
+
* match, and `sum(order.total)` over that join counts every order once per item. These are
|
|
41
|
+
* aggregated in their own subquery, one row per parent, and joined on the parent's key (see
|
|
42
|
+
* aggregate.js). They can be aggregated but never grouped by - grouping by a to-many field
|
|
43
|
+
* isn't "one group per parent", it's a different grain.
|
|
44
|
+
*
|
|
45
|
+
* `hasOne` is treated as to-many on purpose: nothing stops a database holding two rows for one
|
|
46
|
+
* parent, and a join would then silently double-count. (The eager loader quietly takes the first.)
|
|
47
|
+
*
|
|
48
|
+
* Supported shape: any number of to-one hops, OR one to-many relation first (followed by any to-one
|
|
49
|
+
* hops inside it): `customer.company.country`, `items.amount`, `items.product.price`. A to-many
|
|
50
|
+
* after a to-one hop (`customer.orders.total`) isn't supported yet, nor are two to-many relations.
|
|
51
|
+
*
|
|
52
|
+
* @typedef {{ name: string, relation: object, from: object, to: object, parentField: string, targetField: string }} ToOneHop
|
|
53
|
+
* @typedef {{ name: string, relation: object, kind: string, from: object, to: object, localField: string,
|
|
54
|
+
* childField?: string, through?: string, pivotKey?: string, pivotOther?: string, relatedKey?: string,
|
|
55
|
+
* insideHops: ToOneHop[] }} ToManyPath
|
|
56
|
+
* @typedef {{ hops: ToOneHop[], many: ToManyPath|null, model: object, field: string|null, def: object|null }} ResolvedPath
|
|
57
|
+
*/
|
|
58
|
+
/**
|
|
59
|
+
* @param {object} model - the base model
|
|
60
|
+
* @param {import('../models/registry.js').ModelRegistry|undefined} modelRegistry
|
|
61
|
+
* @param {string} path
|
|
62
|
+
* @param {object} options
|
|
63
|
+
* @param {(message: string) => never} options.fail
|
|
64
|
+
* @param {string} options.context - e.g. `groupBy "customer.country"`, prefixed to every message
|
|
65
|
+
* @param {boolean} [options.allowMany] - a to-many relation may appear (aggregates yes, group keys no)
|
|
66
|
+
* @param {boolean} [options.allowRelationEnd] - the path may end at a relation (only `count` does)
|
|
67
|
+
* @returns {ResolvedPath}
|
|
68
|
+
*/
|
|
69
|
+
export declare function resolvePath(model: object, modelRegistry: import('../models/registry.js').ModelRegistry | undefined, path: string, { fail, context, allowMany, allowRelationEnd }: {
|
|
70
|
+
fail: (message: string) => never;
|
|
71
|
+
context: string;
|
|
72
|
+
allowMany?: boolean;
|
|
73
|
+
allowRelationEnd?: boolean;
|
|
74
|
+
}): ResolvedPath;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type GroupKey = {
|
|
2
|
+
alias: string;
|
|
3
|
+
kind: "field" | "bucket";
|
|
4
|
+
field: string;
|
|
5
|
+
fieldPath: string;
|
|
6
|
+
bucket?: string;
|
|
7
|
+
hops: object[];
|
|
8
|
+
def: object;
|
|
9
|
+
};
|
|
10
|
+
export type AggregateColumn = {
|
|
11
|
+
alias: string;
|
|
12
|
+
fn: "count" | "countDistinct" | "sum" | "avg" | "min" | "max";
|
|
13
|
+
field: string | null;
|
|
14
|
+
fieldPath: string | null;
|
|
15
|
+
hops: object[];
|
|
16
|
+
many: object | null;
|
|
17
|
+
def: object | null;
|
|
18
|
+
};
|
|
19
|
+
export type AggregatePlan = {
|
|
20
|
+
keys: GroupKey[];
|
|
21
|
+
aggregates: AggregateColumn[];
|
|
22
|
+
order: Array<{
|
|
23
|
+
entry: GroupKey | AggregateColumn;
|
|
24
|
+
direction: "asc" | "desc";
|
|
25
|
+
}>;
|
|
26
|
+
limit?: number;
|
|
27
|
+
offset?: number;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
31
|
+
* @param {object} options - the options object given to aggregate()
|
|
32
|
+
* @param {import('../models/registry.js').ModelRegistry} [modelRegistry] - needed to follow relations
|
|
33
|
+
* @returns {AggregatePlan}
|
|
34
|
+
* @throws {ValidationError} keyed by the option at fault: `groupBy`, `aggregates` or `orderBy`
|
|
35
|
+
*/
|
|
36
|
+
export declare function planAggregate(model: import('../models/define-model.js').ModelDescriptor, options?: object, modelRegistry?: import('../models/registry.js').ModelRegistry): AggregatePlan;
|