@mikro-orm/knex 6.0.0-dev.45 → 6.0.0-dev.47

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.
@@ -77,6 +77,7 @@ class AbstractSqlConnection extends core_1.Connection {
77
77
  }
78
78
  }
79
79
  async execute(queryOrKnex, params = [], method = 'all', ctx) {
80
+ await this.ensureConnection();
80
81
  if (core_1.Utils.isObject(queryOrKnex)) {
81
82
  ctx ??= (queryOrKnex.client.transacting ? queryOrKnex : null);
82
83
  const q = queryOrKnex.toSQL();
@@ -177,5 +178,5 @@ class AbstractSqlConnection extends core_1.Connection {
177
178
  };
178
179
  }
179
180
  }
180
- exports.AbstractSqlConnection = AbstractSqlConnection;
181
181
  AbstractSqlConnection.__patched = false;
182
+ exports.AbstractSqlConnection = AbstractSqlConnection;
@@ -124,7 +124,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
124
124
  qb.where(where);
125
125
  const kqb = qb.getKnexQuery().clear('select');
126
126
  if (type === query_1.QueryType.COUNT) {
127
- kqb.select(qb.raw('count(*) as count'));
127
+ kqb.select(this.connection.getKnex().raw('count(*) as count'));
128
128
  }
129
129
  else { // select
130
130
  kqb.select('*');
@@ -255,8 +255,12 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
255
255
  const set = new Set();
256
256
  data.forEach(row => core_1.Utils.keys(row).forEach(k => set.add(k)));
257
257
  const props = [...set].map(name => meta?.properties[name] ?? { name, fieldNames: [name] });
258
- const fields = core_1.Utils.flatten(props.map(prop => prop.fieldNames));
258
+ let fields = core_1.Utils.flatten(props.map(prop => prop.fieldNames));
259
+ const duplicates = core_1.Utils.findDuplicates(fields);
259
260
  const params = [];
261
+ if (duplicates.length) {
262
+ fields = core_1.Utils.unique(fields);
263
+ }
260
264
  /* istanbul ignore next */
261
265
  const tableName = meta ? this.getTableName(meta, options) : this.platform.quoteIdentifier(entityName);
262
266
  let sql = `insert into ${tableName} `;
@@ -279,8 +283,16 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
279
283
  const keys = [];
280
284
  props.forEach(prop => {
281
285
  if (prop.fieldNames.length > 1) {
282
- params.push(...(row[prop.name] ?? prop.fieldNames.map(() => null)));
283
- keys.push(...(row[prop.name] ?? prop.fieldNames).map(() => '?'));
286
+ const param = row[prop.name] ?? prop.fieldNames.map(() => null);
287
+ const key = (row[prop.name] ?? prop.fieldNames).map(() => '?');
288
+ prop.fieldNames.forEach((field, idx) => {
289
+ if (duplicates.includes(field)) {
290
+ param.splice(idx, 1);
291
+ key.splice(idx, 1);
292
+ }
293
+ });
294
+ params.push(...param);
295
+ keys.push(...key);
284
296
  }
285
297
  else if (prop.customType && 'convertToDatabaseValueSQL' in prop.customType && !this.platform.isRaw(row[prop.name])) {
286
298
  keys.push(prop.customType.convertToDatabaseValueSQL('?', this.platform));
@@ -294,9 +306,10 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
294
306
  return '(' + (keys.join(', ') || 'default') + ')';
295
307
  }).join(', ');
296
308
  }
297
- if (this.platform.usesReturningStatement()) {
298
- /* istanbul ignore next */
299
- const returningProps = meta.hydrateProps.filter(prop => prop.persist !== false && (prop.primary || prop.defaultRaw));
309
+ if (meta && this.platform.usesReturningStatement()) {
310
+ const returningProps = meta.hydrateProps
311
+ .filter(prop => prop.persist !== false && ((prop.primary && prop.autoincrement) || prop.defaultRaw))
312
+ .filter(prop => !(prop.name in data[0]) || core_1.Utils.isRawSql(data[0][prop.name]));
300
313
  const returningFields = core_1.Utils.flatten(returningProps.map(prop => prop.fieldNames));
301
314
  /* istanbul ignore next */
302
315
  sql += returningFields.length > 0 ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}` : '';
@@ -363,7 +376,15 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
363
376
  }
364
377
  const collections = options.processCollections ? data.map(d => this.extractManyToMany(entityName, d)) : [];
365
378
  const keys = new Set();
366
- data.forEach(row => core_1.Utils.keys(row).forEach(k => keys.add(k)));
379
+ const returning = new Set();
380
+ data.forEach(row => {
381
+ core_1.Utils.keys(row).forEach(k => {
382
+ keys.add(k);
383
+ if (core_1.Utils.isRawSql(row[k])) {
384
+ returning.add(k);
385
+ }
386
+ });
387
+ });
367
388
  const pkCond = core_1.Utils.flatten(meta.primaryKeys.map(pk => meta.properties[pk].fieldNames)).map(pk => `${this.platform.quoteIdentifier(pk)} = ?`).join(' and ');
368
389
  const params = [];
369
390
  let sql = `update ${this.getTableName(meta, options)} set `;
@@ -423,6 +444,11 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
423
444
  return '?';
424
445
  });
425
446
  sql += ` in (${conds.join(', ')})`;
447
+ if (this.platform.usesReturningStatement() && returning.size > 0) {
448
+ const returningFields = core_1.Utils.flatten([...returning].map(prop => meta.properties[prop].fieldNames));
449
+ /* istanbul ignore next */
450
+ sql += returningFields.length > 0 ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}` : '';
451
+ }
426
452
  const res = await this.rethrow(this.execute(sql, params, 'run', options.ctx));
427
453
  for (let i = 0; i < collections.length; i++) {
428
454
  await this.processManyToMany(meta, where[i], collections[i], false, options);
@@ -612,7 +638,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
612
638
  const aliased = qb.ref(tableAlias ? `${tableAlias}__${prop.fieldNames[0]}` : prop.fieldNames[0]).toString();
613
639
  if (prop.customType?.convertToJSValueSQL && tableAlias) {
614
640
  const prefixed = qb.ref(prop.fieldNames[0]).withSchema(tableAlias).toString();
615
- return [qb.raw(prop.customType.convertToJSValueSQL(prefixed, this.platform) + ' as ' + aliased).toString()];
641
+ return [prop.customType.convertToJSValueSQL(prefixed, this.platform) + ' as ' + aliased];
616
642
  }
617
643
  if (prop.formula) {
618
644
  const alias = qb.ref(tableAlias ?? qb.alias).toString();
@@ -27,6 +27,9 @@ class AbstractSqlPlatform extends core_1.Platform {
27
27
  return new schema_1.SqlSchemaGenerator(em ?? driver);
28
28
  }
29
29
  quoteValue(value) {
30
+ if (core_1.Utils.isRawSql(value)) {
31
+ return this.formatQuery(value.sql, value.params ?? []);
32
+ }
30
33
  if (this.isRaw(value)) {
31
34
  return value;
32
35
  }
package/README.md CHANGED
@@ -2,9 +2,7 @@
2
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
3
  </h1>
4
4
 
5
- TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/)
6
- and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL,
7
- MariaDB, PostgreSQL and SQLite databases.
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 databases.
8
6
 
9
7
  > Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Nextras Orm](https://nextras.org/orm/).
10
8
 
@@ -31,13 +29,9 @@ So what benefits does it bring to us?
31
29
 
32
30
  ### Implicit Transactions
33
31
 
34
- First and most important implication of having Unit of Work is that it allows handling
35
- transactions automatically.
32
+ First and most important implication of having Unit of Work is that it allows handling transactions automatically.
36
33
 
37
- When you call `em.flush()`, all computed changes are queried inside a database
38
- transaction (if supported by given driver). This means that you can control the boundaries
39
- of transactions simply by calling `em.persistLater()` and once all your changes
40
- are ready, calling `flush()` will run them inside a transaction.
34
+ 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.
41
35
 
42
36
  > You can also control the transaction boundaries manually via `em.transactional(cb)`.
43
37
 
@@ -55,9 +49,7 @@ await em.flush();
55
49
 
56
50
  ### ChangeSet based persistence
57
51
 
58
- MikroORM allows you to implement your domain/business logic directly in the entities.
59
- To maintain always valid entities, you can use constructors to mark required properties.
60
- Let's define the `User` entity used in previous example:
52
+ 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:
61
53
 
62
54
  ```typescript
63
55
  @Entity()
@@ -69,10 +61,10 @@ export class User {
69
61
  @Property()
70
62
  name!: string;
71
63
 
72
- @OneToOne()
64
+ @OneToOne(() => Address)
73
65
  address?: Address;
74
66
 
75
- @ManyToMany()
67
+ @ManyToMany(() => Car)
76
68
  cars = new Collection<Car>(this);
77
69
 
78
70
  constructor(name: string) {
@@ -95,7 +87,9 @@ then call `em.flush()`. This will trigger computing of change sets. Only entitie
95
87
  no transaction will be started.
96
88
 
97
89
  ```typescript
98
- const user = await em.findOneOrFail(User, 1, ['cars', 'address']);
90
+ const user = await em.findOneOrFail(User, 1, {
91
+ populate: ['cars', 'address.city'],
92
+ });
99
93
  user.title = 'Mr.';
100
94
  user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity
101
95
  user.cars.getItems().forEach(car => car.forSale = true); // cars is 1:m collection of Car entities
@@ -110,53 +104,49 @@ await em.flush();
110
104
 
111
105
  ```sql
112
106
  begin;
113
- update user set title = 'Mr.' where id = 1;
114
- update user_address set street = '10 Downing Street' where id = 123;
115
- update car set for_sale = true where id = 1;
116
- update car set for_sale = true where id = 2;
117
- update car set for_sale = true where id = 3;
118
- insert into car (brand, owner) values ('VW', 1);
107
+ update "user" set "title" = 'Mr.' where "id" = 1;
108
+ update "user_address" set "street" = '10 Downing Street' where "id" = 123;
109
+ update "car"
110
+ set "for_sale" = case
111
+ when ("id" = 1) then true
112
+ when ("id" = 2) then true
113
+ when ("id" = 3) then true
114
+ else "for_sale" end
115
+ where "id" in (1, 2, 3)
116
+ insert into "car" ("brand", "owner") values ('VW', 1);
119
117
  commit;
120
118
  ```
121
119
 
122
- ### Only One Instance of Entity
120
+ ### Identity Map
123
121
 
124
- Thanks to Identity Map, you will always have only one instance of given entity in one context.
125
- This allows for some optimizations (skipping loading of already loaded entities), as well as
126
- comparison by identity (`ent1 === ent2`).
122
+ 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`).
127
123
 
128
124
  ## 📖 Documentation
129
125
 
130
- MikroORM v4 documentation, included in this repo in the root directory, is built with
131
- [Jekyll](https://jekyllrb.com/) and publicly hosted on GitHub Pages at https://mikro-orm.io.
132
-
133
- There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages
134
- (via `semantic-release`).
126
+ 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.
135
127
 
136
- > You can browse MikroORM v3 docs at [https://mikro-orm.io/docs/3.6/installation](https://mikro-orm.io/docs/3.6/installation).
137
-
138
- > To upgrade to v4, please see the [upgrading guide](https://mikro-orm.io/docs/upgrading-v3-to-v4).
128
+ There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
139
129
 
140
130
  ## ✨ Core Features
141
131
 
142
- - [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities/)
143
- - [Identity Map](https://mikro-orm.io/docs/identity-map/)
144
- - [Entity References](https://mikro-orm.io/docs/entity-references/)
145
- - [Using Entity Constructors](https://mikro-orm.io/docs/using-entity-constructors/)
146
- - [Modelling Relationships](https://mikro-orm.io/docs/relationships/)
147
- - [Collections](https://mikro-orm.io/docs/collections/)
148
- - [Unit of Work](https://mikro-orm.io/docs/unit-of-work/)
149
- - [Transactions](https://mikro-orm.io/docs/transactions/)
150
- - [Cascading persist and remove](https://mikro-orm.io/docs/cascading/)
151
- - [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys/)
152
- - [Filters](https://mikro-orm.io/docs/filters/)
153
- - [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder/)
154
- - [Preloading Deeply Nested Structures via populate](https://mikro-orm.io/docs/nested-populate/)
155
- - [Property Validation](https://mikro-orm.io/docs/property-validation/)
156
- - [Lifecycle Hooks](https://mikro-orm.io/docs/lifecycle-hooks/)
157
- - [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js/)
158
- - [Schema Generator](https://mikro-orm.io/docs/schema-generator/)
159
- - [Entity Generator](https://mikro-orm.io/docs/entity-generator/)
132
+ - [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities)
133
+ - [Identity Map](https://mikro-orm.io/docs/identity-map)
134
+ - [Entity References](https://mikro-orm.io/docs/entity-references)
135
+ - [Using Entity Constructors](https://mikro-orm.io/docs/entity-constructors)
136
+ - [Modelling Relationships](https://mikro-orm.io/docs/relationships)
137
+ - [Collections](https://mikro-orm.io/docs/collections)
138
+ - [Unit of Work](https://mikro-orm.io/docs/unit-of-work)
139
+ - [Transactions](https://mikro-orm.io/docs/transactions)
140
+ - [Cascading persist and remove](https://mikro-orm.io/docs/cascading)
141
+ - [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
142
+ - [Filters](https://mikro-orm.io/docs/filters)
143
+ - [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
144
+ - [Preloading Deeply Nested Structures via populate](https://mikro-orm.io/docs/nested-populate)
145
+ - [Property Validation](https://mikro-orm.io/docs/property-validation)
146
+ - [Lifecycle Hooks](https://mikro-orm.io/docs/lifecycle-hooks)
147
+ - [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
148
+ - [Schema Generator](https://mikro-orm.io/docs/schema-generator)
149
+ - [Entity Generator](https://mikro-orm.io/docs/entity-generator)
160
150
 
161
151
  ## 📦 Example Integrations
162
152
 
@@ -173,27 +163,14 @@ You can find example integrations for some popular frameworks in the [`mikro-orm
173
163
  - [NextJS + MySQL](https://github.com/jonahallibone/mikro-orm-nextjs)
174
164
 
175
165
  ### JavaScript Examples
176
- - [Express + MongoDB](https://github.com/mikro-orm/express-js-example-app)
177
166
 
178
- ## Articles
179
-
180
- - Introducing MikroORM, TypeScript data-mapper ORM with Identity Map
181
- - on [medium.com](https://medium.com/dailyjs/introducing-mikro-orm-typescript-data-mapper-orm-with-identity-map-9ba58d049e02)
182
- - on [dev.to](https://dev.to/b4nan/introducing-mikroorm-typescript-data-mapper-orm-with-identity-map-pc8)
183
- - Handling transactions and concurrency in MikroORM
184
- - on [medium.com](https://medium.com/dailyjs/handling-transactions-and-concurrency-in-mikro-orm-ba80d0a65805)
185
- - on [dev.to](https://dev.to/b4nan/handling-transactions-and-concurrency-in-mikroorm-2cfj)
186
- - MikroORM 3: Knex.js, CLI, Schema Updates, Entity Generator and more…
187
- - on [medium.com](https://medium.com/dailyjs/mikro-orm-3-knex-js-cli-schema-updates-entity-generator-and-more-e51ecbbc508c)
188
- - on [dev.to](https://dev.to/b4nan/mikroorm-3-knex-js-cli-schema-updates-entity-generator-and-more-3g56)
167
+ - [Express + MongoDB](https://github.com/mikro-orm/express-js-example-app)
189
168
 
190
169
  ## 🚀 Quick Start
191
170
 
192
171
  First install the module via `yarn` or `npm` and do not forget to install the database driver as well:
193
172
 
194
- > Since v4, you should install the driver package, but not the db connector itself,
195
- > e.g. install `@mikro-orm/sqlite`, but not `sqlite3` as that is already included
196
- > in the driver package.
173
+ > 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.
197
174
 
198
175
  ```sh
199
176
  yarn add @mikro-orm/core @mikro-orm/mongodb # for mongo
@@ -213,8 +190,7 @@ npm i -s @mikro-orm/core @mikro-orm/postgresql # for postgresql
213
190
  npm i -s @mikro-orm/core @mikro-orm/sqlite # for sqlite
214
191
  ```
215
192
 
216
- Next you will need to enable support for [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html)
217
- as well as `esModuleInterop` in `tsconfig.json` via:
193
+ 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:
218
194
 
219
195
  ```json
220
196
  "experimentalDecorators": true,
@@ -222,11 +198,11 @@ as well as `esModuleInterop` in `tsconfig.json` via:
222
198
  "esModuleInterop": true,
223
199
  ```
224
200
 
201
+ Alternatively, you can use [`EntitySchema`](https://mikro-orm.io/docs/entity-schema).
202
+
225
203
  Then call `MikroORM.init` as part of bootstrapping your app:
226
204
 
227
- > To access driver specific methods like `em.createQueryBuilder()` we need to specify
228
- > the driver type when calling `MikroORM.init()`. Alternatively we can cast the
229
- > `orm.em` to `EntityManager` exported from the driver package:
205
+ > 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:
230
206
  >
231
207
  > ```ts
232
208
  > import { EntityManager } from '@mikro-orm/postgresql';
@@ -245,14 +221,11 @@ const orm = await MikroORM.init<PostgreSqlDriver>({
245
221
  console.log(orm.em); // access EntityManager via `em` property
246
222
  ```
247
223
 
248
- There are more ways to configure your entities, take a look at
249
- [installation page](https://mikro-orm.io/docs/installation/).
224
+ There are more ways to configure your entities, take a look at [installation page](https://mikro-orm.io/docs/installation/).
250
225
 
251
226
  > Read more about all the possible configuration options in [Advanced Configuration](https://mikro-orm.io/docs/configuration) section.
252
227
 
253
- Then you will need to fork entity manager for each request so their
254
- [identity maps](https://mikro-orm.io/docs/identity-map/) will not collide.
255
- To do so, use the `RequestContext` helper:
228
+ 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:
256
229
 
257
230
  ```typescript
258
231
  const app = express();
@@ -262,15 +235,11 @@ app.use((req, res, next) => {
262
235
  });
263
236
  ```
264
237
 
265
- > You should register this middleware as the last one just before request handlers and before
266
- > any of your custom middleware that is using the ORM. There might be issues when you register
267
- > it before request processing middleware like `queryParser` or `bodyParser`, so definitely
268
- > register the context after them.
238
+ > 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.
269
239
 
270
240
  More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
271
241
 
272
- Now you can start defining your entities (in one of the `entities` folders). This is how
273
- simple entity can look like in mongo driver:
242
+ Now you can start defining your entities (in one of the `entities` folders). This is how simple entity can look like in mongo driver:
274
243
 
275
244
  **`./entities/MongoBook.ts`**
276
245
 
@@ -287,10 +256,10 @@ export class MongoBook {
287
256
  @Property()
288
257
  title: string;
289
258
 
290
- @ManyToOne()
259
+ @ManyToOne(() => Author)
291
260
  author: Author;
292
261
 
293
- @ManyToMany()
262
+ @ManyToMany(() => BookTag)
294
263
  tags = new Collection<BookTag>(this);
295
264
 
296
265
  constructor(title: string, author: Author) {
@@ -331,15 +300,11 @@ export class UuidBook {
331
300
  }
332
301
  ```
333
302
 
334
- More information can be found in
335
- [defining entities section](https://mikro-orm.io/docs/defining-entities/) in docs.
303
+ More information can be found in [defining entities section](https://mikro-orm.io/docs/defining-entities/) in docs.
336
304
 
337
- When you have your entities defined, you can start using ORM either via `EntityManager`
338
- or via `EntityRepository`s.
305
+ When you have your entities defined, you can start using ORM either via `EntityManager` or via `EntityRepository`s.
339
306
 
340
- To save entity state to database, you need to persist it. Persist takes care or deciding
341
- whether to use `insert` or `update` and computes appropriate change-set. Entity references
342
- that are not persisted yet (does not have identifier) will be cascade persisted automatically.
307
+ 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.
343
308
 
344
309
  ```typescript
345
310
  // use constructors in your entities for required parameters
@@ -356,13 +321,13 @@ const book3 = new Book('My Life on The Wall, part 3', author);
356
321
  book3.publisher = publisher;
357
322
 
358
323
  // just persist books, author and publisher will be automatically cascade persisted
359
- await orm.em.persistAndFlush([book1, book2, book3]);
324
+ await em.persistAndFlush([book1, book2, book3]);
360
325
  ```
361
326
 
362
327
  To fetch entities from database you can use `find()` and `findOne()` of `EntityManager`:
363
328
 
364
329
  ```typescript
365
- const authors = orm.em.find(Author, {});
330
+ const authors = em.find(Author, {}, { populate: ['books'] });
366
331
 
367
332
  for (const author of authors) {
368
333
  console.log(author); // instance of Author entity
@@ -375,16 +340,11 @@ for (const author of authors) {
375
340
  }
376
341
  ```
377
342
 
378
- More convenient way of fetching entities from database is by using `EntityRepository`, that
379
- carries the entity name so you do not have to pass it to every `find` and `findOne` calls:
343
+ 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:
380
344
 
381
345
  ```typescript
382
- const booksRepository = orm.em.getRepository(Book);
383
-
384
- // with sorting, limit and offset parameters, populating author references
385
- const books = await booksRepository.find({ author: '...' }, ['author'], { title: QueryOrder.DESC }, 2, 1);
346
+ const booksRepository = em.getRepository(Book);
386
347
 
387
- // or with options object
388
348
  const books = await booksRepository.find({ author: '...' }, {
389
349
  populate: ['author'],
390
350
  limit: 1,
@@ -392,17 +352,14 @@ const books = await booksRepository.find({ author: '...' }, {
392
352
  orderBy: { title: QueryOrder.DESC },
393
353
  });
394
354
 
395
- console.log(books); // Book[]
355
+ console.log(books); // Loaded<Book, 'author'>[]
396
356
  ```
397
357
 
398
- Take a look at docs about [working with `EntityManager`](https://mikro-orm.io/docs/entity-manager/)
399
- or [using `EntityRepository` instead](https://mikro-orm.io/docs/repositories/).
358
+ 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/).
400
359
 
401
360
  ## 🤝 Contributing
402
361
 
403
- Contributions, issues and feature requests are welcome. Please read
404
- [CONTRIBUTING.md](CONTRIBUTING.md)
405
- for details on the process for submitting pull requests to us.
362
+ Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.
406
363
 
407
364
  ## Authors
408
365
 
@@ -16,10 +16,6 @@ export declare class SqlEntityManager<D extends AbstractSqlDriver = AbstractSqlD
16
16
  * Shortcut for `createQueryBuilder()`
17
17
  */
18
18
  qb<T extends object>(entityName: EntityName<T>, alias?: string, type?: ConnectionType): QueryBuilder<T>;
19
- /**
20
- * Creates raw SQL query that won't be escaped when used as a parameter.
21
- */
22
- raw<R = Knex.Raw>(sql: string, bindings?: Knex.RawBinding[] | Knex.ValueDict): R;
23
19
  /**
24
20
  * Returns configured knex instance.
25
21
  */
@@ -20,14 +20,6 @@ class SqlEntityManager extends core_1.EntityManager {
20
20
  qb(entityName, alias, type) {
21
21
  return this.createQueryBuilder(entityName, alias, type);
22
22
  }
23
- /**
24
- * Creates raw SQL query that won't be escaped when used as a parameter.
25
- */
26
- raw(sql, bindings = []) {
27
- const raw = this.getKnex().raw(sql, bindings);
28
- raw.__raw = true; // tag it as there is now way to check via `instanceof`
29
- return raw;
30
- }
31
23
  /**
32
24
  * Returns configured knex instance.
33
25
  */
package/index.mjs CHANGED
@@ -138,6 +138,7 @@ export const QueryOperator = mod.QueryOperator;
138
138
  export const QueryOrder = mod.QueryOrder;
139
139
  export const QueryOrderNumeric = mod.QueryOrderNumeric;
140
140
  export const QueryType = mod.QueryType;
141
+ export const RawQueryFragment = mod.RawQueryFragment;
141
142
  export const ReadOnlyException = mod.ReadOnlyException;
142
143
  export const Reference = mod.Reference;
143
144
  export const ReferenceKind = mod.ReferenceKind;
@@ -187,6 +188,7 @@ export const equals = mod.equals;
187
188
  export const expr = mod.expr;
188
189
  export const helper = mod.helper;
189
190
  export const knex = mod.knex;
191
+ export const raw = mod.raw;
190
192
  export const ref = mod.ref;
191
193
  export const rel = mod.rel;
192
194
  export const serialize = mod.serialize;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/knex",
3
- "version": "6.0.0-dev.45",
3
+ "version": "6.0.0-dev.47",
4
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
5
  "main": "index.js",
6
6
  "module": "index.mjs",
@@ -63,9 +63,9 @@
63
63
  "sqlstring": "2.3.3"
64
64
  },
65
65
  "devDependencies": {
66
- "@mikro-orm/core": "^5.6.12"
66
+ "@mikro-orm/core": "^5.6.15"
67
67
  },
68
68
  "peerDependencies": {
69
- "@mikro-orm/core": "~6.0.0-dev.45"
69
+ "@mikro-orm/core": "~6.0.0-dev.47"
70
70
  }
71
71
  }
@@ -12,7 +12,7 @@ const CriteriaNode_1 = require("./CriteriaNode");
12
12
  class CriteriaNodeFactory {
13
13
  static createNode(metadata, entityName, payload, parent, key) {
14
14
  const customExpression = CriteriaNode_1.CriteriaNode.isCustomExpression(key || '');
15
- const scalar = core_1.Utils.isPrimaryKey(payload) || payload instanceof RegExp || payload instanceof Date || customExpression;
15
+ const scalar = core_1.Utils.isPrimaryKey(payload) || core_1.Utils.isRawSql(payload) || payload instanceof RegExp || payload instanceof Date || customExpression;
16
16
  if (Array.isArray(payload) && !scalar) {
17
17
  return this.createArrayNode(metadata, entityName, payload, parent, key);
18
18
  }
@@ -5,8 +5,8 @@ import type { AnyEntity, ConnectionType, Dictionary, EntityData, EntityName, Ent
5
5
  import { LockMode, PopulateHint, QueryFlag } from '@mikro-orm/core';
6
6
  import { QueryType } from './enums';
7
7
  import type { AbstractSqlDriver } from '../AbstractSqlDriver';
8
- import { QueryBuilderHelper } from './QueryBuilderHelper';
9
8
  import type { Alias } from './QueryBuilderHelper';
9
+ import { QueryBuilderHelper } from './QueryBuilderHelper';
10
10
  import type { SqlEntityManager } from '../SqlEntityManager';
11
11
  import type { Field } from '../typings';
12
12
  /**
@@ -77,7 +77,7 @@ export declare class QueryBuilder<T extends object = AnyEntity> {
77
77
  /**
78
78
  * @internal
79
79
  */
80
- constructor(entityName: EntityName<T> | QueryBuilder<T>, metadata: MetadataStorage, driver: AbstractSqlDriver, context?: Knex.Transaction<any, any[]> | undefined, alias?: string, connectionType?: ConnectionType | undefined, em?: SqlEntityManager<AbstractSqlDriver<import("../AbstractSqlConnection").AbstractSqlConnection, import("../AbstractSqlPlatform").AbstractSqlPlatform>> | undefined);
80
+ constructor(entityName: EntityName<T> | QueryBuilder<T>, metadata: MetadataStorage, driver: AbstractSqlDriver, context?: Knex.Transaction<any, any[]> | undefined, alias?: string, connectionType?: ConnectionType | undefined, em?: SqlEntityManager<AbstractSqlDriver<import("..").AbstractSqlConnection, import("..").AbstractSqlPlatform>> | undefined);
81
81
  select(fields: Field<T> | Field<T>[], distinct?: boolean): SelectQueryBuilder<T>;
82
82
  addSelect(fields: Field<T> | Field<T>[]): SelectQueryBuilder<T>;
83
83
  distinct(): SelectQueryBuilder<T>;
@@ -116,7 +116,6 @@ export declare class QueryBuilder<T extends object = AnyEntity> {
116
116
  ref(field: string): Knex.Ref<string, {
117
117
  [x: string]: string;
118
118
  }>;
119
- raw<R = Knex.Raw>(sql: string, bindings?: Knex.RawBinding[] | Knex.ValueDict): R;
120
119
  limit(limit?: number, offset?: number): this;
121
120
  offset(offset?: number): this;
122
121
  withSchema(schema?: string): this;
@@ -116,7 +116,7 @@ class QueryBuilder {
116
116
  this._fields = this.mainAlias.metadata.primaryKeys;
117
117
  }
118
118
  else {
119
- this._fields = [this.raw('*')];
119
+ this._fields = [(0, core_1.raw)('*')];
120
120
  }
121
121
  if (distinct) {
122
122
  this.flags.add(core_1.QueryFlag.DISTINCT);
@@ -278,11 +278,6 @@ class QueryBuilder {
278
278
  ref(field) {
279
279
  return this.knex.ref(field);
280
280
  }
281
- raw(sql, bindings = []) {
282
- const raw = this.knex.raw(sql, bindings);
283
- raw.__raw = true; // tag it as there is now way to check via `instanceof`
284
- return raw;
285
- }
286
281
  limit(limit, offset = 0) {
287
282
  this.ensureNotFinalized();
288
283
  this._limit = limit;
@@ -374,7 +369,7 @@ class QueryBuilder {
374
369
  if (this.lockMode) {
375
370
  this.helper.getLockSQL(qb, this.lockMode, this.lockTables);
376
371
  }
377
- this.helper.finalize(this.type ?? enums_1.QueryType.SELECT, qb, this.mainAlias.metadata);
372
+ this.helper.finalize(this.type ?? enums_1.QueryType.SELECT, qb, this.mainAlias.metadata, this._data);
378
373
  return qb;
379
374
  }
380
375
  /**
@@ -523,7 +518,11 @@ class QueryBuilder {
523
518
  * Provides promise-like interface so we can await the QB instance.
524
519
  */
525
520
  then(onfulfilled, onrejected) {
526
- switch (this.type ?? enums_1.QueryType.SELECT) {
521
+ let type = this.type ?? enums_1.QueryType.SELECT;
522
+ if (this.flags.has(core_1.QueryFlag.UPDATE_SUB_QUERY) || this.flags.has(core_1.QueryFlag.DELETE_SUB_QUERY)) {
523
+ type = enums_1.QueryType.UPDATE;
524
+ }
525
+ switch (type) {
527
526
  case enums_1.QueryType.INSERT:
528
527
  case enums_1.QueryType.UPDATE:
529
528
  case enums_1.QueryType.DELETE:
@@ -546,7 +545,10 @@ class QueryBuilder {
546
545
  /* istanbul ignore next */
547
546
  alias = meta?.properties[f]?.fieldNames[0] ?? alias;
548
547
  }
549
- return qb.as(alias);
548
+ const ret = qb.as(alias);
549
+ // tag the instance, so it is possible to detect it easily
550
+ Object.defineProperty(ret, '__as', { enumerable: false, value: alias });
551
+ return ret;
550
552
  }
551
553
  clone() {
552
554
  const qb = new QueryBuilder(this.mainAlias.entityName, this.metadata, this.driver, this.context, this.mainAlias.aliasName, this.connectionType, this.em);
@@ -863,6 +865,7 @@ class QueryBuilder {
863
865
  if (this._offset) {
864
866
  subQuery.offset(this._offset);
865
867
  }
868
+ const addToSelect = [];
866
869
  if (this._orderBy.length > 0) {
867
870
  const orderBy = [];
868
871
  for (const orderMap of this._orderBy) {
@@ -870,15 +873,31 @@ class QueryBuilder {
870
873
  const [a, f] = this.helper.splitField(field);
871
874
  const prop = this.helper.getProperty(f, a);
872
875
  const type = this.platform.castColumn(prop);
873
- orderBy.push({
874
- [`min(${this.ref(this.helper.mapper(field, this.type, undefined, null))}${type})`]: direction,
875
- });
876
+ const fieldName = this.helper.mapper(field, this.type, undefined, null);
877
+ if (!prop?.persist && !prop?.formula) {
878
+ addToSelect.push(fieldName);
879
+ }
880
+ orderBy.push({ [`min(${this.ref(fieldName)}${type})`]: direction });
876
881
  }
877
882
  }
878
883
  subQuery.orderBy(orderBy);
879
884
  }
880
885
  subQuery.finalized = true;
881
886
  const knexQuery = subQuery.as(this.mainAlias.aliasName).clearSelect().select(pks);
887
+ if (addToSelect.length > 0) {
888
+ addToSelect.forEach(prop => {
889
+ const field = this._fields.find(field => {
890
+ if (typeof field === 'object' && field && '__as' in field) {
891
+ return field.__as === prop;
892
+ }
893
+ // not perfect, but should work most of the time, ideally we should check only the alias (`... as alias`)
894
+ return field.toString().includes(prop);
895
+ });
896
+ if (field) {
897
+ knexQuery.select(field);
898
+ }
899
+ });
900
+ }
882
901
  // multiple sub-queries are needed to get around mysql limitations with order by + limit + where in + group by (o.O)
883
902
  // https://stackoverflow.com/questions/17892762/mysql-this-version-of-mysql-doesnt-yet-support-limit-in-all-any-some-subqu
884
903
  const subSubQuery = this.getKnex().select(pks).from(knexQuery);
@@ -48,7 +48,7 @@ export declare class QueryBuilderHelper {
48
48
  private getOperatorReplacement;
49
49
  getQueryOrder(type: QueryType, orderBy: FlatQueryOrderMap | FlatQueryOrderMap[], populate: Dictionary<string>): string;
50
50
  getQueryOrderFromObject(type: QueryType, orderBy: FlatQueryOrderMap, populate: Dictionary<string>): string;
51
- finalize(type: QueryType, qb: Knex.QueryBuilder, meta?: EntityMetadata): void;
51
+ finalize(type: QueryType, qb: Knex.QueryBuilder, meta?: EntityMetadata, data?: Dictionary): void;
52
52
  splitField<T>(field: EntityKey<T>, greedyAlias?: boolean): [string, EntityKey<T>];
53
53
  getLockSQL(qb: Knex.QueryBuilder, lockMode: LockMode, lockTables?: string[]): void;
54
54
  updateVersionProperty(qb: Knex.QueryBuilder, data: Dictionary): void;
@@ -19,6 +19,9 @@ class QueryBuilderHelper {
19
19
  this.metadata = this.driver.getMetadata();
20
20
  }
21
21
  mapper(field, type = enums_1.QueryType.SELECT, value, alias) {
22
+ if (core_1.Utils.isRawSql(field)) {
23
+ return this.platform.formatQuery(field.sql, field.params ?? []);
24
+ }
22
25
  if (typeof field !== 'string') {
23
26
  return field;
24
27
  }
@@ -460,11 +463,23 @@ class QueryBuilderHelper {
460
463
  });
461
464
  return ret.join(', ');
462
465
  }
463
- finalize(type, qb, meta) {
464
- const useReturningStatement = type === enums_1.QueryType.INSERT && this.platform.usesReturningStatement() && meta && !meta.compositePK;
465
- if (useReturningStatement) {
466
- const returningProps = meta.hydrateProps.filter(prop => prop.persist !== false && (prop.primary || prop.defaultRaw));
467
- qb.returning(core_1.Utils.flatten(returningProps.map(prop => prop.fieldNames)));
466
+ finalize(type, qb, meta, data) {
467
+ if (!meta || !data || !this.platform.usesReturningStatement()) {
468
+ return;
469
+ }
470
+ if (type === enums_1.QueryType.INSERT) {
471
+ const returningProps = meta.hydrateProps
472
+ .filter(prop => prop.persist !== false && ((prop.primary && prop.autoincrement) || prop.defaultRaw))
473
+ .filter(prop => !(prop.name in data) || core_1.Utils.isRawSql(data[prop.name]));
474
+ if (returningProps.length > 0) {
475
+ qb.returning(core_1.Utils.flatten(returningProps.map(prop => prop.fieldNames)));
476
+ }
477
+ }
478
+ if (type === enums_1.QueryType.UPDATE) {
479
+ const returningProps = meta.hydrateProps.filter(prop => core_1.Utils.isRawSql(data[prop.name]));
480
+ if (returningProps.length > 0) {
481
+ qb.returning(core_1.Utils.flatten(returningProps.map(prop => prop.fieldNames)));
482
+ }
468
483
  }
469
484
  }
470
485
  splitField(field, greedyAlias = false) {
@@ -5,5 +5,6 @@ import type { IQueryBuilder } from '../typings';
5
5
  */
6
6
  export declare class ScalarCriteriaNode<T extends object> extends CriteriaNode<T> {
7
7
  process(qb: IQueryBuilder<T>, alias?: string): any;
8
+ willAutoJoin<T>(qb: IQueryBuilder<T>, alias?: string): boolean;
8
9
  shouldJoin(): boolean;
9
10
  }
@@ -22,6 +22,9 @@ class ScalarCriteriaNode extends CriteriaNode_1.CriteriaNode {
22
22
  }
23
23
  return this.payload;
24
24
  }
25
+ willAutoJoin(qb, alias) {
26
+ return this.shouldJoin();
27
+ }
25
28
  shouldJoin() {
26
29
  if (!this.parent || !this.prop) {
27
30
  return false;
@@ -287,7 +287,7 @@ class DatabaseTable {
287
287
  return '' + val;
288
288
  }
289
289
  addIndex(meta, index, type) {
290
- const properties = core_1.Utils.flatten(core_1.Utils.asArray(index.properties).map(prop => meta.properties[prop].fieldNames));
290
+ const properties = core_1.Utils.unique(core_1.Utils.flatten(core_1.Utils.asArray(index.properties).map(prop => meta.properties[prop].fieldNames)));
291
291
  if (properties.length === 0 && !index.expression) {
292
292
  return;
293
293
  }
@@ -29,8 +29,8 @@ export declare abstract class SchemaHelper {
29
29
  configureColumn(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>): Knex.ColumnBuilder;
30
30
  configureColumnDefault(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>): Knex.ColumnBuilder;
31
31
  getPreAlterTable(tableDiff: TableDifference, safe: boolean): string;
32
- getAlterColumnAutoincrement(tableName: string, column: Column): string;
33
- getChangeColumnCommentSQL(tableName: string, to: Column): string;
32
+ getAlterColumnAutoincrement(tableName: string, column: Column, schemaName?: string): string;
33
+ getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
34
34
  getNamespaces(connection: AbstractSqlConnection): Promise<string[]>;
35
35
  getColumns(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<Column[]>;
36
36
  getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<IndexDef[]>;
@@ -129,10 +129,10 @@ class SchemaHelper {
129
129
  getPreAlterTable(tableDiff, safe) {
130
130
  return '';
131
131
  }
132
- getAlterColumnAutoincrement(tableName, column) {
132
+ getAlterColumnAutoincrement(tableName, column, schemaName) {
133
133
  return '';
134
134
  }
135
- getChangeColumnCommentSQL(tableName, to) {
135
+ getChangeColumnCommentSQL(tableName, to, schemaName) {
136
136
  return '';
137
137
  }
138
138
  async getNamespaces(connection) {
@@ -294,13 +294,13 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
294
294
  this.helper.configureColumn(column, col, this.knex, changedProperties);
295
295
  }
296
296
  for (const { column } of Object.values(diff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
297
- this.helper.pushTableQuery(table, this.helper.getAlterColumnAutoincrement(tableName, column));
297
+ this.helper.pushTableQuery(table, this.helper.getAlterColumnAutoincrement(tableName, column, schemaName));
298
298
  }
299
299
  for (const { column, changedProperties } of Object.values(diff.changedColumns).filter(diff => diff.changedProperties.has('comment'))) {
300
300
  if (['type', 'nullable', 'autoincrement', 'unsigned', 'default', 'enumItems'].some(t => changedProperties.has(t))) {
301
301
  continue; // will be handled via knex
302
302
  }
303
- this.helper.pushTableQuery(table, this.helper.getChangeColumnCommentSQL(tableName, column));
303
+ this.helper.pushTableQuery(table, this.helper.getChangeColumnCommentSQL(tableName, column, schemaName));
304
304
  }
305
305
  for (const [oldColumnName, column] of Object.entries(diff.renamedColumns)) {
306
306
  this.helper.pushTableQuery(table, this.helper.getRenameColumnSQL(tableName, oldColumnName, column, schemaName));