Skip to content

Commit

Permalink
fix(schema): do not inherit schema for FKs if not a wildcard entity
Browse files Browse the repository at this point in the history
Closes #4918
  • Loading branch information
B4nan committed Nov 17, 2023
1 parent d5af5bd commit cc7fed9
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 5 deletions.
2 changes: 1 addition & 1 deletion packages/knex/src/schema/DatabaseSchema.ts
Expand Up @@ -68,7 +68,7 @@ export class DatabaseSchema {
table.comment = meta.comment;
meta.props
.filter(prop => this.shouldHaveColumn(meta, prop))
.forEach(prop => table.addColumnFromProperty(prop, meta));
.forEach(prop => table.addColumnFromProperty(prop, meta, config));
meta.indexes.forEach(index => table.addIndex(meta, index, 'index'));
meta.uniques.forEach(index => table.addIndex(meta, index, 'unique'));
table.addIndex(meta, { properties: meta.props.filter(prop => prop.primary).map(prop => prop.name) }, 'primary');
Expand Down
19 changes: 16 additions & 3 deletions packages/knex/src/schema/DatabaseTable.ts
@@ -1,4 +1,17 @@
import { Cascade, DateTimeType, DecimalType, EntitySchema, ReferenceType, t, Utils, type Dictionary, type EntityMetadata, type EntityProperty, type NamingStrategy } from '@mikro-orm/core';
import {
Cascade,
DateTimeType,
DecimalType,
EntitySchema,
ReferenceType,
t,
Utils,
type Dictionary,
type EntityMetadata,
type EntityProperty,
type NamingStrategy,
type Configuration,
} from '@mikro-orm/core';
import type { SchemaHelper } from './SchemaHelper';
import type { Check, Column, ForeignKey, Index } from '../typings';
import type { AbstractSqlPlatform } from '../AbstractSqlPlatform';
Expand Down Expand Up @@ -65,7 +78,7 @@ export class DatabaseTable {
this.columns[column.name] = column;
}

addColumnFromProperty(prop: EntityProperty, meta: EntityMetadata) {
addColumnFromProperty(prop: EntityProperty, meta: EntityMetadata, config: Configuration) {
prop.fieldNames.forEach((field, idx) => {
const type = prop.enum ? 'enum' : prop.columnTypes[idx];
const mappedType = this.platform.getMappedType(type);
Expand Down Expand Up @@ -116,7 +129,7 @@ export class DatabaseTable {

if ([ReferenceType.MANY_TO_ONE, ReferenceType.ONE_TO_ONE].includes(prop.reference)) {
const constraintName = this.getIndexName(true, prop.fieldNames, 'foreign');
let schema = prop.targetMeta!.schema === '*' ? this.schema : prop.targetMeta!.schema ?? this.schema;
let schema = prop.targetMeta!.schema === '*' ? this.schema : (prop.targetMeta!.schema ?? config.get('schema', this.platform.getDefaultSchemaName()));

if (prop.referencedTableName.includes('.')) {
schema = undefined;
Expand Down
2 changes: 1 addition & 1 deletion packages/knex/src/schema/SchemaGenerator.ts
Expand Up @@ -272,7 +272,7 @@ export class SchemaGenerator extends AbstractSchemaGenerator<AbstractSqlDriver>
return `${schema}.${referencedTableName.replace(/^\*\./, '')}`;
}

if (schemaName === this.platform.getDefaultSchemaName()) {
if (!schemaName || schemaName === this.platform.getDefaultSchemaName()) {
return tableName;
}

Expand Down
43 changes: 43 additions & 0 deletions tests/features/schema-generator/GH4918.test.ts
@@ -0,0 +1,43 @@
import { MikroORM } from '@mikro-orm/postgresql';
import { Entity, ManyToOne, PrimaryKey, Rel } from '@mikro-orm/core';

@Entity()
class Two {

@PrimaryKey()
id!: string;

@ManyToOne(() => One, { deleteRule: 'cascade' })
one!: Rel<One>;

}

@Entity({ schema: 'test' })
class One {

@PrimaryKey()
id!: string;

@ManyToOne(() => Two, { deleteRule: 'cascade' })
two!: Two;

}

let orm: MikroORM;

beforeAll(async () => {
orm = await MikroORM.init({
entities: [One],
dbName: '4918',
});
await orm.schema.ensureDatabase();
await orm.schema.dropSchema();
});

afterAll(() => orm.close(true));

test('GH #4918', async () => {
const sql = await orm.schema.getCreateSchemaSQL();
expect(sql).toMatchSnapshot();
await orm.schema.execute(sql);
});
19 changes: 19 additions & 0 deletions tests/features/schema-generator/__snapshots__/GH4918.test.ts.snap
@@ -0,0 +1,19 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`GH #4918 1`] = `
"set names 'utf8';
set session_replication_role = 'replica';
create schema if not exists "test";
create table "two" ("id" varchar(255) not null, "one_id" varchar(255) not null, constraint "two_pkey" primary key ("id"));
create table "test"."one" ("id" varchar(255) not null, "two_id" varchar(255) not null, constraint "one_pkey" primary key ("id"));
alter table "two" add constraint "two_one_id_foreign" foreign key ("one_id") references "test"."one" ("id") on update cascade on delete cascade;
alter table "test"."one" add constraint "one_two_id_foreign" foreign key ("two_id") references "two" ("id") on update cascade on delete cascade;
set session_replication_role = 'origin';
"
`;

0 comments on commit cc7fed9

Please sign in to comment.