express-file-cluster 0.5.0 → 0.7.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 (72) hide show
  1. package/README.md +2 -2
  2. package/dist/auth/index.cjs +5 -5
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +4 -4
  6. package/dist/{chunk-VYHJX54R.js → chunk-277BSYVH.js} +2 -1
  7. package/dist/chunk-277BSYVH.js.map +1 -0
  8. package/dist/{chunk-RTFJ32T5.js → chunk-6OGOVV57.js} +1344 -132
  9. package/dist/chunk-6OGOVV57.js.map +1 -0
  10. package/dist/{chunk-QTRGJ2EN.cjs → chunk-AZYXQU3Z.cjs} +1378 -166
  11. package/dist/chunk-AZYXQU3Z.cjs.map +1 -0
  12. package/dist/chunk-BUBXO7WU.js +170 -0
  13. package/dist/chunk-BUBXO7WU.js.map +1 -0
  14. package/dist/chunk-MGH4VDV3.cjs +170 -0
  15. package/dist/chunk-MGH4VDV3.cjs.map +1 -0
  16. package/dist/{chunk-ULQXD4YZ.cjs → chunk-R34R7QPD.cjs} +3 -3
  17. package/dist/{chunk-ULQXD4YZ.cjs.map → chunk-R34R7QPD.cjs.map} +1 -1
  18. package/dist/{chunk-M7MUPWCE.js → chunk-RS4MXCPW.js} +2 -2
  19. package/dist/{chunk-SZT36SGB.cjs → chunk-T4OHFU5T.cjs} +8 -8
  20. package/dist/{chunk-SZT36SGB.cjs.map → chunk-T4OHFU5T.cjs.map} +1 -1
  21. package/dist/{chunk-5PDAWMGF.js → chunk-TRC4DUZB.js} +4 -4
  22. package/dist/{chunk-47K2532L.cjs → chunk-TYR2GZZE.cjs} +7 -7
  23. package/dist/{chunk-47K2532L.cjs.map → chunk-TYR2GZZE.cjs.map} +1 -1
  24. package/dist/{chunk-PMF4GMHD.js → chunk-UBQYQPBU.js} +2 -2
  25. package/dist/{chunk-JJJJTACK.js → chunk-UTM4PEVG.js} +2 -2
  26. package/dist/{chunk-RSBW2B3D.cjs → chunk-YL37D6KM.cjs} +3 -2
  27. package/dist/chunk-YL37D6KM.cjs.map +1 -0
  28. package/dist/{chunk-SFVEQ2T5.cjs → chunk-ZDM5JHVK.cjs} +11 -11
  29. package/dist/{chunk-SFVEQ2T5.cjs.map → chunk-ZDM5JHVK.cjs.map} +1 -1
  30. package/dist/cli/db-runner.cjs +10 -10
  31. package/dist/cli/db-runner.js +3 -3
  32. package/dist/cli/index.cjs +6 -6
  33. package/dist/cli/index.js +4 -4
  34. package/dist/docs/api-reference/ignite.md +3 -0
  35. package/dist/docs/api-reference/table.md +210 -2
  36. package/dist/docs/getting-started/index.md +2 -1
  37. package/dist/docs/getting-started/project-structure.md +1 -1
  38. package/dist/docs/guides/generated-portals.md +1 -1
  39. package/dist/docs/guides/logging.md +38 -0
  40. package/dist/docs/guides/rbac.md +1 -1
  41. package/dist/docs/index.md +1 -1
  42. package/dist/docs/skills/SKILL.md +2 -2
  43. package/dist/docs/skills/api-surface.md +2 -1
  44. package/dist/docs/skills/what-not-to-invent.md +1 -1
  45. package/dist/index.cjs +44 -69
  46. package/dist/index.cjs.map +1 -1
  47. package/dist/index.d.cts +248 -21
  48. package/dist/index.d.ts +248 -21
  49. package/dist/index.js +12 -37
  50. package/dist/index.js.map +1 -1
  51. package/dist/{pgboss-backend-UUJOVEYK.js → pgboss-backend-QKBXVJ6B.js} +3 -3
  52. package/dist/pgboss-backend-TCHI7CHM.cjs +14 -0
  53. package/dist/{pgboss-backend-3E6ATY42.cjs.map → pgboss-backend-TCHI7CHM.cjs.map} +1 -1
  54. package/dist/tasks/index.d.cts +1 -1
  55. package/dist/tasks/index.d.ts +1 -1
  56. package/dist/{types-DJCPAsM4.d.cts → types-B6lVw4bj.d.cts} +49 -2
  57. package/dist/{types-DJCPAsM4.d.ts → types-B6lVw4bj.d.ts} +49 -2
  58. package/package.json +1 -1
  59. package/dist/chunk-3VWD2ZED.js +0 -60
  60. package/dist/chunk-3VWD2ZED.js.map +0 -1
  61. package/dist/chunk-ALBDM5R3.cjs +0 -60
  62. package/dist/chunk-ALBDM5R3.cjs.map +0 -1
  63. package/dist/chunk-QTRGJ2EN.cjs.map +0 -1
  64. package/dist/chunk-RSBW2B3D.cjs.map +0 -1
  65. package/dist/chunk-RTFJ32T5.js.map +0 -1
  66. package/dist/chunk-VYHJX54R.js.map +0 -1
  67. package/dist/pgboss-backend-3E6ATY42.cjs +0 -14
  68. /package/dist/{chunk-M7MUPWCE.js.map → chunk-RS4MXCPW.js.map} +0 -0
  69. /package/dist/{chunk-5PDAWMGF.js.map → chunk-TRC4DUZB.js.map} +0 -0
  70. /package/dist/{chunk-PMF4GMHD.js.map → chunk-UBQYQPBU.js.map} +0 -0
  71. /package/dist/{chunk-JJJJTACK.js.map → chunk-UTM4PEVG.js.map} +0 -0
  72. /package/dist/{pgboss-backend-UUJOVEYK.js.map → pgboss-backend-QKBXVJ6B.js.map} +0 -0
