Skip to content

Commit

Permalink
feat(core): re-export the core package from all drivers (#3816)
Browse files Browse the repository at this point in the history
Every driver now reexport the whole `@mikro-orm/core` package. This
means we no longer have to think about what package to use for imports,
the driver package should be always preferred.

```diff
-import { Entity, PrimaryKey } from '@mikro-orm/core';
-import { MikroORM, EntityManager } from '@mikro-orm/mysql';
+import { Entity, PrimaryKey, MikroORM, EntityManager } from '@mikro-orm/mysql';
```
  • Loading branch information
B4nan committed Jan 13, 2023
1 parent eec881d commit 56d8cad
Show file tree
Hide file tree
Showing 168 changed files with 356 additions and 652 deletions.
10 changes: 10 additions & 0 deletions docs/docs/upgrading-v5-to-v6.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,16 @@ The options always needs to be plain JS object now. This was always only an inte

Use the `connect` option instead.

## All drivers now re-export the `@mikro-orm/core` package

This means we no longer have to think about what package to use for imports, the driver package should be always preferred.

```diff
-import { Entity, PrimaryKey } from '@mikro-orm/core';
-import { MikroORM, EntityManager } from '@mikro-orm/mysql';
+import { Entity, PrimaryKey, MikroORM, EntityManager } from '@mikro-orm/mysql';
```

## Removed `MongoDriver` methods

- `createCollections` in favour of `orm.schema.createSchema()`
Expand Down
12 changes: 6 additions & 6 deletions packages/better-sqlite/src/BetterSqliteSchemaHelper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Connection, Dictionary } from '@mikro-orm/core';
import type { AbstractSqlConnection, Index, Check } from '@mikro-orm/knex';
import type { AbstractSqlConnection, IndexDef, CheckDef } from '@mikro-orm/knex';
import { SchemaHelper } from '@mikro-orm/knex';

export class BetterSqliteSchemaHelper extends SchemaHelper {
Expand Down Expand Up @@ -44,7 +44,7 @@ export class BetterSqliteSchemaHelper extends SchemaHelper {
});
}

async getEnumDefinitions(connection: AbstractSqlConnection, checks: Check[], tableName: string, schemaName: string): Promise<Dictionary<string[]>> {
async getEnumDefinitions(connection: AbstractSqlConnection, checks: CheckDef[], tableName: string, schemaName: string): Promise<Dictionary<string[]>> {
const sql = `select sql from sqlite_master where type = ? and name = ?`;
const tableDefinition = await connection.execute<{ sql: string }>(sql, ['table', tableName], 'get');

Expand All @@ -63,18 +63,18 @@ export class BetterSqliteSchemaHelper extends SchemaHelper {
}, {} as Dictionary<string[]>);
}

