From bc4da9084560fd9c0a1404b420bf35ee6a4349ff Mon Sep 17 00:00:00 2001 From: taozhi8833998 Date: Fri, 2 Aug 2024 09:18:45 +0800 Subject: [PATCH] fix: column constraing in pg --- pegjs/postgresql.pegjs | 5 ++++- src/column.js | 3 ++- test/postgres.spec.js | 6 +++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/pegjs/postgresql.pegjs b/pegjs/postgresql.pegjs index d4581f87..3d2d0ec7 100644 --- a/pegjs/postgresql.pegjs +++ b/pegjs/postgresql.pegjs @@ -1344,7 +1344,10 @@ create_column_definition } column_constraint - = n:(literal_not_null / literal_null) __ df:default_expr? { + = n:constraint_name { + return { constraint: n } + } + / n:(literal_not_null / literal_null) __ df:default_expr? { // => { nullable: literal_null | literal_not_null; default_val: default_expr; } if (n && !n.value) n.value = 'null' return { diff --git a/src/column.js b/src/column.js index 6a173c48..1e827bdf 100644 --- a/src/column.js +++ b/src/column.js @@ -102,7 +102,7 @@ function generatedExpressionToSQL(generated) { function columnOption(definition) { const columnOpt = [] const { - nullable, character_set: characterSet, check, comment, collate, storage, using, + nullable, character_set: characterSet, check, comment, constraint, collate, storage, using, default_val: defaultOpt, generated, auto_increment: autoIncrement, unique: uniqueKey, @@ -117,6 +117,7 @@ function columnOption(definition) { columnOpt.push(type.toUpperCase(), exprToSQL(value)) } const { database } = getParserOpt() + if (constraint) columnOpt.push(toUpper(constraint.keyword), literalToSQL(constraint.constraint)) columnOpt.push(constraintDefinitionToSQL(check)) columnOpt.push(generatedExpressionToSQL(generated)) columnOpt.push(autoIncrementToSQL(autoIncrement), toUpper(primaryKey), toUpper(uniqueKey), commentToSQL(comment)) diff --git a/test/postgres.spec.js b/test/postgres.spec.js index 4f74df2a..d4c62377 100644 --- a/test/postgres.spec.js +++ b/test/postgres.spec.js @@ -1589,10 +1589,10 @@ describe('Postgres', () => { ] }, { - title: '', + title: 'create table with column_constraint', sql: [ - "CREATE TABLE public.tnotok (description text DEFAULT ''::text NOT NULL);", - `CREATE TABLE "public"."tnotok" (description TEXT NOT NULL DEFAULT ''::TEXT)`, + `CREATE TABLE public.tnotok ("id" SERIAL CONSTRAINT users_PK PRIMARY KEY, description text DEFAULT ''::text NOT NULL);`, + `CREATE TABLE "public"."tnotok" ("id" SERIAL CONSTRAINT users_PK PRIMARY KEY, description TEXT NOT NULL DEFAULT ''::TEXT)`, ] }, ]