@kiri-orm/core 0.1.0 → 0.1.1

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.
Files changed (126) hide show
  1. package/dist/types/client/create-client.d.ts +32 -0
  2. package/dist/types/client/index.d.ts +4 -0
  3. package/dist/types/client/model-handle.d.ts +148 -0
  4. package/dist/types/client/module.d.ts +54 -0
  5. package/dist/types/client/orm-client.d.ts +107 -0
  6. package/dist/types/connection.d.ts +40 -0
  7. package/dist/types/crud/aggregate-filter.d.ts +36 -0
  8. package/dist/types/crud/aggregate-paths.d.ts +74 -0
  9. package/dist/types/crud/aggregate-spec.d.ts +36 -0
  10. package/dist/types/crud/aggregate.d.ts +59 -0
  11. package/dist/types/crud/create-many.d.ts +42 -0
  12. package/dist/types/crud/errors.d.ts +16 -0
  13. package/dist/types/crud/index.d.ts +12 -0
  14. package/dist/types/crud/insert-many.d.ts +63 -0
  15. package/dist/types/crud/map-filter.d.ts +18 -0
  16. package/dist/types/crud/order.d.ts +58 -0
  17. package/dist/types/crud/paginate.d.ts +55 -0
  18. package/dist/types/crud/prepare-write.d.ts +55 -0
  19. package/dist/types/crud/repository-factory.d.ts +27 -0
  20. package/dist/types/crud/repository.d.ts +297 -0
  21. package/dist/types/crud/resolve-where.d.ts +24 -0
  22. package/dist/types/crud/row-mapping.d.ts +45 -0
  23. package/dist/types/crud/select.d.ts +74 -0
  24. package/dist/types/crud/sequence.d.ts +56 -0
  25. package/dist/types/crud/transaction.d.ts +19 -0
  26. package/dist/types/diagnostics/index.d.ts +1 -0
  27. package/dist/types/diagnostics/n-plus-one.d.ts +108 -0
  28. package/dist/types/dialect/date-bucket.d.ts +46 -0
  29. package/dist/types/dialect/index.d.ts +1 -0
  30. package/dist/types/domain/compile.d.ts +30 -0
  31. package/dist/types/domain/errors.d.ts +20 -0
  32. package/dist/types/domain/index.d.ts +4 -0
  33. package/dist/types/domain/parse.d.ts +30 -0
  34. package/dist/types/dto/field-schema.d.ts +12 -0
  35. package/dist/types/dto/index.d.ts +3 -0
  36. package/dist/types/dto/jsdoc-generator.d.ts +29 -0
  37. package/dist/types/dto/schema-generator.d.ts +59 -0
  38. package/dist/types/fields/auto-id.d.ts +27 -0
  39. package/dist/types/fields/cast-value.d.ts +19 -0
  40. package/dist/types/fields/computed-access.d.ts +22 -0
  41. package/dist/types/fields/default-for.d.ts +11 -0
  42. package/dist/types/fields/default-registry.d.ts +9 -0
  43. package/dist/types/fields/define-computed-field.d.ts +57 -0
  44. package/dist/types/fields/define-field.d.ts +35 -0
  45. package/dist/types/fields/errors.d.ts +30 -0
  46. package/dist/types/fields/index.d.ts +7 -0
  47. package/dist/types/fields/registry.d.ts +55 -0
  48. package/dist/types/fields/types/boolean.d.ts +5 -0
  49. package/dist/types/fields/types/char.d.ts +12 -0
  50. package/dist/types/fields/types/date.d.ts +10 -0
  51. package/dist/types/fields/types/datetime.d.ts +11 -0
  52. package/dist/types/fields/types/enum.d.ts +11 -0
  53. package/dist/types/fields/types/float.d.ts +11 -0
  54. package/dist/types/fields/types/integer.d.ts +11 -0
  55. package/dist/types/fields/types/json.d.ts +9 -0
  56. package/dist/types/fields/types/text.d.ts +10 -0
  57. package/dist/types/fields/types/uuid.d.ts +14 -0
  58. package/dist/types/fields/validate-value.d.ts +14 -0
  59. package/dist/types/global/connect.d.ts +29 -0
  60. package/dist/types/global/create-model.d.ts +189 -0
  61. package/dist/types/global/create-report.d.ts +32 -0
  62. package/dist/types/global/dto.d.ts +31 -0
  63. package/dist/types/global/glob.d.ts +12 -0
  64. package/dist/types/global/identity-scope.d.ts +18 -0
  65. package/dist/types/global/index.d.ts +12 -0
  66. package/dist/types/global/load-models.d.ts +31 -0
  67. package/dist/types/global/migrate.d.ts +68 -0
  68. package/dist/types/global/n-plus-one.d.ts +42 -0
  69. package/dist/types/global/sequences.d.ts +19 -0
  70. package/dist/types/global/state.d.ts +38 -0
  71. package/dist/types/global/sync-models.d.ts +11 -0
  72. package/dist/types/global/transaction.d.ts +22 -0
  73. package/dist/types/index.d.ts +16 -0
  74. package/dist/types/meta/index.d.ts +5 -0
  75. package/dist/types/meta/query.d.ts +34 -0
  76. package/dist/types/meta/reserved-tables.d.ts +10 -0
  77. package/dist/types/meta/schema.d.ts +18 -0
  78. package/dist/types/meta/snapshot.d.ts +35 -0
  79. package/dist/types/meta/sync-meta.d.ts +42 -0
  80. package/dist/types/meta/upsert.d.ts +81 -0
  81. package/dist/types/migrations/apply.d.ts +18 -0
  82. package/dist/types/migrations/describe.d.ts +11 -0
  83. package/dist/types/migrations/diff.d.ts +141 -0
  84. package/dist/types/migrations/errors.d.ts +23 -0
  85. package/dist/types/migrations/foreign-keys-plan.d.ts +27 -0
  86. package/dist/types/migrations/generate.d.ts +51 -0
  87. package/dist/types/migrations/index.d.ts +7 -0
  88. package/dist/types/migrations/render.d.ts +45 -0
  89. package/dist/types/migrations/runner.d.ts +118 -0
  90. package/dist/types/models/define-model.d.ts +52 -0
  91. package/dist/types/models/errors.d.ts +23 -0
  92. package/dist/types/models/index.d.ts +4 -0
  93. package/dist/types/models/inheritance.d.ts +73 -0
  94. package/dist/types/models/naming.d.ts +44 -0
  95. package/dist/types/models/primary-key.d.ts +39 -0
  96. package/dist/types/models/registry.d.ts +112 -0
  97. package/dist/types/relations/attach-detach.d.ts +76 -0
  98. package/dist/types/relations/cascade-delete.d.ts +29 -0
  99. package/dist/types/relations/commands.d.ts +84 -0
  100. package/dist/types/relations/define-relation.d.ts +106 -0
  101. package/dist/types/relations/eager-load.d.ts +28 -0
  102. package/dist/types/relations/errors.d.ts +21 -0
  103. package/dist/types/relations/foreign-keys.d.ts +76 -0
  104. package/dist/types/relations/index.d.ts +7 -0
  105. package/dist/types/relations/keys.d.ts +14 -0
  106. package/dist/types/relations/pivot-schema.d.ts +24 -0
  107. package/dist/types/relations/with-spec.d.ts +33 -0
  108. package/dist/types/reports/define-report.d.ts +37 -0
  109. package/dist/types/reports/errors.d.ts +9 -0
  110. package/dist/types/reports/index.d.ts +3 -0
  111. package/dist/types/reports/report-handle.d.ts +58 -0
  112. package/dist/types/schema/build-column.d.ts +18 -0
  113. package/dist/types/schema/column-builder-registry.d.ts +30 -0
  114. package/dist/types/schema/default-column-builders.d.ts +9 -0
  115. package/dist/types/schema/errors.d.ts +9 -0
  116. package/dist/types/schema/foreign-keys.d.ts +33 -0
  117. package/dist/types/schema/index.d.ts +6 -0
  118. package/dist/types/schema/introspect-foreign-keys.d.ts +23 -0
  119. package/dist/types/schema/sync.d.ts +63 -0
  120. package/dist/types/uow/entity.d.ts +80 -0
  121. package/dist/types/uow/errors.d.ts +8 -0
  122. package/dist/types/uow/hooks.d.ts +35 -0
  123. package/dist/types/uow/index.d.ts +5 -0
  124. package/dist/types/uow/unit-of-work.d.ts +142 -0
  125. package/dist/types/uow/with-unit-of-work.d.ts +23 -0
  126. package/package.json +9 -3
