rev-dal 0.2.2 → 0.3.0

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 (55) hide show
  1. package/AGENTS.md +39 -78
  2. package/CONTRIBUTING.md +2 -2
  3. package/dist/lib/create-model.d.ts +12 -4
  4. package/dist/lib/create-model.d.ts.map +1 -1
  5. package/dist/lib/create-model.js +3 -2
  6. package/dist/lib/create-model.js.map +1 -1
  7. package/dist/lib/data-access-layer.d.ts.map +1 -1
  8. package/dist/lib/data-access-layer.js +1 -26
  9. package/dist/lib/data-access-layer.js.map +1 -1
  10. package/dist/lib/filter-operator.d.ts +26 -0
  11. package/dist/lib/filter-operator.d.ts.map +1 -0
  12. package/dist/lib/filter-operator.js +167 -0
  13. package/dist/lib/filter-operator.js.map +1 -0
  14. package/dist/lib/filter-where.d.ts +13 -40
  15. package/dist/lib/filter-where.d.ts.map +1 -1
  16. package/dist/lib/filter-where.js +24 -190
  17. package/dist/lib/filter-where.js.map +1 -1
  18. package/dist/lib/model-initializer.d.ts.map +1 -1
  19. package/dist/lib/model-initializer.js +6 -4
  20. package/dist/lib/model-initializer.js.map +1 -1
  21. package/dist/lib/model-manifest.d.ts +24 -2
  22. package/dist/lib/model-manifest.d.ts.map +1 -1
  23. package/dist/lib/model-registry.d.ts +5 -0
  24. package/dist/lib/model-registry.d.ts.map +1 -1
  25. package/dist/lib/model-registry.js +25 -0
  26. package/dist/lib/model-registry.js.map +1 -1
  27. package/dist/lib/model-types.d.ts +114 -29
  28. package/dist/lib/model-types.d.ts.map +1 -1
  29. package/dist/lib/model.d.ts +6 -7
  30. package/dist/lib/model.d.ts.map +1 -1
  31. package/dist/lib/model.js +123 -57
  32. package/dist/lib/model.js.map +1 -1
  33. package/dist/lib/query-builder.d.ts +178 -17
  34. package/dist/lib/query-builder.d.ts.map +1 -1
  35. package/dist/lib/query-builder.js +708 -234
  36. package/dist/lib/query-builder.js.map +1 -1
  37. package/dist/lib/sql-identifiers.d.ts +14 -0
  38. package/dist/lib/sql-identifiers.d.ts.map +1 -0
  39. package/dist/lib/sql-identifiers.js +40 -0
  40. package/dist/lib/sql-identifiers.js.map +1 -0
  41. package/dist/lib/sql-results.d.ts +11 -0
  42. package/dist/lib/sql-results.d.ts.map +1 -0
  43. package/dist/lib/sql-results.js +27 -0
  44. package/dist/lib/sql-results.js.map +1 -0
  45. package/dist/lib/transaction.d.ts +2 -0
  46. package/dist/lib/transaction.d.ts.map +1 -1
  47. package/dist/lib/transaction.js +14 -0
  48. package/dist/lib/transaction.js.map +1 -1
  49. package/dist/lib/type.d.ts +1 -0
  50. package/dist/lib/type.d.ts.map +1 -1
  51. package/dist/lib/type.js.map +1 -1
  52. package/docs/models.md +33 -1
  53. package/docs/queries.md +197 -1
  54. package/package.json +1 -1
  55. package/releases/0.3.0.md +29 -0
package/docs/queries.md CHANGED
@@ -112,11 +112,151 @@ or grouping columns are added implicitly. Use
112
112
  views continue to project hydrated models in JavaScript and do not reduce SQL
113
113
  result columns.
114
114
 
