@meghjs/mcp 0.0.0-stage → 0.7.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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/docs/advanced/caching.md +72 -0
  6. package/dist/docs/advanced/database.md +328 -0
  7. package/dist/docs/advanced/events.md +169 -0
  8. package/dist/docs/advanced/file-uploads.md +141 -0
  9. package/dist/docs/advanced/health.md +81 -0
  10. package/dist/docs/advanced/logging.md +96 -0
  11. package/dist/docs/advanced/mail.md +439 -0
  12. package/dist/docs/advanced/orm/migrations.md +210 -0
  13. package/dist/docs/advanced/orm/models.md +291 -0
  14. package/dist/docs/advanced/orm/queries.md +169 -0
  15. package/dist/docs/advanced/orm/query-builder.md +120 -0
  16. package/dist/docs/advanced/orm/relations.md +179 -0
  17. package/dist/docs/advanced/orm/seeding.md +129 -0
  18. package/dist/docs/advanced/orm.md +145 -0
  19. package/dist/docs/advanced/plugins.md +90 -0
  20. package/dist/docs/advanced/queue.md +217 -0
  21. package/dist/docs/advanced/scheduler.md +253 -0
  22. package/dist/docs/advanced/testing.md +257 -0
  23. package/dist/docs/advanced/views.md +335 -0
  24. package/dist/docs/ai/mcp.md +162 -0
  25. package/dist/docs/cli/basic.md +133 -0
  26. package/dist/docs/cli/database.md +112 -0
  27. package/dist/docs/cli/generators.md +605 -0
  28. package/dist/docs/cli/scaffold/auth.md +172 -0
  29. package/dist/docs/cli/scaffold/domains.md +224 -0
  30. package/dist/docs/cli/scaffold/index.md +77 -0
  31. package/dist/docs/cli/scaffold/rbac.md +118 -0
  32. package/dist/docs/cli/scaffold/templates.md +235 -0
  33. package/dist/docs/core-concept/authentication.md +162 -0
  34. package/dist/docs/core-concept/configuration.md +268 -0
  35. package/dist/docs/core-concept/controller.md +350 -0
  36. package/dist/docs/core-concept/dependency-injection.md +213 -0
  37. package/dist/docs/core-concept/error-handling.md +185 -0
  38. package/dist/docs/core-concept/middleware.md +143 -0
  39. package/dist/docs/core-concept/request-context.md +110 -0
  40. package/dist/docs/core-concept/validation.md +355 -0
  41. package/dist/docs/getting-started/application.md +233 -0
  42. package/dist/docs/getting-started/installation.md +166 -0
  43. package/dist/docs/getting-started/introduction.md +136 -0
  44. package/dist/docs/getting-started/upgrading-0.4.md +125 -0
  45. package/dist/docs/getting-started/upgrading-0.5.md +293 -0
  46. package/dist/docs/getting-started/upgrading-0.6.md +251 -0
  47. package/dist/docs/getting-started/upgrading-0.7.md +225 -0
  48. package/dist/docs/getting-started/upgrading-megh.md +91 -0
  49. package/dist/docs/getting-started/upgrading-next.md +12 -0
  50. package/dist/docs/getting-started/upgrading.md +137 -0
  51. package/dist/docs/getting-started/usage.md +194 -0
  52. package/dist/docs/index.md +58 -0
  53. package/dist/docs/microservices/openapi.md +387 -0
  54. package/dist/docs/microservices/websocket.md +165 -0
  55. package/dist/docs/production/deployment.md +256 -0
  56. package/dist/docs/production/security.md +307 -0
  57. package/dist/docs/reference/api.md +999 -0
  58. package/dist/docs/reference/faq.md +227 -0
  59. package/dist/docs/reference/versioning.md +105 -0
  60. package/dist/docs.d.ts +30 -0
  61. package/dist/docs.js +126 -0
  62. package/dist/index.d.ts +10 -0
  63. package/dist/index.js +22 -0
  64. package/dist/megh.d.ts +59 -0
  65. package/dist/megh.js +207 -0
  66. package/dist/prompts.d.ts +3 -0
  67. package/dist/prompts.js +47 -0
  68. package/dist/result.d.ts +18 -0
  69. package/dist/result.js +48 -0
  70. package/dist/server.d.ts +17 -0
  71. package/dist/server.js +40 -0
  72. package/dist/tools/context.d.ts +11 -0
  73. package/dist/tools/context.js +2 -0
  74. package/dist/tools/database.d.ts +8 -0
  75. package/dist/tools/database.js +58 -0
  76. package/dist/tools/docs.d.ts +3 -0
  77. package/dist/tools/docs.js +63 -0
  78. package/dist/tools/generate.d.ts +10 -0
  79. package/dist/tools/generate.js +177 -0
  80. package/dist/tools/project.d.ts +3 -0
  81. package/dist/tools/project.js +84 -0
  82. package/dist/version.d.ts +2 -0
  83. package/dist/version.js +10 -0
  84. package/package.json +58 -4
