@yandjin-mikro-orm/knex 6.1.4-rc-sti-changes-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/AbstractSqlConnection.d.ts +58 -0
  2. package/AbstractSqlConnection.js +206 -0
  3. package/AbstractSqlDriver.d.ts +73 -0
  4. package/AbstractSqlDriver.js +1378 -0
  5. package/AbstractSqlPlatform.d.ts +25 -0
  6. package/AbstractSqlPlatform.js +86 -0
  7. package/LICENSE +21 -0
  8. package/MonkeyPatchable.d.ts +11 -0
  9. package/MonkeyPatchable.js +39 -0
  10. package/PivotCollectionPersister.d.ts +17 -0
  11. package/PivotCollectionPersister.js +131 -0
  12. package/README.md +383 -0
  13. package/SqlEntityManager.d.ts +25 -0
  14. package/SqlEntityManager.js +40 -0
  15. package/SqlEntityRepository.d.ts +24 -0
  16. package/SqlEntityRepository.js +36 -0
  17. package/index.d.ts +18 -0
  18. package/index.js +40 -0
  19. package/index.mjs +215 -0
  20. package/package.json +71 -0
  21. package/query/ArrayCriteriaNode.d.ts +10 -0
  22. package/query/ArrayCriteriaNode.js +25 -0
  23. package/query/CriteriaNode.d.ts +31 -0
  24. package/query/CriteriaNode.js +147 -0
  25. package/query/CriteriaNodeFactory.d.ts +12 -0
  26. package/query/CriteriaNodeFactory.js +90 -0
  27. package/query/ObjectCriteriaNode.d.ts +15 -0
  28. package/query/ObjectCriteriaNode.js +233 -0
  29. package/query/QueryBuilder.d.ts +291 -0
  30. package/query/QueryBuilder.js +1445 -0
  31. package/query/QueryBuilderHelper.d.ts +64 -0
  32. package/query/QueryBuilderHelper.js +747 -0
  33. package/query/ScalarCriteriaNode.d.ts +10 -0
  34. package/query/ScalarCriteriaNode.js +56 -0
  35. package/query/enums.d.ts +15 -0
  36. package/query/enums.js +20 -0
  37. package/query/index.d.ts +8 -0
  38. package/query/index.js +24 -0
  39. package/schema/DatabaseSchema.d.ts +29 -0
  40. package/schema/DatabaseSchema.js +140 -0
  41. package/schema/DatabaseTable.d.ts +61 -0
  42. package/schema/DatabaseTable.js +727 -0
  43. package/schema/SchemaComparator.d.ts +59 -0
  44. package/schema/SchemaComparator.js +603 -0
  45. package/schema/SchemaHelper.d.ts +56 -0
  46. package/schema/SchemaHelper.js +274 -0
  47. package/schema/SqlSchemaGenerator.d.ts +63 -0
  48. package/schema/SqlSchemaGenerator.js +598 -0
  49. package/schema/index.d.ts +5 -0
  50. package/schema/index.js +21 -0
  51. package/typings.d.ts +174 -0
  52. package/typings.js +2 -0
