From 284bef3f0b029b60e10cc798a663d1622f772fe3 Mon Sep 17 00:00:00 2001 From: Sean Ferguson Date: Fri, 9 Feb 2024 19:36:02 -0500 Subject: [PATCH] fix(sql): strings should be nullable without casting as JSON --- 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; }