Skip to content

Commit

Permalink
fix(core): fix automatic calling of ensureDatabase on init
Browse files Browse the repository at this point in the history
  • Loading branch information
B4nan committed Jan 5, 2024
1 parent 6a12fe1 commit 827b1f1
Show file tree
Hide file tree
Showing 10 changed files with 29 additions and 15 deletions.
9 changes: 5 additions & 4 deletions packages/core/src/MikroORM.ts
Expand Up @@ -125,12 +125,13 @@ export class MikroORM<D extends IDatabaseDriver = IDatabaseDriver, EM extends En
const dbName = this.config.get('dbName')!;
const db = dbName + (clientUrl ? ' on ' + clientUrl : '');

if (this.config.get('ensureDatabase')) {
const options = this.config.get('ensureDatabase');
await this.schema.ensureDatabase(typeof options === 'boolean' ? {} : { ...options, forceCheck: true });
}

if (await this.isConnected()) {
this.logger.log('info', `MikroORM successfully connected to database ${colors.green(db)}`);

if (this.config.get('ensureDatabase')) {
await this.schema.ensureDatabase();
}
} else {
this.logger.error('info', `MikroORM failed to connect to database ${db}`);
}
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/typings.ts
Expand Up @@ -724,6 +724,7 @@ export interface ClearDatabaseOptions {
export interface EnsureDatabaseOptions extends CreateSchemaOptions, ClearDatabaseOptions {
clear?: boolean;
create?: boolean;
forceCheck?: boolean;
}

export interface DropSchemaOptions {
Expand All @@ -748,7 +749,7 @@ export interface RefreshDatabaseOptions extends CreateSchemaOptions {

export interface ISchemaGenerator {
createSchema(options?: CreateSchemaOptions): Promise<void>;
ensureDatabase(): Promise<boolean>;
ensureDatabase(options?: EnsureDatabaseOptions): Promise<boolean>;
getCreateSchemaSQL(options?: CreateSchemaOptions): Promise<string>;
dropSchema(options?: DropSchemaOptions): Promise<void>;
getDropSchemaSQL(options?: Omit<DropSchemaOptions, 'dropDb'>): Promise<string>;
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/utils/Configuration.ts
Expand Up @@ -17,6 +17,7 @@ import type {
MaybePromise,
MigrationObject,
EntityMetadata,
EnsureDatabaseOptions,
} from '../typings';
import { ObjectHydrator } from '../hydration';
import { NullHighlighter } from '../utils/NullHighlighter';
Expand Down Expand Up @@ -547,7 +548,7 @@ export interface MikroORMOptions<D extends IDatabaseDriver = IDatabaseDriver, EM
forceUndefined: boolean;
forceUtcTimezone: boolean;
timezone?: string;
ensureDatabase: boolean;
ensureDatabase: boolean | EnsureDatabaseOptions;
ensureIndexes: boolean;
useBatchInserts?: boolean;
useBatchUpdates?: boolean;
Expand Down
8 changes: 2 additions & 6 deletions packages/knex/src/AbstractSqlConnection.ts
Expand Up @@ -62,12 +62,8 @@ export abstract class AbstractSqlConnection extends Connection {
* @inheritDoc
*/
async isConnected(): Promise<boolean> {
try {
await this.getKnex().raw('select 1');
return true;
} catch {
return false;
}
const check = await this.checkConnection();
return check.ok;
}

/**
Expand Down
9 changes: 7 additions & 2 deletions packages/knex/src/schema/SqlSchemaGenerator.ts
Expand Up @@ -40,7 +40,7 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator<AbstractSqlDrive
override async ensureDatabase(options?: EnsureDatabaseOptions): Promise<boolean> {
const dbName = this.config.get('dbName')!;

if (this.lastEnsuredDatabase === dbName) {
if (this.lastEnsuredDatabase === dbName && !options?.forceCheck) {
return true;
}

Expand Down Expand Up @@ -481,7 +481,12 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator<AbstractSqlDrive
* creates new database and connects to it
*/
override async createDatabase(name: string): Promise<void> {
await this.driver.execute(this.helper.getCreateDatabaseSQL('' + this.knex.ref(name)));
const sql = this.helper.getCreateDatabaseSQL('' + this.knex.ref(name));

if (sql) {
await this.driver.execute(sql);
}

this.config.set('dbName', name);
await this.driver.reconnect();
}
Expand Down
7 changes: 6 additions & 1 deletion packages/sqlite/src/SqliteSchemaHelper.ts
Expand Up @@ -164,8 +164,13 @@ export class SqliteSchemaHelper extends SchemaHelper {
}, {});
}

override getCreateDatabaseSQL(name: string): string {
return '';
}

override async databaseExists(connection: Connection, name: string): Promise<boolean> {
return true;
const tables = await connection.execute(this.getListTablesSQL());
return tables.length > 0;
}

/**
Expand Down
1 change: 1 addition & 0 deletions tests/MikroORM.test.ts
Expand Up @@ -224,6 +224,7 @@ describe('MikroORM', () => {
entities: [Car2, CarOwner2, User2, Sandwich],
debug: ['info'],
logger,
ensureDatabase: false,
});
expect(logger.mock.calls[0][0]).toEqual(`[info] MikroORM version: ${await Utils.getORMVersion()}`);
expect(logger.mock.calls[1][0]).toEqual('[info] MikroORM failed to connect to database not-found on mysql://root@127.0.0.1:3306');
Expand Down
Expand Up @@ -221,6 +221,7 @@ exports[`Migrator (sqlite) generate schema migration: migration-dump 1`] = `

exports[`Migrator (sqlite) up/down params [all or nothing disabled]: all-or-nothing-disabled 1`] = `
[
"select name as table_name from sqlite_master where type = 'table' and name != 'sqlite_sequence' and name != 'geometry_columns' and name != 'spatial_ref_sys' union all select name as table_name from sqlite_temp_master where type = 'table' order by name",
"select name as table_name from sqlite_master where type = 'table' and name != 'sqlite_sequence' and name != 'geometry_columns' and name != 'spatial_ref_sys' union all select name as table_name from sqlite_temp_master where type = 'table' order by name",
"create table \`mikro_orm_migrations\` (\`id\` integer not null primary key autoincrement, \`name\` varchar(255), \`executed_at\` datetime default current_timestamp)",
"select * from \`mikro_orm_migrations\` order by \`id\` asc",
Expand Down Expand Up @@ -262,6 +263,7 @@ exports[`Migrator (sqlite) up/down params [all or nothing disabled]: all-or-noth

exports[`Migrator (sqlite) up/down params [all or nothing enabled]: all-or-nothing 1`] = `
[
"select name as table_name from sqlite_master where type = 'table' and name != 'sqlite_sequence' and name != 'geometry_columns' and name != 'spatial_ref_sys' union all select name as table_name from sqlite_temp_master where type = 'table' order by name",
"select name as table_name from sqlite_master where type = 'table' and name != 'sqlite_sequence' and name != 'geometry_columns' and name != 'spatial_ref_sys' union all select name as table_name from sqlite_temp_master where type = 'table' order by name",
"create table \`mikro_orm_migrations\` (\`id\` integer not null primary key autoincrement, \`name\` varchar(255), \`executed_at\` datetime default current_timestamp)",
"begin",
Expand Down
1 change: 1 addition & 0 deletions tests/features/schema-generator/GH4051.test.ts
Expand Up @@ -52,6 +52,7 @@ test('upsert and insert both correctly serialize json', async () => {
const orm = await MikroORM.init({
dbName: 'mikro_orm_4051',
entities: [Article1, Article2],
connect: false,
});

expect(await orm.schema.getCreateSchemaSQL({ wrap: false })).toBe(
Expand Down
1 change: 1 addition & 0 deletions tests/features/schema-generator/signed-primary-key.test.ts
Expand Up @@ -19,6 +19,7 @@ test('allow signed primary key when explicitly specified', async () => {
const orm = await MikroORM.init({
dbName: 'mikro_orm_signed_primary_key',
entities: [Article],
connect: false,
});

expect(await orm.schema.getCreateSchemaSQL({ wrap: false })).toBe(
Expand Down

0 comments on commit 827b1f1

Please sign in to comment.