@@ -0,0 +1,291 @@
1
+ ---
2
+ title: Models
3
+ description: "Defining MeghORM models with decorators: columns, keys, column names, timestamps, soft deletes and casts."
4
+ ---
5
+
6
+ # Models
7
+
8
+ A model is a class that describes one table. Its decorators give the columns, keys and value conversions, and TypeScript checks every query against them.
9
+
10
+ ## Defining models
11
+
12
+ Extend `Model` and describe the table with decorators:
13
+
14
+ ```ts [src/models/user.model.ts]
15
+ import {
16
+ Model, Table, PrimaryKey, AutoIncrement, Column,
17
+ CreatedAt, UpdatedAt, HasMany,
18
+ } from '@meghjs/core';
19
+ import { Post } from './post.model';
20
+
21
+ @Table('users')
22
+ export class User extends Model {
23
+ @PrimaryKey()
24
+ @AutoIncrement()
25
+ id?: number;
26
+
27
+ @Column({ unique: true })
28
+ email!: string;
29
+
30
+ @Column({ nullable: true })
31
+ name!: string | null;
32
+
33
+ @Column()
34
+ active!: boolean;
35
+
36
+ @CreatedAt()
37
+ created_at?: Date;
38
+
39
+ @UpdatedAt()
40
+ updated_at?: Date;
41
+
42
+ @HasMany(() => Post)
43
+ posts?: Post[];
44
+
45
+ get displayName() {
46
+ return this.name ?? this.email;
47
+ }
48
+
49
+ greet() {
50
+ return `Hi ${this.displayName}`;
51
+ }
52
+ }
53
+ ```
54
+
55
+ Query results are instances of the model, so methods and getters work on them.
56
+
57
+ **Optional fields.** Declare columns the database fills in with `?`: the
58
+ auto-increment `id`, timestamps, columns with a default. They're optional in
59
+ `create()`, and present on every row you load, so `user.id` is a `number` on
60
+ query results.
61
+
62
+ **Fields that aren't columns.** Only decorated fields are saved. For
63
+ TypeScript to leave a field out of `where()` and `create()` too, make it
64
+ `private`, `readonly` or a getter.
65
+
66
+ ### Decorators
67
+
68
+ | Decorator | |
69
+ |---|---|
70
+ | `@Table(name?)` | The table. Without a name, the plural snake_case class name: `BlogPost` → `blog_posts` |
71
+ | `@Column(options?)` | A column. Also `@Column('text')` or `@Column('text', options)` |
72
+ | `@PrimaryKey(options?)` | The primary key. Defaults to `id` when no field has it |
73
+ | `@AutoIncrement()` | A column the database numbers: `SERIAL`/`IDENTITY` on PostgreSQL, `AUTO_INCREMENT` on MySQL, `IDENTITY(1,1)` on SQL Server, `AUTOINCREMENT` on SQLite. Left out of inserts |
74
+ | `@Identity()` | Same as `@AutoIncrement()` |
75
+ | `@CreatedAt()` | Set when the row is inserted. See [Timestamps](#timestamps) |
76
+ | `@UpdatedAt()` | Set on every insert and update |
77
+ | `@DeletedAt()` | Turns on [soft deletes](#soft-deletes) |
78
+ | `@HasMany`, `@HasOne`, `@BelongsTo`, `@BelongsToMany` | [Relations](/advanced/orm/relations) |
79
+
80
+ Column options:
81
+
82
+ | Option | |
83
+ |---|---|
84
+ | `name` | The column's name, when it differs from the property. See [Column names](#column-names) |
85
+ | `type` | `string`, `text`, `integer`, `bigint`, `float`, `double`, `decimal`, `boolean`, `date`, `datetime`, `timestamp`, `time`, `json`, `uuid`, `binary`. `boolean` and `Date` fields are detected from the TypeScript type |
86
+ | `nullable` | Allows `NULL` |
87
+ | `unique` | |
88
+ | `default` | Default value |
89
+ | `length` | For `string` |
90
+ | `precision`, `scale` | For `decimal` |
91
+ | `cast` | How stored values convert. Defaults from `type`; see [Casts](#casts) |
92
+
93
+ Decorated columns are inherited, so shared columns can live in a base class:
94
+
95
+ ```ts
96
+ export abstract class BaseModel extends Model {
97
+ @PrimaryKey()
98
+ @AutoIncrement()
99
+ id?: number;
100
+
101
+ @CreatedAt()
102
+ created_at?: Date;
103
+
104
+ @UpdatedAt()
105
+ updated_at?: Date;
106
+ }
107
+
108
+ @Table()
109
+ export class Tag extends BaseModel {
110
+ @Column()
111
+ name!: string;
112
+ }
113
+ ```
114
+
115
+ ### Column names
116
+
117
+ By default a property is stored in the column with the same name. To use
118
+ camelCase properties with snake_case columns, set the naming strategy once:
119
+
120
+ ```ts
121
+ app.useMeghORM({ naming: 'snake_case' });
122
+
123
+ @Table()
124
+ class Post extends Model {
125
+ @PrimaryKey()
126
+ @AutoIncrement()
127
+ id?: number;
128
+
129
+ @Column()
130
+ authorId!: number; // author_id
131
+
132
+ @Column()
133
+ publishedAt!: Date | null; // published_at
134
+
135
+ @CreatedAt()
136
+ createdAt?: Date; // created_at
137
+ }
138
+ ```
139
+
140
+ Or name a column explicitly, which works with either strategy:
141
+
142
+ ```ts
143
+ @Table('legacy_customers')
144
+ class Customer extends Model {
145
+ @PrimaryKey({ name: 'customer_no' })
146
+ @AutoIncrement()
147
+ id?: number;
148
+
149
+ @Column({ name: 'e_mail' })
150
+ email!: string;
151
+
152
+ @CreatedAt({ name: 'created_on' })
153
+ createdAt?: Date;
154
+ }
155
+ ```
156
+
157
+ Model code then uses property names everywhere: `create()`, `where()`,
158
+ `orderBy()`, `select()`, `withCount()`, `cursorPaginate({ column })`,
159
+ aggregates, query results and JSON. Relation keys may be given as either the
160
+ property or the column, so the defaults (`author_id`) work with an `authorId`
161
+ property.
162
+
163
+ Code that writes SQL itself uses column names: the [query builder](/advanced/orm/query-builder),
164
+ [raw queries](/advanced/orm/query-builder#raw-queries), `where((eb) => …)` expressions and migrations.
165
+ In scripts and tests without an app, call `setNamingStrategy('snake_case')`
166
+ before querying.
167
+
168
+ ::: details Models without decorators
169
+ Models written before decorators keep working: every field is a column except
170
+ relations (declared with `hasMany()` and the others), methods and getters, and
171
+ settings are static fields (`static readonly table = 'users'`, `primaryKey`,
172
+ `generated`, `timestamps`, `softDeletes`, `casts`). Decorators set the same
173
+ settings, so the two styles can be mixed while you migrate.
174
+ :::
175
+
176
+ ## Timestamps
177
+
178
+ ```ts
179
+ @Table()
180
+ class Post extends Model {
181
+ @PrimaryKey()
182
+ @AutoIncrement()
183
+ id?: number;
184
+
185
+ @Column()
186
+ title!: string;
187
+
188
+ @CreatedAt()
189
+ created_at?: Date;
190
+
191
+ @UpdatedAt()
192
+ updated_at?: Date;
193
+ }
194
+ ```
195
+
196
+ The `@CreatedAt` column is set on insert, and the `@UpdatedAt` column on every
197
+ insert and update: `create()`, `save()`, query `update()`, and soft deletes and
198
+ restores. Both are read back as `Date`. Use either one on its own, and name
199
+ the fields after your columns.
200
+
201
+ ## Soft deletes
202
+
203
+ ```ts
204
+ @Table()
205
+ class Post extends Model {
206
+ @PrimaryKey()
207
+ @AutoIncrement()
208
+ id?: number;
209
+
210
+ @DeletedAt()
211
+ deleted_at?: Date | null;
212
+ }
213
+ ```
214
+
215
+ With a `@DeletedAt` column, `delete()` sets it instead of removing the row,
216
+ and every query, eager load included, leaves those rows out:
217
+
218
+ ```ts
219
+ await post.delete();
220
+ post.isTrashed(); // true
221
+ await Post.find(post.id); // undefined
222
+ await Post.withTrashed().find(post.id); // still there
223
+ await Post.onlyTrashed().get(); // only deleted rows
224
+
225
+ await post.restore();
226
+ await Post.onlyTrashed().where('user_id', 1).restore();
227
+
228
+ await post.forceDelete(); // really delete
229
+ await Post.onlyTrashed().forceDelete();
230
+ ```
231
+
232
+ ## Casts
233
+
234
+ Casts convert between what the database stores and what the model holds. A
235
+ column's `type` picks its cast (`boolean`, `json`, `date`, `datetime` and
236
+ `timestamp` have one), and `cast` sets it explicitly:
237
+
238
+ ```ts
239
+ @Table()
240
+ class Member extends Model {
241
+ @PrimaryKey()
242
+ @AutoIncrement()
243
+ id?: number;
244
+
245
+ @Column()
246
+ is_admin!: boolean; // boolean, from the TypeScript type
247
+
248
+ @Column({ type: 'json', nullable: true })
249
+ settings!: { theme: string } | null;
250
+
251
+ @Column({ type: 'date', nullable: true })
252
+ born_on!: Date | null;
253
+
254
+ @Column({ type: 'decimal', cast: 'number' })
255
+ balance!: number;
256
+ }
257
+ ```
258
+
259
+ `boolean` and `Date` fields get their cast from the TypeScript type. A
260
+ nullable field (`boolean | null`) has no single type at runtime, so give it
261
+ `type`.
262
+
263
+ | Cast | Read as | Written as |
264
+ |---|---|---|
265
+ | `'boolean'` | `true` / `false` (from `1`/`0`, `'true'`, …) | the boolean (`1`/`0` on SQLite) |
266
+ | `'number'` | a number, e.g. from Postgres `numeric` / `bigint` strings | the number |
267
+ | `'string'` | a string | the value |
268
+ | `'json'` | the parsed value | JSON text |
269
+ | `'date'` | a `Date` | `YYYY-MM-DD`, from the date's UTC parts |
270
+ | `'datetime'` | a `Date` | the `Date` (ISO text on SQLite) |
271
+ | `{ get, set }` | `get(stored)` | `set(value)` |
272
+
273
+ ```ts
274
+ const csv: CustomCast<string[], string> = {
275
+ get: (stored) => (stored === '' ? [] : stored.split(',')),
276
+ set: (tags) => tags.join(','),
277
+ };
278
+ ```
279
+
280
+ Timestamp and soft-delete columns are cast as `'datetime'` automatically.
281
+ `save()` notices changes made in place, such as `member.settings.theme = 'dark'`.
282
+
283
+ SQLite drivers can only bind numbers, strings and buffers, so on SQLite
284
+ `Date` values become ISO text and booleans become `1`/`0`, in `where()` too.
285
+
286
+ ## Generating models
287
+
288
+ `npx megh make:model user --orm` writes `src/models/user.model.ts`, with its
289
+ columns read from the migrations that create and change the `users` table.
290
+ (Without `--orm`, `make:model` writes a plain class.)
291
+ See [CLI: Model](/cli/generators#model).
@@ -0,0 +1,169 @@
1
+ ---
2
+ title: Queries
3
+ description: "Reading and writing rows with MeghORM models: where clauses, aggregates, scopes, pagination, writes and transactions."
4
+ ---
5
+
6
+ # Queries
7
+
8
+ Models read and write rows through typed queries. Column names and values are checked against the model, and results are model instances.
9
+
10
+ ## Querying
11
+
12
+ ```ts
13
+ await User.all();
14
+ await User.find(1); // User | undefined
15
+ await User.findOrFail(1); // throws a 404 NotFoundException if missing
16
+ await User.findBy('email', 'ann@acme.io'); // first match, or undefined
17
+ await User.findBy({ email: 'ann@acme.io', active: true });
18
+ await User.findByOrFail('email', 'ann@acme.io'); // or a 404
19
+
20
+ await User.where('email', 'ann@acme.io').first();
21
+ await User.where('id', '>', 10).orderBy('name', 'desc').limit(10).offset(20).get();
22
+ await User.where('name', null).get(); // IS NULL
23
+ await User.query().whereIn('id', [1, 2, 3]).get();
24
+ await User.query().whereNotNull('name').count();
25
+ await User.where('email', 'ann@acme.io').exists();
26
+ ```
27
+
28
+ `User.where()`, `User.with()`, `User.whereHas()`, `User.withCount()` and
29
+ `User.scope()` start a query; `User.query()` starts an empty one. Nothing runs
30
+ until `get()`, `first()`, `firstOrFail()`, `count()`, `exists()`, an aggregate,
31
+ a paginate method, `update()` or `delete()` is called.
32
+
33
+ Pass a callback for anything else Kysely can express, such as `OR` groups:
34
+
35
+ ```ts
36
+ await User.where((eb) => eb.or([eb('role', '=', 'admin'), eb('id', '=', 1)])).get();
37
+ ```
38
+
39
+ `select()` fetches only some columns, and the result type narrows to them:
40
+
41
+ ```ts
42
+ const rows = await User.query().select('id', 'email').get();
43
+ rows[0].email; // string
44
+ rows[0].name; // compile error
45
+ ```
46
+
47
+ ### Aggregates
48
+
49
+ ```ts
50
+ await Post.count();
51
+ await Post.sum('views'); // 0 when no rows match
52
+ await Post.where('user_id', 1).avg('views'); // null when no rows match
53
+ await Post.min('published_on'); // casts apply: a Date here
54
+ await Post.max('views');
55
+ ```
56
+
57
+ Aggregates respect filters and soft deletes, like every other query.
58
+
59
+ ### Scopes
60
+
61
+ A scope is a reusable piece of a query, typed for its model:
62
+
63
+ ```ts
64
+ import type { Scope } from '@meghjs/core';
65
+
66
+ const published: Scope<Post> = (q) => q.whereNotNull('published_on');
67
+ const byAuthor: Scope<Post, [number]> = (q, userId) => q.where('user_id', userId);
68
+
69
+ await Post.scope(published).scope(byAuthor, 1).orderBy('id').get();
70
+ ```
71
+
72
+ ### Pagination
73
+
74
+ `paginate()` returns the same `{ data, meta }` shape as the rest of Megh:
75
+
76
+ ```ts
77
+ const page = await Post.query().orderBy('id').paginate({ page: 2, perPage: 20 });
78
+ // page.meta → { total, page, perPage, lastPage, next, prev }
79
+ await Post.paginate({ page: 1 }); // every row
80
+ ```
81
+
82
+ `simplePaginate()` skips the `count(*)` query, which is costly on large
83
+ tables. It fetches one extra row to tell whether another page follows:
84
+
85
+ ```ts
86
+ const page = await Post.query().simplePaginate({ page: 2, perPage: 20 });
87
+ // page.meta → { page, perPage, hasMore, next, prev }
88
+ ```
89
+
90
+ `cursorPaginate()` pages by key instead of by offset. Pages stay stable when
91
+ rows are inserted, and deep pages are as fast as the first. Pass the returned
92
+ `nextCursor` back to get the next page:
93
+
94
+ ```ts
95
+ const first = await Post.where('published', true).cursorPaginate({ perPage: 20 });
96
+ const next = await Post.where('published', true).cursorPaginate({
97
+ perPage: 20,
98
+ cursor: first.meta.nextCursor, // null on the last page
99
+ });
100
+ // meta → { perPage, hasMore, nextCursor }
101
+ ```
102
+
103
+ It orders by the primary key by default; pass `column` (it must be unique)
104
+ and `direction: 'desc'` to change that. An invalid cursor throws a 400
105
+ `BadRequestException`.
106
+
107
+ ### Paging on SQL Server
108
+
109
+ SQL Server has no `LIMIT`, so on SQL Server `limit()` becomes `select top(n)`
110
+ and `offset()` becomes `offset … rows fetch next … rows only`. SQL Server only
111
+ allows an offset after an `ORDER BY`, so a query with an offset but no
112
+ `orderBy()` gets `order by (select null)`, and its row order is not
113
+ guaranteed. Add an `orderBy()` when paging so pages stay stable.
114
+
115
+ ## Creating, updating and deleting
116
+
117
+ ```ts
118
+ // insert and return the stored row (generated columns included)
119
+ const user = await User.create({ email: 'ann@acme.io' }); // id generated, name nullable → optional
120
+
121
+ // or build an instance and save it
122
+ const bob = new User().fill({ email: 'bob@acme.io', name: 'Bob' });
123
+ await bob.save();
124
+
125
+ // save() updates only the columns that changed, and does nothing if none did
126
+ bob.name = 'Robert';
127
+ await bob.save(); // UPDATE users SET name = ? WHERE id = ?
128
+
129
+ await bob.delete();
130
+
131
+ // many rows at once; both return the number of rows affected
132
+ await Post.where('user_id', 1).update({ published: true });
133
+ await Post.where('published', false).delete();
134
+ ```
135
+
136
+ `create()`'s argument is typed from the model: required columns must be
137
+ present, and generated, nullable and timestamp columns may be left out.
138
+
139
+ ## Transactions
140
+
141
+ ```ts
142
+ await Model.transaction(async () => {
143
+ const user = await User.create({ email: 'ann@acme.io' });
144
+ await Profile.create({ user_id: user.id, bio: '' });
145
+ });
146
+ ```
147
+
148
+ Every model query inside the callback uses the transaction, even in functions
149
+ it calls. The transaction commits when the callback resolves and rolls back if
150
+ it throws.
151
+
152
+ A nested `Model.transaction()` runs in a savepoint. If it throws, only its own
153
+ work is rolled back, and the error still reaches the caller:
154
+
155
+ ```ts
156
+ await Model.transaction(async () => {
157
+ await Order.create({ total: 10 });
158
+ try {
159
+ await Model.transaction(async () => {
160
+ await Invoice.create({ order_id: 1 });
161
+ throw new Error('mailer down');
162
+ });
163
+ } catch {
164
+ // the invoice is gone, the order is kept
165
+ }
166
+ });
167
+ ```
168
+
169
+ If the outer transaction rolls back, so does everything nested inside it.
@@ -0,0 +1,120 @@
1
+ ---
2
+ title: Query Builder
3
+ description: The DB query builder and raw SQL in MeghORM, for queries that don't map to a model.
4
+ ---
5
+
6
+ # Query Builder
7
+
8
+ For queries that don't fit a model, such as reports, bulk updates, or tables
9
+ without a model, use `DB.table()`:
10
+
11
+ ```ts
12
+ import { DB } from '@meghjs/core';
13
+
14
+ const top = await DB.table('orders')
15
+ .select('customer_id')
16
+ .selectRaw('sum(total) as revenue')
17
+ .where('status', 'paid')
18
+ .whereBetween('created_at', [from, to])
19
+ .groupBy('customer_id')
20
+ .orderBy('revenue', 'desc')
21
+ .limit(10)
22
+ .get();
23
+ ```
24
+
25
+ Rows are plain objects. Type them with `DB.table<{ id: number; email: string }>('users')`.
26
+ Values are always sent as parameters, never written into the SQL.
27
+
28
+ **Conditions**
29
+
30
+ | | |
31
+ |---|---|
32
+ | `where('status', 'paid')`, `where('total', '>', 100)` | Operators: `=`, `!=`, `<>`, `<`, `<=`, `>`, `>=`, `like`, `not like`, `ilike`, `in`, `not in`, `is`, `is not` |
33
+ | `where({ status: 'paid', currency: 'EUR' })` | Every column equal |
34
+ | `where((q) => q.where('a', 1).orWhere('b', 2))` | A group in parentheses |
35
+ | `orWhere(...)` | Same forms, joined with `or` |
36
+ | `whereIn`, `whereNotIn` | An empty list matches nothing (`whereIn`) or everything (`whereNotIn`) |
37
+ | `whereNull`, `whereNotNull`, `orWhereNull`, `orWhereNotNull` | |
38
+ | `whereBetween`, `whereNotBetween` | `whereBetween('age', [18, 65])` |
39
+ | `whereColumn('updated_at', '>', 'created_at')` | Compare two columns |
40
+ | `whereRaw('lower(email) = ?', [email])`, `orWhereRaw` | SQL with `?` placeholders |
41
+
42
+ `where('x', null)` becomes `x is null`. As in SQL, `and` binds tighter than
43
+ `or`: `.where(a).orWhere(b).where(c)` means `a or (b and c)`.
44
+
45
+ **Shaping the result**
46
+
47
+ | | |
48
+ |---|---|
49
+ | `select('id', 'users.email as contact')`, `selectRaw(sql, bindings?)`, `distinct()` | Columns. All columns by default |
50
+ | `join(table, left, right)`, `join(table, left, op, right)`, `leftJoin`, `rightJoin` | `join('users', 'users.id', 'orders.user_id')` |
51
+ | `orderBy(column, 'asc' \| 'desc')`, `orderByDesc`, `orderByRaw`, `latest(column = 'created_at')`, `oldest` | |
52
+ | `groupBy(...columns)`, `having(column, op, value)`, `havingRaw` | |
53
+ | `limit` / `take`, `offset` / `skip`, `forPage(page, perPage)` | |
54
+
55
+ **Reading**
56
+
57
+ | | |
58
+ |---|---|
59
+ | `get()` | Every row |
60
+ | `first()`, `firstOrFail()` | The first row, `undefined` or a 404 `NotFoundException` |
61
+ | `value(column)`, `pluck(column)` | One column of the first row, or of every row |
62
+ | `exists()`, `doesntExist()` | |
63
+ | `count(column?)`, `sum`, `avg`, `min`, `max` | Grouped and distinct queries count their rows |
64
+ | `paginate({ page, perPage })` | `{ data, meta: { total, page, perPage, lastPage, next, prev } }` |
65
+
66
+ **Writing**
67
+
68
+ ```ts
69
+ await DB.table('tags').insert([{ name: 'ts' }, { name: 'node' }]);
70
+ const id = await DB.table('tags').insertGetId({ name: 'orm' });
71
+ const updated = await DB.table('orders').where('status', 'new').update({ status: 'paid' }); // rows changed
72
+ await DB.table('posts').where('id', 1).increment('views');
73
+ await DB.table('carts').where('updated_at', '<', cutoff).delete();
74
+ ```
75
+
76
+ Objects are stored as JSON. A column a row leaves out gets its database
77
+ default, even in a multi-row insert.
78
+
79
+ **Raw SQL and transactions**
80
+
81
+ ```ts
82
+ const rows = await DB.select('select * from users where email = ?', [email]);
83
+ const changed = await DB.statement('update users set active = ? where last_seen < ?', [false, cutoff]);
84
+
85
+ await DB.transaction(async () => {
86
+ await DB.table('accounts').where('id', from).decrement('balance', amount);
87
+ await DB.table('accounts').where('id', to).increment('balance', amount);
88
+ });
89
+ ```
90
+
91
+ `DB.transaction()` is the same transaction as `Model.transaction()`: model
92
+ queries and `DB` queries inside it share it, and nested calls run in a
93
+ savepoint. `toSQL()` on a query returns the SQL and parameters it would run,
94
+ and `clone()` copies a query so you can build on it.
95
+
96
+ ## Raw queries
97
+
98
+ For full control, `Model.db()` returns the Kysely instance underneath (the
99
+ transaction, inside `Model.transaction()`). Type it from your models with
100
+ `DatabaseOf`:
101
+
102
+ ```ts
103
+ import { Model, type DatabaseOf } from '@meghjs/core';
104
+
105
+ type DB = DatabaseOf<typeof User | typeof Post>;
106
+
107
+ const rows = await Model.db<DB>()
108
+ .selectFrom('posts')
109
+ .innerJoin('users', 'users.id', 'posts.user_id')
110
+ .select(['posts.title', 'users.email'])
111
+ .execute(); // { title: string; email: string }[]
112
+ ```
113
+
114
+ The connection is also registered in the container under `ORM_CONNECTION`:
115
+
116
+ ```ts
117
+ import { MeghContainer, ORM_CONNECTION } from '@meghjs/core';
118
+
119
+ const db = MeghContainer.get(ORM_CONNECTION); // Kysely<any>
120
+ ```