@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
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|