@mikro-orm/knex-compat 7.0.0-dev.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,390 @@
1
+ <h1 align="center">
2
+ <a href="https://mikro-orm.io"><img src="https://raw.githubusercontent.com/mikro-orm/mikro-orm/master/docs/static/img/logo-readme.svg?sanitize=true" alt="MikroORM" /></a>
3
+ </h1>
4
+
5
+ TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite (including libSQL) databases.
6
+
7
+ > Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Hibernate](https://hibernate.org/).
8
+
9
+ [![NPM version](https://img.shields.io/npm/v/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)
10
+ [![NPM dev version](https://img.shields.io/npm/v/@mikro-orm/core/next.svg)](https://www.npmjs.com/package/@mikro-orm/core)
11
+ [![Chat on discord](https://img.shields.io/discord/1214904142443839538?label=discord&color=blue)](https://discord.gg/w8bjxFHS7X)
12
+ [![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)
13
+ [![Coverage Status](https://img.shields.io/coveralls/mikro-orm/mikro-orm.svg)](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
14
+ [![Build Status](https://github.com/mikro-orm/mikro-orm/workflows/tests/badge.svg?branch=master)](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
15
+
16
+ ## 🤔 Unit of What?
17
+
18
+ You might be asking: _What the hell is Unit of Work and why should I care about it?_
19
+
20
+ > Unit of Work maintains a list of objects (_entities_) affected by a business transaction
21
+ > and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)
22
+
23
+ > Identity Map ensures that each object (_entity_) gets loaded only once by keeping every
24
+ > loaded object in a map. Looks up objects using the map when referring to them.
25
+ > [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/identityMap.html)
26
+
27
+ So what benefits does it bring to us?
28
+
29
+ ### Implicit Transactions
30
+
31
+ First and most important implication of having Unit of Work is that it allows handling transactions automatically.
32
+
33
+ When you call `em.flush()`, all computed changes are queried inside a database transaction (if supported by given driver). This means that you can control the boundaries of transactions simply by calling `em.persistLater()` and once all your changes are ready, calling `flush()` will run them inside a transaction.
34
+
35
+ > You can also control the transaction boundaries manually via `em.transactional(cb)`.
36
+
37
+ ```typescript
38
+ const user = await em.findOneOrFail(User, 1);
39
+ user.email = 'foo@bar.com';
40
+ const car = new Car();
41
+ user.cars.add(car);
42
+
43
+ // thanks to bi-directional cascading we only need to persist user entity
44
+ // flushing will create a transaction, insert new car and update user with new email
45
+ // as user entity is managed, calling flush() is enough
46
+ await em.flush();
47
+ ```
48
+
49
+ ### ChangeSet based persistence
50
+
51
+ MikroORM allows you to implement your domain/business logic directly in the entities. To maintain always valid entities, you can use constructors to mark required properties. Let's define the `User` entity used in previous example:
52
+
53
+ ```typescript
54
+ @Entity()
55
+ export class User {
56
+
57
+ @PrimaryKey()
58
+ id!: number;
59
+
60
+ @Property()
61
+ name!: string;
62
+
63
+ @OneToOne(() => Address)
64
+ address?: Address;
65
+
66
+ @ManyToMany(() => Car)
67
+ cars = new Collection<Car>(this);
68
+
69
+ constructor(name: string) {
70
+ this.name = name;
71
+ }
72
+
73
+ }
74
+ ```
75
+
76
+ Now to create new instance of the `User` entity, we are forced to provide the `name`:
77
+
78
+ ```typescript
79
+ const user = new User('John Doe'); // name is required to create new user instance
80
+ user.address = new Address('10 Downing Street'); // address is optional
81
+ ```
82
+
83
+ Once your entities are loaded, make a number of synchronous actions on your entities,
84
+ then call `em.flush()`. This will trigger computing of change sets. Only entities
85
+ (and properties) that were changed will generate database queries, if there are no changes,
86
+ no transaction will be started.
87
+
88
+ ```typescript
89
+ const user = await em.findOneOrFail(User, 1, {
90
+ populate: ['cars', 'address.city'],
91
+ });
92
+ user.title = 'Mr.';
93
+ user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity
94
+ user.cars.getItems().forEach(car => car.forSale = true); // cars is 1:m collection of Car entities
95
+ const car = new Car('VW');
96
+ user.cars.add(car);
97
+
98
+ // now we can flush all changes done to managed entities
99
+ await em.flush();
100
+ ```
101
+
102
+ `em.flush()` will then execute these queries from the example above:
103
+
104
+ ```sql
105
+ begin;
106
+ update "user" set "title" = 'Mr.' where "id" = 1;
107
+ update "user_address" set "street" = '10 Downing Street' where "id" = 123;
108
+ update "car"
109
+ set "for_sale" = case
110
+ when ("id" = 1) then true
111
+ when ("id" = 2) then true
112
+ when ("id" = 3) then true
113
+ else "for_sale" end
114
+ where "id" in (1, 2, 3)
115
+ insert into "car" ("brand", "owner") values ('VW', 1);
116
+ commit;
117
+ ```
118
+
119
+ ### Identity Map
120
+
121
+ Thanks to Identity Map, you will always have only one instance of given entity in one context. This allows for some optimizations (skipping loading of already loaded entities), as well as comparison by identity (`ent1 === ent2`).
122
+
123
+ ## 📖 Documentation
124
+
125
+ MikroORM documentation, included in this repo in the root directory, is built with [Docusaurus](https://docusaurus.io) and publicly hosted on GitHub Pages at https://mikro-orm.io.
126
+
127
+ There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
128
+
129
+ ## ✨ Core Features
130
+
131
+ - [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities)
132
+ - [Identity Map](https://mikro-orm.io/docs/identity-map)
133
+ - [Entity References](https://mikro-orm.io/docs/entity-references)
134
+ - [Using Entity Constructors](https://mikro-orm.io/docs/entity-constructors)
135
+ - [Modelling Relationships](https://mikro-orm.io/docs/relationships)
136
+ - [Collections](https://mikro-orm.io/docs/collections)
137
+ - [Unit of Work](https://mikro-orm.io/docs/unit-of-work)
138
+ - [Transactions](https://mikro-orm.io/docs/transactions)
139
+ - [Cascading persist and remove](https://mikro-orm.io/docs/cascading)
140
+ - [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
141
+ - [Filters](https://mikro-orm.io/docs/filters)
142
+ - [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
143
+ - [Populating relations](https://mikro-orm.io/docs/populating-relations)
144
+ - [Property Validation](https://mikro-orm.io/docs/property-validation)
145
+ - [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
146
+ - [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
147
+ - [Schema Generator](https://mikro-orm.io/docs/schema-generator)
148
+ - [Entity Generator](https://mikro-orm.io/docs/entity-generator)
149
+
150
+ ## 📦 Example Integrations
151
+
152
+ You can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples):
153
+
154
+ ### TypeScript Examples
155
+
156
+ - [Express + MongoDB](https://github.com/mikro-orm/express-ts-example-app)
157
+ - [Nest + MySQL](https://github.com/mikro-orm/nestjs-example-app)
158
+ - [RealWorld example app (Nest + MySQL)](https://github.com/mikro-orm/nestjs-realworld-example-app)
159
+ - [Koa + SQLite](https://github.com/mikro-orm/koa-ts-example-app)
160
+ - [GraphQL + PostgreSQL](https://github.com/driescroons/mikro-orm-graphql-example)
161
+ - [Inversify + PostgreSQL](https://github.com/PodaruDragos/inversify-example-app)
162
+ - [NextJS + MySQL](https://github.com/jonahallibone/mikro-orm-nextjs)
163
+ - [Accounts.js REST and GraphQL authentication + SQLite](https://github.com/darkbasic/mikro-orm-accounts-example)
164
+ - [Nest + Shopify + PostgreSQL + GraphQL](https://github.com/Cloudshelf/Shopify_CSConnector)
165
+ - [Elysia.js + libSQL + Bun](https://github.com/mikro-orm/elysia-bun-example-app)
166
+ - [Electron.js + PostgreSQL](https://github.com/adnanlah/electron-mikro-orm-example-app)
167
+
168
+ ### JavaScript Examples
169
+
170
+ - [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)
171
+
172
+ ## 🚀 Quick Start
173
+
174
+ First install the module via `yarn` or `npm` and do not forget to install the database driver as well:
175
+
176
+ > Since v4, you should install the driver package, but not the db connector itself, e.g. install `@mikro-orm/sqlite`, but not `sqlite3` as that is already included in the driver package.
177
+
178
+ ```sh
179
+ yarn add @mikro-orm/core @mikro-orm/mongodb # for mongo
180
+ yarn add @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
181
+ yarn add @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
182
+ yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql
183
+ yarn add @mikro-orm/core @mikro-orm/mssql # for mssql
184
+ yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite
185
+ yarn add @mikro-orm/core @mikro-orm/libsql # for libsql
186
+ ```
187
+
188
+ or
189
+
190
+ ```sh
191
+ npm i -s @mikro-orm/core @mikro-orm/mongodb # for mongo
192
+ npm i -s @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
193
+ npm i -s @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
194
+ npm i -s @mikro-orm/core @mikro-orm/postgresql # for postgresql
195
+ npm i -s @mikro-orm/core @mikro-orm/mssql # for mssql
196
+ npm i -s @mikro-orm/core @mikro-orm/sqlite # for sqlite
197
+ npm i -s @mikro-orm/core @mikro-orm/libsql # for libsql
198
+ ```
199
+
200
+ Next, if you want to use decorators for your entity definition, you will need to enable support for [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) as well as `esModuleInterop` in `tsconfig.json` via:
201
+
202
+ ```json
203
+ "experimentalDecorators": true,
204
+ "emitDecoratorMetadata": true,
205
+ "esModuleInterop": true,
206
+ ```
207
+
208
+ Alternatively, you can use [`EntitySchema`](https://mikro-orm.io/docs/entity-schema).
209
+
210
+ Then call `MikroORM.init` as part of bootstrapping your app:
211
+
212
+ > To access driver specific methods like `em.createQueryBuilder()` we need to specify the driver type when calling `MikroORM.init()`. Alternatively we can cast the `orm.em` to `EntityManager` exported from the driver package:
213
+ >
214
+ > ```ts
215
+ > import { EntityManager } from '@mikro-orm/postgresql';
216
+ > const em = orm.em as EntityManager;
217
+ > const qb = em.createQueryBuilder(...);
218
+ > ```
219
+
220
+ ```typescript
221
+ import type { PostgreSqlDriver } from '@mikro-orm/postgresql'; // or any other SQL driver package
222
+
223
+ const orm = await MikroORM.init<PostgreSqlDriver>({
224
+ entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir`
225
+ dbName: 'my-db-name',
226
+ type: 'postgresql',
227
+ });
228
+ console.log(orm.em); // access EntityManager via `em` property
229
+ ```
230
+
231
+ There are more ways to configure your entities, take a look at [installation page](https://mikro-orm.io/docs/installation/).
232
+
233
+ > Read more about all the possible configuration options in [Advanced Configuration](https://mikro-orm.io/docs/configuration) section.
234
+
235
+ Then you will need to fork entity manager for each request so their [identity maps](https://mikro-orm.io/docs/identity-map/) will not collide. To do so, use the `RequestContext` helper:
236
+
237
+ ```typescript
238
+ const app = express();
239
+
240
+ app.use((req, res, next) => {
241
+ RequestContext.create(orm.em, next);
242
+ });
243
+ ```
244
+
245
+ > You should register this middleware as the last one just before request handlers and before any of your custom middleware that is using the ORM. There might be issues when you register it before request processing middleware like `queryParser` or `bodyParser`, so definitely register the context after them.
246
+
247
+ More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
248
+
249
+ Now you can start defining your entities (in one of the `entities` folders). This is how simple entity can look like in mongo driver:
250
+
251
+ **`./entities/MongoBook.ts`**
252
+
253
+ ```typescript
254
+ @Entity()
255
+ export class MongoBook {
256
+
257
+ @PrimaryKey()
258
+ _id: ObjectID;
259
+
260
+ @SerializedPrimaryKey()
261
+ id: string;
262
+
263
+ @Property()
264
+ title: string;
265
+
266
+ @ManyToOne(() => Author)
267
+ author: Author;
268
+
269
+ @ManyToMany(() => BookTag)
270
+ tags = new Collection<BookTag>(this);
271
+
272
+ constructor(title: string, author: Author) {
273
+ this.title = title;
274
+ this.author = author;
275
+ }
276
+
277
+ }
278
+ ```
279
+
280
+ For SQL drivers, you can use `id: number` PK:
281
+
282
+ **`./entities/SqlBook.ts`**
283
+
284
+ ```typescript
285
+ @Entity()
286
+ export class SqlBook {
287
+
288
+ @PrimaryKey()
289
+ id: number;
290
+
291
+ }
292
+ ```
293
+
294
+ Or if you want to use UUID primary keys:
295
+
296
+ **`./entities/UuidBook.ts`**
297
+
298
+ ```typescript
299
+ import { randomUUID } from 'node:crypto';
300
+
301
+ @Entity()
302
+ export class UuidBook {
303
+
304
+ @PrimaryKey()
305
+ uuid = randomUUID();
306
+
307
+ }
308
+ ```
309
+
310
+ More information can be found in [defining entities section](https://mikro-orm.io/docs/defining-entities/) in docs.
311
+
312
+ When you have your entities defined, you can start using ORM either via `EntityManager` or via `EntityRepository`s.
313
+
314
+ To save entity state to database, you need to persist it. Persist takes care or deciding whether to use `insert` or `update` and computes appropriate change-set. Entity references that are not persisted yet (does not have identifier) will be cascade persisted automatically.
315
+
316
+ ```typescript
317
+ // use constructors in your entities for required parameters
318
+ const author = new Author('Jon Snow', 'snow@wall.st');
319
+ author.born = new Date();
320
+
321
+ const publisher = new Publisher('7K publisher');
322
+
323
+ const book1 = new Book('My Life on The Wall, part 1', author);
324
+ book1.publisher = publisher;
325
+ const book2 = new Book('My Life on The Wall, part 2', author);
326
+ book2.publisher = publisher;
327
+ const book3 = new Book('My Life on The Wall, part 3', author);
328
+ book3.publisher = publisher;
329
+
330
+ // just persist books, author and publisher will be automatically cascade persisted
331
+ await em.persistAndFlush([book1, book2, book3]);
332
+ ```
333
+
334
+ To fetch entities from database you can use `find()` and `findOne()` of `EntityManager`:
335
+
336
+ ```typescript
337
+ const authors = em.find(Author, {}, { populate: ['books'] });
338
+
339
+ for (const author of authors) {
340
+ console.log(author); // instance of Author entity
341
+ console.log(author.name); // Jon Snow
342
+
343
+ for (const book of author.books) { // iterating books collection
344
+ console.log(book); // instance of Book entity
345
+ console.log(book.title); // My Life on The Wall, part 1/2/3
346
+ }
347
+ }
348
+ ```
349
+
350
+ More convenient way of fetching entities from database is by using `EntityRepository`, that carries the entity name, so you do not have to pass it to every `find` and `findOne` calls:
351
+
352
+ ```typescript
353
+ const booksRepository = em.getRepository(Book);
354
+
355
+ const books = await booksRepository.find({ author: '...' }, {
356
+ populate: ['author'],
357
+ limit: 1,
358
+ offset: 2,
359
+ orderBy: { title: QueryOrder.DESC },
360
+ });
361
+
362
+ console.log(books); // Loaded<Book, 'author'>[]
363
+ ```
364
+
365
+ Take a look at docs about [working with `EntityManager`](https://mikro-orm.io/docs/entity-manager/) or [using `EntityRepository` instead](https://mikro-orm.io/docs/repositories/).
366
+
367
+ ## 🤝 Contributing
368
+
369
+ Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.
370
+
371
+ ## Authors
372
+
373
+ 👤 **Martin Adámek**
374
+
375
+ - Twitter: [@B4nan](https://twitter.com/B4nan)
376
+ - Github: [@b4nan](https://github.com/b4nan)
377
+
378
+ See also the list of contributors who [participated](https://github.com/mikro-orm/mikro-orm/contributors) in this project.
379
+
380
+ ## Show Your Support
381
+
382
+ Please ⭐️ this repository if this project helped you!
383
+
384
+ > If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
385
+
386
+ ## 📝 License
387
+
388
+ Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
389
+
390
+ This project is licensed under the MIT License - see the [LICENSE file](LICENSE) for details.
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { rawKnex as raw } from './raw.js';
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export { rawKnex as raw } from './raw.js';
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@mikro-orm/knex-compat",
3
+ "version": "7.0.0-dev.97",
4
+ "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
+ "type": "module",
6
+ "exports": {
7
+ "./package.json": "./package.json",
8
+ ".": "./index.js"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+ssh://git@github.com/mikro-orm/mikro-orm.git"
13
+ },
14
+ "keywords": [
15
+ "orm",
16
+ "mongo",
17
+ "mongodb",
18
+ "mysql",
19
+ "mariadb",
20
+ "postgresql",
21
+ "sqlite",
22
+ "sqlite3",
23
+ "ts",
24
+ "typescript",
25
+ "js",
26
+ "javascript",
27
+ "entity",
28
+ "ddd",
29
+ "mikro-orm",
30
+ "unit-of-work",
31
+ "data-mapper",
32
+ "identity-map"
33
+ ],
34
+ "author": "Martin Adámek",
35
+ "license": "MIT",
36
+ "bugs": {
37
+ "url": "https://github.com/mikro-orm/mikro-orm/issues"
38
+ },
39
+ "homepage": "https://mikro-orm.io",
40
+ "engines": {
41
+ "node": ">= 22.17.0"
42
+ },
43
+ "scripts": {
44
+ "build": "yarn clean && yarn compile && yarn copy",
45
+ "clean": "yarn run -T rimraf ./dist",
46
+ "compile": "yarn run -T tsc -p tsconfig.build.json",
47
+ "copy": "node ../../scripts/copy.mjs"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "devDependencies": {
53
+ "@mikro-orm/sql": "^6.6.2"
54
+ },
55
+ "peerDependencies": {
56
+ "@mikro-orm/sql": "7.0.0-dev.97",
57
+ "knex": "^3.0.0"
58
+ }
59
+ }
package/raw.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { type AnyString, type Dictionary, type EntityKey, type RawQueryFragment, type QueryBuilder } from '@mikro-orm/sql';
2
+ import type { Knex } from 'knex';
3
+ /**
4
+ * Creates raw SQL query fragment that can be assigned to a property or part of a filter. This fragment is represented
5
+ * by `RawQueryFragment` class instance that can be serialized to a string, so it can be used both as an object value
6
+ * and key. When serialized, the fragment key gets cached and only such cached key will be recognized by the ORM.
7
+ * This adds a runtime safety to the raw query fragments.
8
+ *
9
+ * > **`raw()` helper is required since v6 to use a raw fragment in your query, both through EntityManager and QueryBuilder.**
10
+ *
11
+ * ```ts
12
+ * // as a value
13
+ * await em.find(User, { time: raw('now()') });
14
+ *
15
+ * // as a key
16
+ * await em.find(User, { [raw('lower(name)')]: name.toLowerCase() });
17
+ *
18
+ * // value can be empty array
19
+ * await em.find(User, { [raw('(select 1 = 1)')]: [] });
20
+ * ```
21
+ *
22
+ * The `raw` helper supports several signatures, you can pass in a callback that receives the current property alias:
23
+ *
24
+ * ```ts
25
+ * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
26
+ * ```
27
+ *
28
+ * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
29
+ *
30
+ * ```ts
31
+ * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
32
+ * ```
33
+ *
34
+ * When using inside filters, you might have to use a callback signature to create new raw instance for every filter usage.
35
+ *
36
+ * ```ts
37
+ * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
38
+ * ```
39
+ *
40
+ * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use:
41
+ *
42
+ * ```ts
43
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country")
44
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`)
45
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) })
46
+ * @Entity({ schema: 'library' })
47
+ * export class Author { ... }
48
+ * ```
49
+ *
50
+ * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax:
51
+ *
52
+ * ```ts
53
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
54
+ * @Entity({ schema: 'library' })
55
+ * export class Author { ... }
56
+ * ```
57
+ */
58
+ export declare function rawKnex<T extends object = any, R = any>(sql: Knex.QueryBuilder | Knex.Raw | QueryBuilder<T> | EntityKey<T> | EntityKey<T>[] | AnyString | ((alias: string) => string) | RawQueryFragment, params?: readonly unknown[] | Dictionary<unknown>): NoInfer<R>;
package/raw.js ADDED
@@ -0,0 +1,63 @@
1
+ import { raw, Utils } from '@mikro-orm/sql';
2
+ /**
3
+ * Creates raw SQL query fragment that can be assigned to a property or part of a filter. This fragment is represented
4
+ * by `RawQueryFragment` class instance that can be serialized to a string, so it can be used both as an object value
5
+ * and key. When serialized, the fragment key gets cached and only such cached key will be recognized by the ORM.
6
+ * This adds a runtime safety to the raw query fragments.
7
+ *
8
+ * > **`raw()` helper is required since v6 to use a raw fragment in your query, both through EntityManager and QueryBuilder.**
9
+ *
10
+ * ```ts
11
+ * // as a value
12
+ * await em.find(User, { time: raw('now()') });
13
+ *
14
+ * // as a key
15
+ * await em.find(User, { [raw('lower(name)')]: name.toLowerCase() });
16
+ *
17
+ * // value can be empty array
18
+ * await em.find(User, { [raw('(select 1 = 1)')]: [] });
19
+ * ```
20
+ *
21
+ * The `raw` helper supports several signatures, you can pass in a callback that receives the current property alias:
22
+ *
23
+ * ```ts
24
+ * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
25
+ * ```
26
+ *
27
+ * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
28
+ *
29
+ * ```ts
30
+ * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
31
+ * ```
32
+ *
33
+ * When using inside filters, you might have to use a callback signature to create new raw instance for every filter usage.
34
+ *
35
+ * ```ts
36
+ * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
37
+ * ```
38
+ *
39
+ * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use:
40
+ *
41
+ * ```ts
42
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country")
43
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`)
44
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) })
45
+ * @Entity({ schema: 'library' })
46
+ * export class Author { ... }
47
+ * ```
48
+ *
49
+ * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax:
50
+ *
51
+ * ```ts
52
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
53
+ * @Entity({ schema: 'library' })
54
+ * export class Author { ... }
55
+ * ```
56
+ */
57
+ export function rawKnex(sql, params) {
58
+ if (Utils.isObject(sql) && 'toSQL' in sql) {
59
+ const query = sql.toSQL();
60
+ return raw(query.sql, query.bindings);
61
+ }
62
+ return raw(sql, params);
63
+ }