From fe55b7feb3dc312c31b8dd6dd671ca0150ff5dee Mon Sep 17 00:00:00 2001 From: fergusean Date: Fri, 9 Feb 2024 19:57:08 -0500 Subject: [PATCH] fix(sql): strings should be nullable without casting as JSON (#552) --- packages/mysql/tests/mysql.spec.ts | 19 +++++++++++++++++++ packages/sql/src/platform/default-platform.ts | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/mysql/tests/mysql.spec.ts b/packages/mysql/tests/mysql.spec.ts index 19af392b2..f7d73e50d 100644 --- a/packages/mysql/tests/mysql.spec.ts +++ b/packages/mysql/tests/mysql.spec.ts @@ -323,3 +323,22 @@ test('unique constraint 1', async () => { await expect(p).rejects.toBeInstanceOf(UniqueConstraintFailure); } }); + +test('string/null unions should not render as JSON', async () => { + @entity.name('model6') + class Model { + id: number & PrimaryKey & AutoIncrement = 0; + + constructor(public name: string, public nickName: string | null = null) {} + } + + const database = await databaseFactory([Model]); + await database.persist(new Model('Peter')); + await database.persist(new Model('Christopher', 'Chris')); + + const result = await database.query(Model).orderBy('id', 'asc').find(); + expect(result).toMatchObject([ + {name: 'Peter', nickName: null}, + {name: 'Christopher', nickName: 'Chris'} + ]); +}); diff --git a/packages/sql/src/platform/default-platform.ts b/packages/sql/src/platform/default-platform.ts index 6267f1b04..fb4b95fe8 100644 --- a/packages/sql/src/platform/default-platform.ts +++ b/packages/sql/src/platform/default-platform.ts @@ -31,7 +31,7 @@ export function isNonUndefined(type: Type): boolean { export function typeResolvesToString(type: Type): boolean { if (type.kind === ReflectionKind.string) return true; if (type.kind === ReflectionKind.literal && 'string' === typeof type.literal) return true; - if (type.kind === ReflectionKind.union) return type.types.every(v => typeResolvesToString(v)); + if (type.kind === ReflectionKind.union) return type.types.filter(isNonUndefined).every(v => typeResolvesToString(v)); if (type.kind === ReflectionKind.enum) return typeResolvesToString(type.indexType); return false; }