@mikro-orm/postgresql 7.0.0-dev.7 → 7.0.0-dev.71
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/PostgreSqlConnection.js +5 -5
- package/PostgreSqlMikroORM.d.ts +7 -8
- package/PostgreSqlMikroORM.js +6 -8
- package/PostgreSqlPlatform.d.ts +4 -2
- package/PostgreSqlPlatform.js +7 -4
- package/PostgreSqlSchemaHelper.js +11 -4
- package/README.md +3 -2
- package/index.d.ts +2 -1
- package/index.js +1 -0
- package/package.json +8 -7
- package/raw.d.ts +58 -0
- package/raw.js +64 -0
package/PostgreSqlConnection.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import TypeOverrides from 'pg
|
|
2
|
-
import
|
|
1
|
+
import { Pool, TypeOverrides } from 'pg';
|
|
2
|
+
import Cursor from 'pg-cursor';
|
|
3
3
|
import { PostgresDialect } from 'kysely';
|
|
4
4
|
import array from 'postgres-array';
|
|
5
5
|
import { AbstractSqlConnection, Utils } from '@mikro-orm/knex';
|
|
@@ -8,15 +8,15 @@ export class PostgreSqlConnection extends AbstractSqlConnection {
|
|
|
8
8
|
const options = this.mapOptions(overrides);
|
|
9
9
|
return new PostgresDialect({
|
|
10
10
|
pool: new Pool(options),
|
|
11
|
+
cursor: Cursor,
|
|
11
12
|
onCreateConnection: this.options.onCreateConnection ?? this.config.get('onCreateConnection'),
|
|
12
13
|
});
|
|
13
14
|
}
|
|
14
15
|
mapOptions(overrides) {
|
|
15
16
|
const ret = { ...this.getConnectionOptions() };
|
|
16
17
|
const pool = this.config.get('pool');
|
|
17
|
-
ret
|
|
18
|
-
ret
|
|
19
|
-
ret.idleTimeoutMillis = pool?.idleTimeoutMillis;
|
|
18
|
+
Utils.defaultValue(ret, 'max', pool?.max);
|
|
19
|
+
Utils.defaultValue(ret, 'idleTimeoutMillis', pool?.idleTimeoutMillis);
|
|
20
20
|
// use `select typname, oid, typarray from pg_type order by oid` to get the list of OIDs
|
|
21
21
|
const types = new TypeOverrides();
|
|
22
22
|
[
|
package/PostgreSqlMikroORM.d.ts
CHANGED
|
@@ -1,19 +1,18 @@
|
|
|
1
|
-
import { MikroORM, type Options, type IDatabaseDriver, type EntityManager, type EntityManagerType } from '@mikro-orm/core';
|
|
2
|
-
import { PostgreSqlDriver } from './PostgreSqlDriver.js';
|
|
1
|
+
import { type AnyEntity, type EntityClass, type EntitySchema, MikroORM, type Options, type IDatabaseDriver, type EntityManager, type EntityManagerType } from '@mikro-orm/core';
|
|
3
2
|
import type { SqlEntityManager } from '@mikro-orm/knex';
|
|
3
|
+
import { PostgreSqlDriver } from './PostgreSqlDriver.js';
|
|
4
|
+
export type PostgreSqlOptions<EM extends SqlEntityManager<PostgreSqlDriver> = SqlEntityManager<PostgreSqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> = Options<PostgreSqlDriver, EM, Entities>;
|
|
5
|
+
export declare function definePostgreSqlConfig<EM extends SqlEntityManager<PostgreSqlDriver> = SqlEntityManager<PostgreSqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: Options<PostgreSqlDriver, EM, Entities>): Options<PostgreSqlDriver, EM, Entities>;
|
|
4
6
|
/**
|
|
5
7
|
* @inheritDoc
|
|
6
8
|
*/
|
|
7
|
-
export declare class PostgreSqlMikroORM<EM extends
|
|
8
|
-
private static DRIVER;
|
|
9
|
+
export declare class PostgreSqlMikroORM<EM extends SqlEntityManager<PostgreSqlDriver> = SqlEntityManager<PostgreSqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> extends MikroORM<PostgreSqlDriver, EM, Entities> {
|
|
9
10
|
/**
|
|
10
11
|
* @inheritDoc
|
|
11
12
|
*/
|
|
12
|
-
static init<D extends IDatabaseDriver = PostgreSqlDriver, EM extends EntityManager = D[typeof EntityManagerType] & EntityManager>(options
|
|
13
|
+
static init<D extends IDatabaseDriver = PostgreSqlDriver, EM extends EntityManager<D> = D[typeof EntityManagerType] & EntityManager<D>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: Options<D, EM, Entities>): Promise<MikroORM<D, EM, Entities>>;
|
|
13
14
|
/**
|
|
14
15
|
* @inheritDoc
|
|
15
16
|
*/
|
|
16
|
-
|
|
17
|
+
constructor(options: Options<PostgreSqlDriver, EM, Entities>);
|
|
17
18
|
}
|
|
18
|
-
export type PostgreSqlOptions = Options<PostgreSqlDriver>;
|
|
19
|
-
export declare function definePostgreSqlConfig(options: PostgreSqlOptions): Options<PostgreSqlDriver, SqlEntityManager<PostgreSqlDriver> & EntityManager<IDatabaseDriver<import("@mikro-orm/core").Connection>>>;
|
package/PostgreSqlMikroORM.js
CHANGED
|
@@ -1,24 +1,22 @@
|
|
|
1
1
|
import { defineConfig, MikroORM, } from '@mikro-orm/core';
|
|
2
2
|
import { PostgreSqlDriver } from './PostgreSqlDriver.js';
|
|
3
|
+
export function definePostgreSqlConfig(options) {
|
|
4
|
+
return defineConfig({ driver: PostgreSqlDriver, ...options });
|
|
5
|
+
}
|
|
3
6
|
/**
|
|
4
7
|
* @inheritDoc
|
|
5
8
|
*/
|
|
6
9
|
export class PostgreSqlMikroORM extends MikroORM {
|
|
7
|
-
static DRIVER = PostgreSqlDriver;
|
|
8
10
|
/**
|
|
9
11
|
* @inheritDoc
|
|
10
12
|
*/
|
|
11
13
|
static async init(options) {
|
|
12
|
-
return super.init(options);
|
|
14
|
+
return super.init(definePostgreSqlConfig(options));
|
|
13
15
|
}
|
|
14
16
|
/**
|
|
15
17
|
* @inheritDoc
|
|
16
18
|
*/
|
|
17
|
-
|
|
18
|
-
|
|
19
|
+
constructor(options) {
|
|
20
|
+
super(definePostgreSqlConfig(options));
|
|
19
21
|
}
|
|
20
22
|
}
|
|
21
|
-
/* v8 ignore next 3 */
|
|
22
|
-
export function definePostgreSqlConfig(options) {
|
|
23
|
-
return defineConfig({ driver: PostgreSqlDriver, ...options });
|
|
24
|
-
}
|
package/PostgreSqlPlatform.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type IPostgresInterval } from 'postgres-interval';
|
|
2
|
-
import { type
|
|
2
|
+
import { type Configuration, type EntityProperty, type IsolationLevel, type SimpleColumnMeta, Type } from '@mikro-orm/core';
|
|
3
3
|
import { AbstractSqlPlatform, type IndexDef, PostgreSqlNativeQueryBuilder } from '@mikro-orm/knex';
|
|
4
4
|
import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper.js';
|
|
5
5
|
import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter.js';
|
|
@@ -81,7 +81,9 @@ export declare class PostgreSqlPlatform extends AbstractSqlPlatform {
|
|
|
81
81
|
getJsonDeclarationSQL(): string;
|
|
82
82
|
getSearchJsonPropertyKey(path: string[], type: string | undefined | Type, aliased: boolean, value?: unknown): string;
|
|
83
83
|
getJsonIndexDefinition(index: IndexDef): string[];
|
|
84
|
-
quoteIdentifier(id: string
|
|
84
|
+
quoteIdentifier(id: string | {
|
|
85
|
+
toString: () => string;
|
|
86
|
+
}, quote?: string): string;
|
|
85
87
|
escape(value: any): string;
|
|
86
88
|
private pad;
|
|
87
89
|
/** @internal */
|
package/PostgreSqlPlatform.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Client } from 'pg';
|
|
2
2
|
import parseDate from 'postgres-date';
|
|
3
3
|
import PostgresInterval from 'postgres-interval';
|
|
4
|
-
import {
|
|
4
|
+
import { ALIAS_REPLACEMENT, ARRAY_OPERATORS, raw, RawQueryFragment, Type, Utils, } from '@mikro-orm/core';
|
|
5
5
|
import { AbstractSqlPlatform, PostgreSqlNativeQueryBuilder } from '@mikro-orm/knex';
|
|
6
6
|
import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper.js';
|
|
7
7
|
import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter.js';
|
|
@@ -162,7 +162,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
|
|
|
162
162
|
if (column.nativeEnumName) {
|
|
163
163
|
return column.nativeEnumName;
|
|
164
164
|
}
|
|
165
|
-
if (column.items?.every(item =>
|
|
165
|
+
if (column.items?.every(item => typeof item === 'string')) {
|
|
166
166
|
return 'text';
|
|
167
167
|
}
|
|
168
168
|
return `smallint`;
|
|
@@ -231,7 +231,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
|
|
|
231
231
|
const cast = (key) => raw(type in types ? `(${key})::${types[type]}` : key);
|
|
232
232
|
let lastOperator = '->>';
|
|
233
233
|
// force `->` for operator payloads with array values
|
|
234
|
-
if (Utils.isPlainObject(value) && Object.keys(value).every(key =>
|
|
234
|
+
if (Utils.isPlainObject(value) && Object.keys(value).every(key => ARRAY_OPERATORS.includes(key) && Array.isArray(value[key]))) {
|
|
235
235
|
lastOperator = '->';
|
|
236
236
|
}
|
|
237
237
|
if (path.length === 0) {
|
|
@@ -258,7 +258,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
|
|
|
258
258
|
if (RawQueryFragment.isKnownFragment(id)) {
|
|
259
259
|
return super.quoteIdentifier(id);
|
|
260
260
|
}
|
|
261
|
-
return `${quote}${id.replace('.', `${quote}.${quote}`)}${quote}`;
|
|
261
|
+
return `${quote}${id.toString().replace('.', `${quote}.${quote}`)}${quote}`;
|
|
262
262
|
}
|
|
263
263
|
escape(value) {
|
|
264
264
|
if (typeof value === 'string') {
|
|
@@ -270,6 +270,9 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
|
|
|
270
270
|
if (ArrayBuffer.isView(value)) {
|
|
271
271
|
return `E'\\\\x${value.toString('hex')}'`;
|
|
272
272
|
}
|
|
273
|
+
if (Array.isArray(value)) {
|
|
274
|
+
return value.map(v => this.escape(v)).join(', ');
|
|
275
|
+
}
|
|
273
276
|
return super.escape(value);
|
|
274
277
|
}
|
|
275
278
|
pad(number, digits) {
|
|
@@ -68,7 +68,9 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
68
68
|
const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
|
|
69
69
|
const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
|
|
70
70
|
const enums = this.getEnumDefinitions(checks[key] ?? []);
|
|
71
|
-
|
|
71
|
+
if (columns[key]) {
|
|
72
|
+
table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
|
|
73
|
+
}
|
|
72
74
|
}
|
|
73
75
|
}
|
|
74
76
|
async getAllIndexes(connection, tables) {
|
|
@@ -250,10 +252,14 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
250
252
|
if (row.schema_name && row.schema_name !== this.platform.getDefaultSchemaName()) {
|
|
251
253
|
name = row.schema_name + '.' + name;
|
|
252
254
|
}
|
|
255
|
+
let items = row.enum_value;
|
|
256
|
+
if (!Array.isArray(items)) {
|
|
257
|
+
items = this.platform.unmarshallArray(row.enum_value);
|
|
258
|
+
}
|
|
253
259
|
o[name] = {
|
|
254
260
|
name: row.enum_name,
|
|
255
261
|
schema: row.schema_name,
|
|
256
|
-
items
|
|
262
|
+
items,
|
|
257
263
|
};
|
|
258
264
|
return o;
|
|
259
265
|
}, {});
|
|
@@ -317,7 +323,8 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
317
323
|
}, {});
|
|
318
324
|
}
|
|
319
325
|
createTableColumn(column, table) {
|
|
320
|
-
const
|
|
326
|
+
const pk = table.getPrimaryKey();
|
|
327
|
+
const compositePK = pk?.composite;
|
|
321
328
|
const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
|
|
322
329
|
const col = [this.quote(column.name)];
|
|
323
330
|
if (column.autoincrement && !column.generated && !compositePK) {
|
|
@@ -347,7 +354,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
|
|
|
347
354
|
Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
|
|
348
355
|
Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
|
|
349
356
|
}
|
|
350
|
-
if (column.autoincrement && !
|
|
357
|
+
if (column.autoincrement && !compositePK) {
|
|
351
358
|
Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
|
|
352
359
|
}
|
|
353
360
|
const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
|
package/README.md
CHANGED
|
@@ -11,7 +11,6 @@ TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-or
|
|
|
11
11
|
[](https://discord.gg/w8bjxFHS7X)
|
|
12
12
|
[](https://www.npmjs.com/package/@mikro-orm/core)
|
|
13
13
|
[](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
|
|
14
|
-
[](https://codeclimate.com/github/mikro-orm/mikro-orm/maintainability)
|
|
15
14
|
[](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
|
|
16
15
|
|
|
17
16
|
## 🤔 Unit of What?
|
|
@@ -141,7 +140,7 @@ There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit m
|
|
|
141
140
|
- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
|
|
142
141
|
- [Filters](https://mikro-orm.io/docs/filters)
|
|
143
142
|
- [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
|
|
144
|
-
- [
|
|
143
|
+
- [Populating relations](https://mikro-orm.io/docs/populating-relations)
|
|
145
144
|
- [Property Validation](https://mikro-orm.io/docs/property-validation)
|
|
146
145
|
- [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
|
|
147
146
|
- [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
|
|
@@ -382,6 +381,8 @@ See also the list of contributors who [participated](https://github.com/mikro-or
|
|
|
382
381
|
|
|
383
382
|
Please ⭐️ this repository if this project helped you!
|
|
384
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
|
+
|
|
385
386
|
## 📝 License
|
|
386
387
|
|
|
387
388
|
Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
|
package/index.d.ts
CHANGED
|
@@ -5,4 +5,5 @@ export * from './PostgreSqlPlatform.js';
|
|
|
5
5
|
export * from './PostgreSqlSchemaHelper.js';
|
|
6
6
|
export * from './PostgreSqlExceptionConverter.js';
|
|
7
7
|
export * from './types/index.js';
|
|
8
|
-
export { PostgreSqlMikroORM as MikroORM, PostgreSqlOptions as Options, definePostgreSqlConfig as defineConfig, } from './PostgreSqlMikroORM.js';
|
|
8
|
+
export { PostgreSqlMikroORM as MikroORM, type PostgreSqlOptions as Options, definePostgreSqlConfig as defineConfig, } from './PostgreSqlMikroORM.js';
|
|
9
|
+
export { raw } from './raw.js';
|
package/index.js
CHANGED
|
@@ -6,3 +6,4 @@ export * from './PostgreSqlSchemaHelper.js';
|
|
|
6
6
|
export * from './PostgreSqlExceptionConverter.js';
|
|
7
7
|
export * from './types/index.js';
|
|
8
8
|
export { PostgreSqlMikroORM as MikroORM, definePostgreSqlConfig as defineConfig, } from './PostgreSqlMikroORM.js';
|
|
9
|
+
export { raw } from './raw.js';
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mikro-orm/postgresql",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "7.0.0-dev.
|
|
4
|
+
"version": "7.0.0-dev.71",
|
|
5
5
|
"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.",
|
|
6
6
|
"exports": {
|
|
7
7
|
"./package.json": "./package.json",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
},
|
|
39
39
|
"homepage": "https://mikro-orm.io",
|
|
40
40
|
"engines": {
|
|
41
|
-
"node": ">= 22.
|
|
41
|
+
"node": ">= 22.17.0"
|
|
42
42
|
},
|
|
43
43
|
"scripts": {
|
|
44
44
|
"build": "yarn clean && yarn compile && yarn copy",
|
|
@@ -50,18 +50,19 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@mikro-orm/knex": "7.0.0-dev.
|
|
54
|
-
"pg": "8.
|
|
53
|
+
"@mikro-orm/knex": "7.0.0-dev.71",
|
|
54
|
+
"pg": "8.16.3",
|
|
55
|
+
"pg-cursor": "2.15.3",
|
|
55
56
|
"postgres-array": "3.0.4",
|
|
56
57
|
"postgres-date": "2.1.0",
|
|
57
58
|
"postgres-interval": "4.0.2"
|
|
58
59
|
},
|
|
59
60
|
"devDependencies": {
|
|
60
|
-
"@mikro-orm/core": "^6.
|
|
61
|
-
"kysely": "
|
|
61
|
+
"@mikro-orm/core": "^6.6.1",
|
|
62
|
+
"kysely": "0.28.8"
|
|
62
63
|
},
|
|
63
64
|
"peerDependencies": {
|
|
64
|
-
"@mikro-orm/core": "7.0.0-dev.
|
|
65
|
+
"@mikro-orm/core": "7.0.0-dev.71",
|
|
65
66
|
"kysely": "*"
|
|
66
67
|
}
|
|
67
68
|
}
|
package/raw.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type AnyString, type Dictionary, type EntityKey, type RawQueryFragment, type QueryBuilder } from '@mikro-orm/knex';
|
|
2
|
+
import type { SelectQueryBuilder } from 'kysely';
|
|
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 raw<T extends object = any, R = any>(sql: SelectQueryBuilder<any, any, any> | 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,64 @@
|
|
|
1
|
+
import { raw as raw_, Utils } from '@mikro-orm/knex';
|
|
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 raw(sql, params) {
|
|
58
|
+
if (Utils.isObject(sql) && 'compile' in sql) {
|
|
59
|
+
const query = sql.compile();
|
|
60
|
+
const processed = query.sql.replaceAll(/\$\d+/g, '?');
|
|
61
|
+
return raw_(processed, query.parameters);
|
|
62
|
+
}
|
|
63
|
+
return raw_(sql, params);
|
|
64
|
+
}
|