Skip to content

Commit

Permalink
fix(core): infer property type from columnType for non-inferrable t…
Browse files Browse the repository at this point in the history
…ypes (e.g. unions with `null`)

Closes #4833
  • Loading branch information
B4nan committed Oct 21, 2023
1 parent 1b3c7dc commit 6bc116a
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
5 changes: 5 additions & 0 deletions packages/core/src/metadata/MetadataDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1079,6 +1079,11 @@ export class MetadataDiscovery {
prop.scale ??= pk.scale;
});

if (prop.reference === ReferenceType.SCALAR && prop.type == null && prop.columnTypes) {
const mappedType = this.getMappedType(prop);
prop.type = mappedType.compareAsType();
}

if (prop.columnTypes || !this.schemaHelper) {
return;
}
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/metadata/ReflectMetadataProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ export class ReflectMetadataProvider extends MetadataProvider {
// Instead of requiring the type everywhere, we default to string, which maintains the behaviour,
// as we were mapping it to UnknownType which is a string. This is to prevent defaulting to JSON
// column type, which can be often hard to revert and cause hard to understand issues with PKs.
if (prop.reference === ReferenceType.SCALAR && type === Object) {
// If there are explicitly provided `columnTypes`, we use those instead for the inference, this way
// we can have things like `columnType: 'timestamp'` be respected as `type: 'Date'`.
if (prop.reference === ReferenceType.SCALAR && type === Object && !prop.columnTypes) {
type = String;
}

Expand Down
35 changes: 35 additions & 0 deletions tests/issues/GH4833.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Entity, PrimaryKey, Property } from '@mikro-orm/core';
import { MikroORM } from '@mikro-orm/sqlite';

@Entity()
class Foo {

@PrimaryKey()
id!: number;

@Property()
bar!: string;

@Property({ columnType: 'timestamp(3)', nullable: true })
createdAt: Date | null = null;

}

let orm: MikroORM;

beforeAll(async () => {
orm = await MikroORM.init({
dbName: ':memory:',
entities: [Foo],
});
await orm.schema.createSchema();
});

afterAll(async () => {
await orm.close(true);
});

test(`GH issue 1352`, async () => {
const foo = orm.em.create(Foo, { bar: 'baz' });
orm.em.assign(foo, { createdAt: new Date() });
});

0 comments on commit 6bc116a

Please sign in to comment.