@@ -83,6 +83,7 @@ interface TableOptions {
83
83
  timestamps?: boolean | { createdAt?: string | false; updatedAt?: string | false };
84
84
  indexes?: { fields: Record<string, 1 | -1 | 'text'>; unique?: boolean; name?: string }[];
85
85
  collection?: string; // table name
86
+ relations?: Record<string, { hasMany: string; foreignKey: string } | { hasOne: string; foreignKey: string }>; // see Include
86
87
  }
87
88
  ```
88
89
 
@@ -98,6 +99,154 @@ never drops columns or rows. On top of that:
98
99
 
99
100
  Preview the changes with `efc db sync --dry-run`.
100
101
 
102
+ ### Foreign keys
103
+
104
+ A top-level `ref` field is a real foreign key to the referenced model's `id`:
105
+
106
+ ```ts
107
+ export const Author = defineTable('Author', { name: { type: 'string', required: true } });
108
+ export const Category = defineTable('Category', {
109
+ name: { type: 'string', required: true },
110
+ parent: { type: 'integer', ref: 'Category', onDelete: 'setNull' }, // self-relation
111
+ }, { id: 'serial' });
112
+
113
+ export const Post = defineTable('Post', {
114
+ title: { type: 'string', required: true },
115
+ author: { type: 'uuid', ref: 'Author', required: true, onDelete: 'cascade' },
116
+ reviewer: { type: 'uuid', ref: 'Author' }, // onDelete: 'restrict'
117
+ category: { type: 'integer', ref: 'Category' },
118
+ });
119
+ ```
120
+
121
+ | `onDelete` | Deleting the referenced record… |
122
+ |---|---|
123
+ | `'restrict'` (default) | is refused with a **409** while records point at it |
124
+ | `'cascade'` | deletes the records pointing at it too |
125
+ | `'setNull'` | clears the field on those records (not allowed on `required` fields) |
126
+
127
+ - The field's `type` must match the target's id: `uuid` (or `objectId`) for `id: 'uuid'`,
128
+ `integer` for `'serial'`, `bigint` for `'bigserial'`. A mismatch fails at first use, saying
129
+ which type to declare.
130
+ - Writing an id that doesn't exist is a **400** on that field (`author: Author not found`).
131
+ - Ref columns get an index (`<table>_<column>_idx`) unless `index: false`.
132
+ - The referenced model must be defined (imported) before the model that references it is used.
133
+ - The value is still the id: `post.author` is a string (or number). Loading the referenced
134
+ record with `include` comes next (M3b).
135
+
136
+ Sync creates a missing target table first, then adds the key `NOT VALID` (instant, and existing
137
+ rows can't fail the deploy) and validates it right after the commit. If old rows point at
138
+ records that no longer exist, validation is skipped with a warning naming the count. The key
139
+ still applies to new writes; fix the rows and run `efc db sync` to validate it. Changing
140
+ `onDelete` replaces the key, and removing `ref` drops it. Foreign keys on columns the model
141
+ doesn't declare are left alone.
142
+
143
+ `defineModel` keeps `ref` portable: on PostgreSQL it stays a plain column with no foreign key,
144
+ the same as on MongoDB.
145
+
146
+ ### Many-to-many
147
+
148
+ An array of refs is a many-to-many relation:
149
+
150
+ ```ts
151
+ export const Tag = defineTable('Tag', { label: { type: 'string', required: true, unique: true } });
152
+ export const Post = defineTable('Post', {
153
+ title: { type: 'string', required: true },
154
+ tags: { type: 'array', of: 'uuid', ref: 'Tag' }, // of: matches Tag's id type
155
+ });
156
+
157
+ const post = await Post.create({ data: { title: 'Hello', tags: [news, tech] } });
158
+ post.tags; // [news, tech] — ids, in order
159
+ await Post.findMany({ where: { tags: { has: tech } } });
160
+ await Post.update({ where: { id: post.id }, data: { tags: { push: launch } } });
161
+ await Post.update({ where: { id: post.id }, data: { tags: { set: [tech] } } });
162
+ ```
163
+
164
+ - Records keep the list of ids (`string[]`, `number[]` or `bigint[]`), in the order written, without
165
+ duplicates. New records start with `[]`.
166
+ - Filters are the list filters: `has`, `hasSome`, `hasEvery`, `isEmpty`, `equals`. Updates take a
167
+ list, `{ set: [...] }` or `{ push: id | [...] }` (ids already linked are left in place).
168
+ `select` / `omit` work as for any field. Ordering, grouping and `_sum`-style aggregates on the
169
+ field are refused.
170
+ - The links live in a join table, `<table>_<column>` (`posts_tags`): `owner_id`, `ref_id`,
171
+ `position`, primary key `(owner_id, ref_id)`, an index on `ref_id`, and foreign keys to both
172
+ tables with `ON DELETE CASCADE`. Deleting a post or a tag removes its links (a deleted tag
173
+ disappears from every post's `tags`). There is no `onDelete` option for these fields.
174
+ - An id that doesn't exist is a **400** on the field, and nothing is written.
175
+ - Reads stay one statement (the list is a subquery). A write that changes links runs in a
176
+ transaction: the row, then the links.
177
+ - Self-relations work (`friends: { type: 'array', of: 'uuid', ref: 'Person' }`).
178
+
179
+ **Moving from an array column.** If the table already stores the field as an array (`uuid[]`,
180
+ or `jsonb` from `defineModel`), the first sync copies it into the join table, keeping the order
181
+ and skipping values that aren't ids. The old column stays (sync never drops columns) but is no
182
+ longer read or written, so a `defineModel` over the same table won't see later changes to the
183
+ list.
184
+
185
+ ### Include
186
+
187
+ `include` loads related records into the result: a `ref` field becomes the record it points at,
188
+ a many-to-many field the list of records, and back-relations — declared with `relations` —
189
+ the records pointing here.
190
+
191
+ ```ts
192
+ export const User = defineTable('User', { email: { type: 'string', required: true, unique: true } }, {
193
+ relations: {
194
+ posts: { hasMany: 'Post', foreignKey: 'author' }, // Post.author refs User
195
+ profile: { hasOne: 'Profile', foreignKey: 'user' }, // Profile.user refs User, unique
196
+ },
197
+ });
198
+ export const Tag = defineTable('Tag', { label: { type: 'string', required: true } }, {
199
+ relations: { posts: { hasMany: 'Post', foreignKey: 'tags' } }, // through Post.tags (m:n)
200
+ });
201
+
202
+ const users = await User.findMany({
203
+ include: {
204
+ profile: true,
205
+ posts: {
206
+ where: { published: true },
207
+ orderBy: { createdAt: 'desc' },
208
+ take: 5,
209
+ select: { title: true },
210
+ include: { tags: { select: { label: true } } },
211
+ },
212
+ },
213
+ });
214
+ // [{ id, email, …, profile: { … } | null, posts: [{ title, tags: [{ label }] }] }]
215
+
216
+ await Post.findUnique({ where: { id }, include: { author: true } }); // author: { … } | null
217
+ ```
218
+
219
+ | Relation | Declared as | `include` gives |
220
+ |---|---|---|
221
+ | belongs to | `author: { type: 'uuid', ref: 'User' }` | the record, or `null` (never `null` when `required`) |
222
+ | many-to-many | `tags: { type: 'array', of: 'uuid', ref: 'Tag' }` | the records, in link order |
223
+ | has many | `relations: { posts: { hasMany: 'Post', foreignKey: 'author' } }` | the records (by `id` unless `orderBy`) |
224
+ | has one | `relations: { profile: { hasOne: 'Profile', foreignKey: 'user' } }` | the record or `null` — `foreignKey` must be `unique` |
225
+
226
+ - `true`, or options: `select`, `omit`, a nested `include` (any depth), and on lists `where`,
227
+ `orderBy`, `take`, `skip`. `false` leaves the relation out.
228
+ - `foreignKey` names the field on the other model that refs this one: a scalar `ref` or a
229
+ many-to-many array.
230
+ - **One statement per call**, whatever the depth: each relation is a correlated subquery
231
+ building `jsonb`. Included records read exactly like direct reads (`bigint`s, decimals as
232
+ strings, dates).
233
+ - `findMany`, `findFirst`, `findUnique` (and `…OrThrow`), `create`, `update`, `upsert` and
234
+ `delete` take `include`. Writes read the record back with its relations after writing;
235
+ `delete` reads it first.
236
+ - Self-relations work both ways (`parent` ref + `children: { hasMany: 'Category', foreignKey: 'parent' }`).
237
+
238
+ **Types.** Relations name models by string, so register your models once for typed includes:
239
+
240
+ ```ts
241
+ declare module 'express-file-cluster' {
242
+ interface Tables { User: typeof User; Post: typeof Post; Tag: typeof Tag; Profile: typeof Profile }
243
+ }
244
+ ```
245
+
246
+ Included records are then typed (`select` / `omit` / nested `include` applied), and `include`
247
+ keys, nested `where` and `orderBy` are checked. A relation to an unregistered model still works,
248
+ typed as `Record<string, unknown>`.
249
+
101
250
  ---
102
251
 
103
252
  ## Reading
@@ -151,8 +300,22 @@ const next = await Order.findMany({ orderBy: { qty: 'desc' }, take: 20, cursor:
151
300
  | strings | + `contains`, `startsWith`, `endsWith`, `mode: 'insensitive'` (ILIKE) |
152
301
  | native arrays | `has`, `hasEvery`, `hasSome`, `isEmpty`, `equals` |
153
302
  | objects / arrays of objects / `json` | `equals`, `not`, and with `path: ['a', 'b']`: `equals`, `string_contains`, `string_starts_with`, `string_ends_with`, `array_contains`, `gt`… |
303
+ | relations, to-many (many-to-many fields, `hasMany`) | `some`, `every`, `none` — each a `where` on the related model |
304
+ | relations, to-one (ref fields, `hasOne`) | `is`, `isNot` — a `where` on the related model, or `null` |
154
305
  | combinators | `AND`, `OR`, `NOT` (an object or an array) |
155
306
 
307
+ ```ts
308
+ await User.findMany({ where: { posts: { some: { comments: { some: { approved: false } } } } } });
309
+ await User.findMany({ where: { posts: { none: {} } } }); // users without posts
310
+ await Post.findMany({ where: { author: { is: { role: 'admin' } }, tags: { every: { public: true } } } });
311
+ await Post.findMany({ where: { author: { is: null } } }); // no author
312
+ ```
313
+
314
+ Relation filters are `EXISTS` subqueries — the read stays one statement — and nest to any
315
+ depth. They work wherever `where` does: reads, `count`, `include`, `updateMany`, `deleteMany`.
316
+ `every` holds for records with no related records at all. A ref or many-to-many field still
317
+ takes its own id filters (`author: id`, `tags: { has: id }`); a back-relation only these.
318
+
156
319
  `undefined` values are ignored. Filters on undeclared fields match nothing, as with
157
320
  `defineModel`. `LIKE` wildcards in `contains`, `startsWith` and `endsWith` are escaped.
158
321
 
@@ -202,6 +365,51 @@ await Order.update({
202
365
  (400); a duplicate unique value gives a 409. `updatedAt` is refreshed on every update.
203
366
  `increment`/`decrement` results are not re-checked against `min`/`max`.
204
367
 
368
+ ### Nested writes
369
+
370
+ `create`, `update` and `upsert` can write related records in the same call:
371
+
372
+ ```ts
373
+ await Post.create({
374
+ data: {
375
+ title: 'Hello',
376
+ author: { connect: { email: 'ann@x.io' } }, // a ref: connect / create / connectOrCreate
377
+ tags: { // many-to-many
378
+ connect: [{ label: 'news' }],
379
+ connectOrCreate: [{ where: { label: 'tech' }, create: { label: 'tech' } }],
380
+ create: [{ label: 'launch' }],
381
+ },
382
+ comments: { create: [{ body: 'First!' }] }, // a back-relation (hasMany)
383
+ },
384
+ include: { author: true, tags: true, comments: true },
385
+ });
386
+
387
+ await User.update({
388
+ where: { id },
389
+ data: {
390
+ posts: { connect: [{ id: p1 }], disconnect: [{ id: p2 }], deleteMany: { draft: true } },
391
+ profile: { create: { bio: 'hi' } }, // hasOne: replaces the current one
392
+ },
393
+ });
394
+ ```
395
+
396
+ | Relation | `create` | `update` adds |
397
+ |---|---|---|
398
+ | ref field | `connect`, `create`, `connectOrCreate` (or the id) | `disconnect: true` |
399
+ | many-to-many field | `connect`, `create`, `connectOrCreate` (or ids) | `disconnect`, `set`, `push`, `pull` |
400
+ | `hasMany` | `connect`, `create` | `disconnect`, `set`, `delete`, `deleteMany` |
401
+ | `hasOne` | `connect`, `create` | `disconnect: true`, `delete: true` |
402
+
403
+ - `connect`, `disconnect`, `set` and `delete` take unique wheres (or ids); a list or a single one.
404
+ A `connect` that matches nothing is a **400** on the field.
405
+ - Children created through a back-relation get their foreign key from the parent — leave it out.
406
+ - The whole call runs in **one transaction**: anything failing rolls it all back.
407
+ - `createMany` / `updateMany` write rows only; they refuse nested writes, as in Prisma.
408
+ - `upsert` with nested writes reads first, then creates or updates, in the transaction (without
409
+ nested writes it stays a single `INSERT … ON CONFLICT`).
410
+ - A model first used inside a transaction gets its table right away and its foreign keys once
411
+ the transaction commits, so the sync never waits on the transaction's own locks.
412
+
205
413
  ---
206
414
 
207
415
  ## Aggregation
@@ -246,5 +454,5 @@ Over an empty set, `_sum`, `_avg`, `_min` and `_max` are `null`. `aggregate` als
246
454
  - `raw()` returns the Drizzle `pgTable`, for anything EFC doesn't cover.
247
455
  - `sync({ dryRun })` / `drop()` work as with `defineModel`.
248
456
  - `transaction(async () => …)` covers `defineTable` calls too.
249
- - Relations (`include`, foreign keys, relation filters, nested writes) are planned (M3), not
250
- implemented yet.
457
+ - Relations are complete: foreign keys, many-to-many, `include`, relation filters and nested
458
+ writes (above).
@@ -20,6 +20,7 @@ The interactive wizard walks through:
20
20
  ? Project name: my-api
21
21
  ? Language: TypeScript | JavaScript
22
22
  ? Database: MongoDB | PostgreSQL
23
+ ? Models: defineTable | defineModel (PostgreSQL only)
23
24
  ? Authentication strategy: http-only | localStorage
24
25
  ? Features: (space to toggle)
25
26
  ◉ Multi-core clustering
@@ -31,7 +32,7 @@ The interactive wizard walks through:
31
32
  ◯ Mailer
32
33
  ```
