Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(pgmeta): table editor fails with reserved keyword column names (#41226)

Andrew Valleteau3221a3859606
diff --git a/packages/pg-meta/src/pg-format/reserved.ts b/packages/pg-meta/src/pg-format/reserved.ts
index 42e45df2e5a..bb639661b91 100644
--- a/packages/pg-meta/src/pg-format/reserved.ts
+++ b/packages/pg-meta/src/pg-format/reserved.ts
@@ -33,7 +33,9 @@ export const POSTGRESQL_RESERVED_WORDS = new Set([
'CHECK',
'COALESCE',
'COLLATE',
+ 'COLLATION',
'COLUMN',
+ 'CONCURRENTLY',
'CONSTRAINT',
'CREATE',
'CREDENTIALS',
@@ -41,16 +43,18 @@ export const POSTGRESQL_RESERVED_WORDS = new Set([
'CURRENT_CATALOG',
'CURRENT_DATE',
'CURRENT_ROLE',
+ 'CURRENT_SCHEMA',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
- 'CURRENT_USER',
'CURRENT_USER_ID',
+ 'CURRENT_USER',
'DEC',
'DECIMAL',
'DEFAULT',
'DEFERRABLE',
'DEFLATE',
'DEFRAG',
+ 'DELETE',
'DELTA',
'DELTA32K',
'DESC',
@@ -91,6 +95,7 @@ export const POSTGRESQL_RESERVED_WORDS = new Set([
'INITIALLY',
'INNER',
'INOUT',
+ 'INSERT',
'INT',
'INTEGER',
'INTERSECT',
@@ -99,7 +104,6 @@ export const POSTGRESQL_RESERVED_WORDS = new Set([
'IS',
'ISNULL',
'JOIN',
- 'JSON',
'JSON_ARRAY',
'JSON_ARRAYAGG',
'JSON_EXISTS',
@@ -110,6 +114,7 @@ export const POSTGRESQL_RESERVED_WORDS = new Set([
'JSON_SERIALIZE',
'JSON_TABLE',
'JSON_VALUE',
+ 'JSON',
'LATERAL',
'LEADING',
'LEAST',
@@ -179,9 +184,10 @@ export const POSTGRESQL_RESERVED_WORDS = new Set([
'SUBSTRING',
'SYMMETRIC',
'SYSDATE',
- 'SYSTEM',
'SYSTEM_USER',
+ 'SYSTEM',
'TABLE',
+ 'TABLESAMPLE',
'TAG',
'TDES',
'TEXT255',
@@ -198,6 +204,7 @@ export const POSTGRESQL_RESERVED_WORDS = new Set([
'TRUNCATECOLUMNS',
'UNION',
'UNIQUE',
+ 'UPDATE',
'USER',
'USING',
'VALUES',
diff --git a/packages/pg-meta/test/pg-format.test.ts b/packages/pg-meta/test/pg-format.test.ts
new file mode 100644
index 00000000000..23eca848f26
--- /dev/null
+++ b/packages/pg-meta/test/pg-format.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, test } from 'vitest'
+import { ident, literal } from '../src/pg-format'
+
+describe('pg-format', () => {
+ describe('ident', () => {
+ describe('reserved keywords', () => {
+ test('should quote "collation" reserved keyword', () => {
+ expect(ident('collation')).toBe('"collation"')
+ expect(ident('COLLATION')).toBe('"COLLATION"')
+ expect(ident('Collation')).toBe('"Collation"')
+ })
+
+ test('should quote other reserved keywords', () => {
+ expect(ident('select')).toBe('"select"')
+ expect(ident('from')).toBe('"from"')
+ expect(ident('where')).toBe('"where"')
+ expect(ident('order')).toBe('"order"')
+ expect(ident('group')).toBe('"group"')
+ expect(ident('table')).toBe('"table"')
+ expect(ident('column')).toBe('"column"')
+ expect(ident('create')).toBe('"create"')
+ expect(ident('insert')).toBe('"insert"')
+ expect(ident('update')).toBe('"update"')
+ expect(ident('delete')).toBe('"delete"')
+ })
+
+ test('should not quote non-reserved identifiers', () => {
+ expect(ident('normal_column')).toBe('normal_column')
+ expect(ident('my_table')).toBe('my_table')
+ expect(ident('user_id')).toBe('user_id')
+ expect(ident('_private')).toBe('_private')
+ expect(ident('col1')).toBe('col1')
+ })
+
+ test('should quote identifiers with special characters', () => {
+ expect(ident('column with spaces')).toBe('"column with spaces"')
+ expect(ident('column-with-dashes')).toBe('"column-with-dashes"')
+ expect(ident('column.with.dots')).toBe('"column.with.dots"')
+ expect(ident('column$with$dollar')).toBe('column$with$dollar')
+ })
+
+ test('should handle double quotes in identifiers', () => {
+ expect(ident('quoted"column')).toBe('"quoted""column"')
+ expect(ident('"already quoted"')).toBe('"""already quoted"""')
+ })
+
+ test('should handle camelCase identifiers', () => {
+ expect(ident('camelCaseColumn')).toBe('"camelCaseColumn"')
+ expect(ident('PascalCase')).toBe('"PascalCase"')
+ })
+
+ test('should handle identifiers starting with numbers', () => {
+ expect(ident('123column')).toBe('"123column"')
+ expect(ident('1st_column')).toBe('"1st_column"')
+ })
+ })
+
+ describe('edge cases', () => {
+ test('should throw error for null or undefined', () => {
+ expect(() => ident(null)).toThrow('SQL identifier cannot be null or undefined')
+ expect(() => ident(undefined)).toThrow('SQL identifier cannot be null or undefined')
+ })
+
+ test('should handle boolean values', () => {
+ expect(ident(true)).toBe('"t"')
+ expect(ident(false)).toBe('"f"')
+ })
+
+ test('should handle arrays', () => {
+ expect(ident(['col1', 'col2'])).toBe('col1,col2')
+ expect(ident(['collation', 'select'])).toBe('"collation","select"')
+ })
+
+ test('should throw error for nested arrays', () => {
+ expect(() => ident([['col1']])).toThrow(
+ 'Nested array to grouped list conversion is not supported for SQL identifier'
+ )
+ })
+
+ test('should throw error for objects', () => {
+ expect(() => ident({ name: 'test' })).toThrow('SQL identifier cannot be an object')
+ })
+ })
+ })
+
+ describe('literal', () => {
+ test('should handle null and undefined', () => {
+ expect(literal(null)).toBe('NULL')
+ expect(literal(undefined)).toBe('NULL')
+ })
+
+ test('should handle strings', () => {
+ expect(literal('simple string')).toBe("'simple string'")
+ expect(literal("string with 'quotes'")).toBe("'string with ''quotes'''")
+ expect(literal('string with "double quotes"')).toBe('\'string with "double quotes"\'')
+ })
+
+ test('should handle numbers', () => {
+ expect(literal(123)).toBe('123')
+ expect(literal(0)).toBe('0')
+ expect(literal(-42)).toBe('-42')
+ expect(literal(3.14)).toBe('3.14')
+ })
+
+ test('should handle booleans', () => {
+ expect(literal(true)).toBe("'t'")
+ expect(literal(false)).toBe("'f'")
+ })
+
+ test('should handle special number values', () => {
+ expect(literal(Number.POSITIVE_INFINITY)).toBe("'Infinity'")
+ expect(literal(Number.NEGATIVE_INFINITY)).toBe("'-Infinity'")
+ expect(literal(Number.NaN)).toBe("'NaN'")
+ })
+
+ test('should handle bigint', () => {
+ expect(literal(BigInt(123))).toBe('123')
+ expect(literal(BigInt('9007199254740991'))).toBe('9007199254740991')
+ })
+
+ test('should handle dates', () => {
+ const date = new Date('2024-01-01T00:00:00Z')
+ expect(literal(date)).toBe("'2024-01-01 00:00:00.000+00'")
+ })
+
+ test('should handle arrays', () => {
+ expect(literal([1, 2, 3])).toBe('1,2,3')
+ expect(literal(['a', 'b', 'c'])).toBe("'a','b','c'")
+ })
+
+ test('should handle objects as JSON', () => {
+ expect(literal({ name: 'test' })).toBe('\'{"name":"test"}\'::jsonb')
+ expect(literal({ id: 1, name: 'test' })).toBe('\'{"id":1,"name":"test"}\'::jsonb')
+ })
+
+ test('should handle strings with backslashes', () => {
+ expect(literal('path\\to\\file')).toBe("E'path\\\\to\\\\file'")
+ expect(literal('C:\\Users\\test')).toBe("E'C:\\\\Users\\\\test'")
+ })
+ })
+})
diff --git a/packages/pg-meta/test/query/table-row-query.test.ts b/packages/pg-meta/test/query/table-row-query.test.ts
index 8a48b975391..3d6b55e837e 100644
--- a/packages/pg-meta/test/query/table-row-query.test.ts
+++ b/packages/pg-meta/test/query/table-row-query.test.ts
@@ -1752,4 +1752,98 @@ describe('Table Row Query', () => {
expect(largeRowCustom.PPG).toHaveLength(10) // multi-dimentional array are truncated
expect(largeRowCustom.ACC).toHaveLength(10)
})
+
+ withTestDatabase('should handle reserved keyword "collation" as column name', async (db) => {
+ // Create a table with a column named "collation" (a PostgreSQL reserved keyword)
+ await db.executeQuery(`
+ CREATE TABLE IF NOT EXISTS "public"."test" (
+ id SERIAL PRIMARY KEY,
+ "collation" TEXT
+ );
+
+ DELETE FROM "public"."test";
+ INSERT INTO "public"."test" ("collation")
+ VALUES
+ ('value1'),
+ ('value2'),
+ ('value3');
+ `)
+
+ // Get table metadata
+ const { sql: tablesSql, zod: tablesZod } = pgMeta.tables.list()
+ const tables = tablesZod.parse(await db.executeQuery(tablesSql))
+ const testTable = tables.find((table) => table.name === 'test')
+
+ expect(testTable).toBeDefined()
+
+ // Generate SQL - this should properly quote the "collation" column name
+ const sql = getTableRowsSql({
+ table: testTable!,
+ page: 1,
+ limit: 100,
+ })
+
+ // Verify SQL generation - the "collation" column should be properly quoted
+ expect(sql).toMatchInlineSnapshot(`
+ "with _base_query as (select * from public.test order by test.id asc nulls last limit 100 offset 0)
+ select id,case
+ when octet_length("collation"::text) > 10240
+ then left("collation"::text, 10240) || '...'
+ else "collation"::text
+ end as "collation" from _base_query;"
+ `)
+
+ // Execute the generated SQL and verify the results
+ const queryResult = await db.executeQuery(sql)
+ expect(queryResult.length).toBe(3)
+ expect(queryResult[0].collation).toBe('value1')
+ expect(queryResult[1].collation).toBe('value2')
+ expect(queryResult[2].collation).toBe('value3')
+
+ // Test with ORDER BY on the collation column
+ const sqlWithOrder = getTableRowsSql({
+ table: testTable!,
+ page: 1,
+ limit: 100,
+ sorts: [{ table: 'test', column: 'collation', ascending: true, nullsFirst: false }],
+ })
+
+ // Verify the ORDER BY clause properly quotes the collation column
+ expect(sqlWithOrder).toMatchInlineSnapshot(`
+ "with _base_query as (select * from public.test order by test."collation" asc nulls last limit 100 offset 0)
+ select id,case
+ when octet_length("collation"::text) > 10240
+ then left("collation"::text, 10240) || '...'
+ else "collation"::text
+ end as "collation" from _base_query;"
+ `)
+
+ const queryResultWithOrder = await db.executeQuery(sqlWithOrder)
+ expect(queryResultWithOrder.length).toBe(3)
+ expect(queryResultWithOrder[0].collation).toBe('value1')
+ expect(queryResultWithOrder[1].collation).toBe('value2')
+ expect(queryResultWithOrder[2].collation).toBe('value3')
+
+ // Test with FILTER on the collation column
+ const sqlWithFilter = getTableRowsSql({
+ table: testTable!,
+ page: 1,
+ limit: 100,
+ filters: [{ column: 'collation', operator: '=', value: 'value2' }],
+ })
+
+ // Verify the WHERE clause properly quotes the collation column
+ expect(sqlWithFilter).toMatchInlineSnapshot(`
+ "with _base_query as (select * from public.test where "collation" = 'value2' order by test.id asc nulls last limit 100 offset 0)
+ select id,case
+ when octet_length("collation"::text) > 10240
+ then left("collation"::text, 10240) || '...'
+ else "collation"::text
+ end as "collation" from _base_query;"
+ `)
+
+ const queryResultWithFilter = await db.executeQuery(sqlWithFilter)
+ expect(queryResultWithFilter.length).toBe(1)
+ expect(queryResultWithFilter[0].collation).toBe('value2')
+ })
})