115
+ SQL result aliases used for projections, filtered updates, inline hydration,
116
+ batch metadata, and relation loaders are internal and short. Only allocated metadata is
117
+ removed during decoding; persisted fields keep their PostgreSQL result names.
118
+ When a relation falls back to selecting all columns without schema metadata,
119
+ a metadata-only query discovers result names before allocating internal aliases.
120
+
121
+ Requested model property names are restored when decoding projections and filtered-update return values, including
122
+ names longer than PostgreSQL’s identifier limit.
123
+
124
+ Typed revisioned targets can project revision fields such as `_revID` and
125
+ `_revDate`, just as root projections can. `orderBy()` on a root model field
126
+ uses the root column even when a joined model maps a field to the same column name.
127
+
128
+ Projection column references follow the [column reference conventions](models.md#column-reference-conventions),
129
+ including PostgreSQL folding for unquoted names. Result property names retain
130
+ the requested model field spelling.
131
+
132
+ ### Selecting fields from to-one relations
133
+
134
+ Use `selectRelated()` to select fields from the root model and its declared
135
+ to-one relations. Declare a typed `target: () => RelatedModel` in the manifest
136
+ to infer its persisted field names and types. Relations declared with only
137
+ `targetTable` also support projection, with untyped selected field values.
138
+ Register the target model on the DAL instance that runs the query. If
139
+ cardinality is omitted or `undefined`, direct relations whose mapped source
140
+ column differs from `id` default to to-one. A supplied `sourceColumn` takes
141
+ precedence over `sourceKey`. If any possible source resolves to `id`, specify
142
+ `cardinality: 'one'` to use the relation in a projection. An omitted or `undefined`
143
+ `through` setting makes a relation direct. Through relations require explicit
144
+ `cardinality: 'one'` for projection.
145
+
146
+ Relations with custom target or junction conditions can be projected only when
147
+ no alias is needed. Repeated tables and self-relations require aliases;
148
+ selecting a custom-condition relation in those cases throws. Use a separate
149
+ relation read when that combination is needed.
150
+
151
+ ```typescript
152
+ const rows = await Notification.filterWhere({ recipientId })
153
+ .orderBy('id')
154
+ .limit(25)
155
+ .selectRelated({
156
+ fields: ['id', 'createdAt'],
157
+ relations: { actor: { fields: ['displayName'] } },
158
+ });
159
+ ```
160
+
161
+ Conditional root field lists in both `select(...fields)` and `selectRelated()`
162
+ preserve their alternatives in the result type, including union-valued selectors
163
+ inside a field list. Unconditionally selected fields remain present. To keep
164
+ type checking bounded, the type tracks up to 16 combinations of union-valued
165
+ selectors in a field list. Remaining conditional fields become optional when
166
+ expanding another selector would exceed that budget. Dynamic field arrays are
167
+ also conservative about field presence. Fixed fields on either side of a
168
+ variable-length spread stay required.
169
+ Narrow the returned object before accessing a field selected by only one branch.
170
+
171
+ Undefined relation selections are skipped. A selection that may be undefined
172
+ produces an optional relation property; a definitely undefined selection adds
173
+ no property to the result. When the entire `relations` object is conditional,
174
+ narrow the result by checking which relation property is present.
175
+
176
+ The root ordering and pagination apply to the projected result. Each requested
177
+ relation is a plain object containing only its selected fields, or `null` if
178
+ the left join has no match. Sensitive fields require `includeSensitive()` on
179
+ the root or the `includeSensitive` list in the relevant relation selection.
180
+
181
+ ### Composite chronological cursors
182
+
183
+ For feeds whose timestamps can tie or have microseconds, pass a persisted,
184
+ unique tie-breaker such as `id`. Supported PostgreSQL tie-breaker types are
185
+ `text`, `varchar`, `char`, `uuid`, `smallint`, `integer`, `bigint`, `numeric`,
186
+ and `boolean`. Floating-point and other database types are rejected. The DAL
187
+ checks the database type with a metadata query on each composite-feed page;
188
+ model field declarations alone do not establish cursor precision. The database orders by the timestamp and
189
+ tie-breaker in the same direction and excludes rows with null cursor fields.
190
+ Pass the returned cursor object unchanged to the next page. Its timestamp
191
+ and tie-breaker are lossless strings taken directly from PostgreSQL.
192
+
193
+ ```typescript
194
+ const page = await Change.filterWhere({}).chronologicalFeed({
195
+ cursorField: 'createdAt',
196
+ tieBreaker: 'id',
197
+ direction: 'DESC',
198
+ limit: 25,
199
+ cursor: previousPage?.nextCursor,
200
+ });
201
+ ```
202
+
203
+ Omitting `tieBreaker` uses the original single-field cursor API.
204
+
205
+ Composite feeds reject all inline joins, including those introduced by
206
+ `whereRelated()`: declared cardinality does not prove database uniqueness,
207
+ and duplicate root rows cannot be traversed with a root cursor. Use `whereExists()` to
208
+ filter roots by matching children, and batch joins to load child collections.
209
+
210
+ ### Transaction-bound reads
211
+
212
+ Locking reads require an active transaction at execution time, including when
213
+ rerunning a compiled projection. A checked-out client alone is insufficient;
214
+ use `dal.transaction()` or explicitly issue `BEGIN`. Before executing a locking
215
+ read, the DAL verifies the transaction block with a temporary savepoint.
216
+
217
+ Use `withTransaction(transaction)` on a query builder before executing or
218
+ projecting the query. Model rows, projections, aggregates, and batch joins
219
+ use that client and see writes already made in the same transaction.
220
+ `Model.get(id, { transaction })` and `Model.getAll({ transaction }, ...ids)`
221
+ also accept a client.
222
+ If a relation is named `transaction` or `forUpdate`, pass read settings as the
223
+ third argument to `get()`, for example `Model.get(id, { transaction: true },
224
+ { transaction })`.
225
+
226
+ `increment()` and `decrement()` use the client bound with `withTransaction()`,
227
+ so the counter change commits or rolls back with the transaction.
228
+
229
+ To lock matching root rows until the transaction ends, chain `forUpdate()`
230
+ or pass `forUpdate: true` to `get()` or `getAll()`. A locking read requires a
231
+ client from an active transaction and works with projections.
232
+
233
+ ### Atomic filtered updates
234
+
235
+ On non-revisioned models, chain `update(assignments, options)` after an explicit
236
+ `filterWhere()` predicate. PostgreSQL checks the predicate and writes the literal
237
+ values in one statement. The result contains `rowCount` and, if you specify
238
+ `returning: ['field']`, plain rows with the selected fields. Returning lists use
239
+ the same [selection typing](#selecting-fields-from-to-one-relations) as projections:
240
+ conditional selectors require narrowing, and dynamic arrays make potentially
241
+ omitted fields optional.
242
+
243
+ ```typescript
244
+ const claim = await ResetToken.filterWhere({ id, usedAt: null })
245
+ .update({ usedAt: new Date() }, { returning: ['userId'], transaction });
246
+ ```
247
+
248
+ Field mappings and schema validators apply. List sensitive assignments in
249
+ `updateSensitive` and opt into sensitive return fields with `includeSensitive()`.
250
+ You can supply a transaction through the update options or `withTransaction()`.
251
+ Updates operate on the root model and require an unpaginated query.
252
+
115
253
  ### Deleting records
116
254
 
117
255
  See [Revisions](revisions.md) for soft deletion and transaction behavior.
118
256
 
119
257
  - `delete()` requires at least one predicate; an unfiltered builder throws instead of emptying the table. `deleteById(id)` on a `filterWhere` builder also respects the builder's predicates.
258
+ - Pass `{ transaction }` with a checked-out client from `dal.transaction()` to run a model, instance, or filtered delete in that transaction.
259
+ - A filtered delete also uses the client bound with `withTransaction()`. An explicit client in the delete options takes precedence.
120
260
  - On models with revision tracking, the normal delete is the soft `deleteAllRevisions(user)`. Hard deletes (`filterWhere(...).delete()`, `deleteById()`, `Model.delete(id)`, `instance.delete()`) throw unless you pass `{ purge: true }`. A purge permanently removes the matched documents **and** their archived revisions:
121
261
 
122
262
  ```ts
@@ -126,7 +266,7 @@ await Thing.delete(thingId, { purge: true }); // permanent, removes all rev
126
266
 
127
267
  ### Grouped Aggregations
128
268
 
129
- Use `groupBy()` and `aggregateGrouped()` for batched aggregations:
269
+ Use `groupBy()` and `aggregateGrouped()` for batched aggregations. Pass exactly one grouping column to `aggregateGrouped()`, which returns a map keyed by that column.
130
270
 
131
271
  ```ts
132
272
  // Batch fetch review counts for multiple things in a single query
@@ -148,6 +288,62 @@ The DAL provides `Model.loadManyRelated()` for efficiently loading direct relati
148
288
  and many-to-many associations through junction tables. This is especially useful
149
289
  when hydrating lists of records with their related data (the "N+1 query" problem).
150
290
 
291
+ ### Filtering relation history
292
+
293
+ In a `getJoin()` relation's `_apply` callback, use `filterWhere()` for
294
+ persisted fields and `revisionData()` for revision metadata. The callback's
295
+ `ops` provides the same comparison operators as a root query. Declare a typed
296
+ relation target in the manifest to check field names and predicate values.
297
+ Declare `hasRevisions: true` on revisioned relations. `includeStale()` includes
298
+ archived rows and `includeDeleted()` includes deleted rows. Each option
299
+ controls its own guard.
300
+
301
+ ```typescript
302
+ const authors = await Author.filterWhere({}).getJoin({
303
+ edits: {
304
+ _apply: qb => qb.includeStale()
305
+ .revisionData({ _revDate: qb.ops.lte(cutoff) })
306
+ .whereExists(Revert, {
307
+ not: true,
308
+ filterWhere: { confirmed: true },
309
+ correlate: [
310
+ ['pageId', '=', 'pageId'],
311
+ ['revertedAt', '>', '_revDate'],
312
+ ['restoredBefore', '<', '_revDate'],
313
+ ],
314
+ })
315
+ .asc('_revDate')
316
+ .limit(5, { strategy: 'lateral' }),
317
+ },
318
+ });
319
+ ```
320
+
321
+ `whereExists()` also works on root `filterWhere()` queries. Each comparison
322
+ lists the inner model's field, a comparison operator, and the outer model's
323
+ field. Use `{ coalesce: ['_oldRevOf', 'id'] }` on either side when current and
324
+ archived rows need a shared document key. Each operand must be a persisted field
325
+ of its model. Revision metadata is available on models with revision tracking.
326
+ The inner model's own revision
327
+ guards apply unless you opt out through `includeStale` or `includeDeleted`.
328
+ Handles resolve through the query's DAL. Correlated filters compare ordinary
329
+ values, including arrays and JSON objects, for equality. Use `ops.in()` for
330
+ membership. Inside an `_apply` callback's own `filterWhere()`, a bare array
331
+ is an equality value for a field declared with `types.array()`. For scalar
332
+ fields, a bare array remains membership shorthand. If no target model is
333
+ registered, batch filters use the membership shorthand for bare arrays.
334
+
335
+ Membership casts supplied to `whereIn()`, `ops.in()`, or `ops.notIn()` must be
336
+ PostgreSQL type names, such as `uuid[]`, `app.status[]`, or
337
+ `character varying(12)[]`. SQL expressions and comments outside quoted
338
+ identifiers are rejected before execution.
339
+
340
+ Filters and existence checks run before the related-row limit. By default,
341
+ the DAL ranks related rows per parent in a single set-based query. Use
342
+ `limit(count, { strategy: 'lateral' })` on an indexed relation to give PostgreSQL
343
+ the option to stop scanning each parent's rows once it has enough matches.
344
+ An index starting with the relation key and then the order column supports
345
+ that plan.
346
+
151
347
  ### Basic Usage
152
348
 
153
349
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rev-dal",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "A PostgreSQL data access layer with revision support and rich model typing",
5
5
  "license": "CC0-1.0",
6
6
  "repository": {
@@ -0,0 +1,29 @@
1
+ # 0.3.0
2
+
3
+ ## Features
4
+
5
+ - **Insert if absent** (#38): `insertIfAbsent(data, { conflictFields, transaction })` on non-revisioned models runs `INSERT … ON CONFLICT DO NOTHING` with normal defaults, validation, and field mapping. Returns `true` when a row was inserted.
6
+ - **Transaction-bound reads and row locks** (#37): `get()`, `getAll()`, and query builders can run on a supplied transaction client (`withTransaction(client)`). `forUpdate()` locks matching root rows and requires an active transaction.
7
+ - **Atomic filtered updates** (#36): on non-revisioned models, `filterWhere(…).update(assignments, { returning, transaction })` runs one predicate-scoped `UPDATE` with validated assignments, optionally returning selected fields.
8
+ - **Lossless composite feed cursors** (#40): `chronologicalFeed()` can page by timestamp plus a persisted unique tie-breaker. Cursor values are read from PostgreSQL at full precision.
9
+ - **Projections across to-one relations** (#39): select typed fields from declared to-one relations while preserving left-join and pagination behavior.
10
+ - **Revision filters in batch joins** (#16): batch joins support the same comparison operators as root queries, revision filters, correlated existence filters, and ordered per-parent limits.
11
+
12
+ ## Fixes
13
+
14
+ - `delete()` and `deleteById()` honor the supplied transaction (#34).
15
+ - `aggregateGrouped()` rejects groupings that would merge multiple SQL groups into one result key (#35).
16
+ - `types.virtual()` fields are typed as virtual rather than persisted (#26).
17
+ - Model methods receive a typed `this`, including under `noImplicitThis` (#27).
18
+ - Join, alias, and column-reference handling is more robust: repeated and quoted table references are aliased correctly, projection order and unions are preserved, and casts are validated.
19
+
20
+ ## Migration
21
+
22
+ This is a minor release because of two behavior changes:
23
+
24
+ - **`aggregateGrouped()`** now throws for multi-column groupings that previously returned silently merged results. Review grouped aggregate calls and group by a single field or aggregate the combined key in SQL.
25
+ - **`delete()` / `deleteById()`** now run on the `transaction` option when one is passed, instead of the pool. Code that passed a transaction but relied on the delete committing independently must pass no transaction for that behavior.
26
+
27
+ New method signatures are additive overloads, and new generic parameters on `FilterWhereQueryBuilder` have defaults.
28
+
29
+ No database schema or grant changes are required. Consumer dependency updates and deployments remain separate.