From 4cd60b7515b06c0aac0380aeb46ed10a72090545 Mon Sep 17 00:00:00 2001 From: Mitchell Adair Date: Wed, 24 Jul 2024 14:09:13 -0400 Subject: [PATCH] improve geography type narrowing --- .../src/singlestore-core/columns/geography.ts | 49 +++++++++++++------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/drizzle-orm/src/singlestore-core/columns/geography.ts b/drizzle-orm/src/singlestore-core/columns/geography.ts index 2ae6195d8..b2bc8ac6b 100644 --- a/drizzle-orm/src/singlestore-core/columns/geography.ts +++ b/drizzle-orm/src/singlestore-core/columns/geography.ts @@ -69,23 +69,18 @@ export class SingleStoreGeography sql`${ls[0]} ${ls[1]}`); - return sql`"LINESTRING(${sql.join(points, sql.raw(', '))})"`; - } else { - const polygon = value as GeographyPolygon; - const rings = polygon.map((ring) => { - const points = ring.map((point) => sql`${point[0]} ${point[1]}`); - return sql`(${sql.join(points, sql.raw(', '))})`; - }); - return sql`"POLYGON(${sql.join(rings, sql.raw(', '))})"`; - } + } else if (_isLineString(value)) { + const points = value.map((ls) => sql`${ls[0]} ${ls[1]}`); + return sql`"LINESTRING(${sql.join(points, sql.raw(', '))})"`; + } else if (_isPolygon(value)) { + const rings = value.map((ring) => { + const points = ring.map((point) => sql`${point[0]} ${point[1]}`); + return sql`(${sql.join(points, sql.raw(', '))})`; + }); + return sql`"POLYGON(${sql.join(rings, sql.raw(', '))})"`; } else { throw new Error('value is not Array'); } @@ -129,3 +124,25 @@ export class SingleStoreGeography(name: TName): SingleStoreGeographyBuilderInitial { return new SingleStoreGeographyBuilder(name); } + +function _isPoint(value: GeographyPoint | GeographyLineString | GeographyPolygon): value is GeographyPoint { + return value.length === 2 && typeof value[0] === 'number'; +} + +function _isLineString(value: GeographyPoint | GeographyLineString | GeographyPolygon): value is GeographyLineString { + try { + const test = value as GeographyLineString; + return typeof test[0]![0] === 'number'; + } catch { + return false; + } +} + +function _isPolygon(value: GeographyPoint | GeographyLineString | GeographyPolygon): value is GeographyPolygon { + try { + const test = value as GeographyPolygon; + return typeof test[0]![0]![0] === 'number'; + } catch { + return false; + } +}