@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,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;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Marks a record that was read with a field selection. Non-enumerable and symbol-keyed, so it
|
|
3
|
+
* never shows up in `Object.keys()`, spread or JSON. Carries `{ computed }`, the computed fields
|
|
4
|
+
* that were safe to define on it.
|
|
5
|
+
*/
|
|
6
|
+
export declare const PARTIAL: unique symbol;
|
|
7
|
+
/**
|
|
8
|
+
* Converts a raw DB row (keyed by column name, with driver-native
|
|
9
|
+
* value shapes) into a record keyed by field name, with values run
|
|
10
|
+
* through castValue() so callers always get back the same shapes they
|
|
11
|
+
* put in (Date objects for date/datetime, real objects for json,
|
|
12
|
+
* booleans for boolean) regardless of how a given dialect's driver
|
|
13
|
+
* represents them on the wire.
|
|
14
|
+
*
|
|
15
|
+
* `json` columns need one extra step before casting: SQLite has no
|
|
16
|
+
* native JSON type, so Knex stores it as a text column and the driver
|
|
17
|
+
* hands back a JSON *string*, not the parsed value. Postgres, in
|
|
18
|
+
* contrast, generally hands back an already-parsed object for
|
|
19
|
+
* json/jsonb columns. castValue() alone can't tell these apart
|
|
20
|
+
* (a string is technically valid JSON too), so the string case is
|
|
21
|
+
* parsed here first, before the value ever reaches castValue().
|
|
22
|
+
*
|
|
23
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
24
|
+
* @param {Record<string, unknown>} row
|
|
25
|
+
* @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
|
|
26
|
+
* @param {{ computed?: Set<string>|null }} [options] - `computed`: which computed fields to define
|
|
27
|
+
* (default: all). A row read with `select` only defines the ones whose dependencies it carries; the
|
|
28
|
+
* choice is remembered under PARTIAL so an entity built from the record can make the same one.
|
|
29
|
+
* @returns {Record<string, unknown>}
|
|
30
|
+
*/
|
|
31
|
+
export declare function fromRow(model: import('../models/define-model.js').ModelDescriptor, row: Record<string, unknown>, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry, options?: {
|
|
32
|
+
computed?: Set<string> | null;
|
|
33
|
+
}): Record<string, unknown>;
|
|
34
|
+
/**
|
|
35
|
+
* Converts a record keyed by field name into a plain object keyed by
|
|
36
|
+
* column name, ready to hand to Knex's insert()/update(). Assumes
|
|
37
|
+
* values have already been validated/cast by the caller (see
|
|
38
|
+
* prepareWrite()) - this function only renames keys, it does not
|
|
39
|
+
* validate or coerce anything itself.
|
|
40
|
+
*
|
|
41
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
42
|
+
* @param {Record<string, unknown>} fieldValues
|
|
43
|
+
* @returns {Record<string, unknown>}
|
|
44
|
+
*/
|
|
45
|
+
export declare function toRow(model: import('../models/define-model.js').ModelDescriptor, fieldValues: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Field selection for `find({ select })`: which columns to read, and what has to ride
|
|
3
|
+
* along so the result is still correct.
|
|
4
|
+
*
|
|
5
|
+
* Three things are kept apart on purpose:
|
|
6
|
+
*
|
|
7
|
+
* - what the caller ASKED for (`select`, validated by normalizeSelect());
|
|
8
|
+
* - what that IMPLIES - a computed field can't be read without the stored fields it
|
|
9
|
+
* `depends` on (transitively, through other computed fields), so those are loaded
|
|
10
|
+
* too and appear on the record like any other selected field (expandSelect());
|
|
11
|
+
* - what the ORM needs for ITS OWN bookkeeping - the join keys eager loading matches
|
|
12
|
+
* rows by. These are fetched too but are NOT part of the result unless asked for,
|
|
13
|
+
* so `select: ["title"]` with `with: ["author"]` doesn't leak `authorId`
|
|
14
|
+
* (planSelect().hidden, removed by stripHidden() once loading is done).
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Validates `select` and returns it as a de-duplicated array of field names, or `null`
|
|
18
|
+
* when there is no selection (meaning: every field, exactly as before `select` existed).
|
|
19
|
+
* Stored and computed fields are both accepted.
|
|
20
|
+
*
|
|
21
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
22
|
+
* @param {unknown} select
|
|
23
|
+
* @returns {string[]|null}
|
|
24
|
+
* @throws {ValidationError}
|
|
25
|
+
*/
|
|
26
|
+
export declare function normalizeSelect(model: import('../models/define-model.js').ModelDescriptor, select: unknown): string[] | null;
|
|
27
|
+
/**
|
|
28
|
+
* Splits a validated selection into the stored fields to read and the computed fields to
|
|
29
|
+
* define, following `depends` transitively: `fullName` depends on `firstName` and
|
|
30
|
+
* `initials`, `initials` depends on `firstName` and `lastName` -> stored { firstName,
|
|
31
|
+
* lastName }, computed { fullName, initials }.
|
|
32
|
+
*
|
|
33
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
34
|
+
* @param {string[]} names - output of normalizeSelect()
|
|
35
|
+
* @returns {{ fields: Set<string>, computed: Set<string> }}
|
|
36
|
+
*/
|
|
37
|
+
export declare function expandSelect(model: import('../models/define-model.js').ModelDescriptor, names: string[]): {
|
|
38
|
+
fields: Set<string>;
|
|
39
|
+
computed: Set<string>;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Turns a (possibly absent) selection plus the join keys some relation needs into what
|
|
43
|
+
* the query should read.
|
|
44
|
+
*
|
|
45
|
+
* - `columns`: column names to `select`, or `null` for "all columns" (no selection made;
|
|
46
|
+
* the SQL is then identical to what it was before `select` existed).
|
|
47
|
+
* - `computed`: the computed fields to define on each record, or `null` for "all". A
|
|
48
|
+
* computed field whose dependencies weren't loaded would compute from `undefined`, so
|
|
49
|
+
* with a selection only the requested ones (and what they need) are defined.
|
|
50
|
+
* - `hidden`: fields read only because `requiredKeys` needs them; strip them from the
|
|
51
|
+
* result with stripHidden() once whatever needed them is done.
|
|
52
|
+
*
|
|
53
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
54
|
+
* @param {string[]|null} names - output of normalizeSelect()
|
|
55
|
+
* @param {string[]} [requiredKeys] - stored fields that must be read regardless
|
|
56
|
+
* @returns {{ columns: string[]|null, computed: Set<string>|null, hidden: string[] }}
|
|
57
|
+
*/
|
|
58
|
+
export declare function planSelect(model: import('../models/define-model.js').ModelDescriptor, names: string[] | null, requiredKeys?: string[]): {
|
|
59
|
+
columns: string[] | null;
|
|
60
|
+
computed: Set<string> | null;
|
|
61
|
+
hidden: string[];
|
|
62
|
+
};
|
|
63
|
+
/** Removes fields that were read only for the ORM's own use (see planSelect().hidden). */
|
|
64
|
+
export declare function stripHidden(records: any, hidden: any): void;
|
|
65
|
+
/**
|
|
66
|
+
* For the tracked APIs (`client.models.x.find`, global `Model.find`): a document needs its
|
|
67
|
+
* primary key for `save()`, `delete()` and the identity map, so it is always read even if
|
|
68
|
+
* `select` left it out. Plain `Repository.find` returns exactly what was asked for.
|
|
69
|
+
*
|
|
70
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
71
|
+
* @param {object} [options] - find options
|
|
72
|
+
* @returns {object} `options`, with the primary key added to `select` when needed
|
|
73
|
+
*/
|
|
74
|
+
export declare function withPrimaryKey(model: import('../models/define-model.js').ModelDescriptor, options?: object): object;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** True for a Postgres-family Knex instance. */
|
|
2
|
+
export declare function isPostgres(db: any): boolean;
|
|
3
|
+
/**
|
|
4
|
+
* Keeps a Postgres `serial` primary key's sequence ahead of ids that were
|
|
5
|
+
* supplied explicitly.
|
|
6
|
+
*
|
|
7
|
+
* Inserting `{ id: 5 }` into a serial column never touches its sequence, so
|
|
8
|
+
* a later auto-assigned id walks up to 5 and fails with a duplicate key
|
|
9
|
+
* (or, worse, in the SAME statement: `[{ id: 1 }, {}]` gives the second row
|
|
10
|
+
* nextval() = 1). SQLite has no such problem - it picks max(rowid) + 1.
|
|
11
|
+
*
|
|
12
|
+
* Called BEFORE inserting a batch that contains explicit ids. It moves the
|
|
13
|
+
* sequence to the largest of: its own next value, the largest explicit id in
|
|
14
|
+
* the batch, and the largest id already in the table (which also repairs a
|
|
15
|
+
* sequence an earlier explicit insert left behind). It never moves the
|
|
16
|
+
* sequence backwards; the cost is at most one skipped number.
|
|
17
|
+
*
|
|
18
|
+
* A no-op for any other dialect, for uuid / non-auto keys, and when the batch
|
|
19
|
+
* has no explicit key.
|
|
20
|
+
*
|
|
21
|
+
* @param {import('knex').Knex} db - connection or transaction
|
|
22
|
+
* @param {object} model
|
|
23
|
+
* @param {Record<string, unknown>[]} valuesList - validated rows about to be inserted
|
|
24
|
+
* @returns {Promise<boolean>} whether the sequence was touched
|
|
25
|
+
*/
|
|
26
|
+
export declare function advanceSequence(db: import('knex').Knex, model: object, valuesList: Record<string, unknown>[]): Promise<boolean>;
|
|
27
|
+
/**
|
|
28
|
+
* Repairs one model's auto-increment sequence so the next generated id is past every
|
|
29
|
+
* id in the table.
|
|
30
|
+
*
|
|
31
|
+
* advanceSequence() covers ids written through this ORM's own inserts. Anything that
|
|
32
|
+
* puts ids in behind its back - a raw `client.db` / `getConnection()` insert, a seed
|
|
33
|
+
* script, a dump restore, a manual renumbering - leaves the sequence behind, and the
|
|
34
|
+
* next auto-assigned id then collides. This is the remedy for those.
|
|
35
|
+
*
|
|
36
|
+
* Safe to run any time and any number of times. It never moves a sequence backwards
|
|
37
|
+
* (so ids of deleted rows aren't reused), and costs at most one skipped number.
|
|
38
|
+
* A no-op on SQLite, and for uuid / non-auto / missing keys.
|
|
39
|
+
*
|
|
40
|
+
* @param {import('knex').Knex} db - connection or transaction
|
|
41
|
+
* @param {object} model
|
|
42
|
+
* @returns {Promise<boolean>} whether a sequence was found and moved
|
|
43
|
+
*/
|
|
44
|
+
export declare function syncSequence(db: import('knex').Knex, model: object): Promise<boolean>;
|
|
45
|
+
/**
|
|
46
|
+
* syncSequence() for every model in a registry. (Named apart from the global API's `syncSequences()`, which wraps it: both are re-exported from the package root.)
|
|
47
|
+
*
|
|
48
|
+
* @param {import('knex').Knex} db - connection or transaction
|
|
49
|
+
* @param {import('../models/registry.js').ModelRegistry} registry
|
|
50
|
+
* @returns {Promise<Array<{ model: string, table: string, synced: boolean }>>} one entry per model
|
|
51
|
+
*/
|
|
52
|
+
export declare function syncRegistrySequences(db: import('knex').Knex, registry: import('../models/registry.js').ModelRegistry): Promise<Array<{
|
|
53
|
+
model: string;
|
|
54
|
+
table: string;
|
|
55
|
+
synced: boolean;
|
|
56
|
+
}>>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs `fn` inside a Knex transaction, passing the transaction object
|
|
3
|
+
* through so it can be handed to Repository methods' `{ trx }` option
|
|
4
|
+
* (e.g. `repo.create(data, { trx })`) to include them in the same
|
|
5
|
+
* atomic unit. This is a thin pass-through to Knex's own
|
|
6
|
+
* `db.transaction()` - it exists mainly so the transaction API is
|
|
7
|
+
* discoverable from `@kiri-orm/core`'s exports without needing to know
|
|
8
|
+
* Knex's API is what's underneath.
|
|
9
|
+
*
|
|
10
|
+
* If `fn` throws (or returns a rejected promise), Knex rolls the
|
|
11
|
+
* transaction back automatically and the rejection propagates to the
|
|
12
|
+
* caller here.
|
|
13
|
+
*
|
|
14
|
+
* @template T
|
|
15
|
+
* @param {import('knex').Knex} db
|
|
16
|
+
* @param {(trx: import('knex').Knex.Transaction) => Promise<T>} fn
|
|
17
|
+
* @returns {Promise<T>}
|
|
18
|
+
*/
|
|
19
|
+
export declare function runInTransaction<T>(db: import('knex').Knex, fn: (trx: import('knex').Knex.Transaction) => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { DEFAULT_THRESHOLD, NPlusOneError, QueryMonitor, describeFindings, normalizeSql, scanForNPlusOne, statementOf, watchForNPlusOne, } from "./n-plus-one.js";
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An N+1 detector: notices when the same SQL statement is sent over and over, which is what
|
|
3
|
+
* "load the parent, then query for each child" looks like from the database's side - one query
|
|
4
|
+
* for the list, then one more per row.
|
|
5
|
+
*
|
|
6
|
+
* It watches the connection's `query` events (which also carry the queries of any transaction on
|
|
7
|
+
* it), reduces every statement to its SHAPE, and counts repeats of a shape. Two statements have the
|
|
8
|
+
* same shape when only their values differ:
|
|
9
|
+
*
|
|
10
|
+
* select * from post where id = $1 -- and the same with = ?, or any id
|
|
11
|
+
* select * from comment where post_id in (?, ?, ?) -- and the same with a list of any length
|
|
12
|
+
*
|
|
13
|
+
* So looping `findOne({ id })` over a hundred ids is one shape seen 100 times, while one batched
|
|
14
|
+
* `find({ with })` is a few different shapes seen once each.
|
|
15
|
+
*
|
|
16
|
+
* It is a heuristic and says so: a legitimate loop (a batch job paging through rows) repeats a
|
|
17
|
+
* statement too. That is why it reports and, unless you ask it to, doesn't throw - and why the
|
|
18
|
+
* threshold and the time window are yours to set. Only SELECTs are counted by default: a loop of
|
|
19
|
+
* inserts is a different, usually deliberate, pattern.
|
|
20
|
+
*
|
|
21
|
+
* Meant for development and tests, not production: it adds a cheap string pass per statement.
|
|
22
|
+
*
|
|
23
|
+
* It reports WHAT repeated (the statement, and how many times), not WHERE it was called from. That
|
|
24
|
+
* would need the caller's stack, and by the time knex emits its query event that is gone: query builders
|
|
25
|
+
* are non-native thenables, and V8's async stack traces don't continue through them. The statement itself
|
|
26
|
+
* - it names the table and the column - is what to search your code for.
|
|
27
|
+
*
|
|
28
|
+
* @typedef {{ shape: string, sql: string, statement: string, count: number }} Finding
|
|
29
|
+
*/
|
|
30
|
+
export type Finding = {
|
|
31
|
+
shape: string;
|
|
32
|
+
sql: string;
|
|
33
|
+
statement: string;
|
|
34
|
+
count: number;
|
|
35
|
+
};
|
|
36
|
+
export declare const DEFAULT_THRESHOLD = 5;
|
|
37
|
+
/**
|
|
38
|
+
* Reduces a statement to its shape: the same text with the values and the list lengths taken out.
|
|
39
|
+
* Postgres `$1` and SQLite `?` placeholders both become `?`; `in (?, ?, ?)` becomes `in (?)`; a
|
|
40
|
+
* multi-row `values (?, ?), (?, ?)` becomes one row.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} sql
|
|
43
|
+
* @returns {string}
|
|
44
|
+
*/
|
|
45
|
+
export declare function normalizeSql(sql: string): string;
|
|
46
|
+
/** The kind of statement: `select`, `insert`, `update`, `delete`, or a bookkeeping word. A CTE counts as a select. */
|
|
47
|
+
export declare function statementOf(sql: any): string;
|
|
48
|
+
export declare class NPlusOneError extends Error {
|
|
49
|
+
findings: Finding[];
|
|
50
|
+
/** @param {Finding[]} findings */
|
|
51
|
+
constructor(findings: Finding[]);
|
|
52
|
+
}
|
|
53
|
+
/** A readable report: each repeated statement, how often, and what to do about it. */
|
|
54
|
+
export declare function describeFindings(findings: any): string;
|
|
55
|
+
export declare class QueryMonitor {
|
|
56
|
+
#private;
|
|
57
|
+
/**
|
|
58
|
+
* @param {object} [options]
|
|
59
|
+
* @param {number} [options.threshold] - repeats of one shape that count as N+1 (default 5)
|
|
60
|
+
* @param {number} [options.windowMs] - a shape's count starts over after this long without it; `Infinity`
|
|
61
|
+
* (the default) counts everything seen. A live watcher usually wants a few hundred ms.
|
|
62
|
+
* @param {string[]} [options.statements] - which statements to count (default `["select"]`)
|
|
63
|
+
* @param {RegExp[]} [options.ignore] - statements to skip, matched against the SQL; added to the ORM's own
|
|
64
|
+
* (sequence maintenance), not replacing them
|
|
65
|
+
* @param {(finding: Finding) => void} [options.onDetect] - called once when a shape first reaches the threshold
|
|
66
|
+
* @param {() => number} [options.now] - clock, for tests
|
|
67
|
+
*/
|
|
68
|
+
constructor({ threshold, windowMs, statements, ignore, onDetect, now }?: {
|
|
69
|
+
threshold?: number;
|
|
70
|
+
windowMs?: number;
|
|
71
|
+
statements?: string[];
|
|
72
|
+
ignore?: RegExp[];
|
|
73
|
+
onDetect?: (finding: Finding) => void;
|
|
74
|
+
now?: () => number;
|
|
75
|
+
});
|
|
76
|
+
/** Starts listening on a connection (or transaction). One monitor watches one connection at a time. */
|
|
77
|
+
attach(db: any): this;
|
|
78
|
+
/** Stops listening. Safe to call twice. The findings so far are kept. */
|
|
79
|
+
detach(): this;
|
|
80
|
+
/** Forgets everything counted so far. */
|
|
81
|
+
reset(): this;
|
|
82
|
+
/** The shapes that reached the threshold, most repeated first. @returns {Finding[]} */
|
|
83
|
+
get findings(): Finding[];
|
|
84
|
+
/** Throws NPlusOneError if anything was found. */
|
|
85
|
+
assertClean(): void;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Runs `fn` while watching `db`, then reports what repeated. Never throws for findings.
|
|
89
|
+
*
|
|
90
|
+
* @template T
|
|
91
|
+
* @param {import('knex').Knex} db
|
|
92
|
+
* @param {() => Promise<T>} fn
|
|
93
|
+
* @param {ConstructorParameters<typeof QueryMonitor>[0]} [options]
|
|
94
|
+
* @returns {Promise<{ result: T, findings: Finding[] }>}
|
|
95
|
+
*/
|
|
96
|
+
export declare function scanForNPlusOne<T>(db: import('knex').Knex, fn: () => Promise<T>, options?: ConstructorParameters<typeof QueryMonitor>[0]): Promise<{
|
|
97
|
+
result: T;
|
|
98
|
+
findings: Finding[];
|
|
99
|
+
}>;
|
|
100
|
+
/**
|
|
101
|
+
* A live watcher for development: warns (once per statement) on the console the moment one shape
|
|
102
|
+
* repeats `threshold` times within `windowMs`. Call `.detach()` to stop.
|
|
103
|
+
*
|
|
104
|
+
* @param {import('knex').Knex} db
|
|
105
|
+
* @param {ConstructorParameters<typeof QueryMonitor>[0]} [options] - `windowMs` defaults to 250, `onDetect` to console.warn
|
|
106
|
+
* @returns {QueryMonitor}
|
|
107
|
+
*/
|
|
108
|
+
export declare function watchForNPlusOne(db: import('knex').Knex, options?: ConstructorParameters<typeof QueryMonitor>[0]): QueryMonitor;
|