rev-dal 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/AGENTS.md +234 -0
  2. package/CONTRIBUTING.md +83 -0
  3. package/LICENSE +121 -0
  4. package/README.md +67 -2
  5. package/dist/index.d.ts +48 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +26 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/lib/clone.d.ts +24 -0
  10. package/dist/lib/clone.d.ts.map +1 -0
  11. package/dist/lib/clone.js +83 -0
  12. package/dist/lib/clone.js.map +1 -0
  13. package/dist/lib/create-model.d.ts +207 -0
  14. package/dist/lib/create-model.d.ts.map +1 -0
  15. package/dist/lib/create-model.js +230 -0
  16. package/dist/lib/create-model.js.map +1 -0
  17. package/dist/lib/data-access-layer.d.ts +140 -0
  18. package/dist/lib/data-access-layer.d.ts.map +1 -0
  19. package/dist/lib/data-access-layer.js +389 -0
  20. package/dist/lib/data-access-layer.js.map +1 -0
  21. package/dist/lib/errors.d.ts +139 -0
  22. package/dist/lib/errors.d.ts.map +1 -0
  23. package/dist/lib/errors.js +206 -0
  24. package/dist/lib/errors.js.map +1 -0
  25. package/dist/lib/filter-where.d.ts +199 -0
  26. package/dist/lib/filter-where.d.ts.map +1 -0
  27. package/dist/lib/filter-where.js +563 -0
  28. package/dist/lib/filter-where.js.map +1 -0
  29. package/dist/lib/ml-string.d.ts +63 -0
  30. package/dist/lib/ml-string.d.ts.map +1 -0
  31. package/dist/lib/ml-string.js +331 -0
  32. package/dist/lib/ml-string.js.map +1 -0
  33. package/dist/lib/model-factory.d.ts +25 -0
  34. package/dist/lib/model-factory.d.ts.map +1 -0
  35. package/dist/lib/model-factory.js +57 -0
  36. package/dist/lib/model-factory.js.map +1 -0
  37. package/dist/lib/model-handle.d.ts +67 -0
  38. package/dist/lib/model-handle.d.ts.map +1 -0
  39. package/dist/lib/model-handle.js +182 -0
  40. package/dist/lib/model-handle.js.map +1 -0
  41. package/dist/lib/model-initializer.d.ts +96 -0
  42. package/dist/lib/model-initializer.d.ts.map +1 -0
  43. package/dist/lib/model-initializer.js +182 -0
  44. package/dist/lib/model-initializer.js.map +1 -0
  45. package/dist/lib/model-manifest.d.ts +112 -0
  46. package/dist/lib/model-manifest.d.ts.map +1 -0
  47. package/dist/lib/model-manifest.js +2 -0
  48. package/dist/lib/model-manifest.js.map +1 -0
  49. package/dist/lib/model-registry.d.ts +81 -0
  50. package/dist/lib/model-registry.d.ts.map +1 -0
  51. package/dist/lib/model-registry.js +139 -0
  52. package/dist/lib/model-registry.js.map +1 -0
  53. package/dist/lib/model-types.d.ts +380 -0
  54. package/dist/lib/model-types.d.ts.map +1 -0
  55. package/dist/lib/model-types.js +2 -0
  56. package/dist/lib/model-types.js.map +1 -0
  57. package/dist/lib/model.d.ts +503 -0
  58. package/dist/lib/model.d.ts.map +1 -0
  59. package/dist/lib/model.js +1423 -0
  60. package/dist/lib/model.js.map +1 -0
  61. package/dist/lib/postgres-config.d.ts +3 -0
  62. package/dist/lib/postgres-config.d.ts.map +1 -0
  63. package/dist/lib/postgres-config.js +2 -0
  64. package/dist/lib/postgres-config.js.map +1 -0
  65. package/dist/lib/query-builder.d.ts +607 -0
  66. package/dist/lib/query-builder.d.ts.map +1 -0
  67. package/dist/lib/query-builder.js +1734 -0
  68. package/dist/lib/query-builder.js.map +1 -0
  69. package/dist/lib/revision.d.ts +55 -0
  70. package/dist/lib/revision.d.ts.map +1 -0
  71. package/dist/lib/revision.js +307 -0
  72. package/dist/lib/revision.js.map +1 -0
  73. package/dist/lib/runtime.d.ts +18 -0
  74. package/dist/lib/runtime.d.ts.map +1 -0
  75. package/dist/lib/runtime.js +134 -0
  76. package/dist/lib/runtime.js.map +1 -0
  77. package/dist/lib/transaction.d.ts +17 -0
  78. package/dist/lib/transaction.d.ts.map +1 -0
  79. package/dist/lib/transaction.js +30 -0
  80. package/dist/lib/transaction.js.map +1 -0
  81. package/dist/lib/type.d.ts +130 -0
  82. package/dist/lib/type.d.ts.map +1 -0
  83. package/dist/lib/type.js +376 -0
  84. package/dist/lib/type.js.map +1 -0
  85. package/docs/models.md +406 -0
  86. package/docs/multilingual-text.md +142 -0
  87. package/docs/queries.md +374 -0
  88. package/docs/revisions.md +61 -0
  89. package/package.json +60 -4
  90. package/releases/0.2.0.md +18 -0
  91. package/releases/0.2.1.md +22 -0
  92. package/releases/README.md +7 -0
  93. package/setup-db-grants.sql +51 -0