33
34
 
34
- Generated models and routes are identical for both databases — `defineModel` compiles to mongoose or Drizzle at runtime. See [Database](../guides/database.md).
35
+ On **PostgreSQL**, models default to [`defineTable`](../api-reference/table.md): PostgreSQL-native, with real foreign keys between the generated models (a user's sessions, invoices, tickets…), `relations` for `include`, and Prisma-style queries in the generated routes. Pick **defineModel** instead for the portable API. On **MongoDB**, models are `defineModel`, which compiles to mongoose. See [Database](../guides/database.md).
35
36
 
36
37
  Depending on what you toggle on, you'll see follow-up questions:
37
38
 
@@ -70,7 +70,7 @@ See [Background Tasks](../core-concepts/background-tasks.md).
70
70
 
71
71
  ## `src/model/` — Data models
72
72
 
73
- Engine-agnostic model definitions using `defineModel()` — they compile to a mongoose model on MongoDB or a Drizzle table on PostgreSQL, with the same API on both.
73
+ Model definitions. On PostgreSQL (by default) they're [`defineTable`](../api-reference/table.md) models — PostgreSQL-native, with foreign keys and `relations` between them — and `src/model/index.ts` imports them all and declares the `Tables` map that types `include`; add new models there. On MongoDB (or with the **defineModel** choice) they're engine-agnostic `defineModel()` models, which compile to mongoose or Drizzle with the same API on both.
74
74
 
75
75
  See [Database Guide](../guides/database.md).
76
76
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  `create-efc-app`'s **User portal** and **Admin portal** feature options scaffold a large, ready-to-run set of models and routes — everything from auth extras (2FA, sessions, password reset) to admin content management (blogs, FAQs, coupons). This page is the complete inventory, so nothing you didn't ask for shows up as a surprise, and nothing you did enable goes undocumented.
4
4
 
5
- > On MongoDB, every model below is a real `defineModel`-backed collection and every route has working database logic. **On PostgreSQL, model files are commented-out Drizzle stubs and route bodies are `// TODO` placeholders** — the PostgreSQL adapter isn't implemented in the runtime yet. See [Database](./database.md).
5
+ > Every model below is real on both databases. On MongoDB they're `defineModel` collections. On PostgreSQL they're [`defineTable`](../api-reference/table.md) models (or `defineModel`, if you picked it) linked by foreign keys — `Session`, `Notification`, `File`, `SupportTicket`, `Subscription`, `Invoice` and `ApiKey` reference `User` (deleted with it), `Subscription` references `Plan`, `Invoice` its `Subscription`, `AuditLog`, `Blog` and assigned tickets an `Admin` (cleared when it's deleted), and `Category` its parent — with matching `relations` (`user.sessions`, `plan.subscriptions`, `category.children`…) for `include`. A reference stays a plain id when its target model isn't generated. See [Database](./database.md).
6
6
 
7
7
  ---
8
8
 
@@ -13,6 +13,7 @@ ignite({
13
13
  level: 'info', // trace | debug | info | warn | error | fatal | silent
14
14
  pretty: undefined, // default: true in a non-production TTY, JSON otherwise
15
15
  requests: true, // one line per completed request
16
+ queries: false, // model operation logging — see "Query logging" below
16
17
  },
17
18
  });
18
19
  ```
@@ -59,6 +60,43 @@ In production the same record is JSON:
59
60
 
60
61
  ---
61
62
 
63
+ ## Query logging
64
+
65
+ `logging.queries` reports model operations — every `defineModel` and `defineTable` call — with the model, operation, duration, how many database statements it issued, and the request ID:
66
+
67
+ ```ts
68
+ logging: { queries: true } // every operation, plus slow-query warnings
69
+ logging: { queries: { slowMs: 200 } } // only operations taking ≥ 200 ms (production)
70
+ logging: { queries: { all: true, slowMs: 200, nPlusOne: 5 } }
71
+ ```
72
+
73
+ | Option | Default | |
74
+ |---|---|---|
75
+ | `all` | `true` with `queries: true`, else `false` | log every operation at `info` |
76
+ | `slowMs` | `500` | operations at least this slow log at `warn` with `slow=true` |
77
+ | `nPlusOne` | `10` | warn when one request runs the same `Model.operation` this many times; `false` disables |
78
+
79
+ ```
80
+ 12:00:01 INFO [w2] 3f9c2a1b Post.findMany 2.1ms model=Post op=findMany durationMs=2.1 statements=1
81
+ 12:00:01 WARN [w2] 3f9c2a1b Slow query: Order.aggregate 812.4ms model=Order op=aggregate durationMs=812.4 statements=1 slow=true
82
+ ```
83
+
84
+ `statements` counts the SQL statements (PostgreSQL) or MongoDB commands the call sent, including nested work such as `populate`; first-use auto-sync is not counted. An operation that throws is still logged, with `error`.
85
+
86
+ ### N+1 detection
87
+
88
+ Querying inside a loop is the classic N+1 problem. When one request runs the same model operation `nPlusOne` times, EFC warns once for that request, naming the line that made the call:
89
+
90
+ ```
91
+ 12:00:01 WARN [w2] 3f9c2a1b Possible N+1: User.findById ran 10 times in one request — load them in one query instead model=User op=findById count=10 site=GET (/app/src/api/posts.ts:14:30)
92
+ ```
93
+
94
+ Load them together instead — `User.find({ id: { $in: ids } })`, `populate`, or `findMany({ where: { id: { in: ids } } })`. Only top-level calls count (not `populate`'s), and only inside a request.
95
+
96
+ On MongoDB, query logging takes mongoose's `debug` hook (`mongoose.set('debug', …)`) to count commands, so it replaces any `debug` setting of your own while it is on.
97
+
98
+ ---
99
+
62
100
  ## Errors
63
101
 
64
102
  Unhandled errors are logged at `error` with the request ID and full stack (`err`) before the 500 response is sent. Task failures log the task name, job ID and attempt number.
@@ -53,7 +53,7 @@ Both approaches produce the same 401/403 behavior — RBAC-on just centralizes t
53
53
 
54
54
  ### `Role` model
55
55
 
56
- A `src/model/Role.ts` model is created (MongoDB: a real `defineModel`-backed collection; PostgreSQL: a commented-out Drizzle stub, per the current [database support status](./database.md)).
56
+ A `src/model/Role.ts` model is created (`defineModel` on MongoDB, `defineTable` on PostgreSQL by default).
57
57
 
58
58
  ### Admin role management routes
59
59
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  **express-file-cluster (EFC)** is an opinionated backend framework built on Express. It removes routing ceremony, saturates every CPU core automatically, and ships a production-grade background-task subsystem — all from a single `ignite()` call.
4
4
 
5
- > **Status: v0.5.0 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries), BullMQ and pg-boss tasks with cron and dead-letter tooling, and migrations are all implemented.
5
+ > **Status: v0.7.1 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries and relations: foreign keys, many-to-many, `include`, relation filters, nested writes), query logging, BullMQ and pg-boss tasks with cron and dead-letter tooling, and migrations are all implemented.
6
6
 
7
7
  ---
8
8
 
@@ -37,8 +37,8 @@ Load **only** the module the work points to. Each is self-contained.
37
37
  docs/ ← full documentation
38
38
  ```
39
39
 
40
- ## Status (v0.5.0 — Beta, Phase 2 complete + defineTable)
40
+ ## Status (v0.7.1 — Beta, Phase 2 complete + defineTable with relations)
41
41
 
42
- Implemented: file-based router (incl. `[[id]]`, `[...slug]`, `[[...slug]]`), request validation (`export const schema`, Standard Schema), multi-core clustering with graceful shutdown, http-only + localStorage auth, structured logging (pino, request IDs), `defineModel` on MongoDB (mongoose) **and** PostgreSQL (Drizzle) with validation, query options, bulk ops, transactions, `sync()`/`drop()`, BullMQ **and** pg-boss task backends with cron schedules and dead-letter CLI, worker_threads for CPU-bound tasks, migrations/seeds/studio (`efc db`), full CLI.
42
+ Implemented: file-based router (incl. `[[id]]`, `[...slug]`, `[[...slug]]`), request validation (`export const schema`, Standard Schema), multi-core clustering with graceful shutdown, http-only + localStorage auth, structured logging (pino, request IDs), `defineModel` on MongoDB (mongoose) **and** PostgreSQL (Drizzle) with validation, query options, bulk ops, transactions, `sync()`/`drop()`, PostgreSQL-native `defineTable` (Prisma-style queries, foreign keys, many-to-many, `include`, relation filters, nested writes), query logging (`logging.queries`), BullMQ **and** pg-boss task backends with cron schedules and dead-letter CLI, worker_threads for CPU-bound tasks, migrations/seeds/studio (`efc db`), full CLI.
43
43
 
44
44
  **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`, schema-diff migration generation.
@@ -51,7 +51,7 @@ function defineTable(name: string, schema: TableSchema, options?: TableOptions):
51
51
  // arrays: has hasEvery hasSome isEmpty · jsonb: { path: [...], equals | string_contains | array_contains | gt… }
52
52
  // AND / OR / NOT · undefined ignored · undeclared fields match nothing
53
53
  // data ops: { increment | decrement | multiply | divide } (numbers), { push } (arrays), { set }, null unsets
54
- // unique where: id | unique field | all fields of a unique index. No relations/include yet (M3).
54
+ // unique where: id | unique field | all fields of a unique index. Top-level `ref` = FK, `onDelete: 'restrict'|'cascade'|'setNull'`, ref type must match target id (uuid/objectId | integer for serial | bigint for bigserial). Array of refs `{ type: 'array', of: <id type>, ref }` = many-to-many (join table, record keeps id list, list filters, set/push). `include` loads refs, m:n and `options.relations` back-relations (hasMany/hasOne + foreignKey) in one statement; typed via `interface Tables` augmentation. Relation filters `some/every/none`, `is/isNot`; nested writes `connect/create/connectOrCreate/disconnect/set/delete/deleteMany` (one transaction; not in createMany/updateMany).
55
55
 
56
56
  class ModelValidationError extends HttpError { issues: { path: string; message: string }[] } // status 400
57
57
 
@@ -127,6 +127,7 @@ interface LoggingConfig {
127
127
  level?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'silent'; // default 'info'
128
128
  pretty?: boolean; // default: non-production TTY
129
129
  requests?: boolean; // default true
130
+ queries?: boolean | { all?: boolean; slowMs?: number; nPlusOne?: number | false }; // default off; slowMs 500, nPlusOne 10
130
131
  }
131
132
  ```
132
133
 
@@ -39,7 +39,7 @@ defineTable() // ← EXISTS (PostgreSQL-only, Prisma-style) — see api
39
39
  defineCollection() // ← NOT YET — planned (MongoDB-native API, prisma-parity-plan M5)
40
40
  Model.findMany() / findUnique() / groupBy() // ← only on defineTable, NOT on defineModel
41
41
  Table.find() / findById() / $gt / $inc // ← defineModel vocabulary, NOT on defineTable
42
- Table.findMany({ include }) // ← relations/include NOT YET (M3)
42
+ Table.findMany({ include }) // ← EXISTS; so do relation filters `{ posts: { some } }` and nested writes `{ connect }` (defineTable only)
43
43
  defineModel(..., { type: 'integer' | 'bigint' | 'decimal' | 'uuid' | 'json' }) // ← defineTable-only types
44
44
  Model.updateOne(f, u, { upsert: true }) // ← no options arg; use Model.upsert(filter, create, update)
45
45
  getModel() // ← does NOT exist as a public export