async getPrimaryKeys(connection: AbstractSqlConnection, indexes: Index[] = [], tableName: string, schemaName?: string): Promise<string[]> {
async getPrimaryKeys(connection: AbstractSqlConnection, indexes: IndexDef[] = [], tableName: string, schemaName?: string): Promise<string[]> {
const sql = `pragma table_info(\`${tableName}\`)`;
const cols = await connection.execute<{ pk: number; name: string }[]>(sql);

return cols.filter(col => !!col.pk).map(col => col.name);
}

async getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<Index[]> {
async getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<IndexDef[]> {
const sql = `pragma table_info(\`${tableName}\`)`;
const cols = await connection.execute<{ pk: number; name: string }[]>(sql);
const indexes = await connection.execute<any[]>(`pragma index_list(\`${tableName}\`)`);
const ret: Index[] = [];
const ret: IndexDef[] = [];

for (const col of cols.filter(c => c.pk)) {
ret.push({
Expand All @@ -98,7 +98,7 @@ export class BetterSqliteSchemaHelper extends SchemaHelper {
return this.mapIndexes(ret);
}

async getChecks(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<Check[]> {
async getChecks(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<CheckDef[]> {
// Not supported at the moment.
return [];
}
Expand Down
16 changes: 8 additions & 8 deletions packages/cli/src/commands/MigrationCommandFactory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ArgumentsCamelCase, Argv, CommandModule } from 'yargs';
import type { Configuration, MikroORM, MikroORMOptions, IMigrator, MigrateOptions } from '@mikro-orm/core';
import type { Configuration, MikroORM, Options, IMigrator, MigrateOptions } from '@mikro-orm/core';
import { Utils, colors } from '@mikro-orm/core';
import { CLIHelper } from '../CLIHelper';

Expand All @@ -15,7 +15,7 @@ export class MigrationCommandFactory {
fresh: 'Clear the database and rerun all migrations',
};

static create<U extends Options = Options>(command: MigratorMethod): CommandModule<unknown, U> & { builder: (args: Argv) => Argv<U>; handler: (args: ArgumentsCamelCase<U>) => Promise<void> } {
static create<U extends Opts = Opts>(command: MigratorMethod): CommandModule<unknown, U> & { builder: (args: Argv) => Argv<U>; handler: (args: ArgumentsCamelCase<U>) => Promise<void> } {
return {
command: `migration:${command}`,
describe: MigrationCommandFactory.DESCRIPTIONS[command],
Expand Down Expand Up @@ -81,8 +81,8 @@ export class MigrationCommandFactory {
});
}

static async handleMigrationCommand(args: ArgumentsCamelCase<Options>, method: MigratorMethod): Promise<void> {
const options = { pool: { min: 1, max: 1 } } as Partial<MikroORMOptions>;
static async handleMigrationCommand(args: ArgumentsCamelCase<Opts>, method: MigratorMethod): Promise<void> {
const options = { pool: { min: 1, max: 1 } } as Options;
const orm = await CLIHelper.getORM(undefined, options);
const migrator = orm.getMigrator();

Expand Down Expand Up @@ -117,7 +117,7 @@ export class MigrationCommandFactory {
});
}

private static async handleUpDownCommand(args: ArgumentsCamelCase<Options>, migrator: IMigrator, method: MigratorMethod) {
private static async handleUpDownCommand(args: ArgumentsCamelCase<Opts>, migrator: IMigrator, method: MigratorMethod) {
const opts = MigrationCommandFactory.getUpDownOptions(args);
await migrator[method](opts as string[]);
const message = this.getUpDownSuccessMessage(method as 'up' | 'down', opts);
Expand All @@ -143,7 +143,7 @@ export class MigrationCommandFactory {
});
}

private static async handleCreateCommand(migrator: IMigrator, args: ArgumentsCamelCase<Options>, config: Configuration): Promise<void> {
private static async handleCreateCommand(migrator: IMigrator, args: ArgumentsCamelCase<Opts>, config: Configuration): Promise<void> {
const ret = await migrator.createMigration(args.path, args.blank, args.initial);

if (ret.diff.up.length === 0) {
Expand Down Expand Up @@ -176,7 +176,7 @@ export class MigrationCommandFactory {
process.exit(1);
}

private static async handleFreshCommand(args: ArgumentsCamelCase<Options>, migrator: IMigrator, orm: MikroORM) {
private static async handleFreshCommand(args: ArgumentsCamelCase<Opts>, migrator: IMigrator, orm: MikroORM) {
const generator = orm.getSchemaGenerator();
await generator.dropSchema({ dropMigrationsTable: true });
CLIHelper.dump(colors.green('Dropped schema successfully'));
Expand Down Expand Up @@ -237,4 +237,4 @@ export class MigrationCommandFactory {
type MigratorMethod = 'create' | 'check' | 'up' | 'down' | 'list' | 'pending' | 'fresh';
type CliUpDownOptions = { to?: string | number; from?: string | number; only?: string };
type GenerateOptions = { dump?: boolean; blank?: boolean; initial?: boolean; path?: string; disableFkChecks?: boolean; seed: string };
type Options = GenerateOptions & CliUpDownOptions;
type Opts = GenerateOptions & CliUpDownOptions;
1 change: 1 addition & 0 deletions packages/knex/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export { SqlEntityRepository as EntityRepository } from './SqlEntityRepository';

/** @ignore */
export { Knex, knex } from 'knex';
export * from '@mikro-orm/core';
14 changes: 7 additions & 7 deletions packages/knex/src/schema/DatabaseTable.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Dictionary, EntityMetadata, EntityProperty, NamingStrategy } from '@mikro-orm/core';
import { Cascade, DateTimeType, DecimalType, EntitySchema, ReferenceType, t, Utils } from '@mikro-orm/core';
import type { SchemaHelper } from './SchemaHelper';
import type { Check, Column, ForeignKey, Index } from '../typings';
import type { CheckDef, Column, ForeignKey, IndexDef } from '../typings';
import type { AbstractSqlPlatform } from '../AbstractSqlPlatform';

/**
Expand All @@ -10,8 +10,8 @@ import type { AbstractSqlPlatform } from '../AbstractSqlPlatform';
export class DatabaseTable {

private columns: Dictionary<Column> = {};
private indexes: Index[] = [];
private checks: Check[] = [];
private indexes: IndexDef[] = [];
private checks: CheckDef[] = [];
private foreignKeys: Dictionary<ForeignKey> = {};
public comment?: string;

Expand All @@ -31,15 +31,15 @@ export class DatabaseTable {
return this.columns[name];
}

getIndexes(): Index[] {
getIndexes(): IndexDef[] {
return this.indexes;
}

getChecks(): Check[] {
getChecks(): CheckDef[] {
return this.checks;
}

init(cols: Column[], indexes: Index[] = [], checks: Check[] = [], pks: string[], fks: Dictionary<ForeignKey> = {}, enums: Dictionary<string[]> = {}): void {
init(cols: Column[], indexes: IndexDef[] = [], checks: CheckDef[] = [], pks: string[], fks: Dictionary<ForeignKey> = {}, enums: Dictionary<string[]> = {}): void {
this.indexes = indexes;
this.checks = checks;
this.foreignKeys = fks;
Expand Down Expand Up @@ -374,7 +374,7 @@ export class DatabaseTable {
});
}

addCheck(check: Check) {
addCheck(check: CheckDef) {
this.checks.push(check);
}

Expand Down
10 changes: 5 additions & 5 deletions packages/knex/src/schema/SchemaComparator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { inspect } from 'util';
import type { Dictionary, EntityProperty } from '@mikro-orm/core';
import { BooleanType, DateTimeType, Utils } from '@mikro-orm/core';
import type { Check, Column, ForeignKey, Index, SchemaDifference, TableDifference } from '../typings';
import type { CheckDef, Column, ForeignKey, IndexDef, SchemaDifference, TableDifference } from '../typings';
import type { DatabaseSchema } from './DatabaseSchema';
import type { DatabaseTable } from './DatabaseTable';
import type { AbstractSqlPlatform } from '../AbstractSqlPlatform';
Expand Down Expand Up @@ -332,7 +332,7 @@ export class SchemaComparator {
* however ambiguities between different possibilities should not lead to renaming at all.
*/
private detectIndexRenamings(tableDifferences: TableDifference): void {
const renameCandidates: Dictionary<[Index, Index][]> = {};
const renameCandidates: Dictionary<[IndexDef, IndexDef][]> = {};

// Gather possible rename candidates by comparing each added and removed index based on semantics.
for (const addedIndex of Object.values(tableDifferences.addedIndexes)) {
Expand Down Expand Up @@ -477,7 +477,7 @@ export class SchemaComparator {
* Finds the difference between the indexes index1 and index2.
* Compares index1 with index2 and returns index2 if there are any differences or false in case there are no differences.
*/
diffIndex(index1: Index, index2: Index): boolean {
diffIndex(index1: IndexDef, index2: IndexDef): boolean {
// if one of them is a custom expression or full text index, compare only by name
if (index1.expression || index2.expression || index1.type === 'fulltext' || index2.type === 'fulltext') {
return index1.keyName !== index2.keyName;
Expand All @@ -489,7 +489,7 @@ export class SchemaComparator {
/**
* Checks if the other index already fulfills all the indexing and constraint needs of the current one.
*/
isIndexFulfilledBy(index1: Index, index2: Index): boolean {
isIndexFulfilledBy(index1: IndexDef, index2: IndexDef): boolean {
// allow the other index to be equally large only. It being larger is an option but it creates a problem with scenarios of the kind PRIMARY KEY(foo,bar) UNIQUE(foo)
if (index1.columnNames.length !== index2.columnNames.length) {
return false;
Expand Down Expand Up @@ -523,7 +523,7 @@ export class SchemaComparator {
return index1.primary === index2.primary && index1.unique === index2.unique;
}

diffCheck(check1: Check, check2: Check): boolean {
diffCheck(check1: CheckDef, check2: CheckDef): boolean {
// check constraint definition might be normalized by the driver,
// e.g. quotes might be added (https://github.com/mikro-orm/mikro-orm/issues/3827)
const simplify = (str?: string) => str?.replace(/['"`()]/g, '').toLowerCase();
Expand Down
18 changes: 9 additions & 9 deletions packages/knex/src/schema/SchemaHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Connection, Dictionary } from '@mikro-orm/core';
import { BigIntType, EnumType, Utils } from '@mikro-orm/core';
import type { AbstractSqlConnection } from '../AbstractSqlConnection';
import type { AbstractSqlPlatform } from '../AbstractSqlPlatform';
import type { Check, Column, Index, Table, TableDifference } from '../typings';
import type { CheckDef, Column, IndexDef, Table, TableDifference } from '../typings';
import type { DatabaseTable } from './DatabaseTable';
import type { DatabaseSchema } from './DatabaseSchema';

Expand Down Expand Up @@ -35,7 +35,7 @@ export abstract class SchemaHelper {
return true;
}

async getPrimaryKeys(connection: AbstractSqlConnection, indexes: Index[] = [], tableName: string, schemaName?: string): Promise<string[]> {
async getPrimaryKeys(connection: AbstractSqlConnection, indexes: IndexDef[] = [], tableName: string, schemaName?: string): Promise<string[]> {
const pks = indexes.filter(i => i.primary).map(pk => pk.columnNames);
return Utils.flatten(pks);
}
Expand All @@ -60,7 +60,7 @@ export abstract class SchemaHelper {
return unquote(t.table_name);
}

async getEnumDefinitions(connection: AbstractSqlConnection, checks: Check[], tableName: string, schemaName?: string): Promise<Dictionary<string[]>> {
async getEnumDefinitions(connection: AbstractSqlConnection, checks: CheckDef[], tableName: string, schemaName?: string): Promise<Dictionary<string[]>> {
return {};
}

Expand Down Expand Up @@ -93,7 +93,7 @@ export abstract class SchemaHelper {
return `alter table ${tableReference} rename column ${oldColumnName} to ${columnName}`;
}

getCreateIndexSQL(tableName: string, index: Index): string {
getCreateIndexSQL(tableName: string, index: IndexDef): string {
/* istanbul ignore if */
if (index.expression) {
return index.expression;
Expand All @@ -105,11 +105,11 @@ export abstract class SchemaHelper {
return `create index ${keyName} on ${tableName} (${index.columnNames.map(c => this.platform.quoteIdentifier(c)).join(', ')})`;
}

getDropIndexSQL(tableName: string, index: Index): string {
getDropIndexSQL(tableName: string, index: IndexDef): string {
return `drop index ${this.platform.quoteIdentifier(index.keyName)}`;
}

getRenameIndexSQL(tableName: string, index: Index, oldIndexName: string): string {
getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string {
return [this.getDropIndexSQL(tableName, { ...index, keyName: oldIndexName }), this.getCreateIndexSQL(tableName, index)].join(';\n');
}

Expand Down Expand Up @@ -189,15 +189,15 @@ export abstract class SchemaHelper {
throw new Error('Not supported by given driver');
}

async getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<Index[]> {
async getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<IndexDef[]> {
throw new Error('Not supported by given driver');
}

async getChecks(connection: AbstractSqlConnection, tableName: string, schemaName?: string, columns?: Column[]): Promise<Check[]> {
async getChecks(connection: AbstractSqlConnection, tableName: string, schemaName?: string, columns?: Column[]): Promise<CheckDef[]> {
throw new Error('Not supported by given driver');
}

protected async mapIndexes(indexes: Index[]): Promise<Index[]> {
protected async mapIndexes(indexes: IndexDef[]): Promise<IndexDef[]> {
const map = {} as Dictionary;

indexes.forEach(index => {
Expand Down
10 changes: 5 additions & 5 deletions packages/knex/src/schema/SqlSchemaGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Knex } from 'knex';
import type { Dictionary, EntityMetadata, MikroORM, ISchemaGenerator } from '@mikro-orm/core';
import { AbstractSchemaGenerator, Utils } from '@mikro-orm/core';
import type { Check, ForeignKey, Index, SchemaDifference, TableDifference } from '../typings';
import type { CheckDef, ForeignKey, IndexDef, SchemaDifference, TableDifference } from '../typings';
import { DatabaseSchema } from './DatabaseSchema';
import type { DatabaseTable } from './DatabaseTable';
import type { AbstractSqlDriver } from '../AbstractSqlDriver';
Expand Down Expand Up @@ -520,7 +520,7 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator<AbstractSqlDrive
});
}

private createIndex(table: Knex.CreateTableBuilder, index: Index, tableDef: DatabaseTable, createPrimary = false) {
private createIndex(table: Knex.CreateTableBuilder, index: IndexDef, tableDef: DatabaseTable, createPrimary = false) {
if (index.primary && !createPrimary) {
return;
}
Expand All @@ -543,7 +543,7 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator<AbstractSqlDrive
}
}

private dropIndex(table: Knex.CreateTableBuilder, index: Index, oldIndexName = index.keyName) {
private dropIndex(table: Knex.CreateTableBuilder, index: IndexDef, oldIndexName = index.keyName) {
if (index.primary) {
table.dropPrimary(oldIndexName);
} else if (index.unique) {
Expand All @@ -553,11 +553,11 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator<AbstractSqlDrive
}
}

private createCheck(table: Knex.CreateTableBuilder, check: Check) {
private createCheck(table: Knex.CreateTableBuilder, check: CheckDef) {
table.check(check.expression as string, {}, check.name);
}

private dropCheck(table: Knex.CreateTableBuilder, check: Check) {
private dropCheck(table: Knex.CreateTableBuilder, check: CheckDef) {
table.dropChecks(check.name);
}

Expand Down
18 changes: 9 additions & 9 deletions packages/knex/src/typings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export interface ForeignKey {
deleteRule?: string;
}

export interface Index {
export interface IndexDef {
columnNames: string[];
keyName: string;
unique: boolean;
Expand All @@ -73,7 +73,7 @@ export interface Index {
type?: string | Readonly<{ indexType?: string; storageEngineIndexType?: 'hash' | 'btree'; predicate?: Knex.QueryBuilder }>; // for back compatibility mainly, to allow using knex's `index.type` option (e.g. gin index)
}

export interface Check<T = unknown> {
export interface CheckDef<T = unknown> {
name: string;
expression: string | CheckCallback<T>;
definition?: string;
Expand All @@ -96,13 +96,13 @@ export interface TableDifference {
changedColumns: Dictionary<ColumnDifference>;
removedColumns: Dictionary<Column>;
renamedColumns: Dictionary<Column>;
addedIndexes: Dictionary<Index>;
changedIndexes: Dictionary<Index>;
removedIndexes: Dictionary<Index>;
renamedIndexes: Dictionary<Index>;
addedChecks: Dictionary<Check>;
changedChecks: Dictionary<Check>;
removedChecks: Dictionary<Check>;
addedIndexes: Dictionary<IndexDef>;
changedIndexes: Dictionary<IndexDef>;
removedIndexes: Dictionary<IndexDef>;
renamedIndexes: Dictionary<IndexDef>;
addedChecks: Dictionary<CheckDef>;
changedChecks: Dictionary<CheckDef>;
removedChecks: Dictionary<CheckDef>;
addedForeignKeys: Dictionary<ForeignKey>;
changedForeignKeys: Dictionary<ForeignKey>;
removedForeignKeys: Dictionary<ForeignKey>;
Expand Down

0 comments on commit 56d8cad

Please sign in to comment.