@@ -0,0 +1,56 @@
1
+ import type { Knex } from "knex";
2
+ import { type Connection, type Dictionary } from "@yandjin-mikro-orm/core";
3
+ import type { AbstractSqlConnection } from "../AbstractSqlConnection";
4
+ import type { AbstractSqlPlatform } from "../AbstractSqlPlatform";
5
+ import type { CheckDef, Column, IndexDef, Table, TableDifference } from "../typings";
6
+ import type { DatabaseTable } from "./DatabaseTable";
7
+ import type { DatabaseSchema } from "./DatabaseSchema";
8
+ export declare abstract class SchemaHelper {
9
+ protected readonly platform: AbstractSqlPlatform;
10
+ constructor(platform: AbstractSqlPlatform);
11
+ getSchemaBeginning(charset: string): string;
12
+ disableForeignKeysSQL(): string;
13
+ enableForeignKeysSQL(): string;
14
+ getSchemaEnd(): string;
15
+ finalizeTable(table: Knex.TableBuilder, charset: string, collate?: string): void;
16
+ supportsSchemaConstraints(): boolean;
17
+ getPrimaryKeys(connection: AbstractSqlConnection, indexes: IndexDef[] | undefined, tableName: string, schemaName?: string): Promise<string[]>;
18
+ getForeignKeys(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<Dictionary>;
19
+ protected getTableKey(t: Table): string;
20
+ getEnumDefinitions(connection: AbstractSqlConnection, checks: CheckDef[], tableName: string, schemaName?: string): Promise<Dictionary<string[]>>;
21
+ getDropNativeEnumSQL(name: string, schema?: string): string;
22
+ getAlterNativeEnumSQL(name: string, schema?: string, value?: string): string;
23
+ loadInformationSchema(schema: DatabaseSchema, connection: AbstractSqlConnection, tables: Table[], schemas?: string[]): Promise<void>;
24
+ getListTablesSQL(schemaName?: string): string;
25
+ getRenameColumnSQL(tableName: string, oldColumnName: string, to: Column, schemaName?: string): string;
26
+ getCreateIndexSQL(tableName: string, index: IndexDef, partialExpression?: boolean): string;
27
+ getDropIndexSQL(tableName: string, index: IndexDef): string;
28
+ getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string;
29
+ hasNonDefaultPrimaryKeyName(table: DatabaseTable): boolean;
30
+ createTableColumn(table: Knex.TableBuilder, column: Column, fromTable: DatabaseTable, changedProperties?: Set<string>, alter?: boolean): Knex.ColumnBuilder;
31
+ configureColumn(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>): Knex.ColumnBuilder;
32
+ configureColumnDefault(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>): Knex.ColumnBuilder;
33
+ getPreAlterTable(tableDiff: TableDifference, safe: boolean): string;
34
+ getPostAlterTable(tableDiff: TableDifference, safe: boolean): string;
35
+ getAlterColumnAutoincrement(tableName: string, column: Column, schemaName?: string): string;
36
+ getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
37
+ getNamespaces(connection: AbstractSqlConnection): Promise<string[]>;
38
+ getColumns(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<Column[]>;
39
+ getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<IndexDef[]>;
40
+ getChecks(connection: AbstractSqlConnection, tableName: string, schemaName?: string, columns?: Column[]): Promise<CheckDef[]>;
41
+ protected mapIndexes(indexes: IndexDef[]): Promise<IndexDef[]>;
42
+ getForeignKeysSQL(tableName: string, schemaName?: string): string;
43
+ mapForeignKeys(fks: any[], tableName: string, schemaName?: string): Dictionary;
44
+ normalizeDefaultValue(defaultValue: string, length?: number, defaultValues?: Dictionary<string[]>): string | number;
45
+ getCreateDatabaseSQL(name: string): string;
46
+ getDropDatabaseSQL(name: string): string;
47
+ getDatabaseExistsSQL(name: string): string;
48
+ getDatabaseNotExistsError(dbName: string): string;
49
+ getManagementDbName(): string;
50
+ getDefaultEmptyString(): string;
51
+ databaseExists(connection: Connection, name: string): Promise<boolean>;
52
+ /**
53
+ * Uses `raw` method injected in `AbstractSqlConnection` to allow adding custom queries inside alter statements.
54
+ */
55
+ pushTableQuery(table: Knex.TableBuilder, expression: string, grouping?: string): void;
56
+ }
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SchemaHelper = void 0;
4
+ const core_1 = require("@yandjin-mikro-orm/core");
5
+ class SchemaHelper {
6
+ platform;
7
+ constructor(platform) {
8
+ this.platform = platform;
9
+ }
10
+ getSchemaBeginning(charset) {
11
+ return `${this.disableForeignKeysSQL()}\n\n`;
12
+ }
13
+ disableForeignKeysSQL() {
14
+ return "";
15
+ }
16
+ enableForeignKeysSQL() {
17
+ return "";
18
+ }
19
+ getSchemaEnd() {
20
+ return `${this.enableForeignKeysSQL()}\n`;
21
+ }
22
+ finalizeTable(table, charset, collate) {
23
+ //
24
+ }
25
+ supportsSchemaConstraints() {
26
+ return true;
27
+ }
28
+ async getPrimaryKeys(connection, indexes = [], tableName, schemaName) {
29
+ const pks = indexes.filter((i) => i.primary).map((pk) => pk.columnNames);
30
+ return core_1.Utils.flatten(pks);
31
+ }
32
+ async getForeignKeys(connection, tableName, schemaName) {
33
+ const fks = await connection.execute(this.getForeignKeysSQL(tableName, schemaName));
34
+ return this.mapForeignKeys(fks, tableName, schemaName);
35
+ }
36
+ getTableKey(t) {
37
+ const unquote = (str) => str.replace(/['"`]/g, "");
38
+ const parts = t.table_name.split(".");
39
+ if (parts.length > 1) {
40
+ return `${unquote(parts[0])}.${unquote(parts[1])}`;
41
+ }
42
+ if (t.schema_name) {
43
+ return `${unquote(t.schema_name)}.${unquote(t.table_name)}`;
44
+ }
45
+ return unquote(t.table_name);
46
+ }
47
+ async getEnumDefinitions(connection, checks, tableName, schemaName) {
48
+ return {};
49
+ }
50
+ getDropNativeEnumSQL(name, schema) {
51
+ throw new Error("Not supported by given driver");
52
+ }
53
+ getAlterNativeEnumSQL(name, schema, value) {
54
+ throw new Error("Not supported by given driver");
55
+ }
56
+ async loadInformationSchema(schema, connection, tables, schemas) {
57
+ for (const t of tables) {
58
+ const table = schema.addTable(t.table_name, t.schema_name);
59
+ table.comment = t.table_comment;
60
+ const cols = await this.getColumns(connection, table.name, table.schema);
61
+ const indexes = await this.getIndexes(connection, table.name, table.schema);
62
+ const checks = await this.getChecks(connection, table.name, table.schema, cols);
63
+ const pks = await this.getPrimaryKeys(connection, indexes, table.name, table.schema);
64
+ const fks = await this.getForeignKeys(connection, table.name, table.schema);
65
+ const enums = await this.getEnumDefinitions(connection, checks, table.name, table.schema);
66
+ table.init(cols, indexes, checks, pks, fks, enums);
67
+ }
68
+ }
69
+ getListTablesSQL(schemaName) {
70
+ throw new Error("Not supported by given driver");
71
+ }
72
+ getRenameColumnSQL(tableName, oldColumnName, to, schemaName) {
73
+ tableName = this.platform.quoteIdentifier(tableName);
74
+ oldColumnName = this.platform.quoteIdentifier(oldColumnName);
75
+ const columnName = this.platform.quoteIdentifier(to.name);
76
+ const schemaReference = schemaName !== undefined && schemaName !== "public"
77
+ ? '"' + schemaName + '".'
78
+ : "";
79
+ const tableReference = schemaReference + tableName;
80
+ return `alter table ${tableReference} rename column ${oldColumnName} to ${columnName}`;
81
+ }
82
+ getCreateIndexSQL(tableName, index, partialExpression = false) {
83
+ /* istanbul ignore next */
84
+ if (index.expression && !partialExpression) {
85
+ return index.expression;
86
+ }
87
+ tableName = this.platform.quoteIdentifier(tableName);
88
+ const keyName = this.platform.quoteIdentifier(index.keyName);
89
+ const sql = `create ${index.unique ? "unique " : ""}index ${keyName} on ${tableName} `;
90
+ if (index.expression && partialExpression) {
91
+ return `${sql}(${index.expression})`;
92
+ }
93
+ return `${sql}(${index.columnNames.map((c) => this.platform.quoteIdentifier(c)).join(", ")})`;
94
+ }
95
+ getDropIndexSQL(tableName, index) {
96
+ return `drop index ${this.platform.quoteIdentifier(index.keyName)}`;
97
+ }
98
+ getRenameIndexSQL(tableName, index, oldIndexName) {
99
+ return [
100
+ this.getDropIndexSQL(tableName, { ...index, keyName: oldIndexName }),
101
+ this.getCreateIndexSQL(tableName, index),
102
+ ].join(";\n");
103
+ }
104
+ hasNonDefaultPrimaryKeyName(table) {
105
+ const pkIndex = table.getPrimaryKey();
106
+ if (!pkIndex || !this.platform.supportsCustomPrimaryKeyNames()) {
107
+ return false;
108
+ }
109
+ const defaultName = this.platform.getDefaultPrimaryName(table.name, pkIndex.columnNames);
110
+ return pkIndex?.keyName !== defaultName;
111
+ }
112
+ createTableColumn(table, column, fromTable, changedProperties, alter) {
113
+ const compositePK = fromTable.getPrimaryKey()?.composite;
114
+ if (column.autoincrement &&
115
+ !column.generated &&
116
+ !compositePK &&
117
+ (!changedProperties ||
118
+ changedProperties.has("autoincrement") ||
119
+ changedProperties.has("type"))) {
120
+ const primaryKey = !changedProperties && !this.hasNonDefaultPrimaryKeyName(fromTable);
121
+ if (column.mappedType instanceof core_1.BigIntType) {
122
+ return table.bigIncrements(column.name, { primaryKey });
123
+ }
124
+ return table.increments(column.name, { primaryKey });
125
+ }
126
+ if (column.mappedType instanceof core_1.EnumType &&
127
+ column.enumItems?.every((item) => core_1.Utils.isString(item))) {
128
+ return table.enum(column.name, column.enumItems);
129
+ }
130
+ let columnType = column.type;
131
+ if (column.generated) {
132
+ columnType += ` generated always as ${column.generated}`;
133
+ }
134
+ return table.specificType(column.name, columnType);
135
+ }
136
+ configureColumn(column, col, knex, changedProperties) {
137
+ const guard = (key) => !changedProperties || changedProperties.has(key);
138
+ core_1.Utils.runIfNotEmpty(() => col.nullable(), column.nullable && guard("nullable"));
139
+ core_1.Utils.runIfNotEmpty(() => col.notNullable(), !column.nullable && !column.generated);
140
+ core_1.Utils.runIfNotEmpty(() => col.unsigned(), column.unsigned);
141
+ core_1.Utils.runIfNotEmpty(() => col.comment(column.comment), column.comment);
142
+ this.configureColumnDefault(column, col, knex, changedProperties);
143
+ return col;
144
+ }
145
+ configureColumnDefault(column, col, knex, changedProperties) {
146
+ const guard = (key) => !changedProperties || changedProperties.has(key);
147
+ if (changedProperties) {
148
+ core_1.Utils.runIfNotEmpty(() => col.defaultTo(column.default == null ? null : knex.raw(column.default)), guard("default"));
149
+ }
150
+ else {
151
+ core_1.Utils.runIfNotEmpty(() => col.defaultTo(knex.raw(column.default)), column.default != null && column.default !== "null");
152
+ }
153
+ return col;
154
+ }
155
+ getPreAlterTable(tableDiff, safe) {
156
+ return "";
157
+ }
158
+ getPostAlterTable(tableDiff, safe) {
159
+ return "";
160
+ }
161
+ getAlterColumnAutoincrement(tableName, column, schemaName) {
162
+ return "";
163
+ }
164
+ getChangeColumnCommentSQL(tableName, to, schemaName) {
165
+ return "";
166
+ }
167
+ async getNamespaces(connection) {
168
+ return [];
169
+ }
170
+ async getColumns(connection, tableName, schemaName) {
171
+ throw new Error("Not supported by given driver");
172
+ }
173
+ async getIndexes(connection, tableName, schemaName) {
174
+ throw new Error("Not supported by given driver");
175
+ }
176
+ async getChecks(connection, tableName, schemaName, columns) {
177
+ throw new Error("Not supported by given driver");
178
+ }
179
+ async mapIndexes(indexes) {
180
+ const map = {};
181
+ indexes.forEach((index) => {
182
+ if (map[index.keyName]) {
183
+ map[index.keyName].composite = true;
184
+ map[index.keyName].columnNames.push(index.columnNames[0]);
185
+ }
186
+ else {
187
+ map[index.keyName] = index;
188
+ }
189
+ });
190
+ return Object.values(map);
191
+ }
192
+ getForeignKeysSQL(tableName, schemaName) {
193
+ throw new Error("Not supported by given driver");
194
+ }
195
+ mapForeignKeys(fks, tableName, schemaName) {
196
+ return fks.reduce((ret, fk) => {
197
+ if (ret[fk.constraint_name]) {
198
+ ret[fk.constraint_name].columnNames.push(fk.column_name);
199
+ ret[fk.constraint_name].referencedColumnNames.push(fk.referenced_column_name);
200
+ }
201
+ else {
202
+ ret[fk.constraint_name] = {
203
+ columnNames: [fk.column_name],
204
+ constraintName: fk.constraint_name,
205
+ localTableName: schemaName ? `${schemaName}.${tableName}` : tableName,
206
+ referencedTableName: fk.referenced_schema_name
207
+ ? `${fk.referenced_schema_name}.${fk.referenced_table_name}`
208
+ : fk.referenced_table_name,
209
+ referencedColumnNames: [fk.referenced_column_name],
210
+ updateRule: fk.update_rule.toLowerCase(),
211
+ deleteRule: fk.delete_rule.toLowerCase(),
212
+ };
213
+ }
214
+ return ret;
215
+ }, {});
216
+ }
217
+ normalizeDefaultValue(defaultValue, length, defaultValues = {}) {
218
+ if (defaultValue == null) {
219
+ return defaultValue;
220
+ }
221
+ const raw = core_1.RawQueryFragment.getKnownFragment(defaultValue);
222
+ if (raw) {
223
+ return this.platform.formatQuery(raw.sql, raw.params);
224
+ }
225
+ const genericValue = defaultValue.replace(/\(\d+\)/, "(?)").toLowerCase();
226
+ const norm = defaultValues[genericValue];
227
+ if (!norm) {
228
+ return defaultValue;
229
+ }
230
+ return norm[0].replace("(?)", length != null ? `(${length})` : "");
231
+ }
232
+ getCreateDatabaseSQL(name) {
233
+ return `create database ${name}`;
234
+ }
235
+ getDropDatabaseSQL(name) {
236
+ return `drop database if exists ${name}`;
237
+ }
238
+ getDatabaseExistsSQL(name) {
239
+ return `select 1 from information_schema.schemata where schema_name = '${name}'`;
240
+ }
241
+ getDatabaseNotExistsError(dbName) {
242
+ return `Unknown database '${dbName}'`;
243
+ }
244
+ getManagementDbName() {
245
+ return "information_schema";
246
+ }
247
+ getDefaultEmptyString() {
248
+ return "''";
249
+ }
250
+ async databaseExists(connection, name) {
251
+ try {
252
+ const res = await connection.execute(this.getDatabaseExistsSQL(name));
253
+ return res.length > 0;
254
+ }
255
+ catch (e) {
256
+ if (e instanceof Error &&
257
+ e.message.includes(this.getDatabaseNotExistsError(name))) {
258
+ return false;
259
+ }
260
+ throw e;
261
+ }
262
+ }
263
+ /**
264
+ * Uses `raw` method injected in `AbstractSqlConnection` to allow adding custom queries inside alter statements.
265
+ */
266
+ pushTableQuery(table, expression, grouping = "alterTable") {
267
+ table._statements.push({
268
+ grouping,
269
+ method: "raw",
270
+ args: [expression],
271
+ });
272
+ }
273
+ }
274
+ exports.SchemaHelper = SchemaHelper;
@@ -0,0 +1,63 @@
1
+ import { AbstractSchemaGenerator, type MikroORM, type ISchemaGenerator, type ClearDatabaseOptions, type CreateSchemaOptions, type EnsureDatabaseOptions, type DropSchemaOptions, type UpdateSchemaOptions } from "@yandjin-mikro-orm/core";
2
+ import type { SchemaDifference } from "../typings";
3
+ import { DatabaseSchema } from "./DatabaseSchema";
4
+ import type { AbstractSqlDriver } from "../AbstractSqlDriver";
5
+ export declare class SqlSchemaGenerator extends AbstractSchemaGenerator<AbstractSqlDriver> implements ISchemaGenerator {
6
+ private readonly helper;
7
+ private readonly options;
8
+ protected lastEnsuredDatabase?: string;
9
+ static register(orm: MikroORM): void;
10
+ createSchema(options?: CreateSchemaOptions): Promise<void>;
11
+ /**
12
+ * Returns true if the database was created.
13
+ */
14
+ ensureDatabase(options?: EnsureDatabaseOptions): Promise<boolean>;
15
+ getTargetSchema(schema?: string): DatabaseSchema;
16
+ getCreateSchemaSQL(options?: CreateSchemaOptions): Promise<string>;
17
+ dropSchema(options?: DropSchemaOptions): Promise<void>;
18
+ clearDatabase(options?: ClearDatabaseOptions): Promise<void>;
19
+ getDropSchemaSQL(options?: Omit<DropSchemaOptions, "dropDb">): Promise<string>;
20
+ private getSchemaName;
21
+ updateSchema(options?: UpdateSchemaOptions<DatabaseSchema>): Promise<void>;
22
+ getUpdateSchemaSQL(options?: UpdateSchemaOptions<DatabaseSchema>): Promise<string>;
23
+ getUpdateSchemaMigrationSQL(options?: UpdateSchemaOptions<DatabaseSchema>): Promise<{
24
+ up: string;
25
+ down: string;
26
+ }>;
27
+ private prepareSchemaForComparison;
28
+ diffToSQL(schemaDiff: SchemaDifference, options: {
29
+ wrap?: boolean;
30
+ safe?: boolean;
31
+ dropTables?: boolean;
32
+ schema?: string;
33
+ }): Promise<string>;
34
+ private getReferencedTableName;
35
+ private createForeignKey;
36
+ /**
37
+ * We need to drop foreign keys first for all tables to allow dropping PK constraints.
38
+ */
39
+ private preAlterTable;
40
+ private postAlterTable;
41
+ private splitTableName;
42
+ private alterTable;
43
+ /**
44
+ * creates new database and connects to it
45
+ */
46
+ createDatabase(name: string): Promise<void>;
47
+ dropDatabase(name?: string): Promise<void>;
48
+ execute(sql: string, options?: {
49
+ wrap?: boolean;
50
+ }): Promise<void>;
51
+ private wrapSchema;
52
+ private createSchemaBuilder;
53
+ private createTable;
54
+ private createIndex;
55
+ private dropIndex;
56
+ private createCheck;
57
+ private dropCheck;
58
+ private dropTable;
59
+ private createForeignKeys;
60
+ private dump;
61
+ private get knex();
62
+ }
63
+ export { SqlSchemaGenerator as SchemaGenerator };