From e28ae9232e80fc6f8753dd047498b8ded0f43860 Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Wed, 6 Nov 2024 17:10:58 -0500 Subject: [PATCH] fix: ensure `Alias#colnames` is optional Closes #4 --- scripts/generateTypes.ts | 17 +++++++++-------- scripts/typeMappings.ts | 5 +++++ src/lib/ast.ts | 2 +- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/scripts/generateTypes.ts b/scripts/generateTypes.ts index df1213f..45613c8 100644 --- a/scripts/generateTypes.ts +++ b/scripts/generateTypes.ts @@ -1,6 +1,6 @@ import fs from 'node:fs' import type { NodeFieldMetadataByTag } from './inferFieldMetadata' -import { typeMappings } from './typeMappings' +import { nullableFields, typeMappings } from './typeMappings' /** A record of node tag -> field name -> nullability */ const nodeFieldsByTag: NodeFieldMetadataByTag = JSON.parse( @@ -320,10 +320,9 @@ async function main() { continue } - let fieldType = applyTypeMapping( - typeName + '.' + fieldName, - field.c_type, - ) + const fieldPath = typeName + '.' + fieldName + + let fieldType = applyTypeMapping(fieldPath, field.c_type) if (fieldName === 'type' && fieldType === 'NodeTag') { // Strangely, the result of pg_query_parse doesn't actually include @@ -387,9 +386,11 @@ async function main() { warnUnknownType(typeName + '.' + fieldName, 'list type') } - const nullable = fieldMetadata - ? fieldMetadata[fieldName]?.[0] ?? true - : /\b(NULL|NIL)\b/.test(field.comment ?? '') + const nullable = + (fieldMetadata + ? fieldMetadata[fieldName]?.[0] ?? true + : /\b(NULL|NIL)\b/.test(field.comment ?? '')) || + nullableFields.has(fieldPath) fieldTsDef += ` ${fieldName}${nullable ? '?' : ''}: ${fieldType}\n` } diff --git a/scripts/typeMappings.ts b/scripts/typeMappings.ts index 153cf4d..e3b24cc 100644 --- a/scripts/typeMappings.ts +++ b/scripts/typeMappings.ts @@ -26,6 +26,11 @@ export const typeMappings: Record = { 'SelectStmt.valuesLists': 'List[]', } +/** + * If a field's nullability is incorrectly inferred, add it here. + */ +export const nullableFields = new Set(['Alias.colnames']) + function Node(types: string) { return types .split(' | ') diff --git a/src/lib/ast.ts b/src/lib/ast.ts index 772c016..f02cb6c 100644 --- a/src/lib/ast.ts +++ b/src/lib/ast.ts @@ -4966,7 +4966,7 @@ export type Alias = { /** aliased rel name (never qualified) */ aliasname: string /** optional list of column aliases */ - colnames: { String: String }[] + colnames?: { String: String }[] } /**