Skip to content

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

fix: move column create request to query route (#35532)

Han Qiao80791c01b583
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
index 408f3ecce1f..b5f3f59a59b 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
@@ -173,7 +173,7 @@ const ColumnEditor = ({
if (isEmpty(errors)) {
const payload = isNewRecord
- ? generateCreateColumnPayload(selectedTable.id, columnFields)
+ ? generateCreateColumnPayload(selectedTable, columnFields)
: generateUpdateColumnPayload(column!, selectedTable, columnFields)
const configuration = {
columnId: column?.id,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
index f50842258c6..ed670017759 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
@@ -84,13 +84,14 @@ export const generateColumnFieldFromPostgresColumn = (
}
export const generateCreateColumnPayload = (
- tableId: number,
+ table: PostgresTable,
field: ColumnField
): CreateColumnPayload => {
const isIdentity = field.format.includes('int') ? field.isIdentity : false
- const defaultValue = field.defaultValue as any
+ const defaultValue = field.defaultValue
const payload: CreateColumnPayload = {
- tableId,
+ schema: table.schema,
+ table: table.name,
isIdentity,
name: field.name.trim(),
comment: field.comment?.trim(),
@@ -106,9 +107,7 @@ export const generateCreateColumnPayload = (
...(!isIdentity &&
defaultValue && {
defaultValueFormat:
- isNull(defaultValue) || isSQLExpression(defaultValue)
- ? 'expression'
- : ('literal' as 'expression' | 'literal'),
+ isNull(defaultValue) || isSQLExpression(defaultValue) ? 'expression' : 'literal',
}),
}
return payload
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index c15f39c0fd4..c47098b4afc 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -230,7 +230,7 @@ export const createColumn = async ({
try {
// Once pg-meta supports composite keys, we can remove this logic
const { isPrimaryKey, ...formattedPayload } = payload
- const column = await createDatabaseColumn({
+ await createDatabaseColumn({
projectRef: projectRef,
connectionString: connectionString,
payload: formattedPayload,
@@ -246,18 +246,18 @@ export const createColumn = async ({
await dropConstraint(
projectRef,
connectionString,
- column.schema,
- column.table,
+ payload.schema,
+ payload.table,
primaryKey.name
)
}
- const primaryKeyColumns = existingPrimaryKeys.concat([column.name])
+ const primaryKeyColumns = existingPrimaryKeys.concat([formattedPayload.name])
await addPrimaryKey(
projectRef,
connectionString,
- column.schema,
- column.table,
+ payload.schema,
+ payload.table,
primaryKeyColumns
)
}
@@ -267,13 +267,13 @@ export const createColumn = async ({
await addForeignKey({
projectRef,
connectionString,
- table: { schema: column.schema, name: column.table },
+ table: { schema: payload.schema, name: payload.table },
foreignKeys: foreignKeyRelations,
})
}
if (!skipSuccessMessage) {
- toast.success(`Successfully created column "${column.name}"`, { id: toastId })
+ toast.success(`Successfully created column "${formattedPayload.name}"`, { id: toastId })
}
return { error: undefined }
} catch (error: any) {
@@ -496,7 +496,7 @@ export const createTable = async ({
for (const column of columns) {
// We create all columns without primary keys first
- const columnPayload = generateCreateColumnPayload(table.id, {
+ const columnPayload = generateCreateColumnPayload(table, {
...column,
isPrimaryKey: false,
})
@@ -699,7 +699,7 @@ export const updateTable = async ({
toast.loading(`Adding column ${column.name} to ${updatedTable.name}`, { id: toastId })
// Ensure that columns do not created as primary key first, cause the primary key will
// be added later on further down in the code
- const columnPayload = generateCreateColumnPayload(updatedTable.id, {
+ const columnPayload = generateCreateColumnPayload(updatedTable, {
...column,
isPrimaryKey: false,
})
diff --git a/apps/studio/data/database-columns/database-column-create-mutation.ts b/apps/studio/data/database-columns/database-column-create-mutation.ts
index 0a96c279bba..74bc316d5d3 100644
--- a/apps/studio/data/database-columns/database-column-create-mutation.ts
+++ b/apps/studio/data/database-columns/database-column-create-mutation.ts
@@ -1,11 +1,15 @@
+import pgMeta from '@supabase/pg-meta'
import { useMutation, UseMutationOptions } from '@tanstack/react-query'
import { toast } from 'sonner'
import type { components } from 'data/api'
-import { handleError, post } from 'data/fetchers'
+import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
-export type CreateColumnBody = components['schemas']['CreateColumnBody']
+export type CreateColumnBody = Omit<components['schemas']['CreateColumnBody'], 'tableId'> & {
+ schema: string
+ table: string
+}
export type DatabaseColumnCreateVariables = {
projectRef: string
@@ -18,20 +22,30 @@ export async function createDatabaseColumn({
connectionString,
payload,
}: DatabaseColumnCreateVariables) {
- let headers = new Headers()
- if (connectionString) headers.set('x-connection-encrypted', connectionString)
-
- const { data, error } = await post('/platform/pg-meta/{ref}/columns', {
- params: {
- header: { 'x-connection-encrypted': connectionString! },
- path: { ref: projectRef },
- },
- body: payload,
- headers,
+ const { sql } = pgMeta.columns.create({
+ schema: payload.schema,
+ table: payload.table,
+ name: payload.name,
+ type: payload.type,
+ default_value: payload.defaultValue,
+ default_value_format: payload.defaultValueFormat,
+ is_identity: payload.isIdentity,
+ identity_generation: payload.identityGeneration,
+ is_nullable: payload.isNullable,
+ is_primary_key: payload.isPrimaryKey,
+ is_unique: payload.isUnique,
+ comment: payload.comment,
+ check: payload.check,
+ })
+
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: ['column', 'create'],
})
- if (error) handleError(error)
- return data
+ return result
}
type DatabaseColumnCreateData = Awaited<ReturnType<typeof createDatabaseColumn>>
diff --git a/packages/pg-meta/src/pg-meta-columns.ts b/packages/pg-meta/src/pg-meta-columns.ts
index 1be182cbb8a..aaedd84dd22 100644
--- a/packages/pg-meta/src/pg-meta-columns.ts
+++ b/packages/pg-meta/src/pg-meta-columns.ts
@@ -83,13 +83,7 @@ where
}
}
-type ColumnIdentifier =
- | Pick<PGColumn, 'id'>
- | {
- schema: string
- table: string
- name: string
- }
+type ColumnIdentifier = Pick<PGColumn, 'id'> | Pick<PGColumn, 'name' | 'schema' | 'table'>
function getIdentifierWhereClause(identifier: ColumnIdentifier) {
if ('id' in identifier && identifier.id) {
@@ -112,7 +106,8 @@ function retrieve(identifier: ColumnIdentifier): {
}
function create({
- table_id,
+ schema,
+ table,
name,
type,
default_value,
@@ -125,7 +120,8 @@ function create({
comment,
check,
}: {
- table_id: number
+ schema: string
+ table: string
name: string
type: string
default_value?: any
@@ -143,50 +139,53 @@ function create({
if (default_value !== undefined) {
throw new Error('Columns cannot both be identity and have a default value')
}
+
defaultValueClause = `GENERATED ${identity_generation} AS IDENTITY`
- } else if (default_value !== undefined) {
- const formattedDefault =
- // Here we must wrap the litteral value into a String in case it receive a direct number to quote and escape
- // for the execute(format()) call. Maybe we should change the `default_value` to only accept a string instead ?
- default_value_format === 'expression' ? default_value : `'${literal(String(default_value))}'`
- defaultValueClause = `DEFAULT ${formattedDefault}`
+ } else {
+ if (default_value === undefined) {
+ // skip
+ } else if (default_value_format === 'expression') {
+ defaultValueClause = `DEFAULT ${default_value}`
+ } else {
+ defaultValueClause = `DEFAULT ${literal(default_value)}`
+ }
}
- const constraints: string[] = []
- if (is_nullable === false) constraints.push('NOT NULL')
- if (is_primary_key) constraints.push('PRIMARY KEY')
- if (is_unique) constraints.push('UNIQUE')
- if (check) constraints.push(`CHECK (${check})`)
+ let isNullableClause = ''
+ if (is_nullable !== undefined) {
+ isNullableClause = is_nullable ? 'NULL' : 'NOT NULL'
+ }
+ const isPrimaryKeyClause = is_primary_key ? 'PRIMARY KEY' : ''
+ const isUniqueClause = is_unique ? 'UNIQUE' : ''
+ const checkSql = check === undefined ? '' : `CHECK (${check})`
+ const commentSql =
+ comment === undefined
+ ? ''
+ : `COMMENT ON COLUMN ${ident(schema)}.${ident(table)}.${ident(name)} IS ${literal(comment)}`
const sql = `
-DO $$
-DECLARE
- v_schema name;
- v_table name;
-BEGIN
- SELECT n.nspname, c.relname INTO v_schema, v_table
- FROM pg_class c
- JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE c.oid = ${literal(table_id)};
-
- IF v_schema IS NULL THEN
- RAISE EXCEPTION 'Table with id % not found', ${literal(table_id)};
- END IF;
-
- execute(format(
- 'ALTER TABLE %I.%I ADD COLUMN %I %s ${defaultValueClause} ${constraints.join(' ')}',
- v_schema,
- v_table,
- ${literal(name)},
- ${literal(type)}
- ));
-
- ${comment ? `execute(format('COMMENT ON COLUMN %I.%I.%I IS %L', v_schema, v_table, ${literal(name)}, quote_ident(${literal(comment)})));` : ''}
-END $$;`
+BEGIN;
+ ALTER TABLE ${ident(schema)}.${ident(table)} ADD COLUMN ${ident(name)} ${typeIdent(type)}
+ ${defaultValueClause}
+ ${isNullableClause}
+ ${isPrimaryKeyClause}
+ ${isUniqueClause}
+ ${checkSql};
+ ${commentSql};
+COMMIT;`
return { sql }
}
+// TODO: make this more robust - use type_id or type_schema + type_name instead of just type.
+const typeIdent = (type: string) => {
+ return type.endsWith('[]')
+ ? `${ident(type.slice(0, -2))}[]`
+ : type.includes('.')
+ ? type
+ : ident(type)
+}
+
function update(
id: string,
{
diff --git a/packages/pg-meta/test/columns.test.ts b/packages/pg-meta/test/columns.test.ts
index f2088abb7ea..3b524386408 100644
--- a/packages/pg-meta/test/columns.test.ts
+++ b/packages/pg-meta/test/columns.test.ts
@@ -1,4 +1,4 @@
-import { test, beforeAll, afterAll, expect } from 'vitest'
+import { test, beforeAll, afterAll, expect, describe } from 'vitest'
import pgMeta from '../src/index'
import { createTestDatabase, cleanupRoot } from './db/utils'
@@ -178,18 +178,10 @@ withTestDatabase('retrieve, create, update, delete column', async ({ executeQuer
// Create test table using pure SQL
await executeQuery('CREATE TABLE t ()')
- // Get table ID
- const tableId = Number(
- (
- await executeQuery(
- "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
- )
- )[0].oid
- )
-
// Create column
const { sql: createColumnSql } = await pgMeta.columns.create({
- table_id: tableId,
+ schema: 'public',
+ table: 't',
name: 'c',
type: 'int2',
default_value: 42,
@@ -214,7 +206,7 @@ withTestDatabase('retrieve, create, update, delete column', async ({ executeQuer
"check": null,
"comment": "foo",
"data_type": "smallint",
- "default_value": "'42'::smallint",
+ "default_value": "42",
"enums": [],
"format": "int2",
"id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
@@ -337,18 +329,10 @@ withTestDatabase('primary key column', async ({ executeQuery }) => {
// Create test table using pure SQL
await executeQuery('CREATE TABLE t ()')
- // Get table ID
- const tableId = Number(
- (
- await executeQuery(
- "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
- )
- )[0].oid
- )
-
// Create column with primary key
const { sql: createColumnSql } = await pgMeta.columns.create({
- table_id: tableId,
+ schema: 'public',
+ table: 't',
name: 'c',
type: 'int2',
is_primary_key: true,
@@ -378,18 +362,10 @@ withTestDatabase('unique column', async ({ executeQuery }) => {
// Create test table using pure SQL
await executeQuery('CREATE TABLE t ()')
- // Get table ID
- const tableId = Number(
- (
- await executeQuery(
- "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
- )
- )[0].oid
- )
-
// Create column with unique constraint
const { sql: createColumnSql } = await pgMeta.columns.create({
- table_id: tableId,
+ schema: 'public',
+ table: 't',
name: 'c',
type: 'int2',
is_unique: true,
@@ -416,124 +392,178 @@ withTestDatabase('unique column', async ({ executeQuery }) => {
`)
})
-withTestDatabase('array column', async ({ executeQuery }) => {
- // Create test table using pure SQL
- await executeQuery('CREATE TABLE t ()')
+describe('array column', async () => {
+ const db = await createTestDatabase()
+ await db.executeQuery('CREATE TABLE t ()')
- // Get table ID
- const tableId = Number(
- (
- await executeQuery(
- "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
- )
- )[0].oid
- )
-
- // Create array column
- const { sql: createColumnSql } = await pgMeta.columns.create({
- table_id: tableId,
- name: 'c',
- type: 'int2[]',
+ afterAll(async () => {
+ await db.cleanup()
})
- await executeQuery(createColumnSql)
- // Retrieve and verify the created column
- const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
- schema: 'public',
- table: 't',
- name: 'c',
- })
- const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
-
- expect(column).toMatchInlineSnapshot(
- {
- id: expect.stringMatching(/^\d+\.1$/),
+ test.concurrent.for([
+ // numerical types
+ { type: 'int2[]', etype: '_int2' },
+ { type: 'int4[]', etype: '_int4' },
+ { type: 'int8[]', etype: '_int8' },
+ { type: 'float4[]', etype: '_float4' },
+ { type: 'float8[]', etype: '_float8' },
+ { type: 'numeric[]', etype: '_numeric' },
+ // json types
+ { type: 'json[]', etype: '_json' },
+ { type: 'jsonb[]', etype: '_jsonb' },
+ // text types
+ { type: 'text[]', etype: '_text' },
+ { type: 'varchar[]', etype: '_varchar' },
+ // datetime types
+ { type: 'timestamp[]', etype: '_timestamp' },
+ { type: 'timestamptz[]', etype: '_timestamptz' },
+ { type: 'date[]', etype: '_date' },
+ { type: 'time[]', etype: '_time' },
+ { type: 'timetz[]', etype: '_timetz' },
+ // other types
+ { type: 'uuid[]', etype: '_uuid' },
+ { type: 'bool[]', etype: '_bool' },
+ { type: 'bytea[]', etype: '_bytea' },
+ ])('$type -> $etype', async (c, { expect, task }) => {
+ const id = { schema: 'public', table: 't', name: `c${task.id}` }
+
+ // Create column with default value
+ const { sql } = pgMeta.columns.create({
+ ...id,
+ type: c.type,
+ default_value: null,
+ })
+ await db.executeQuery(sql)
+
+ // Retrieve and verify the created column
+ const expected = pgMeta.columns.retrieve(id)
+ const result = await db.executeQuery(expected.sql)
+ const column = expected.zod.parse(result[0])
+
+ expect(column).toStrictEqual({
+ ...id,
+ data_type: 'ARRAY',
+ default_value: null,
+ format: c.etype,
+ id: expect.stringMatching(/^\d+\.\d+$/),
+ ordinal_position: expect.any(Number),
table_id: expect.any(Number),
- },
- `
- {
- "check": null,
- "comment": null,
- "data_type": "ARRAY",
- "default_value": null,
- "enums": [],
- "format": "_int2",
- "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
- "identity_generation": null,
- "is_generated": false,
- "is_identity": false,
- "is_nullable": true,
- "is_unique": false,
- "is_updatable": true,
- "name": "c",
- "ordinal_position": 1,
- "schema": "public",
- "table": "t",
- "table_id": Any<Number>,
- }
- `
- )
+ check: null,
+ comment: null,
+ enums: [],
+ identity_generation: null,
+ is_generated: false,
+ is_identity: false,
+ is_nullable: true,
+ is_unique: false,
+ is_updatable: true,
+ })
+ })
})
-withTestDatabase('column with default value', async ({ executeQuery }) => {
- // Create test table using pure SQL
- await executeQuery('CREATE TABLE t ()')
-
- // Get table ID
- const tableId = Number(
- (
- await executeQuery(
- "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
- )
- )[0].oid
- )
+describe('column with default value', async () => {
+ const db = await createTestDatabase()
+ await db.executeQuery('CREATE TABLE t ()')
- // Create column with default value
- const { sql: createColumnSql } = await pgMeta.columns.create({
- table_id: tableId,
- name: 'c',
- type: 'timestamptz',
- default_value: 'NOW()',
- default_value_format: 'expression',
+ afterAll(async () => {
+ await db.cleanup()
})
- await executeQuery(createColumnSql)
- // Retrieve and verify the created column
- const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({
- schema: 'public',
- table: 't',
- name: 'c',
- })
- const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])
-
- expect(column).toMatchInlineSnapshot(
+ test.concurrent.for([
+ // numerical types
+ { type: 'int2', value: 0, etype: 'smallint', evalue: '0' },
+ { type: 'int4', value: 1, etype: 'integer', evalue: '1' },
+ { type: 'int8', value: -1, etype: 'bigint', evalue: `'-1'::integer` },
+ { type: 'float4', value: 0.1, etype: 'real', evalue: '0.1' },
+ { type: 'float8', value: -0.1, etype: 'double precision', evalue: `'-0.1'::numeric` },
+ { type: 'numeric', value: 1e2, etype: 'numeric', evalue: '100' },
+ // json types
{
- id: expect.stringMatching(/^\d+\.1$/),
- table_id: expect.any(Number),
+ type: 'json',
+ value: { a: 0, b: '1', c: true },
+ etype: 'json',
+ evalue: `'{\"a\": 0, \"b\": \"1\", \"c\": true}'::jsonb`,
},
- `
+ // json array must be stringified, otherwise it will be converted to pg array literal
+ { type: 'jsonb', value: JSON.stringify([null]), etype: 'jsonb', evalue: `'[null]'::jsonb` },
+ // text types
+ { type: 'text', value: `quote's`, etype: 'text', evalue: `'quote''s'::text` },
+ { type: 'varchar', value: '\n', etype: 'character varying', evalue: `'\n'::character varying` },
+ // datetime types
{
- "check": null,
- "comment": null,
- "data_type": "timestamp with time zone",
- "default_value": "now()",
- "enums": [],
- "format": "timestamptz",
- "id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,
- "identity_generation": null,
- "is_generated": false,
- "is_identity": false,
- "is_nullable": true,
- "is_unique": false,
- "is_updatable": true,
- "name": "c",
- "ordinal_position": 1,
- "schema": "public",
- "table": "t",
- "table_id": Any<Number>,
- }
- `
- )
+ type: 'timestamp',
+ value: `now() - INTERVAL '1 day'`,
+ etype: 'timestamp without time zone',
+ evalue: `(now() - '1 day'::interval)`,
+ exp: true,
+ },
+ {
+ type: 'timestamptz',
+ value: 'NOW()',
+ etype: 'timestamp with time zone',
+ evalue: 'now()',
+ exp: true,
+ },
+ { type: 'date', value: '2025-05-09', etype: 'date', evalue: `'2025-05-09'::date` },
+ {
+ type: 'time',
+ value: '11:22:33',
+ etype: 'time without time zone',
+ evalue: `'11:22:33'::time without time zone`,
+ },
+ {
+ type: 'timetz',
+ value: '11:22:33+0800',
+ etype: 'time with time zone',
+ evalue: `'11:22:33+08'::time with time zone`,
+ },
+ // other types
+ {
+ type: 'uuid',
+ value: 'gen_random_uuid()',
+ etype: 'uuid',
+ evalue: 'gen_random_uuid()',
+ exp: true,
+ },
+ { type: 'bool', value: true, etype: 'boolean', evalue: 'true' },
+ // https://www.postgresql.org/docs/current/datatype-binary.html#DATATYPE-BINARY-BYTEA-ESCAPE-FORMAT
+ { type: 'bytea', value: `\\000`, etype: 'bytea', evalue: `'\\x00'::bytea` },
+ ])('$type -> $value', async (c, { expect, task }) => {
+ const id = { schema: 'public', table: 't', name: `c${task.id}` }
+
+ // Create column with default value
+ const { sql } = pgMeta.columns.create({
+ ...id,
+ type: c.type,
+ default_value: c.value,
+ default_value_format: c.exp ? 'expression' : 'literal',
+ })
+ await db.executeQuery(sql)
+
+ // Retrieve and verify the created column
+ const expected = pgMeta.columns.retrieve(id)
+ const result = await db.executeQuery(expected.sql)
+ const column = expected.zod.parse(result[0])
+
+ expect(column).toStrictEqual({
+ ...id,
+ data_type: c.etype,
+ default_value: c.evalue,
+ format: c.type,
+ id: expect.stringMatching(/^\d+\.\d+$/),
+ ordinal_position: expect.any(Number),
+ table_id: expect.any(Number),
+ check: null,
+ comment: null,
+ enums: [],
+ identity_generation: null,
+ is_generated: false,
+ is_identity: false,
+ is_nullable: true,
+ is_unique: false,
+ is_updatable: true,
+ })
+ })
})
// https://github.com/supabase/supabase/issues/3553
@@ -542,18 +572,10 @@ withTestDatabase('alter column to type with uppercase', async ({ executeQuery })
await executeQuery('CREATE TABLE t ()')
await executeQuery('CREATE TYPE "T" AS ENUM ()')
- // Get table ID
- const tableId = Number(
- (
- await executeQuery(
- "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
- )
- )[0].oid
- )
-
// Create and then update column
const { sql: createSql } = await pgMeta.columns.create({
- table_id: tableId,
+ schema: 'public',
+ table: 't',
name: 'c',
type: 'text',
is_unique: false,
@@ -615,18 +637,10 @@ withTestDatabase('enums are populated in enum array columns', async ({ executeQu
await executeQuery(`CREATE TYPE test_enum AS ENUM ('a')`)
await executeQuery('CREATE TABLE t ()')
- // Get table ID
- const tableId = Number(
- (
- await executeQuery(
- "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
- )
- )[0].oid
- )
-
// Create column
const { sql: createSql } = await pgMeta.columns.create({
- table_id: tableId,
+ schema: 'public',
+ table: 't',
name: 'c',
type: '_test_enum',
})
@@ -819,18 +833,10 @@ withTestDatabase('column with fully-qualified type', async ({ executeQuery }) =>
create type s.my_type as enum ();
`)
- // Get table ID using pure SQL
- const tableId = Number(
- (
- await executeQuery(
- "SELECT oid FROM pg_class WHERE relname = 't' AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')"
- )
- )[0].oid
- )
-
// Create column with fully-qualified type
const { sql: createColumnSql } = await pgMeta.columns.create({
- table_id: tableId,
+ schema: 'public',
+ table: 't',
name: 'c',
type: 's.my_type',
})