@@ -0,0 +1,374 @@
1
+ # Queries and relations
2
+
3
+ [README](../README.md) · [Models](models.md) · [Revisions](revisions.md)
4
+
5
+ ## Querying Data
6
+
7
+ Define and initialize your models as described in [Models and bootstrap](models.md).
8
+ Every manifest-based model ships a typed query entry point:
9
+
10
+ - **`Model.filterWhere(literal)`** – Typed builder defined in `rev-dal/lib/filter-where`. Features include:
11
+ - Typed predicate literals keyed by manifest fields.
12
+ - Operator helpers exposed via `Model.ops` (`neq`, `gt/gte/lt/lte`, `in/notIn`, `between/notBetween`, `containsAll`, `containsAny`, `jsonContains`, `not`, `like/ilike/notLike/notIlike`).
13
+ - Automatic revision guards (`_old_rev_of IS NULL`, `_rev_deleted = false`) with opt-outs (`includeDeleted()`, `includeStale()`).
14
+ - Revision history helpers: `getAllRevisions(documentId)` returns all revisions (current + archived), `getRevisionByRevId(revId, documentId)` finds a specific revision.
15
+ - Fluent chaining (`and`, `or`, `revisionData`, `orderBy`, `orderByRelation`, `limit`, `offset`, `getJoin`, `whereRelated`, `whereIn`, `chronologicalFeed`, `delete`, `count`, `average`, `groupBy`, `aggregateGrouped`).
16
+ - Promise-like behaviour so `await Model.filterWhere({ ... })` works without `.run()`.
17
+ - Input safety: `limit`/`offset` accept only non-negative integers and sort directions only `ASC`/`DESC` (case-insensitive); anything else throws a `TypeError`. An empty `whereIn(field, [])` or `ops.containsAny([])` matches no rows rather than dropping the filter.
18
+
19
+ Example:
20
+
21
+ ```ts
22
+ const { containsAll, neq } = Thing.ops;
23
+ const things = await Thing.filterWhere({ urls: containsAll(targetUrls) })
24
+ .and({ createdBy: neq(blockedUserId) })
25
+ .orderBy('created_on', 'DESC')
26
+ .limit(25)
27
+ .run();
28
+
29
+ // Aggregates reuse the same revision-safe predicates
30
+ const averageRating = await Review.filterWhere({ thingID }).average('starRating');
31
+ const reviewCount = await Review.filterWhere({ thingID }).count();
32
+
33
+ // Atomic counters for numeric schema fields (throws on non-numeric columns)
34
+ const { rows } = await User.filterWhere({ id: someUser }).increment('inviteLinkCount', {
35
+ by: 1,
36
+ returning: ['inviteLinkCount'],
37
+ });
38
+
39
+ // Or decrement the same field atomically
40
+ await User.filterWhere({ id: someUser }).decrement('inviteLinkCount', { by: 1 });
41
+
42
+ // Average rating per category
43
+ const avgPrices = await Product.filterWhere({})
44
+ .groupBy('category')
45
+ .aggregateGrouped('AVG', { aggregateField: 'price' });
46
+ // Returns: Map<string, number> { 'electronics' => 299.99, 'books' => 19.99, ... }
47
+
48
+ // String pattern matching with LIKE/ILIKE operators
49
+ const { ilike, notLike } = WikiPage.ops;
50
+ const searchResults = await WikiPage.filterWhere({ slug: ilike(`%${query}%`) }).run();
51
+ const nonMetaPages = await WikiPage.filterWhere({ slug: notLike('meta/%') }).count();
52
+
53
+ // Revision history lookups
54
+ const allRevisions = await WikiPage.filterWhere({})
55
+ .getAllRevisions(page.id)
56
+ .orderBy('_revDate', 'DESC')
57
+ .run();
58
+
59
+ const specificRevision = await WikiPage.filterWhere({})
60
+ .getRevisionByRevId(revId, page.id)
61
+ .first();
62
+ ```
63
+
64
+ ### Selecting fields without loading models
65
+
66
+ Use `select(...fields)` as the final query-building step to fetch only the
67
+ persisted fields you need. It returns a promise-like query with `run()` and
68
+ `first()`. Results are plain objects with exactly the selected properties, typed
69
+ as read-only and shallowly frozen at runtime. They have no model methods such as
70
+ `save()`. Nested JSON values are not frozen.
71
+
72
+ ```ts
73
+ const accounts = await Account.filterWhere({ isActive: true })
74
+ .orderBy('id')
75
+ .limit(25)
76
+ .select('id', 'displayName');
77
+ // Only id and displayName are selected in SQL; other fields are unavailable.
78
+
79
+ const revisionIds = [currentRevId, ...sourceRevisionIds];
80
+ const counters = await WikiPage.filterWhere({})
81
+ .getAllRevisions(page.id)
82
+ .revisionData({ _revID: WikiPage.ops.in(revisionIds) })
83
+ .select('_revID', 'bodyEditCounts');
84
+ // Fetches revision IDs and counters without transferring historical bodies.
85
+
86
+ const account = await Account.filterWhere({ id: accountId })
87
+ .includeSensitive('email') // Required if email is marked sensitive
88
+ .select('id', 'email')
89
+ .first(); // Selected row or null
90
+ ```
91
+
92
+ Selections use public model field names, including camelCase mappings and, on
93
+ revision-enabled models, metadata such as `_revID` and `_revDate`. Returned names
94
+ and value types follow those fields; SQL columns are aliased to the public names.
95
+ Values come from the PostgreSQL driver without model defaults, virtual-field
96
+ calculation, or hydration hooks. Unknown fields and virtual fields are rejected.
97
+ Selecting a sensitive field without an explicit `includeSensitive()` opt-in
98
+ throws; opting in does not add that field unless it is also selected.
99
+
100
+ Apply filters, revision-history helpers, sorting, pagination, and sensitive-field
101
+ opt-ins before `select()`. The projection captures the query and parameter values
102
+ at that point; later changes to the original builder do not affect it. Normal
103
+ revision guards still apply unless disabled with the existing revision helpers.
104
+ `first()` returns `null` when no row matches. It limits the query to one row and
105
+ preserves `limit(0)`. In contrast, `Model.get(id)` returns an instance or throws
106
+ `DocumentNotFound` when the record does not exist.
107
+
108
+ An empty selection is rejected. Projection cannot be combined with `getJoin()`,
109
+ `whereRelated()` (which currently creates a join), or `groupBy()`; no identity
110
+ or grouping columns are added implicitly. Use
111
+ `aggregateGrouped()` for grouped aggregates. Existing `defineView()` / `fetchView()`
112
+ views continue to project hydrated models in JavaScript and do not reduce SQL
113
+ result columns.
114
+
115
+ ### Deleting records
116
+
117
+ See [Revisions](revisions.md) for soft deletion and transaction behavior.
118
+
119
+ - `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.
120
+ - 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
+
122
+ ```ts
123
+ await doc.deleteAllRevisions(user); // soft delete (keeps history)
124
+ await Thing.delete(thingId, { purge: true }); // permanent, removes all revisions
125
+ ```
126
+
127
+ ### Grouped Aggregations
128
+
129
+ Use `groupBy()` and `aggregateGrouped()` for batched aggregations:
130
+
131
+ ```ts
132
+ // Batch fetch review counts for multiple things in a single query
133
+ const { in: inOp } = Review.ops;
134
+ const counts = await Review.filterWhere({ thingID: inOp(thingIds) })
135
+ .groupBy('thingID')
136
+ .aggregateGrouped('COUNT');
137
+
138
+ things.forEach(thing => {
139
+ thing.reviewCount = counts.get(thing.id) ?? 0;
140
+ });
141
+ ```
142
+
143
+ Supports `COUNT`, `AVG`, `SUM`, `MIN`, `MAX`. Returns `Map<string, number>` keyed by the first `groupBy` field. For aggregates other than COUNT, specify `aggregateField` option.
144
+
145
+ ## Batch Loading Relations
146
+
147
+ The DAL provides `Model.loadManyRelated()` for efficiently loading direct relations
148
+ and many-to-many associations through junction tables. This is especially useful
149
+ when hydrating lists of records with their related data (the "N+1 query" problem).
150
+
151
+ ### Basic Usage
152
+
153
+ ```ts
154
+ // Load teams for multiple reviews in a single query
155
+ const reviewIds = reviews.map(r => r.id);
156
+ const reviewTeamMap = await Review.loadManyRelated('teams', reviewIds);
157
+
158
+ // Populate each review with its teams
159
+ reviews.forEach(review => {
160
+ review.teams = reviewTeamMap.get(review.id) || [];
161
+ });
162
+ ```
163
+
164
+ ### How It Works
165
+
166
+ `loadManyRelated()` uses the relation metadata defined in your manifest to:
167
+
168
+ 1. Build a single SQL query that filters the target column directly or joins through a junction table
169
+ 2. Apply revision system guards (`_old_rev_of IS NULL`, `_rev_deleted = false`) when needed
170
+ 3. Group results by source ID
171
+ 4. Return a `Map<sourceId, TargetInstance[]>` for easy assignment
172
+
173
+ **Before** (manual SQL):
174
+ ```ts
175
+ const query = `
176
+ SELECT rt.review_id, t.* FROM teams t
177
+ JOIN review_teams rt ON t.id = rt.team_id
178
+ WHERE rt.review_id IN (${placeholders})
179
+ AND (t._old_rev_of IS NULL)
180
+ AND (t._rev_deleted IS NULL OR t._rev_deleted = false)
181
+ `;
182
+ const result = await dal.query(query, reviewIds);
183
+ // Manual grouping logic...
184
+ ```
185
+
186
+ **After** (DAL helper):
187
+ ```ts
188
+ const reviewTeamMap = await Review.loadManyRelated('teams', reviewIds);
189
+ ```
190
+
191
+ ### Requirements
192
+
193
+ The relation must be defined in your model's manifest with a target model registered
194
+ on the DAL. For many-to-many relations, provide a `through` object specifying the
195
+ junction table and its `sourceForeignKey` and `targetForeignKey` columns. For direct
196
+ relations, `targetKey` identifies the target field matched against the supplied
197
+ source values. Set `hasRevisions` for revision-aware filtering in either case.
198
+
199
+ For example, a user's direct `posts` relation can use `sourceKey: 'id'` and
200
+ `targetKey: 'authorID'`. Calling `User.loadManyRelated('posts', userIds)` returns
201
+ posts grouped by author ID. The helper uses the values you supply; it does not
202
+ fetch source rows to resolve a different `sourceKey`.
203
+
204
+ Example manifest configuration:
205
+ ```ts
206
+ const reviewManifest = {
207
+ tableName: 'reviews',
208
+ hasRevisions: true as const,
209
+ schema: { /* ... */ },
210
+ relations: [
211
+ {
212
+ name: 'teams',
213
+ targetTable: 'teams',
214
+ sourceKey: 'id',
215
+ targetKey: 'id',
216
+ hasRevisions: true,
217
+ through: {
218
+ table: 'review_teams',
219
+ sourceForeignKey: 'review_id',
220
+ targetForeignKey: 'team_id',
221
+ },
222
+ cardinality: 'many',
223
+ },
224
+ ] as const,
225
+ } as const satisfies ModelManifest;
226
+ ```
227
+
228
+ ### Edge Cases
229
+
230
+ - **Empty input**: Returns empty `Map` when given `[]`
231
+ - **No matches**: Returns empty `Map` when no associations exist
232
+ - **Deleted records**: Automatically excludes soft-deleted related records when `hasRevisions: true`
233
+ - **Sensitive fields**: Excluded from loaded records, as with inline joins
234
+ - **Type safety**: Results are typed as `Map<string, ModelInstance<JsonObject, JsonObject>[]>`, requiring a cast to the specific target type when needed
235
+
236
+ ## Writing Many-to-Many Associations
237
+
238
+ The DAL provides `Model.addManyRelated()` for batch-inserting associations into many-to-many junction tables. This complements `loadManyRelated()` by handling the write side of many-to-many relationships.
239
+
240
+ ### Basic Usage
241
+
242
+ ```ts
243
+ // Associate a thing with multiple files
244
+ const Thing = dalFixture.getModel('things');
245
+ await Thing.addManyRelated('files', thingId, [file1.id, file2.id]);
246
+
247
+ // Associate a review with teams
248
+ const Review = dalFixture.getModel('reviews');
249
+ await Review.addManyRelated('teams', reviewId, teamIds);
250
+ ```
251
+
252
+ ### How It Works
253
+
254
+ `addManyRelated()` uses the relation metadata defined in your manifest to:
255
+
256
+ 1. Build a parameterized INSERT query for the junction table
257
+ 2. Apply schema namespace prefixing for test isolation
258
+ 3. Handle duplicate associations gracefully via `ON CONFLICT DO NOTHING` (default)
259
+ 4. Validate inputs and provide helpful error messages
260
+
261
+ **Before** (manual SQL):
262
+ ```ts
263
+ const runtime = this.constructor as Record<string, any>;
264
+ const dalInstance = runtime.dal as Record<string, any>;
265
+ const junctionTable = dalInstance.schemaNamespace
266
+ ? `${dalInstance.schemaNamespace}thing_files`
267
+ : 'thing_files';
268
+ const insertValues: Array<string | undefined> = [];
269
+ const valueClauses: string[] = [];
270
+ let paramIndex = 1;
271
+
272
+ validFiles.forEach(file => {
273
+ valueClauses.push(`($${paramIndex}, $${paramIndex + 1})`);
274
+ insertValues.push(this.id, file.id);
275
+ paramIndex += 2;
276
+ });
277
+
278
+ if (valueClauses.length) {
279
+ const insertQuery = `
280
+ INSERT INTO ${junctionTable} (thing_id, file_id)
281
+ VALUES ${valueClauses.join(', ')}
282
+ ON CONFLICT DO NOTHING
283
+ `;
284
+ await dalInstance.query(insertQuery, insertValues);
285
+ }
286
+ ```
287
+
288
+ **After** (DAL helper):
289
+ ```ts
290
+ const Thing = this.constructor as ThingModel;
291
+ await Thing.addManyRelated('files', this.id!, validFiles.map(f => f.id!));
292
+ ```
293
+
294
+ ### Requirements
295
+
296
+ The relation must be defined in your model's manifest with:
297
+ - A `through` object specifying the junction table
298
+ - Proper `sourceForeignKey` and `targetForeignKey` columns
299
+ - `cardinality: 'many'`
300
+
301
+ Example manifest configuration:
302
+ ```ts
303
+ const thingManifest = {
304
+ hasRevisions: true as const,
305
+ tableName: 'things',
306
+ relations: [
307
+ {
308
+ name: 'files',
309
+ targetTable: 'files',
310
+ sourceKey: 'id',
311
+ targetKey: 'id',
312
+ hasRevisions: true,
313
+ through: {
314
+ table: 'thing_files',
315
+ sourceForeignKey: 'thing_id',
316
+ targetForeignKey: 'file_id',
317
+ },
318
+ cardinality: 'many',
319
+ },
320
+ ] as const,
321
+ } as const satisfies ModelManifest;
322
+ ```
323
+
324
+ ### Conflict Handling
325
+
326
+ By default, duplicate associations are silently ignored:
327
+
328
+ ```ts
329
+ // Associate once
330
+ await Review.addManyRelated('teams', reviewId, [teamId]);
331
+
332
+ // Associate again - no error, no duplicate row
333
+ await Review.addManyRelated('teams', reviewId, [teamId]);
334
+ ```
335
+
336
+ For strict validation, use `{ onConflict: 'error' }`:
337
+
338
+ ```ts
339
+ await Review.addManyRelated('teams', reviewId, [teamId], { onConflict: 'error' });
340
+ // Throws if association already exists
341
+ ```
342
+
343
+ ### Edge Cases
344
+
345
+ - **Empty input**: Returns immediately when given `[]` with no database query
346
+ - **Invalid relation**: Throws helpful error listing available relations
347
+ - **Non-junction relation**: Throws error if relation doesn't have a `through` table
348
+ - **Invalid source ID**: Throws error for empty or non-string source IDs
349
+ - **Schema isolation**: Automatically handles test namespace prefixing
350
+
351
+ ### Instance Method Pattern
352
+
353
+ When writing instance methods that create associations, follow this pattern:
354
+
355
+ ```ts
356
+ async addFilesByIDsAndSave(this: ThingInstance, fileIDs: string[]): Promise<ThingInstance> {
357
+ // 1. Validate and fetch related records
358
+ const { in: inOp } = File.ops;
359
+ const validFiles = await File.filterWhere({ id: inOp(fileIDs as [string, ...string[]]) }).run();
360
+
361
+ if (!validFiles.length) {
362
+ return this;
363
+ }
364
+
365
+ // 2. Insert associations using static helper
366
+ const Thing = this.constructor as ThingModel;
367
+ await Thing.addManyRelated('files', this.id!, validFiles.map(f => f.id!));
368
+
369
+ // 3. Update in-memory representation
370
+ this.files = [...(this.files ?? []), ...validFiles];
371
+
372
+ return this;
373
+ }
374
+ ```
@@ -0,0 +1,61 @@
1
+ # Revisions
2
+
3
+ [README](../README.md) · [Models](models.md) · [Queries](queries.md)
4
+
5
+ Models with `hasRevisions: true` gain revision metadata fields and helpers:
6
+
7
+ - Static helpers (`createFirstRevision`, `getNotStaleOrDeleted`, revision-aware `filterWhere`, etc.).
8
+ - Instance helpers (`newRevision`, `deleteAllRevisions`).
9
+ - `filterWhere.revisionData()` exposes typed predicates for `_rev*` columns when querying revision metadata.
10
+
11
+ `_revSummary` is disabled by default. If you want it, add the column in your
12
+ schema and call `setRevisionSummaryEnabled(true)` at bootstrap.
13
+
14
+ ## Saving revisions and edit conflicts
15
+
16
+ `newRevision()` only prepares the new revision in memory. The following `save()`
17
+ updates the current row and archives the previous revision in one transaction, so
18
+ a failure leaves no partial history. The archived copy is a deep snapshot taken
19
+ when `newRevision()` runs, so editing nested values in place afterwards
20
+ (`rev.title[lang] = …`, `rev.tags.push(…)`) only changes the new revision. Make
21
+ edits after calling `newRevision()`: changes made to the instance before it are
22
+ archived as part of the previous revision. `deleteAllRevisions()` and `saveAll()`
23
+ are likewise all-or-nothing.
24
+
25
+ Saves use optimistic concurrency: the update only applies if the stored revision
26
+ is still the one this copy was loaded from. If someone else saved a revision in
27
+ the meantime, `save()` writes nothing and throws `RevisionConflictError`
28
+ (`code: 'REVISION_CONFLICT'`), carrying `documentId`, `expectedRevId` and
29
+ `currentRevId`. The DAL never retries automatically, since re-applying a stale
30
+ edit would overwrite the other change; the application decides:
31
+
32
+ ```ts
33
+ import { RevisionConflictError } from 'rev-dal/lib/errors';
34
+
35
+ const rev = await page.newRevision(user, { tags: ['edit'] });
36
+ rev.body = newBody;
37
+ try {
38
+ await rev.save();
39
+ } catch (error) {
40
+ if (error instanceof RevisionConflictError) {
41
+ // e.g. show an edit-conflict view, or reload and reapply the change
42
+ }
43
+ throw error;
44
+ }
45
+ ```
46
+
47
+ To include these writes in a larger transaction, pass the client from
48
+ `dal.transaction()`: `save({ transaction: client })`,
49
+ `saveAll(joinOptions, { transaction: client })` or
50
+ `deleteAllRevisions(user, { transaction: client })`. The caller then owns
51
+ COMMIT/ROLLBACK. The handle must be a checked-out PostgreSQL `PoolClient` in an
52
+ active transaction; passing a `Pool` is rejected. rev-dal does not issue `BEGIN`
53
+ on a supplied client, so use `dal.transaction()` or explicitly begin the
54
+ transaction yourself before passing it.
55
+
56
+ Errors raised by the DAL itself (`ValidationError`, `DocumentNotFound`,
57
+ `RevisionConflictError`, …) reach the caller with their own type; only raw
58
+ PostgreSQL errors are converted.
59
+
60
+ See [query deletion options](queries.md#deleting-records) for permanent purges and
61
+ [querying data](queries.md#querying-data) for revision-history lookups.
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "rev-dal",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "A PostgreSQL data access layer with revision support and rich model typing",
5
+ "license": "CC0-1.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/permacommons/rev-dal.git"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "registry": "https://registry.npmjs.org/"
13
+ },
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./lib/*": {
24
+ "types": "./dist/lib/*.d.ts",
25
+ "import": "./dist/lib/*.js"
26
+ },
27
+ "./setup-db-grants.sql": "./setup-db-grants.sql"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "setup-db-grants.sql",
32
+ "README.md",
33
+ "CONTRIBUTING.md",
34
+ "AGENTS.md",
35
+ "releases",
36
+ "docs",
37
+ "LICENSE"
38
+ ],
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.build.json",
41
+ "lint": "biome check .",
42
+ "lint:fix": "biome check --write .",
43
+ "prepare": "npm run build",
44
+ "test": "node --import tsx --test --test-concurrency=1 test/**/*.test.ts",
45
+ "test:types": "tsc -p tsconfig.type-tests.json --noEmit",
46
+ "test:release": "node --test scripts/release.test.mjs",
47
+ "typecheck": "tsc -p tsconfig.json --noEmit"
48
+ },
49
+ "dependencies": {
50
+ "entities": "^1.1.2",
51
+ "is-uuid": "^1.0.2",
52
+ "pg": "^8.17.0",
53
+ "striptags": "^3.2.0"
54
+ },
55
+ "devDependencies": {
56
+ "@biomejs/biome": "^2.3.13",
57
+ "@types/node": "^22.10.1",
58
+ "@types/pg": "^8.15.6",
59
+ "tsx": "^4.21.0",
60
+ "typescript": "^5.9.3"
61
+ }
62
+ }
@@ -0,0 +1,18 @@
1
+ # 0.2.0
2
+
3
+ Unreleased: publication failed before upload. Superseded by 0.2.1.
4
+
5
+ ## First npm release
6
+
7
+ - Distribute compiled ESM, TypeScript declarations, documentation, and the database-grant SQL export; require Node.js 22 or later.
8
+ - Include revision history, optimistic edit conflicts, typed queries and projections, relation operations, and multilingual text helpers.
9
+ - Resolve typed models through a DAL instance using model handles or manifests.
10
+ - Publish through repository-owned GitHub Actions workflows with tested tarball integrity and provenance.
11
+
12
+ ## Migrating from Git installs
13
+
14
+ - Replace the Git dependency with an exact npm version when ready: `npm install --save-exact rev-dal@0.2.0`. Existing root imports, exported `rev-dal/lib/*` subpaths, and the SQL export remain available.
15
+ - Compared with the consumers' previous Git pin (`ef55702`), declarations now enable strict null checks. Handle nullable results explicitly where TypeScript reports them.
16
+ - Transaction arguments must be checked-out PostgreSQL clients in an active transaction; passing a pool is rejected. Prefer `dal.transaction()`.
17
+ - This release adds no database migration or grant change. Applications still own their schemas.
18
+ - Consumer dependency upgrades and deployments are separate from this release.
@@ -0,0 +1,22 @@
1
+ # 0.2.1
2
+
3
+ ## First npm release
4
+
5
+ - Distribute compiled ESM, TypeScript declarations, documentation, and the database-grant SQL export; require Node.js 22 or later.
6
+ - Include revision history, optimistic edit conflicts, typed queries and projections, relation operations, and multilingual text helpers.
7
+ - Resolve typed models through a DAL instance using model handles or manifests.
8
+ - Publish through repository-owned GitHub Actions workflows with tested tarball integrity and provenance.
9
+
10
+ ## Migrating from Git installs
11
+
12
+ - Replace the Git dependency with an exact npm version when ready: `npm install --save-exact rev-dal@0.2.0`. Existing root imports, exported `rev-dal/lib/*` subpaths, and the SQL export remain available.
13
+ - Compared with the consumers' previous Git pin (`ef55702`), declarations now enable strict null checks. Handle nullable results explicitly where TypeScript reports them.
14
+ - Transaction arguments must be checked-out PostgreSQL clients in an active transaction; passing a pool is rejected. Prefer `dal.transaction()`.
15
+ - This release adds no database migration or grant change. Applications still own their schemas.
16
+ - Consumer dependency upgrades and deployments are separate from this release.
17
+
18
+ ## Publishing fix
19
+
20
+ - Normalize artifact paths before invoking npm so downloaded tarballs are published as local files.
21
+ - Version 0.2.0 was not published because its publishing command misinterpreted a relative path. This version is the first npm publication.
22
+
@@ -0,0 +1,7 @@
1
+ # Release notes
2
+
3
+ Each release has a `<version>.md` file, beginning with `# <version>` and containing
4
+ its changes and any consumer migration instructions. The preparation workflow
5
+ creates this file alongside the version bump. Released notes and tags are immutable.
6
+
7
+ See [the release runbook](../AGENTS.md#releases) for setup, commands, and recovery.
@@ -0,0 +1,51 @@
1
+ -- PostgreSQL database grants setup
2
+ -- Usage:
3
+ -- psql -v app_db=libreviews -v app_user=libreviews_user \
4
+ -- -v test_db=libreviews_test -v test_user=libreviews_user \
5
+ -- -f setup-db-grants.sql
6
+
7
+ \if :{?app_db}
8
+ \else
9
+ \echo 'Missing required variable: app_db'
10
+ \quit 1
11
+ \endif
12
+
13
+ \if :{?app_user}
14
+ \else
15
+ \echo 'Missing required variable: app_user'
16
+ \quit 1
17
+ \endif
18
+
19
+ \if :{?test_db}
20
+ \else
21
+ \echo 'Missing required variable: test_db'
22
+ \quit 1
23
+ \endif
24
+
25
+ \if :{?test_user}
26
+ \else
27
+ \echo 'Missing required variable: test_user'
28
+ \quit 1
29
+ \endif
30
+
31
+ -- Grant database-level permissions
32
+ GRANT ALL PRIVILEGES ON DATABASE :"app_db" TO :"app_user";
33
+ GRANT ALL PRIVILEGES ON DATABASE :"test_db" TO :"test_user";
34
+
35
+ -- Configure the primary application database
36
+ \c :"app_db";
37
+ GRANT ALL ON SCHEMA public TO :"app_user";
38
+ GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO :"app_user";
39
+ GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO :"app_user";
40
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO :"app_user";
41
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO :"app_user";
42
+ CREATE EXTENSION IF NOT EXISTS "pgcrypto";
43
+
44
+ -- Configure the test database
45
+ \c :"test_db";
46
+ GRANT ALL ON SCHEMA public TO :"test_user";
47
+ GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO :"test_user";
48
+ GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO :"test_user";
49
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO :"test_user";
50
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO :"test_user";
51
+ CREATE EXTENSION IF NOT EXISTS "pgcrypto";