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 Nov 5, 2023
1 parent 78dfbf2 commit 175c059
Show file tree
Hide file tree
Showing 166 changed files with 353 additions and 645 deletions.
10 changes: 10 additions & 0 deletions docs/docs/upgrading-v5-to-v6.md
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
@@ -1,5 +1,5 @@
import type { Connection, Dictionary } from '@mikro-orm/core';
import { SchemaHelper, type AbstractSqlConnection, type Index, type Check } from '@mikro-orm/knex';
import { SchemaHelper, type AbstractSqlConnection, type IndexDef, type CheckDef } from '@mikro-orm/knex';

export class BetterSqliteSchemaHelper extends SchemaHelper {

Expand Down Expand Up @@ -43,7 +43,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 @@ -62,18 +62,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 @@ -97,7 +97,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
@@ -1,5 +1,5 @@
import type { ArgumentsCamelCase, Argv, CommandModule } from 'yargs';
import { Utils, colors, type Configuration, type Dictionary, type MikroORM, type MikroORMOptions, type IMigrator, MigrateOptions } from '@mikro-orm/core';
import { Utils, colors, type Configuration, type Dictionary, type MikroORM, type Options, type IMigrator, MigrateOptions } from '@mikro-orm/core';
import { CLIHelper } from '../CLIHelper';

export class MigrationCommandFactory {
Expand All @@ -14,7 +14,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 @@ -85,9 +85,9 @@ export class MigrationCommandFactory {
});
}

static async handleMigrationCommand(args: ArgumentsCamelCase<Options>, method: MigratorMethod): Promise<void> {
static async handleMigrationCommand(args: ArgumentsCamelCase<Opts>, method: MigratorMethod): Promise<void> {
// to be able to run have a master transaction, but run marked migrations outside of it, we need a second connection
const options = { pool: { min: 1, max: 2 } } as Partial<MikroORMOptions>;
const options = { pool: { min: 1, max: 2 } } as Options;
const orm = await CLIHelper.getORM(undefined, options);
const migrator = orm.getMigrator();

Expand Down Expand Up @@ -126,7 +126,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 Down Expand Up @@ -156,7 +156,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, args.name);

if (ret.diff.up.length === 0) {
Expand Down Expand Up @@ -189,7 +189,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, dropDb: args.dropDb });
CLIHelper.dump(colors.green('Dropped schema successfully'));
Expand Down Expand Up @@ -250,4 +250,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; name?: string };
type Options = GenerateOptions & CliUpDownOptions & { dropDb?: boolean };
type Opts = GenerateOptions & CliUpDownOptions & { dropDb?: boolean };
1 change: 1 addition & 0 deletions packages/knex/src/index.ts
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
@@ -1,6 +1,6 @@
import { Cascade, DateTimeType, DecimalType, EntitySchema, ReferenceType, t, Utils, type Dictionary, type EntityMetadata, type EntityProperty, type NamingStrategy } 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 @@ -9,8 +9,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 @@ -34,15 +34,15 @@ export class DatabaseTable {
delete 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 @@ -385,7 +385,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
Expand Up @@ -9,7 +9,7 @@ import {
type Dictionary,
type EntityProperty,
} 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 @@ -340,7 +340,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 @@ -489,7 +489,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 @@ -501,7 +501,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 @@ -535,7 +535,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
Expand Up @@ -2,7 +2,7 @@ import type { Knex } from 'knex';
import { BigIntType, EnumType, Utils, type Connection, type Dictionary } 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 @@ -34,7 +34,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 @@ -59,7 +59,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 @@ -92,7 +92,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 @@ -104,11 +104,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 @@ -188,15 +188,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
@@ -1,6 +1,6 @@
import type { Knex } from 'knex';
import { AbstractSchemaGenerator, Utils, type Dictionary, type EntityMetadata, type MikroORM, ISchemaGenerator } 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 @@ -523,7 +523,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 @@ -546,7 +546,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 @@ -556,11 +556,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
Expand Up @@ -66,7 +66,7 @@ export interface ForeignKey {
deleteRule?: string;
}

export interface Index {
export interface IndexDef {
columnNames: string[];
keyName: string;
unique: boolean;
Expand All @@ -76,7 +76,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 @@ -99,13 +99,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 175c059

Please sign in to comment.