@@ -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,4 @@
1
+ export { createClient } from "./create-client.js";
2
+ export { OrmClient } from "./orm-client.js";
3
+ export { ModelHandle } from "./model-handle.js";
4
+ export { defineModule } from "./module.js";
@@ -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;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Builds and runs one aggregate query: groups rows, computes count/sum/avg/min/max, filters
3
+ * before and after grouping, and returns plain result rows. Always exactly ONE statement,
4
+ * however many groups, aggregates, or relations are involved - there is no per-group or
5
+ * per-parent follow-up query, so no N+1.
6
+ *
7
+ * Reads are plain: no entities, no identity map, no hooks, no `save()`. A result row is a
8
+ * summary of many records, not any one of them. See Repository.aggregate() for the options.
9
+ *
10
+ * ## Following relations without distorting the numbers
11
+ *
12
+ * Fields reached through a to-one relation (`customer.country`) are LEFT JOINed: a row has at
13
+ * most one customer, so the row count can't change.
14
+ *
15
+ * A to-many relation (`items.amount`) can't be joined - `sum(order.total)` over orders joined
16
+ * to their items counts every order once per item. Instead each to-many relation gets its own
17
+ * subquery that collapses the related rows to ONE ROW PER PARENT:
18
+ *
19
+ * LEFT JOIN (SELECT order_id AS k, sum(amount) AS s0, count(amount) AS c0
20
+ * FROM item GROUP BY order_id) AS m1 ON m1.k = order.id
21
+ *
22
+ * so parents still appear exactly once, and the outer query combines the per-parent subtotals:
23
+ * count and sum add up, min/max take the min/max, and avg is total-sum / total-count (NOT an
24
+ * average of averages, which would weight a parent with one item the same as one with fifty).
25
+ * countDistinct can't be assembled from subtotals, so it isn't offered across a to-many.
26
+ *
27
+ * When any relation is involved, the filtered base rows are wrapped as a derived table with the
28
+ * model's own name, so the WHERE half of the filter keeps its plain unqualified column names and
29
+ * runs before any join. With no relation the query has no derived table and no joins.
30
+ *
31
+ * @param {object} ctx
32
+ * @param {import('knex').Knex} ctx.db - connection or transaction
33
+ * @param {import('../models/define-model.js').ModelDescriptor} ctx.model
34
+ * @param {Record<string, unknown>|unknown[]} ctx.filter
35
+ * @param {object} ctx.options
36
+ * @param {import('../fields/registry.js').FieldTypeRegistry} ctx.fieldTypeRegistry
37
+ * @param {import('../models/registry.js').ModelRegistry} [ctx.modelRegistry]
38
+ * @param {boolean} [withOrder] - false when only the number of groups is wanted
39
+ * @returns {{ query: import('knex').Knex.QueryBuilder, plan: import('./aggregate-spec.js').AggregatePlan }}
40
+ */
41
+ export declare function buildAggregateQuery({ db, model, filter, options, fieldTypeRegistry, modelRegistry }: {
42
+ db: import('knex').Knex;
43
+ model: import('../models/define-model.js').ModelDescriptor;
44
+ filter: Record<string, unknown> | unknown[];
45
+ options: object;
46
+ fieldTypeRegistry: import('../fields/registry.js').FieldTypeRegistry;
47
+ modelRegistry?: import('../models/registry.js').ModelRegistry;
48
+ }, withOrder?: boolean): {
49
+ query: import('knex').Knex.QueryBuilder;
50
+ plan: import('./aggregate-spec.js').AggregatePlan;
51
+ };
52
+ /** Runs the query. @returns {Promise<Array<Record<string, unknown>>>} */
53
+ export declare function runAggregate(ctx: any): Promise<Array<Record<string, unknown>>>;
54
+ /**
55
+ * How many groups the aggregate would return, ignoring orderBy/limit/offset: one statement,
56
+ * counting the grouped query as a derived table.
57
+ * @returns {Promise<number>}
58
+ */
59
+ export declare function countAggregateGroups(ctx: any): Promise<number>;
@@ -0,0 +1,42 @@
1
+ export type CreateRuntime = {
2
+ /**
3
+ * - connection used unless `options.trx` overrides it
4
+ */
5
+ db: import('knex').Knex;
6
+ /**
7
+ * - needed only when payloads contain relations
8
+ */
9
+ modelRegistry?: import('../models/registry.js').ModelRegistry;
10
+ fieldTypeRegistry: import('../fields/registry.js').FieldTypeRegistry;
11
+ /**
12
+ * - omit for hook-free creation (plain Repository)
13
+ */
14
+ hooks?: import('../uow/hooks.js').HookRegistry;
15
+ /**
16
+ * - turns a stored record into what callers
17
+ * get back (a tracked entity); omit to return plain records
18
+ */
19
+ wrap?: (modelName: string, record: Record<string, unknown>) => object;
20
+ };
21
+ /**
22
+ * Creates every record in `dataList` (and any relations named in
23
+ * their payloads) with a query count independent of how many there are.
24
+ * All-or-nothing: if anything fails, nothing is written.
25
+ *
26
+ * @param {CreateRuntime} runtime
27
+ * @param {import('../models/define-model.js').ModelDescriptor} model
28
+ * @param {Record<string, unknown>[]} dataList
29
+ * @param {Object} [options]
30
+ * @param {import('knex').Knex.Transaction} [options.trx] - run inside this transaction instead of opening one
31
+ * @param {number} [options.chunkSize] - lower the rows-per-INSERT below the dialect's limit
32
+ * @param {string[]} [options.labels] - per-row prefixes for validation error keys; defaults to
33
+ * `[0]`, `[1]`, ...; `create()` passes `[""]` so its error keys stay plain field names
34
+ * @returns {Promise<object[]>} one result per input, in input order (`runtime.wrap`'s output, else the stored record)
35
+ * @throws {ValidationError} row-level problems, keyed by row (`[3].title`, `[3].items[1].quantity`)
36
+ * @throws {RelationError} malformed relation payloads
37
+ */
38
+ export declare function createRecords(runtime: CreateRuntime, model: import('../models/define-model.js').ModelDescriptor, dataList: Record<string, unknown>[], options?: {
39
+ trx?: import('knex').Knex.Transaction;
40
+ chunkSize?: number;
41
+ labels?: string[];
42
+ }): Promise<object[]>;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Thrown by Repository#create()/#update() when field validation fails,
3
+ * or when the caller references a field name that isn't on the model
4
+ * (a filter key, a write key, etc.) - both are surfaced through the
5
+ * same `fieldErrors` shape so a caller only needs to handle one error
6
+ * type to report every kind of "your data/filter was wrong" problem.
7
+ */
8
+ export declare class ValidationError extends Error {
9
+ modelName: string;
10
+ fieldErrors: Record<string, string[]>;
11
+ /**
12
+ * @param {string} modelName
13
+ * @param {Record<string, string[]>} fieldErrors
14
+ */
15
+ constructor(modelName: string, fieldErrors: Record<string, string[]>);
16
+ }