@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,12 @@
1
+ export { Repository, createRepository } from "./repository.js";
2
+ export { RepositoryFactory } from "./repository-factory.js";
3
+ export { runInTransaction } from "./transaction.js";
4
+ export { ValidationError } from "./errors.js";
5
+ export { fromRow, toRow } from "./row-mapping.js";
6
+ export { prepareWrite, assertPrimaryKeyUntouched } from "./prepare-write.js";
7
+ export { mapFilterToColumns } from "./map-filter.js";
8
+ export { resolveWhere, isEmptyFilter } from "./resolve-where.js";
9
+ export { createRecords } from "./create-many.js";
10
+ export { advanceSequence, syncSequence, syncRegistrySequences } from "./sequence.js";
11
+ export { planAggregate } from "./aggregate-spec.js";
12
+ export { runAggregate, buildAggregateQuery, countAggregateGroups } from "./aggregate.js";
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @param {import('knex').Knex} db - a Knex instance or transaction
3
+ * @returns {{ maxRows: number, maxParams: number }}
4
+ */
5
+ export declare function insertLimitsFor(db: import('knex').Knex): {
6
+ maxRows: number;
7
+ maxParams: number;
8
+ };
9
+ /**
10
+ * How many rows of `columnCount` columns fit in one INSERT on this
11
+ * connection. `requested` can only lower the answer, never raise it
12
+ * above what the dialect can actually execute.
13
+ *
14
+ * @param {import('knex').Knex} db
15
+ * @param {number} columnCount
16
+ * @param {number} [requested]
17
+ * @returns {number}
18
+ */
19
+ export declare function rowsPerStatement(db: import('knex').Knex, columnCount: number, requested?: number): number;
20
+ /**
21
+ * @template T
22
+ * @param {T[]} items
23
+ * @param {number} size
24
+ * @returns {T[][]}
25
+ */
26
+ export declare function chunkArray<T>(items: T[], size: number): T[][];
27
+ /**
28
+ * Pairs each INSERT ... RETURNING row back up with the input row that
29
+ * produced it.
30
+ *
31
+ * Both Postgres and SQLite return rows in insertion order in
32
+ * practice, and that is the fast path here. But nothing in either
33
+ * SQL standard guarantees it, and getting it wrong is not a cosmetic
34
+ * bug: a hasMany child or pivot row would be attached to the wrong
35
+ * parent, silently. So the fast path is *verified* against each row's
36
+ * `id` (the primary-key convention used throughout this ORM), and if
37
+ * any pair disagrees, rows are matched by `id` instead. A model with
38
+ * no `id` field has nothing to verify against and stays positional.
39
+ *
40
+ * @param {import('../models/define-model.js').ModelDescriptor} model
41
+ * @param {Record<string, unknown>[]} valuesList - validated field values, in input order
42
+ * @param {Record<string, unknown>[]} records - returned records, in whatever order the DB used
43
+ * @returns {Record<string, unknown>[]} records in input order
44
+ */
45
+ export declare function alignToInput(model: import('../models/define-model.js').ModelDescriptor, valuesList: Record<string, unknown>[], records: Record<string, unknown>[]): Record<string, unknown>[];
46
+ /**
47
+ * Inserts many already-validated rows with as few statements as the
48
+ * dialect allows - one INSERT ... RETURNING per chunk - and returns
49
+ * the stored records, cast back into field values, in input order.
50
+ *
51
+ * This does NOT open a transaction: with more than one chunk the
52
+ * caller is responsible for atomicity (see createRecords()).
53
+ *
54
+ * @param {import('knex').Knex} db - connection or transaction
55
+ * @param {import('../models/define-model.js').ModelDescriptor} model
56
+ * @param {Record<string, unknown>[]} valuesList - output of prepareWrite(...).values, one per row
57
+ * @param {import('../fields/registry.js').FieldTypeRegistry} fieldTypeRegistry
58
+ * @param {{ chunkSize?: number }} [options]
59
+ * @returns {Promise<Record<string, unknown>[]>}
60
+ */
61
+ export declare function insertRecords(db: import('knex').Knex, model: import('../models/define-model.js').ModelDescriptor, valuesList: Record<string, unknown>[], fieldTypeRegistry: import('../fields/registry.js').FieldTypeRegistry, options?: {
62
+ chunkSize?: number;
63
+ }): Promise<Record<string, unknown>[]>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Converts a `{ fieldName: value }` equality filter into a
3
+ * `{ columnName: value }` filter suitable for Knex's `.where()`,
4
+ * casting each value through its field's type along the way (so
5
+ * `{ id: "1" }` matches the same rows as `{ id: 1 }` would).
6
+ *
7
+ * This is intentionally simple equality-only matching - the
8
+ * Odoo-style domain DSL with AND/OR/comparison operators is Phase 8.
9
+ * Phase 5 only needs enough filtering to make create/find/update/
10
+ * delete usable.
11
+ *
12
+ * @param {import('../models/define-model.js').ModelDescriptor} model
13
+ * @param {Record<string, unknown>} filter
14
+ * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
15
+ * @returns {Record<string, unknown>}
16
+ * @throws {ValidationError} if `filter` references an unknown field
17
+ */
18
+ export declare function mapFilterToColumns(model: import('../models/define-model.js').ModelDescriptor, filter: Record<string, unknown>, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry): Record<string, unknown>;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Normalizes `orderBy` into `[{ field, direction }]`, validating field names.
3
+ *
4
+ * Accepted forms (all interchangeable):
5
+ * "title" ascending
6
+ * "-title" descending (leading minus)
7
+ * ["title", "-createdAt"] several keys, in priority order
8
+ * [["title", "desc"]] [field, direction] pairs
9
+ * { field: "title", direction: "desc" } (also inside an array)
10
+ *
11
+ * Only stored fields can be ordered by - computed fields have no column.
12
+ *
13
+ * @param {object} model
14
+ * @param {unknown} orderBy
15
+ * @returns {Array<{ field: string, direction: "asc"|"desc" }>}
16
+ */
17
+ export declare function normalizeOrderBy(model: object, orderBy: unknown): Array<{
18
+ field: string;
19
+ direction: "asc" | "desc";
20
+ }>;
21
+ /**
22
+ * The shape half of normalizeOrderBy(): turns every accepted spelling of `orderBy`
23
+ * (`"-views"`, `["title", "desc"]`, `["a", "-b"]`, `{ field, direction }`, a list of
24
+ * those) into `[{ field, direction }]`, rejecting a malformed entry, a bad direction or a
25
+ * repeated field via `fail(message)`. It does NOT check that a field exists - the caller
26
+ * knows what can be sorted (an ordinary query: model fields; an aggregate: group keys and
27
+ * aggregate aliases).
28
+ *
29
+ * @param {unknown} orderBy
30
+ * @param {(message: string) => never} fail
31
+ * @returns {Array<{ field: string, direction: "asc"|"desc" }>}
32
+ */
33
+ export declare function parseOrderBy(orderBy: unknown, fail: (message: string) => never): Array<{
34
+ field: string;
35
+ direction: "asc" | "desc";
36
+ }>;
37
+ /**
38
+ * Validates `limit` / `offset`: non-negative integers when given.
39
+ */
40
+ export declare function validatePaging(model: any, { limit, offset }: {
41
+ limit: any;
42
+ offset: any;
43
+ }): void;
44
+ /**
45
+ * Applies ordering and paging to a Knex query builder.
46
+ *
47
+ * Pages are only stable if the order is total, so whenever the caller
48
+ * orders or skips rows, the primary key is appended as a final
49
+ * tie-breaker (unless it is already in the list). A bare `limit` with no
50
+ * `orderBy` and no `offset` stays exactly as it always was: unordered.
51
+ *
52
+ * @returns {import('knex').Knex.QueryBuilder}
53
+ */
54
+ export declare function applyOrderAndPaging(query: any, model: any, { orderBy, limit, offset }: {
55
+ limit: any;
56
+ offset: any;
57
+ orderBy: any;
58
+ }): import('knex').Knex.QueryBuilder;
@@ -0,0 +1,55 @@
1
+ export type Page = {
2
+ items: unknown[];
3
+ page: number;
4
+ perPage: number;
5
+ total: number | null;
6
+ pageCount: number | null;
7
+ hasNext: boolean;
8
+ hasPrevious: boolean;
9
+ };
10
+ /**
11
+ * Page-number pagination: `paginate(filter, { page, perPage, ...findOptions })` returns one page of
12
+ * rows plus what a UI needs to draw the pager.
13
+ *
14
+ * ```js
15
+ * const result = await Post.paginate({ status: "published" }, { page: 2, perPage: 20, orderBy: "-views", with: ["author"] });
16
+ * // { items: [...], page: 2, perPage: 20, total: 137, pageCount: 7, hasNext: true, hasPrevious: true }
17
+ * ```
18
+ *
19
+ * It is `count()` plus `find({ limit, offset })`, so it takes everything find() takes (`orderBy`,
20
+ * `select`, `with`, `trx`, ...) and works the same on the plain Repository, `client.models.*` and
21
+ * `createModel()` models - `items` are whatever that surface's find() returns (entities / documents on
22
+ * the tracked ones).
23
+ *
24
+ * - **Stable pages.** find() adds the primary key as a final tiebreaker whenever an offset is used, so
25
+ * rows with equal sort values land on exactly one page. Without that, paging by `status` could show a
26
+ * row twice and skip another.
27
+ * - **Two statements** (count, then the page); one if the page is past the end (nothing to fetch), or
28
+ * with `total: false`.
29
+ * - **`total: false`** skips the count - which can be the expensive part on a big table - and finds
30
+ * `hasNext` by asking for one row more than the page. `total` and `pageCount` are then `null`.
31
+ * - The two statements aren't one snapshot: rows added between them can make `total` a little off. Pass a
32
+ * transaction (`trx`) for a consistent read.
33
+ *
34
+ * Page numbers start at 1. A page past the last is not an error: it is empty, with the real `total`.
35
+ *
36
+ * @typedef {{ items: unknown[], page: number, perPage: number, total: number|null, pageCount: number|null,
37
+ * hasNext: boolean, hasPrevious: boolean }} Page
38
+ */
39
+ export declare const DEFAULT_PER_PAGE = 20;
40
+ /**
41
+ * @param {{ modelName: string, count: (filter: unknown, options: object) => Promise<number>,
42
+ * find: (filter: unknown, options: object) => Promise<unknown[]> }} source - how to count and to fetch
43
+ * @param {Record<string, unknown>|unknown[]} filter
44
+ * @param {{ page?: number, perPage?: number, total?: boolean }} [options] - the rest goes to find()
45
+ * @returns {Promise<Page>}
46
+ */
47
+ export declare function paginateWith({ modelName, count, find }: {
48
+ modelName: string;
49
+ count: (filter: unknown, options: object) => Promise<number>;
50
+ find: (filter: unknown, options: object) => Promise<unknown[]>;
51
+ }, filter?: Record<string, unknown> | unknown[], options?: {
52
+ page?: number;
53
+ perPage?: number;
54
+ total?: boolean;
55
+ }): Promise<Page>;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Validates and casts a plain `{ fieldName: value }` object against a
3
+ * model's fields, ready to be handed to toRow() for the actual write.
4
+ *
5
+ * Order matters here: each present value is **cast first, then
6
+ * validated** - not the other way around. castValue() coerces loose
7
+ * input (a numeric string for an integer field, "true" for a boolean)
8
+ * into the field's canonical representation; validateValue() then
9
+ * checks constraints (min/max, maxLength, enum membership) against
10
+ * that canonical value. Validating before casting would reject
11
+ * perfectly reasonable input like `{ id: "1" }` for an integer field,
12
+ * since validateValue()'s type check is intentionally strict and
13
+ * doesn't coerce - only castValue() does.
14
+ *
15
+ * Collects every problem across every field into one `errors` map
16
+ * rather than throwing on the first bad field, so a caller (or a
17
+ * future DTO/form layer) can report everything wrong with a record at
18
+ * once instead of a frustrating one-error-at-a-time loop.
19
+ *
20
+ * @param {import('../models/define-model.js').ModelDescriptor} model
21
+ * @param {Record<string, unknown>} data
22
+ * @param {Object} [options]
23
+ * @param {boolean} [options.partial] - if true (update semantics),
24
+ * fields absent from `data` are left untouched: no default is
25
+ * applied and they don't appear in the returned `values`. If false
26
+ * (create semantics, the default), an absent field's default is
27
+ * applied via defaultFor() before casting/validation.
28
+ * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
29
+ * @returns {{ errors: Record<string, string[]>, values: Record<string, unknown> }}
30
+ */
31
+ export declare function prepareWrite(model: import('../models/define-model.js').ModelDescriptor, data: Record<string, unknown>, options?: {
32
+ partial?: boolean;
33
+ }, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry): {
34
+ errors: Record<string, string[]>;
35
+ values: Record<string, unknown>;
36
+ };
37
+ /**
38
+ * Refuses an update that names the model's primary key.
39
+ *
40
+ * A primary key is fixed once the row exists. Letting it change would (a) orphan
41
+ * every foreign key and pivot row that points at the old value, since nothing here
42
+ * rewrites them, and (b) on Postgres let an auto-increment key jump to a value the
43
+ * sequence hasn't reached yet, so a later auto-assigned id collides with it. Both are
44
+ * silent until something else breaks, so the write is rejected up front - before any
45
+ * hook runs or any SQL is sent.
46
+ *
47
+ * Applies to every primary key, auto-assigned or not. A model with no primary key
48
+ * has nothing to protect. Renumbering a row deliberately is still possible through
49
+ * raw SQL (`client.db` / `getConnection()`); follow it with `syncSequences()`.
50
+ *
51
+ * @param {import('../models/define-model.js').ModelDescriptor} model
52
+ * @param {Record<string, unknown>} data - the fields about to be written
53
+ * @throws {ValidationError}
54
+ */
55
+ export declare function assertPrimaryKeyUntouched(model: import('../models/define-model.js').ModelDescriptor, data: Record<string, unknown>): void;
@@ -0,0 +1,27 @@
1
+ import { Repository } from "./repository.js";
2
+ /**
3
+ * Ties a `db` connection to a `ModelRegistry` and hands out a
4
+ * `Repository` per model name, e.g.:
5
+ *
6
+ * const repos = new RepositoryFactory(db, registry);
7
+ * await repos.for("invoice").create({ customerId: 1 });
8
+ *
9
+ * Repositories are built lazily and cached, since a Repository is
10
+ * just a thin, stateless-except-for-config wrapper around a model
11
+ * descriptor - reusing one instance per model avoids rebuilding it on
12
+ * every call without changing any behavior.
13
+ */
14
+ export declare class RepositoryFactory {
15
+ #private;
16
+ /**
17
+ * @param {import('knex').Knex} db
18
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
19
+ * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
20
+ */
21
+ constructor(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry);
22
+ /**
23
+ * @param {string} modelName
24
+ * @returns {Repository}
25
+ */
26
+ for(modelName: string): Repository;
27
+ }
@@ -0,0 +1,297 @@
1
+ /**
2
+ * The CRUD surface for a single model. Every method speaks in field
3
+ * names and JS-native value types (Dates, booleans, parsed JSON) -
4
+ * column names, casting, and raw Knex calls are all handled
5
+ * internally, so a caller never needs to write SQL or touch Knex
6
+ * directly to manage rows of a model.
7
+ *
8
+ * Every method accepts an optional `{ trx }` in its options so a
9
+ * caller can run several operations as one atomic unit via Knex's own
10
+ * transaction API - see runInTransaction() in transaction.js for a
11
+ * thin convenience wrapper around `db.transaction()`.
12
+ *
13
+ * `find`/`findOne` accept `{ with: ["relationName", ...] }` to
14
+ * eager-load relations (Phase 7) - this requires a `modelRegistry` to
15
+ * be supplied at construction time, since resolving a relation means
16
+ * looking up its target model. `load()` does the same for a single
17
+ * already-fetched record (lazy loading).
18
+ *
19
+ * They also accept `{ select: ["field", ...] }` to read only some columns (Phase 14), and
20
+ * `with` can narrow each relation the same way: `{ with: { author: { select: ["name"] } } }`.
21
+ */
22
+ export declare class Repository {
23
+ #private;
24
+ db: import("knex").Knex<any, any[]>;
25
+ model: import("../models/define-model.js").ModelDescriptor;
26
+ fieldTypeRegistry: import("../fields/registry.js").FieldTypeRegistry;
27
+ modelRegistry: import("../models/registry.js").ModelRegistry | undefined;
28
+ /**
29
+ * @param {import('knex').Knex} db
30
+ * @param {import('../models/define-model.js').ModelDescriptor} model
31
+ * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
32
+ * @param {import('../models/registry.js').ModelRegistry} [modelRegistry] - required for `with`/`load()`
33
+ */
34
+ constructor(db: import('knex').Knex, model: import('../models/define-model.js').ModelDescriptor, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry, modelRegistry?: import('../models/registry.js').ModelRegistry);
35
+ /**
36
+ * Validates `data` against the model (applying defaults for any
37
+ * field not provided), inserts one row, and returns the created
38
+ * record as read back from the DB - so DB-level defaults and any
39
+ * driver-side coercion are reflected in what's returned.
40
+ *
41
+ * `data` may also carry `hasMany` / `belongsToMany` relation values
42
+ * as `Command.*()` entries or ids (see `Command`), which are
43
+ * written in the same operation; that requires a `modelRegistry`.
44
+ * A plain create with no relation values is still exactly one
45
+ * INSERT.
46
+ *
47
+ * @param {Record<string, unknown>} data
48
+ * @param {{ trx?: import('knex').Knex.Transaction }} [options]
49
+ * @returns {Promise<Record<string, unknown>>}
50
+ * @throws {ValidationError}
51
+ */
52
+ create(data: Record<string, unknown>, options?: {
53
+ trx?: import('knex').Knex.Transaction;
54
+ }): Promise<Record<string, unknown>>;
55
+ /**
56
+ * Creates many records at once, with a query count that does not
57
+ * grow with the number of records: one multi-row INSERT per chunk
58
+ * (chunked to what the dialect allows), plus a fixed number of
59
+ * statements per relation written via `Command.*()` values - however
60
+ * many rows carry them. All-or-nothing: runs in a single transaction
61
+ * (yours, if you pass `{ trx }`), so a failure part-way leaves
62
+ * nothing behind.
63
+ *
64
+ * Validation runs on every row before anything is written, and
65
+ * failures are reported per row (`[3].title`).
66
+ *
67
+ * @param {Record<string, unknown>[]} dataList
68
+ * @param {{ trx?: import('knex').Knex.Transaction, chunkSize?: number }} [options]
69
+ * @returns {Promise<Record<string, unknown>[]>} stored records, in input order
70
+ * @throws {ValidationError}
71
+ */
72
+ createMany(dataList: Record<string, unknown>[], options?: {
73
+ trx?: import('knex').Knex.Transaction;
74
+ chunkSize?: number;
75
+ }): Promise<Record<string, unknown>[]>;
76
+ /**
77
+ * Finds records matching `filter`, which may be either a plain
78
+ * equality object (`{ status: "paid" }`, Phase 5) or a domain array
79
+ * (`[["status", "=", "paid"]]`, Phase 8 - supports comparisons,
80
+ * `in`/`not in`, `like`/`ilike`, and nested `&`/`|`/`!` groups).
81
+ *
82
+ * `select` limits which fields are read (default: all). Stored and computed fields
83
+ * are both accepted; a computed field brings the stored fields it depends on along with it,
84
+ * and they appear on the record too. The primary key is NOT added for you here - ask for it
85
+ * if you want it (the `client.models` and `createModel()` APIs always include it, because
86
+ * a document needs it to save). Join keys needed by `with` are read but not returned
87
+ * unless selected.
88
+ *
89
+ * `with` loads relations in one extra query per relation per level, and takes a name, a
90
+ * dotted path, or an object that narrows each relation - see relations/with-spec.js:
91
+ * `{ author: { select: ["name"] }, comments: { select: ["body"], with: ["user"] } }`.
92
+ *
93
+ * @param {Record<string, unknown>|unknown[]} [filter]
94
+ * @param {{ trx?: import('knex').Knex.Transaction, limit?: number, offset?: number,
95
+ * orderBy?: string|string[]|Array<[string, "asc"|"desc"]>|{field: string, direction?: "asc"|"desc"},
96
+ * select?: string[], with?: string[]|object }} [options]
97
+ * @returns {Promise<Record<string, unknown>[]>}
98
+ * @throws {ValidationError} `select` names an unknown field (here or inside `with`)
99
+ * @throws {RelationError} `with` names an unknown relation or option
100
+ */
101
+ find(filter?: Record<string, unknown> | unknown[], options?: {
102
+ trx?: import('knex').Knex.Transaction;
103
+ limit?: number;
104
+ offset?: number;
105
+ orderBy?: string | string[] | Array<[string, "asc" | "desc"]> | {
106
+ field: string;
107
+ direction?: "asc" | "desc";
108
+ };
109
+ select?: string[];
110
+ with?: string[] | object;
111
+ }): Promise<Record<string, unknown>[]>;
112
+ /**
113
+ * Groups rows and computes count / sum / avg / min / max over them, in one SQL statement.
114
+ *
115
+ * ```js
116
+ * await repo.aggregate([["status", "!=", "cancelled"], ["revenue", ">", 1000]], {
117
+ * groupBy: ["customerId", "placedAt:month"],
118
+ * aggregates: { orders: "count", revenue: { sum: "total" }, biggest: { max: "total" } },
119
+ * orderBy: "-revenue",
120
+ * limit: 10,
121
+ * });
122
+ * // [{ customerId: 7, placedAt_month: Date, orders: 12, revenue: 5400, biggest: 900 }, ...]
123
+ * ```
124
+ *
125
+ * `filter` is written like find()'s and may mention both ordinary fields and the
126
+ * aggregates' names: conditions on rows run before grouping (WHERE), conditions on an
127
+ * aggregate after (HAVING), sorted out for you - see aggregate-filter.js. A condition that
128
+ * mixes the two inside an OR or NOT is rejected.
129
+ *
130
+ * `groupBy`: a field, `"dateField:bucket"` (hour, day, week, month, quarter, year - always UTC,
131
+ * weeks start Monday), or `{ field, bucket, as }`; an array of those. `aggregates`:
132
+ * `{ name: "count" }` counts rows, otherwise `{ name: { fn: "field" } }` with fn one of
133
+ * count (non-null values), countDistinct, sum, avg, min, max. With no `groupBy` the result is a
134
+ * single row. Computed fields can't be grouped or aggregated (the database can't see them).
135
+ *
136
+ * Fields may be reached through relations with a dotted path. Through a to-one relation
137
+ * (`customer.company.country`) a field can be grouped by or aggregated. Through a to-many relation
138
+ * (`items.amount`, `tags.name`, or `{ count: "items" }`) it can only be aggregated, and each parent still
139
+ * counts once: the related rows are first collapsed to one subtotal per parent (see aggregate.js), so
140
+ * `sum("total")` next to `sum("items.amount")` is never inflated by the number of items.
141
+ *
142
+ * Always returns an array of plain objects (counts, sums and averages as numbers, min/max in the
143
+ * field's own type, a bucket as the Date it starts at). Not entities: nothing is tracked.
144
+ *
145
+ * @param {Record<string, unknown>|unknown[]} [filter]
146
+ * @param {{ groupBy?: unknown, aggregates?: Record<string, unknown>, orderBy?: unknown,
147
+ * limit?: number, offset?: number, trx?: import('knex').Knex.Transaction }} options
148
+ * @returns {Promise<Array<Record<string, unknown>>>}
149
+ * @throws {ValidationError} anything wrong with `groupBy`, `aggregates`, `orderBy` or the `filter`
150
+ */
151
+ aggregate(filter?: Record<string, unknown> | unknown[], options?: {
152
+ groupBy?: unknown;
153
+ aggregates?: Record<string, unknown>;
154
+ orderBy?: unknown;
155
+ limit?: number;
156
+ offset?: number;
157
+ trx?: import('knex').Knex.Transaction;
158
+ }): Promise<Array<Record<string, unknown>>>;
159
+ /**
160
+ * Number of rows matching `filter` (any filter find() accepts).
161
+ * @param {Record<string, unknown>|unknown[]} [filter]
162
+ * @param {{ trx?: import('knex').Knex.Transaction }} [options]
163
+ * @returns {Promise<number>}
164
+ */
165
+ count(filter?: Record<string, unknown> | unknown[], options?: {
166
+ trx?: import('knex').Knex.Transaction;
167
+ }): Promise<number>;
168
+ /** Sum of a numeric field over the matching rows; `null` when no row has a value. */
169
+ sum(field: any, filter?: {}, options?: {}): Promise<unknown>;
170
+ /** Average of a numeric field over the matching rows; `null` when no row has a value. */
171
+ avg(field: any, filter?: {}, options?: {}): Promise<unknown>;
172
+ /** Smallest value of a field over the matching rows (a Date for a date field); `null` when none. */
173
+ min(field: any, filter?: {}, options?: {}): Promise<unknown>;
174
+ /** Largest value of a field over the matching rows; `null` when none. */
175
+ max(field: any, filter?: {}, options?: {}): Promise<unknown>;
176
+ /**
177
+ * Like find(), but returns the first match or null. Useful for
178
+ * lookups expected to match at most one row (e.g. a unique field).
179
+ * Accepts `with` the same as find().
180
+ *
181
+ * @param {Record<string, unknown>} [filter]
182
+ * @param {{ trx?: import('knex').Knex.Transaction, select?: string[], with?: string[]|object }} [options]
183
+ * @returns {Promise<Record<string, unknown>|null>}
184
+ */
185
+ findOne(filter?: Record<string, unknown>, options?: {
186
+ trx?: import('knex').Knex.Transaction;
187
+ select?: string[];
188
+ with?: string[] | object;
189
+ }): Promise<Record<string, unknown> | null>;
190
+ /**
191
+ * Lazily loads one relation for one already-fetched record, attaches it onto `record` under
192
+ * `relationName` (same as eager loading would) and returns it. It is `loadMany([record], ...)`.
193
+ *
194
+ * Calling this in a loop is the classic N+1: one statement per record. If you have several records,
195
+ * call loadMany() once - it costs one statement for all of them.
196
+ *
197
+ * @param {Record<string, unknown>} record
198
+ * @param {string} relationName
199
+ * @param {{ trx?: import('knex').Knex.Transaction, select?: string[], with?: string[]|object,
200
+ * where?: unknown, orderBy?: unknown, limit?: number, offset?: number }} [options] - as for one entry of `with`
201
+ * @returns {Promise<unknown>}
202
+ */
203
+ load(record: Record<string, unknown>, relationName: string, options?: {
204
+ trx?: import('knex').Knex.Transaction;
205
+ select?: string[];
206
+ with?: string[] | object;
207
+ where?: unknown;
208
+ orderBy?: unknown;
209
+ limit?: number;
210
+ offset?: number;
211
+ }): Promise<unknown>;
212
+ /**
213
+ * Loads relations onto a whole set of already-fetched records, in ONE statement per relation
214
+ * (two for a belongsToMany with no ordering or limit) however many records there are - the same
215
+ * batched loader `find({ with })` uses, for when you already hold the records.
216
+ *
217
+ * ```js
218
+ * const posts = await repo.find({ status: "draft" });
219
+ * await repo.loadMany(posts, "author"); // one relation
220
+ * await repo.loadMany(posts, "comments", { orderBy: "-likes", limit: 3 }); // constrained: each post's top 3
221
+ * await repo.loadMany(posts, ["author", { tags: { select: ["name"] } }]); // several, in any `with` shape
222
+ * ```
223
+ *
224
+ * `spec` is a relation name (its constraints in `options`: `select`, `with`, `where`, `orderBy`,
225
+ * `limit`, `offset`, exactly as one entry of `find({ with })`), or any whole `with` value. Records are
226
+ * changed in place and the same array is returned. An empty array sends nothing (the spec is still
227
+ * checked). Every record must carry the field its relation is matched by (a belongsTo's foreign key,
228
+ * otherwise its local key); one read with a `select` that left it out gets a RelationError naming it.
229
+ *
230
+ * @param {Record<string, unknown>[]} records
231
+ * @param {string|string[]|object} spec
232
+ * @param {{ trx?: import('knex').Knex.Transaction, select?: string[], with?: string[]|object,
233
+ * where?: unknown, orderBy?: unknown, limit?: number, offset?: number }} [options] - only with a relation name
234
+ * @returns {Promise<Record<string, unknown>[]>} `records`
235
+ */
236
+ loadMany(records: Record<string, unknown>[], spec: string | string[] | object, options?: {
237
+ trx?: import('knex').Knex.Transaction;
238
+ select?: string[];
239
+ with?: string[] | object;
240
+ where?: unknown;
241
+ orderBy?: unknown;
242
+ limit?: number;
243
+ offset?: number;
244
+ }): Promise<Record<string, unknown>[]>;
245
+ /**
246
+ * One page of rows plus the numbers a pager needs; see paginate.js.
247
+ *
248
+ * @param {Record<string, unknown>|unknown[]} [filter]
249
+ * @param {{ page?: number, perPage?: number, total?: boolean }} [options] - and anything find() takes
250
+ * @returns {Promise<import('./paginate.js').Page>}
251
+ */
252
+ paginate(filter?: Record<string, unknown> | unknown[], options?: {
253
+ page?: number;
254
+ perPage?: number;
255
+ total?: boolean;
256
+ }): Promise<import('./paginate.js').Page>;
257
+ /**
258
+ * Validates and casts `data` (partial: only the provided fields are
259
+ * touched, no defaults applied), then updates every row matching
260
+ * `filter` (plain equality object or domain array - see find()).
261
+ * Requires at least one field in `data` - an accidental
262
+ * `update(filter, {})` is a caller bug, not a valid no-op, so it
263
+ * throws rather than silently doing nothing. The primary key can't be
264
+ * part of `data` at all (see assertPrimaryKeyUntouched()).
265
+ *
266
+ * @param {Record<string, unknown>|unknown[]} filter
267
+ * @param {Record<string, unknown>} data
268
+ * @param {{ trx?: import('knex').Knex.Transaction }} [options]
269
+ * @returns {Promise<number>} count of rows updated
270
+ * @throws {ValidationError}
271
+ */
272
+ update(filter: Record<string, unknown> | unknown[], data: Record<string, unknown>, options?: {
273
+ trx?: import('knex').Knex.Transaction;
274
+ }): Promise<number>;
275
+ /**
276
+ * Deletes every row matching `filter` (plain equality object or
277
+ * domain array - see find()). Requires a non-empty filter -
278
+ * `delete({})` or `delete([])` would silently wipe the whole table,
279
+ * which is almost never what's intended, so both are rejected
280
+ * outright rather than treated as "delete everything".
281
+ *
282
+ * @param {Record<string, unknown>|unknown[]} filter
283
+ * @param {{ trx?: import('knex').Knex.Transaction }} [options]
284
+ * @returns {Promise<number>} count of rows deleted
285
+ */
286
+ delete(filter: Record<string, unknown> | unknown[], options?: {
287
+ trx?: import('knex').Knex.Transaction;
288
+ }): Promise<number>;
289
+ }
290
+ /**
291
+ * @param {import('knex').Knex} db
292
+ * @param {import('../models/define-model.js').ModelDescriptor} model
293
+ * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
294
+ * @param {import('../models/registry.js').ModelRegistry} [modelRegistry]
295
+ * @returns {Repository}
296
+ */
297
+ export declare function createRepository(db: import('knex').Knex, model: import('../models/define-model.js').ModelDescriptor, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry, modelRegistry?: import('../models/registry.js').ModelRegistry): Repository;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Resolves a `Repository` filter into whatever Knex's `.where()`
3
+ * expects. An array is treated as a domain (Phase 8); anything else
4
+ * (a plain object) is treated as the simple equality filter Phase 5
5
+ * already supported. Both return values work identically as an
6
+ * argument to Knex's `.where()` - a plain object (AND-equality across
7
+ * its keys) or a callback function - so callers can use `.where(resolveWhere(...))`
8
+ * without needing to know which shape they got.
9
+ *
10
+ * @param {import('../models/define-model.js').ModelDescriptor} model
11
+ * @param {Record<string, unknown>|unknown[]} filter
12
+ * @param {import('../fields/registry.js').FieldTypeRegistry} fieldTypeRegistry
13
+ * @param {import('../models/registry.js').ModelRegistry} [modelRegistry] - required for domains that traverse a relation
14
+ */
15
+ export declare function resolveWhere(model: import('../models/define-model.js').ModelDescriptor, filter: Record<string, unknown> | unknown[], fieldTypeRegistry: import('../fields/registry.js').FieldTypeRegistry, modelRegistry?: import('../models/registry.js').ModelRegistry): Record<string, unknown> | ((qb: import('knex').Knex.QueryBuilder) => void);
16
+ /**
17
+ * True if `filter` is "empty" in the sense that it would match every
18
+ * row - an empty object `{}` or an empty domain array `[]`. Used by
19
+ * update()/delete() to refuse an accidental all-rows operation
20
+ * regardless of which filter style was used.
21
+ *
22
+ * @param {Record<string, unknown>|unknown[]} filter
23
+ */
24
+ export declare function isEmptyFilter(filter: Record<string, unknown> | unknown[]): boolean;