The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
studio: ColumnTypeRef cascade + FK type comparison fixes (2/7) (#45903)
Charisd79a276824d5
diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.types.ts b/apps/studio/components/interfaces/Auth/Policies/Policies.types.tsindex 5b01fea84f7..911fb6426fc 100644--- a/apps/studio/components/interfaces/Auth/Policies/Policies.types.ts+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.types.ts@@ -1,3 +1,5 @@+import type { DisplayableSqlFragment, SafeSqlFragment } from '@supabase/pg-meta'+export interface PolicyFormField {id?: numbername: string@@ -19,8 +21,8 @@ export interface PostgresPolicyCreatePayload {name: stringtable: stringschema?: string- definition?: string- check?: string+ definition?: SafeSqlFragment+ check?: SafeSqlFragmentaction?: 'PERMISSIVE' | 'RESTRICTIVE'command?: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'ALL'roles?: string[]@@ -29,7 +31,30 @@ export interface PostgresPolicyCreatePayload {export interface PostgresPolicyUpdatePayload {id: numbername?: string- definition?: string- check?: string+ definition?: SafeSqlFragment+ check?: SafeSqlFragmentroles?: string[]}++/**+ * Pre-acceptance shape of {@link PostgresPolicyCreatePayload}. `definition`/`check` are+ * `DisplayableSqlFragment` because they originate from form input and have not yet been+ * promoted via `acceptUntrustedSql`. Promotion must happen at the user gesture+ * (the Save click in `PolicyEditorModal`), not inside a utility.+ */+export interface DraftPostgresPolicyCreatePayload extends Omit<+ PostgresPolicyCreatePayload,+ 'definition' | 'check'+> {+ definition?: DisplayableSqlFragment+ check?: DisplayableSqlFragment+}++/** Pre-acceptance shape of {@link PostgresPolicyUpdatePayload}. See {@link DraftPostgresPolicyCreatePayload}. */+export interface DraftPostgresPolicyUpdatePayload extends Omit<+ PostgresPolicyUpdatePayload,+ 'definition' | 'check'+> {+ definition?: DisplayableSqlFragment+ check?: DisplayableSqlFragment+}diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.utils.test.ts b/apps/studio/components/interfaces/Auth/Policies/Policies.utils.test.tsindex fe78ee7e615..e785b11c2b9 100644--- a/apps/studio/components/interfaces/Auth/Policies/Policies.utils.test.ts+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.utils.test.ts@@ -1,3 +1,4 @@+import { safeSql } from '@supabase/pg-meta'import { beforeEach, describe, expect, it, vi } from 'vitest'import {@@ -249,7 +250,7 @@ describe('Policies.utils - Policy Generation', () => {command: 'SELECT',table: 'posts',schema: 'public',- definition: 'true',+ definition: safeSql`true`,action: 'PERMISSIVE',roles: ['public'],},@@ -342,7 +343,7 @@ describe('Policies.utils - Policy Generation', () => {command: 'SELECT',table: 'posts',schema: 'public',- definition: 'true',+ definition: safeSql`true`,action: 'PERMISSIVE',roles: ['public'],},diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.utils.ts b/apps/studio/components/interfaces/Auth/Policies/Policies.utils.tsindex 81f38781a7d..d98c9322558 100644--- a/apps/studio/components/interfaces/Auth/Policies/Policies.utils.ts+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.utils.ts@@ -1,12 +1,19 @@+import {+ acceptUntrustedSql,+ ident,+ safeSql,+ untrustedSql,+ type DisplayableSqlFragment,+ type SafeSqlFragment,+} from '@supabase/pg-meta'import type { PGPolicy } from '@supabase/pg-meta'-import { ident } from '@supabase/pg-meta/src/pg-format'import { has, isEmpty, isEqual } from 'lodash'import {+ DraftPostgresPolicyCreatePayload,+ DraftPostgresPolicyUpdatePayload,PolicyFormField,PolicyForReview,- PostgresPolicyCreatePayload,- PostgresPolicyUpdatePayload,} from './Policies.types'import { generateSqlPolicy } from '@/data/ai/sql-policy-mutation'import type { CreatePolicyBody } from '@/data/database-policies/database-policy-create-mutation'@@ -113,16 +120,22 @@ const createSQLStatementForUpdatePolicy = (return { description, statement }}+// These constructors return DRAFT payloads — `definition`/`check` are still+// `DisplayableSqlFragment`. Promotion to `SafeSqlFragment` must happen at the user gesture+// (the Save click in `PolicyEditorModal`), not here, since this module has no guarantee that+// it was reached via a deliberate user action.export const createPayloadForCreatePolicy = (policyFormFields: PolicyFormField-): PostgresPolicyCreatePayload => {- const { command, definition, check, roles } = policyFormFields+): DraftPostgresPolicyCreatePayload => {+ const { name, schema, table, command, definition, check, roles } = policyFormFieldsreturn {- ...policyFormFields,+ name,+ schema,+ table,action: 'PERMISSIVE',command: command || undefined,- definition: definition || undefined,- check: check || undefined,+ definition: !definition ? undefined : untrustedSql(definition),+ check: !check ? undefined : untrustedSql(check),roles: roles.length > 0 ? roles : undefined,}}@@ -130,28 +143,25 @@ export const createPayloadForCreatePolicy = (export const createPayloadForUpdatePolicy = (policyFormFields: PolicyFormField,originalPolicyFormFields: PGPolicy-): PostgresPolicyUpdatePayload => {+): DraftPostgresPolicyUpdatePayload => {const { definition, check } = policyFormFields- const formattedPolicyFormFields = {- ...policyFormFields,- definition: definition ? definition.replace(/\s+/g, ' ').trim() : definition,- check: check ? check.replace(/\s+/g, ' ').trim() : check,- }+ const formattedDefinition = definition ? definition.replace(/\s+/g, ' ').trim() : definition+ const formattedCheck = check ? check.replace(/\s+/g, ' ').trim() : check- const payload: PostgresPolicyUpdatePayload = { id: originalPolicyFormFields.id }+ const payload: DraftPostgresPolicyUpdatePayload = { id: originalPolicyFormFields.id }- if (!isEqual(formattedPolicyFormFields.name, originalPolicyFormFields.name)) {- payload.name = formattedPolicyFormFields.name+ if (!isEqual(policyFormFields.name, originalPolicyFormFields.name)) {+ payload.name = policyFormFields.name}- if (!isEqual(formattedPolicyFormFields.definition, originalPolicyFormFields.definition)) {- payload.definition = formattedPolicyFormFields.definition || undefined+ if (!isEqual(formattedDefinition, originalPolicyFormFields.definition)) {+ payload.definition = !formattedDefinition ? undefined : untrustedSql(formattedDefinition)}- if (!isEqual(formattedPolicyFormFields.check, originalPolicyFormFields.check)) {- payload.check = formattedPolicyFormFields.check || undefined+ if (!isEqual(formattedCheck, originalPolicyFormFields.check)) {+ payload.check = !formattedCheck ? undefined : untrustedSql(formattedCheck)}- if (!isEqual(formattedPolicyFormFields.roles, originalPolicyFormFields.roles)) {- if (formattedPolicyFormFields.roles.length === 0) payload.roles = ['public']- else payload.roles = formattedPolicyFormFields.roles || undefined+ if (!isEqual(policyFormFields.roles, originalPolicyFormFields.roles)) {+ if (policyFormFields.roles.length === 0) payload.roles = ['public']+ else payload.roles = policyFormFields.roles || undefined}return payload@@ -160,17 +170,43 @@ export const createPayloadForUpdatePolicy = (// --- Policy Generation ---/**- * Generated policy extends CreatePolicyBody with additional fields for display.- * - sql: Full CREATE POLICY SQL statement for preview- * - Required fields that are optional in CreatePolicyBody+ * A policy generated for display/staging in the table editor.+ * `definition`/`check` are `DisplayableSqlFragment` because generators have different provenance:+ * programmatic generation produces `SafeSqlFragment` (composed via `safeSql`), AI generation+ * produces `UntrustedSqlFragment` (third-party output). Consumers must promote via+ * `acceptUntrustedSql` at a user gesture before executing.*/export type GeneratedPolicy = Required<Pick<CreatePolicyBody, 'name' | 'table' | 'schema' | 'action' | 'roles'>> &- Pick<CreatePolicyBody, 'command' | 'definition' | 'check'> & {+ Pick<CreatePolicyBody, 'command'> & {+ definition?: DisplayableSqlFragment+ check?: DisplayableSqlFragmentsql: string}+/**+ * A {@link GeneratedPolicy} whose `definition`/`check` have already been promoted to+ * `SafeSqlFragment`. Producing one of these is the contract that says: the user gesture+ * required to execute this SQL has already happened.+ */+export type AcceptedGeneratedPolicy = Omit<GeneratedPolicy, 'definition' | 'check'> & {+ definition?: SafeSqlFragment+ check?: SafeSqlFragment+}++/**+ * Promotes a {@link GeneratedPolicy} to an {@link AcceptedGeneratedPolicy}.+ * ONLY call from an event handler tied to a deliberate user action (e.g. the Save click+ * on the table editor). Never call from useEffect, render, or any path that runs without+ * a user gesture.+ */+export const acceptGeneratedPolicy = (policy: GeneratedPolicy): AcceptedGeneratedPolicy => ({+ ...policy,+ definition: policy.definition === undefined ? undefined : acceptUntrustedSql(policy.definition),+ check: policy.check === undefined ? undefined : acceptUntrustedSql(policy.check),+})+type Relationship = {source_schema: stringsource_table_name: string@@ -270,23 +306,22 @@ const findPathToAuthUsers = (}/** Generates SQL expression for RLS policy based on FK path to auth.users */-const buildPolicyExpression = (path: Relationship[]): string => {- if (path.length === 0) return ''+const buildPolicyExpression = (path: Relationship[]): SafeSqlFragment => {+ if (path.length === 0) return safeSql``// Direct FK to auth.usersif (path.length === 1) {- return `(select auth.uid()) = ${ident(path[0].source_column_name)}`+ return safeSql`(select auth.uid()) = ${ident(path[0].source_column_name)}`}// Indirect path - build EXISTS with JOINsconst [first, ...rest] = path- const firstTarget = `${ident(first.target_table_schema)}.${ident(first.target_table_name)}`- const source = `${ident(first.source_schema)}.${ident(first.source_table_name)}`+ const firstTarget = safeSql`${ident(first.target_table_schema)}.${ident(first.target_table_name)}`+ const source = safeSql`${ident(first.source_schema)}.${ident(first.source_table_name)}`const last = path[path.length - 1]- const joins = rest- .slice(0, -1)- .map((r) => {+ const joins = rest.slice(0, -1).reduce<SafeSqlFragment>(+ (acc, r) => {const targetSchema = ident(r.target_table_schema)const targetTable = ident(r.target_table_name)const targetColumn = ident(r.target_column_name)@@ -294,11 +329,13 @@ const buildPolicyExpression = (path: Relationship[]): string => {const sourceSchema = ident(r.source_schema)const sourceTable = ident(r.source_table_name)const sourceColumn = ident(r.source_column_name)- return `join ${targetSchema}.${targetTable} on ${targetSchema}.${targetTable}.${targetColumn} = ${sourceSchema}.${sourceTable}.${sourceColumn}`- })- .join('\n ')+ const join = safeSql`join ${targetSchema}.${targetTable} on ${targetSchema}.${targetTable}.${targetColumn} = ${sourceSchema}.${sourceTable}.${sourceColumn}`+ return acc.length === 0 ? join : safeSql`${acc}\n ${join}`+ },+ safeSql``+ )- return `exists (+ return safeSql`exists (select 1 from ${firstTarget}${joins}where ${firstTarget}.${ident(first.target_column_name)} = ${source}.${ident(first.source_column_name)}@@ -383,15 +420,13 @@ export const generateAiPoliciesForTable = async ({if (!connectionString) return []try {- const aiPolicies = await generateSqlPolicy({+ return await generateSqlPolicy({tableName: table.name,schema: table.schema,columns: columns.map((col) => col.name.trim()),projectRef,connectionString: connectionString ?? '',})- // AI response now includes all structured fields- return aiPolicies as GeneratedPolicy[]} catch (error) {console.log('AI policy generation failed:', error)return []diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsxindex 3076480255e..ba98ee0bdfb 100644--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx@@ -1,4 +1,4 @@-import type { PGPolicy } from '@supabase/pg-meta'+import { acceptUntrustedSql, PGPolicy } from '@supabase/pg-meta'import { isEmpty, noop } from 'lodash'import { useCallback, useEffect, useState } from 'react'import { toast } from 'sonner'@@ -6,6 +6,8 @@ import { Modal } from 'ui'import { POLICY_MODAL_VIEWS } from '../Policies.constants'import {+ DraftPostgresPolicyCreatePayload,+ DraftPostgresPolicyUpdatePayload,PolicyFormField,PolicyForReview,PostgresPolicyCreatePayload,@@ -28,6 +30,24 @@ import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialoimport useLatest from '@/hooks/misc/useLatest'import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'+// Call only from a user-gesture handler (the Save click). Promotes the draft payload's+// `definition`/`check` from `DisplayableSqlFragment` to executable `SafeSqlFragment`.+const acceptCreatePayload = (+ draft: DraftPostgresPolicyCreatePayload+): PostgresPolicyCreatePayload => ({+ ...draft,+ definition: draft.definition === undefined ? undefined : acceptUntrustedSql(draft.definition),+ check: draft.check === undefined ? undefined : acceptUntrustedSql(draft.check),+})++const acceptUpdatePayload = (+ draft: DraftPostgresPolicyUpdatePayload+): PostgresPolicyUpdatePayload => ({+ ...draft,+ definition: draft.definition === undefined ? undefined : acceptUntrustedSql(draft.definition),+ check: draft.check === undefined ? undefined : acceptUntrustedSql(draft.check),+})+interface PolicyEditorModalProps {visible?: booleanschema?: string@@ -163,10 +183,11 @@ export const PolicyEditorModal = ({onReviewPolicy()}+ // The Save click is the explicit user gesture that promotes editor SQL to executable.const onReviewSave = () => {const payload = isNewPolicy- ? createPayloadForCreatePolicy(policyFormFields)- : createPayloadForUpdatePolicy(policyFormFields, selectedPolicyToEdit)+ ? acceptCreatePayload(createPayloadForCreatePolicy(policyFormFields))+ : acceptUpdatePayload(createPayloadForUpdatePolicy(policyFormFields, selectedPolicyToEdit))onSavePolicy(payload)setIsDirty(false)}diff --git a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsxindex ec14624c487..450ea08914a 100644--- a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx+++ b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx@@ -1,4 +1,4 @@-import type { PGSchema, PGTable } from '@supabase/pg-meta'+import type { PGSchema } from '@supabase/pg-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'import {Background,@@ -64,6 +64,7 @@ import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useIsProtectedSchema } from '@/hooks/useProtectedSchemas'import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'import { tablesToSQL } from '@/lib/helpers'+import type { SafePostgresTable } from '@/lib/postgres-types'import { SHORTCUT_IDS } from '@/state/shortcuts/registry'import { useShortcut } from '@/state/shortcuts/useShortcut'import { useTableEditorStateSnapshot } from '@/state/table-editor'@@ -75,7 +76,7 @@ export const SchemaGraph = () => {const { resolvedTheme } = useTheme()const { data: project } = useSelectedProjectQuery()const { selectedSchema, setSelectedSchema } = useQuerySchemaState()- const [selectedTable, setSelectedTable] = useState<PGTable | null>(null)+ const [selectedTable, setSelectedTable] = useState<SafePostgresTable | null>(null)const snap = useTableEditorStateSnapshot()const { isDownloading, exportSchemaToImage } = useExportSchemaToImage()diff --git a/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx b/apps/studio/components/interfaces/Database/Tables/ColumnList.tsxindex 59d22f78532..b282284b55c 100644--- a/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx+++ b/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx@@ -1,4 +1,3 @@-import type { PGColumn } from '@supabase/pg-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { noop } from 'lodash'@@ -48,6 +47,7 @@ import {getUniqueIndexColumnNames,} from './ColumnList.utils'import { ConstraintToken } from './ConstraintToken'+import { displayColumnType } from '@/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils'import AlertError from '@/components/ui/AlertError'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { DropdownMenuItemTooltip } from '@/components/ui/DropdownMenuItemTooltip'@@ -57,8 +57,9 @@ import { isTableLike } from '@/data/table-editor/table-editor-types'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useIsProtectedSchema } from '@/hooks/useProtectedSchemas'+import type { SafePostgresColumn } from '@/lib/postgres-types'-const getColumnTypeAffordancePresentation = (column: PGColumn) => {+const getColumnTypeAffordancePresentation = (column: SafePostgresColumn) => {const { kind, label } = getColumnTypeAffordance(column.format)const iconClassName = 'text-foreground-muted'@@ -98,8 +99,8 @@ const getColumnTypeAffordancePresentation = (column: PGColumn) => {interface ColumnListProps {onAddColumn: () => void- onEditColumn: (column: PGColumn) => void- onDeleteColumn: (column: PGColumn) => void+ onEditColumn: (column: SafePostgresColumn) => void+ onDeleteColumn: (column: SafePostgresColumn) => void}export const ColumnList = ({@@ -322,7 +323,11 @@ export const ColumnList = ({<span>{column.data_type}</span>{column.format !== column.data_type && (<span className="text-xs text-foreground-light">- {column.format}+ {displayColumnType(+ column.format,+ column.format_schema,+ column.data_type === 'ARRAY'+ )}</span>)}</div>@@ -343,7 +348,13 @@ export const ColumnList = ({</div></TableCell><TableCell>- <p className="text-foreground-lighter">{column.format}</p>+ <p className="text-foreground-lighter">+ {displayColumnType(+ column.format,+ column.format_schema,+ column.data_type === 'ARRAY'+ )}+ </p></TableCell><TableCell><div className="flex flex-wrap gap-1.5">{constraintTokens}</div>diff --git a/apps/studio/components/interfaces/Database/Tables/TableList.tsx b/apps/studio/components/interfaces/Database/Tables/TableList.tsxindex c185e8c0d4f..9482d574220 100644--- a/apps/studio/components/interfaces/Database/Tables/TableList.tsx+++ b/apps/studio/components/interfaces/Database/Tables/TableList.tsx@@ -1,4 +1,3 @@-import type { PGTable } from '@supabase/pg-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { noop } from 'lodash'@@ -55,14 +54,15 @@ import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useIsProtectedSchema } from '@/hooks/useProtectedSchemas'import { onSearchInputEscape } from '@/lib/keyboard'+import type { SafePostgresTable } from '@/lib/postgres-types'import { SHORTCUT_IDS } from '@/state/shortcuts/registry'import { useShortcut } from '@/state/shortcuts/useShortcut'interface TableListProps {onAddTable: () => void- onEditTable: (table: PGTable) => void- onDeleteTable: (table: PGTable) => void- onDuplicateTable: (table: PGTable) => void+ onEditTable: (table: SafePostgresTable) => void+ onDeleteTable: (table: SafePostgresTable) => void+ onDuplicateTable: (table: SafePostgresTable) => void}export const TableList = ({diff --git a/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts b/apps/studio/components/interfaces/Database/Tables/Tables.utils.tsindex 6b19bcca627..ba680101425 100644--- a/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts+++ b/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts@@ -1,6 +1,7 @@-import type { PGForeignTable, PGMaterializedView, PGTable, PGView } from '@supabase/pg-meta'+import { PGForeignTable, PGMaterializedView, PGView } from '@supabase/pg-meta'import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'+import type { SafePostgresTable } from '@/lib/postgres-types'// [Joshen] We just need name, schema, description, rows, size, and the number of columns// Just missing partitioned tables as missing pg-meta support@@ -10,7 +11,7 @@ export const formatAllEntities = ({materializedViews = [],foreignTables = [],}: {- tables?: PGTable[]+ tables?: SafePostgresTable[]views?: PGView[]materializedViews?: PGMaterializedView[]foreignTables?: PGForeignTable[]diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsxindex 58d8a8f2398..f7f276487f6 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx@@ -1,4 +1,4 @@-import type { PGColumn, PGTable } from '@supabase/pg-meta'+import { safeSql } from '@supabase/pg-meta'import { useParams } from 'common'import { isEmpty, noop } from 'lodash'import { ExternalLink, Plus } from 'lucide-react'@@ -36,7 +36,7 @@ import type {import ColumnDefaultValue from './ColumnDefaultValue'import {generateColumnField,- generateColumnFieldFromPostgresColumn,+ generateColumnFieldFromPGColumn,generateCreateColumnPayload,generateUpdateColumnPayload,getPlaceholderText,@@ -50,6 +50,7 @@ import {FormSectionContent,FormSectionLabel,} from '@/components/ui/Forms/FormSection'+import { SafeSqlInput } from '@/components/ui/SafeSqlInput'import {Constraint,CONSTRAINT_TYPE,@@ -60,13 +61,16 @@ import {useForeignKeyConstraintsQuery,} from '@/data/database/foreign-key-constraints-query'import { useEnumeratedTypesQuery } from '@/data/enumerated-types/enumerated-types-query'+import type { RetrieveTableResult } from '@/data/tables/table-retrieve-query'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useProtectedSchemas } from '@/hooks/useProtectedSchemas'import { DOCS_URL } from '@/lib/constants'+import type { SafePostgresColumn } from '@/lib/postgres-types'+import type { DeepReadonly } from '@/lib/type-helpers'export interface ColumnEditorProps {- column?: Readonly<PGColumn>- selectedTable: PGTable+ column?: DeepReadonly<SafePostgresColumn>+ selectedTable: RetrieveTableResultvisible: booleanclosePanel: () => voidsaveChanges: (@@ -145,7 +149,7 @@ export const ColumnEditor = ({setForeignKeySelectorOpen(false)const columnFields = isNewRecord? generateColumnField({ schema: selectedTable.schema, table: selectedTable.name })- : generateColumnFieldFromPostgresColumn(column, selectedTable, foreignKeyMeta)+ : generateColumnFieldFromPGColumn(column, selectedTable, foreignKeyMeta)setColumnFields(columnFields)setFkRelations(formatForeignKeys(foreignKeys))}@@ -324,7 +328,10 @@ export const ColumnEditor = ({<FormSectionContent loading={false} className="lg:col-span-8!"><ColumnTypeshowRecommendation- value={columnFields?.format ?? ''}+ value={{+ format: columnFields?.format ?? '',+ formatSchema: columnFields?.formatSchema,+ }}layout="vertical"enumTypes={enumTypes}error={errors.format}@@ -334,7 +341,9 @@ export const ColumnEditor = ({: ''}disabled={lockColumnType}- onOptionSelect={(format: string) => onUpdateField({ format, defaultValue: null })}+ onOptionSelect={({ format, formatSchema }) =>+ onUpdateField({ format, formatSchema, defaultValue: null })+ }/>{columnFields.foreignKey === undefined && (<div className="space-y-4">@@ -397,12 +406,14 @@ export const ColumnEditor = ({column={columnFields}relations={fkRelations}closePanel={closePanel}- onUpdateColumnType={(format: string) => {- if (format[0] === '_') {- onUpdateField({ format: format.slice(1), isArray: true, isIdentity: false })- } else {- onUpdateField({ format })- }+ onUpdateColumnType={({ format, formatSchema, isArray }) => {+ const bareFormat = isArray && format.startsWith('_') ? format.slice(1) : format+ onUpdateField({+ format: bareFormat,+ formatSchema,+ isArray,+ isIdentity: isArray ? false : columnFields.isIdentity,+ })}}onOpenChange={setForeignKeySelectorOpen}onUpdateFkRelations={setFkRelations}@@ -485,11 +496,11 @@ export const ColumnEditor = ({</Tooltip><FormItemLayout isReactForm={false} label="CHECK constraint" labelOptional="Optional">- <Input+ <SafeSqlInputtype="text"placeholder={placeholder}- value={columnFields?.check ?? ''}- onChange={(event) => onUpdateField({ check: event.target.value })}+ value={columnFields?.check ?? safeSql``}+ onChange={(_event, value) => onUpdateField({ check: value })}className="[&_input]:font-mono"/></FormItemLayout>diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.tsindex 068dfd55b77..40a5d968cc4 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts@@ -1,4 +1,4 @@-import { FOREIGN_KEY_CASCADE_ACTION } from '@supabase/pg-meta'+import { FOREIGN_KEY_CASCADE_ACTION, ident, safeSql, type SafeSqlFragment } from '@supabase/pg-meta'import type { PGColumn } from '@supabase/pg-meta'import { isNull } from 'lodash'import { toast } from 'sonner'@@ -10,10 +10,32 @@ import {UpdateColumnPayload,} from '../SidePanelEditor.types'import type { ForeignKeyConstraint } from '@/data/database/foreign-key-constraints-query'-import type { RetrievedTableColumn, RetrieveTableResult } from '@/data/tables/table-retrieve-query'+import type { RetrieveTableResult } from '@/data/tables/table-retrieve-query'import { uuidv4 } from '@/lib/helpers'+import type { SafePostgresColumn } from '@/lib/postgres-types'+import { trimSafeSqlFragment } from '@/lib/sql'+import type { DeepReadonly } from '@/lib/type-helpers'import type { Dictionary } from '@/types'+// Schemas where types are considered "unqualified" — matches the ColumnType dropdown convention,+// which omits formatSchema for built-in (pg_catalog) and public types.+const isImplicitTypeSchema = (schema: string | undefined) =>+ schema === 'public' || schema === 'pg_catalog'++export const normalizeFormatSchema = (schema: string | undefined): string | undefined =>+ isImplicitTypeSchema(schema) ? undefined : schema++export const displayColumnType = (+ format: string,+ formatSchema: string | undefined,+ isArray?: boolean+): string => {+ const bareFormat = isArray && format.startsWith('_') ? format.slice(1) : format+ const normalized = normalizeFormatSchema(formatSchema)+ const qualified = normalized ? `${normalized}.${bareFormat}` : bareFormat+ return isArray ? `${qualified}[]` : qualified+}+const isSQLExpression = (input: string) => {if (['CURRENT_DATE'].includes(input)) return true@@ -33,9 +55,15 @@ const isSQLExpression = (input: string) => {}export const generateColumnField = (- field: { name?: string; table?: string; schema?: string; format?: string } = {}+ field: {+ name?: string+ table?: string+ schema?: string+ format?: string+ formatSchema?: string+ } = {}): ColumnField => {- const { name, table, schema, format } = field+ const { name, table, schema, format, formatSchema } = fieldreturn {id: uuidv4(),name: name || '',@@ -43,6 +71,7 @@ export const generateColumnField = (schema: schema || '',comment: '',format: format || '',+ formatSchema,defaultValue: null,foreignKey: undefined,check: null,@@ -56,8 +85,15 @@ export const generateColumnField = (}}-export const generateColumnFieldFromPostgresColumn = (- column: PGColumn,+// SafePostgresColumn (the type carried through Studio state) doesn't expose the type's schema,+// but the column row returned by pg-meta's tables.retrieve does. Look it up by id.+const lookupFormatSchema = (+ column: DeepReadonly<SafePostgresColumn>,+ table: RetrieveTableResult+): string | undefined => table.columns?.find((c) => c.id === column.id)?.format_schema++export const generateColumnFieldFromPGColumn = (+ column: DeepReadonly<SafePostgresColumn>,table: RetrieveTableResult,foreignKeys: ForeignKeyConstraint[]): ColumnField => {@@ -74,6 +110,7 @@ export const generateColumnFieldFromPostgresColumn = (name: column.name,comment: column?.comment,format: isArray ? column.format.slice(1) : column.format,+ formatSchema: normalizeFormatSchema(lookupFormatSchema(column, table)),defaultValue: column?.default_value as string | null,check: column.check,isArray: isArray,@@ -99,8 +136,8 @@ export const generateCreateColumnPayload = (isIdentity,name: field.name.trim(),comment: field.comment?.trim(),- type: field.isArray ? `${field.format}[]` : field.format,- check: field.check?.trim() || undefined,+ type: { schema: field.formatSchema, name: field.format, isArray: field.isArray },+ check: trimSafeSqlFragment(field.check) ?? undefined,isUnique: field.isUnique,isPrimaryKey: field.isPrimaryKey,...(!field.isPrimaryKey && !isIdentity && { isNullable: field.isNullable }),@@ -118,7 +155,7 @@ export const generateCreateColumnPayload = (}export const generateUpdateColumnPayload = (- originalColumn: RetrievedTableColumn,+ originalColumn: DeepReadonly<SafePostgresColumn>,table: RetrieveTableResult,field: ColumnField): Partial<UpdateColumnPayload> => {@@ -127,9 +164,8 @@ export const generateUpdateColumnPayload = (// Only append the properties which are getting updatedconst name = field.name.trim()- const type = field.isArray ? `${field.format}[]` : field.formatconst comment = field.comment?.trim()- const check = field.check?.trim()+ const check = trimSafeSqlFragment(field.check) ?? undefinedconst payload: Partial<UpdateColumnPayload> = {}// [Joshen] Trimming on the original name as well so we don't rename columns that already@@ -144,12 +180,17 @@ export const generateUpdateColumnPayload = (payload.check = check}- const originalFormat =- originalColumn.data_type === 'ARRAY'- ? `${originalColumn.format.replace(/^_/, '')}[]`- : originalColumn.format- if (originalFormat !== type) {- payload.type = type+ const originalIsArray = originalColumn.data_type === 'ARRAY'+ const originalFormat = originalIsArray+ ? originalColumn.format.replace(/^_/, '')+ : originalColumn.format+ const originalFormatSchema = normalizeFormatSchema(lookupFormatSchema(originalColumn, table))+ if (+ originalFormat !== field.format ||+ originalFormatSchema !== field.formatSchema ||+ originalIsArray !== field.isArray+ ) {+ payload.type = { schema: field.formatSchema, name: field.format, isArray: field.isArray }}if (originalColumn.default_value !== field.defaultValue) {@@ -213,7 +254,7 @@ export const getForeignKeyUIState = (}export const getColumnForeignKey = (- column: PGColumn,+ column: DeepReadonly<PGColumn>,table: RetrieveTableResult,foreignKeys: ForeignKeyConstraint[]) => {@@ -258,49 +299,49 @@ export const getForeignKeyCascadeAction = (action?: string) => {}}-export const getPlaceholderText = (format?: string, columnFieldName?: string) => {- const columnName = columnFieldName || 'column_name'+export const getPlaceholderText = (format?: string, columnFieldName?: string): SafeSqlFragment => {+ const col = ident(columnFieldName || 'column_name')switch (format) {case 'int2':case 'int4':case 'int8':case 'numeric':- return `"${columnName}" > 0`+ return safeSql`${col} > 0`case 'float4':case 'float8':- return `"${columnName}" > 0.0`+ return safeSql`${col} > 0.0`case 'text':case 'varchar':- return `length("${columnName}") <= 50`+ return safeSql`length(${col}) <= 50`case 'json':case 'jsonb':- return `jsonb_typeof("${columnName}"->'active') = 'boolean'`+ return safeSql`jsonb_typeof(${col}->'active') = 'boolean'`case 'bool':- return `"${columnName}" in (true, false)`+ return safeSql`${col} in (true, false)`case 'date':- return `"${columnName}" > '2024-01-01'`+ return safeSql`${col} > '2024-01-01'`case 'time':- return `"${columnName}" between '09:00:00' and '12:00:00'`+ return safeSql`${col} between '09:00:00' and '12:00:00'`case 'timetz':- return `"${columnName}" at time zone 'UTC' between '09:00:00+00' and '17:00:00+00'`+ return safeSql`${col} at time zone 'UTC' between '09:00:00+00' and '17:00:00+00'`case 'uuid':- return `"${columnName}" '00000000-0000-0000-0000-000000000000'`+ return safeSql`${col} '00000000-0000-0000-0000-000000000000'`case 'timestamp':- return `"${columnName}" > '2023-01-01 00:00' and "${columnName}" < '2025-01-01 00:00'`+ return safeSql`${col} > '2023-01-01 00:00' and ${col} < '2025-01-01 00:00'`case 'timestamptz':- return `"${columnName}" > '2023-01-01 00:00:00+00' and "${columnName}" < '2025-01-01 00:00:00+00'`+ return safeSql`${col} > '2023-01-01 00:00:00+00' and ${col} < '2025-01-01 00:00:00+00'`default:- return `length("${columnName}") < 500`+ return safeSql`length(${col}) < 500`}}diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsxindex 00dffd37e90..f59235fde17 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx@@ -7,6 +7,7 @@ import type { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'import type { ColumnField } from '../SidePanelEditor.types'import { ForeignKeyRow } from '../TableEditor/ForeignKeysManagement/ForeignKeyRow'import { checkIfRelationChanged } from '../TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils'+import { normalizeFormatSchema } from './ColumnEditor.utils'import { useForeignKeyConstraintsQuery } from '@/data/database/foreign-key-constraints-query'import { useTableEditorQuery } from '@/data/table-editor/table-editor-query'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'@@ -17,7 +18,11 @@ interface ColumnForeignKeyProps {relations: ForeignKey[]closePanel: () => voidonOpenChange?: (open: boolean) => void- onUpdateColumnType: (type: string) => void+ onUpdateColumnType: (selection: {+ format: string+ formatSchema?: string+ isArray: boolean+ }) => voidonUpdateFkRelations: (fks: ForeignKey[]) => void}@@ -52,6 +57,8 @@ const ColumnForeignKey = ({id: c.id,name: c.name,format: c.format || column.format,+ formatSchema: normalizeFormatSchema(c.format_schema),+ isArray: c.data_type === 'ARRAY',isNewColumn: false,}})@@ -126,7 +133,14 @@ const ColumnForeignKey = ({name: table.name,columns:column.isNewColumn && column.name- ? formattedColumnsForFkSelector.concat(column)+ ? formattedColumnsForFkSelector.concat({+ id: column.id,+ name: column.name,+ format: column.format,+ formatSchema: column.formatSchema,+ isArray: column.isArray,+ isNewColumn: column.isNewColumn,+ }): formattedColumnsForFkSelector.map((c) => {if (c.id === column.id) return { ...c, name: column.name }else return c@@ -149,8 +163,14 @@ const ColumnForeignKey = ({} else {onUpdateFkRelations(relations.concat([fk]))}- const targetType = fk.columns.find((col) => col.source === column.name)?.targetType- if (targetType) onUpdateColumnType(targetType)+ const matched = fk.columns.find((col) => col.source === column.name)+ if (matched?.targetType) {+ onUpdateColumnType({+ format: matched.targetType,+ formatSchema: matched.targetTypeSchema,+ isArray: matched.targetIsArray ?? false,+ })+ }}}/>)}diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnType.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnType.tsxindex ac61d5734bb..b3d03f6f9f2 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnType.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnType.tsx@@ -25,10 +25,7 @@ import {CommandList_Shadcn_,CommandSeparator_Shadcn_,CriticalIcon,- Input_Shadcn_ as Input,- InputGroup,- InputGroupAddon,- InputGroupInput,+ Input,Label_Shadcn_,Popover_Shadcn_,PopoverContent_Shadcn_,@@ -38,7 +35,6 @@ import {TooltipContent,TooltipTrigger,} from 'ui'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import {POSTGRES_DATA_TYPE_OPTIONS,@@ -48,8 +44,10 @@ import {import type { PostgresDataTypeOption } from '../SidePanelEditor.types'import type { EnumeratedType } from '@/data/enumerated-types/enumerated-types-query'+export type ColumnTypeSelection = { format: string; formatSchema?: string }+interface ColumnTypeProps {- value: string+ value: ColumnTypeSelectionenumTypes: EnumeratedType[]className?: stringerror?: any@@ -58,9 +56,18 @@ interface ColumnTypeProps {layout?: 'horizontal' | 'vertical'description?: ReactNodeshowRecommendation?: boolean- onOptionSelect: (value: string) => void+ onOptionSelect: (selection: ColumnTypeSelection) => void}+const renderValue = ({ format, formatSchema }: ColumnTypeSelection) =>+ formatSchema ? `${formatSchema}.${format}` : format++const matchesBuiltin = (optionName: string, value: ColumnTypeSelection) =>+ !value.formatSchema && optionName === value.format++const matchesEnum = (option: { name: string; schema: string }, value: ColumnTypeSelection) =>+ option.name === value.format && option.schema === (value.formatSchema || 'public')+const ColumnType = ({value,className,@@ -75,22 +82,25 @@ const ColumnType = ({}: ColumnTypeProps) => {const [open, setOpen] = useState(false)const listboxId = useId()- const availableTypes = POSTGRES_DATA_TYPES.concat(- enumTypes.map((type) => type.format.replaceAll('"', ''))- )- const isAvailableType = value ? availableTypes.includes(value) : true- const recommendation = RECOMMENDED_ALTERNATIVE_DATA_TYPE[value]+ const hasValue = value.format.length > 0+ const isAvailableType =+ !hasValue ||+ POSTGRES_DATA_TYPES.some((name) => matchesBuiltin(name, value)) ||+ enumTypes.some((option) => matchesEnum(option, value))+ const recommendation = !value.formatSchema+ ? RECOMMENDED_ALTERNATIVE_DATA_TYPE[value.format]+ : undefined+ const displayValue = renderValue(value)const unsupportedDataTypeText = `This column's data type cannot be changed via the Table Editor as it is not supported yet. You can do so through the SQL Editor instead.`- const getOptionByName = (name: string) => {- // handle built in types- const pgOption = POSTGRES_DATA_TYPE_OPTIONS.find((option) => option.name === name)- if (pgOption) return pgOption-- // handle custom enums- const enumType = enumTypes.find((type) => type.format === name)- return enumType ? { ...enumType, type: 'enum' } : undefined+ const getOptionType = (selection: ColumnTypeSelection) => {+ const pgOption = POSTGRES_DATA_TYPE_OPTIONS.find((option) =>+ matchesBuiltin(option.name, selection)+ )+ if (pgOption) return pgOption.type+ const enumType = enumTypes.find((type) => matchesEnum(type, selection))+ return enumType ? 'enum' : ''}const inferIcon = (type: string) => {@@ -124,19 +134,17 @@ const ColumnType = ({return (<Tooltip><TooltipTrigger>- <FormItemLayout- layout={showLabel ? layout : undefined}+ <Input+ readOnly+ disabledlabel={showLabel ? 'Type' : ''}- description={showLabel ? unsupportedDataTypeText : undefined}- isReactForm={false}- >- <InputGroup>- <InputGroupInput readOnly disabled size="small" value={value} />- <InputGroupAddon align="inline-start">- {inferIcon(POSTGRES_DATA_TYPE_OPTIONS.find((x) => x.name === value)?.type ?? '')}- </InputGroupAddon>- </InputGroup>- </FormItemLayout>+ layout={showLabel ? layout : undefined}+ className="md:gap-x-0 [&>div>div]:text-left"+ size="small"+ icon={inferIcon(getOptionType(value))}+ value={displayValue}+ descriptionText={showLabel ? unsupportedDataTypeText : undefined}+ /></TooltipTrigger>{!showLabel && (<TooltipContent side="bottom" className="w-80">@@ -151,14 +159,15 @@ const ColumnType = ({return (<Tooltip><TooltipTrigger>- <FormItemLayout- layout={showLabel ? layout : undefined}+ <Input+ readOnly+ disabledlabel={showLabel ? 'Type' : ''}- description={showLabel ? unsupportedDataTypeText : undefined}- isReactForm={false}- >- <Input readOnly disabled size="small" value={value} />- </FormItemLayout>+ layout={showLabel ? 'horizontal' : undefined}+ className="md:gap-x-0"+ size="small"+ value={displayValue}+ /></TooltipTrigger>{!showLabel && description && (<TooltipContent side="bottom">@@ -180,17 +189,14 @@ const ColumnType = ({size={'small'}aria-expanded={open}aria-controls={listboxId}- className={cn(- 'w-full bg-foreground/[.026]! justify-between',- !value && 'text-foreground-lighter'- )}+ className={cn('w-full justify-between', !hasValue && 'text-foreground-lighter')}iconRight={<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />}- title={value && value.replaceAll('"', '')}+ title={displayValue}>- {value ? (+ {hasValue ? (<div className="flex gap-2 items-center">- <span>{inferIcon(getOptionByName(value)?.type ?? '')}</span>- <span className="block truncate">{value.replaceAll('"', '')}</span>+ <span>{inferIcon(getOptionType(value))}</span>+ <span className="block truncate">{displayValue}</span></div>) : ('Choose a column type...'@@ -215,72 +221,75 @@ const ColumnType = ({<CommandList_Shadcn_><ScrollArea className="h-[240px]"><CommandGroup_Shadcn_ heading="Postgres data types">- {POSTGRES_DATA_TYPE_OPTIONS.map((option: PostgresDataTypeOption) => (- <CommandItem_Shadcn_- key={option.name}- value={option.name}- className={cn('relative', option.name === value ? 'bg-surface-200' : '')}- onSelect={(value: string) => {- onOptionSelect(value)- setOpen(false)- }}- >- <div className="flex items-center gap-2 pr-6">- <span>{inferIcon(option.type)}</span>- <span className="text-foreground">{option.name}</span>- <span className="text-foreground-lighter">{option.description}</span>- </div>- <span className="absolute right-3 top-2">- {option.name === value ? <Check className="text-brand" size={14} /> : ''}- </span>- </CommandItem_Shadcn_>- ))}+ {POSTGRES_DATA_TYPE_OPTIONS.map((option: PostgresDataTypeOption) => {+ const isSelected = matchesBuiltin(option.name, value)+ return (+ <CommandItem_Shadcn_+ key={option.name}+ value={option.name}+ className={cn('relative', isSelected ? 'bg-surface-200' : '')}+ onSelect={() => {+ onOptionSelect({ format: option.name })+ setOpen(false)+ }}+ >+ <div className="flex items-center gap-2 pr-6">+ <span>{inferIcon(option.type)}</span>+ <span className="text-foreground">{option.name}</span>+ <span className="text-foreground-lighter">{option.description}</span>+ </div>+ <span className="absolute right-3 top-2">+ {isSelected ? <Check className="text-brand" size={14} /> : ''}+ </span>+ </CommandItem_Shadcn_>+ )+ })}</CommandGroup_Shadcn_>{enumTypes.length > 0 && (<><CommandSeparator_Shadcn_ /><CommandGroup_Shadcn_ heading="Other types">- {enumTypes.map((option) => (- <CommandItem_Shadcn_- key={option.id}- value={option.format}- className={cn(- 'relative',- option.format === value ? 'bg-surface-200' : ''- )}- onSelect={(value: string) => {- // [Joshen] For camel case types specifically, format property includes escaped double quotes- // which will cause the POST columns call to error out. So we strip it specifically in this context- onOptionSelect(- option.schema === 'public' ? value.replaceAll('"', '') : value- )- setOpen(false)- }}- >- <div className="flex items-center gap-2">- <div>- <ListPlus size={16} className="text-foreground" strokeWidth={1.5} />- </div>- <span className="text-foreground">- {option.format.replaceAll('"', '')}- </span>- {option.comment !== undefined && (- <span- title={option.comment ?? ''}- className="text-foreground-lighter"- >- {option.comment}+ {enumTypes.map((option) => {+ const isSelected = matchesEnum(option, value)+ return (+ <CommandItem_Shadcn_+ key={option.id}+ value={option.format}+ className={cn('relative', isSelected ? 'bg-surface-200' : '')}+ onSelect={() => {+ onOptionSelect({+ format: option.name,+ formatSchema:+ option.schema === 'public' ? undefined : option.schema,+ })+ setOpen(false)+ }}+ >+ <div className="flex items-center gap-2">+ <div>+ <ListPlus size={16} className="text-foreground" strokeWidth={1.5} />+ </div>+ <span className="text-foreground">+ {option.format.replaceAll('"', '')}</span>- )}- {option.format === value && (- <span className="absolute right-3 top-2">- <Check className="text-brand" size={14} />- </span>- )}- </div>- </CommandItem_Shadcn_>- ))}+ {option.comment !== undefined && (+ <span+ title={option.comment ?? ''}+ className="text-foreground-lighter"+ >+ {option.comment}+ </span>+ )}+ {isSelected && (+ <span className="absolute right-3 top-2">+ <Check className="text-brand" size={14} />+ </span>+ )}+ </div>+ </CommandItem_Shadcn_>+ )+ })}</CommandGroup_Shadcn_></>)}@@ -301,8 +310,8 @@ const ColumnType = ({<AlertDescription_Shadcn_><p>Postgres recommends against using the data type{' '}- <code className="text-code-inline">{value}</code> unless you have a very specific use- case.+ <code className="text-code-inline">{displayValue}</code> unless you have a very+ specific use case.</p><div className="flex items-center space-x-2 mt-3"><Button asChild type="default" icon={<ExternalLink />}>@@ -310,7 +319,10 @@ const ColumnType = ({Read more</Link></Button>- <Button type="primary" onClick={() => onOptionSelect(recommendation.alternative)}>+ <Button+ type="primary"+ onClick={() => onOptionSelect({ format: recommendation.alternative })}+ >Use {recommendation.alternative}</Button></div>diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/HeaderTitle.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/HeaderTitle.tsxindex 342cde8291f..4b44810f9be 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/HeaderTitle.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/HeaderTitle.tsx@@ -1,8 +1,10 @@import type { PGColumn, PGTable } from '@supabase/pg-meta'+import type { DeepReadonly } from '@/lib/type-helpers'+interface Props {table: PGTable- column?: PGColumn+ column?: DeepReadonly<PGColumn>}export const HeaderTitle = ({ table, column }: Props) => {diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsxindex 2b24e6f45d6..441d6f1f7a0 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx@@ -18,6 +18,7 @@ import {import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { ActionBar } from '../ActionBar'+import { displayColumnType, normalizeFormatSchema } from '../ColumnEditor/ColumnEditor.utils'import { NUMERICAL_TYPES, TEXT_TYPES } from '../SidePanelEditor.constants'import type { ColumnField } from '../SidePanelEditor.types'import { FOREIGN_KEY_CASCADE_OPTIONS } from './ForeignKeySelector.constants'@@ -52,7 +53,14 @@ interface ForeignKeySelectorProps {table: {id: numbername: string- columns: { id: string; name: string; format: string; isNewColumn: boolean }[]+ columns: {+ id: string+ name: string+ format: string+ formatSchema?: string+ isArray?: boolean+ isNewColumn: boolean+ }[]}column?: ColumnField // For ColumnEditor, to prefill when adding a new foreign keyforeignKey?: ForeignKey@@ -145,11 +153,23 @@ export const ForeignKeySelector = ({const updatedRelations = fk.columns.map((x, i) => {if (i === idx) {if (key === 'target') {- const targetType = selectedTable?.columns?.find((col) => col.name === value)?.format- return { ...x, [key]: value, targetType }+ const targetCol = selectedTable?.columns?.find((col) => col.name === value)+ return {+ ...x,+ [key]: value,+ targetType: targetCol?.format,+ targetTypeSchema: normalizeFormatSchema(targetCol?.format_schema),+ targetIsArray: targetCol?.data_type === 'ARRAY',+ }} else {- const sourceType = table.columns.find((col) => col.name === value)?.format as string- return { ...x, [key]: value, sourceType }+ const sourceCol = table.columns.find((col) => col.name === value)+ return {+ ...x,+ [key]: value,+ sourceType: sourceCol?.format,+ sourceTypeSchema: normalizeFormatSchema(sourceCol?.formatSchema),+ sourceIsArray: sourceCol?.isArray ?? false,+ }}} else {return x@@ -186,32 +206,70 @@ export const ForeignKeySelector = ({const typeErrors: SelectorTypeError[] = []fk.columns.forEach((column) => {- const { source, target, sourceType: sType, targetType: tType } = column+ const {+ source,+ target,+ sourceType: sType,+ sourceTypeSchema: sSchema,+ sourceIsArray: sArr,+ targetType: tType,+ targetTypeSchema: tSchema,+ targetIsArray: tArr,+ } = columnconst sourceColumn = table.columns.find((col) => col.name === source)+ const targetColumn = selectedTable?.columns?.find((col) => col.name === target)const sourceType = sType ?? sourceColumn?.format ?? ''- const targetType =- tType ?? selectedTable?.columns?.find((col) => col.name === target)?.format ?? ''+ const targetType = tType ?? targetColumn?.format ?? ''+ const sourceTypeSchema = sSchema ?? normalizeFormatSchema(sourceColumn?.formatSchema)+ const targetTypeSchema = tSchema ?? normalizeFormatSchema(targetColumn?.format_schema)+ const sourceIsArray = sArr ?? sourceColumn?.isArray ?? false+ const targetIsArray = tArr ?? targetColumn?.data_type === 'ARRAY'// [Joshen] Doing this way so that its more readable// If either source or target not selected yet, thats okayif (source === '' || target === '') return- // If source and target are in the same type of data types, thats okay+ // pg-meta emits `_X` as the format string for arrays of X. Normalize before+ // running family checks so that an array column is never accidentally classified+ // as a member of a scalar family.+ const bareSource =+ sourceIsArray && sourceType.startsWith('_') ? sourceType.slice(1) : sourceType+ const bareTarget =+ targetIsArray && targetType.startsWith('_') ? targetType.slice(1) : targetType++ // Same-family scalars are interchangeable; arrays must match exactly.if (- (NUMERICAL_TYPES.includes(sourceType) && NUMERICAL_TYPES.includes(targetType)) ||- (TEXT_TYPES.includes(sourceType) && TEXT_TYPES.includes(targetType)) ||- (sourceType === 'uuid' && targetType === 'uuid')+ !sourceIsArray &&+ !targetIsArray &&+ ((NUMERICAL_TYPES.includes(sourceType) && NUMERICAL_TYPES.includes(targetType)) ||+ (TEXT_TYPES.includes(sourceType) && TEXT_TYPES.includes(targetType)) ||+ (sourceType === 'uuid' && targetType === 'uuid')))return- // Otherwise just check if the format is equal to each other- if (sourceType === targetType) return+ // Otherwise require an exact match across the full (format, format_schema, isArray) triple.+ if (+ bareSource === bareTarget &&+ sourceTypeSchema === targetTypeSchema &&+ sourceIsArray === targetIsArray+ )+ return+ const entry: SelectorTypeError = {+ source,+ sourceType,+ sourceTypeSchema,+ sourceIsArray,+ target,+ targetType,+ targetTypeSchema,+ targetIsArray,+ }if (sourceColumn?.isNewColumn && targetType !== '') {- return typeNotice.push({ source, sourceType, target, targetType })+ return typeNotice.push(entry)}- typeErrors.push({ source, sourceType, target, targetType })+ typeErrors.push(entry)})setErrors({ types: typeErrors, typeNotice })@@ -370,7 +428,13 @@ export const ForeignKeySelector = ({<div className="flex items-center gap-2"><span className="text-foreground">{column.name}</span><span className="text-foreground-lighter">- {column.format === '' ? '-' : column.format}+ {column.format === ''+ ? '-'+ : displayColumnType(+ column.format,+ column.formatSchema,+ column.isArray+ )}</span></div></SelectItem_Shadcn_>@@ -397,7 +461,13 @@ export const ForeignKeySelector = ({<div className="flex items-center gap-2"><span className="text-foreground">{column.name}</span><span className="text-foreground-lighter">- {column.format === '' ? '-' : column.format}+ {column.format === ''+ ? '-'+ : displayColumnType(+ column.format,+ column.format_schema,+ column.data_type === 'ARRAY'+ )}</span></div></SelectItem_Shadcn_>@@ -435,9 +505,18 @@ export const ForeignKeySelector = ({return (<li key={`type-error-${idx}`}><code className="text-code-inline">{x.source}</code> (- {x.sourceType}) and{' '}- <code className="text-code-inline">{x.target}</code>(- {x.targetType})+ {displayColumnType(+ x.sourceType,+ x.sourceTypeSchema,+ x.sourceIsArray+ )}+ ) and <code className="text-code-inline">{x.target}</code>(+ {displayColumnType(+ x.targetType,+ x.targetTypeSchema,+ x.targetIsArray+ )}+ )</li>)})}@@ -458,7 +537,12 @@ export const ForeignKeySelector = ({<li key={`type-error-${idx}`}><div className="flex items-center gap-x-1"><code className="text-code-inline">{x.source}</code>{' '}- <ArrowRight size={14} /> {x.targetType}+ <ArrowRight size={14} />{' '}+ {displayColumnType(+ x.targetType,+ x.targetTypeSchema,+ x.targetIsArray+ )}</div></li>)diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.tsindex a37e35dcaea..849c93b5a4b 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts@@ -5,7 +5,16 @@ export interface ForeignKey {schema: stringtable: string- columns: { source: string; sourceType?: string; target: string; targetType?: string }[]+ columns: {+ source: string+ sourceType?: string+ sourceTypeSchema?: string+ sourceIsArray?: boolean+ target: string+ targetType?: string+ targetTypeSchema?: string+ targetIsArray?: boolean+ }[]deletionAction: stringupdateAction: stringtoRemove?: boolean@@ -20,6 +29,10 @@ export interface SelectorErrors {export interface SelectorTypeError {source: stringsourceType: string+ sourceTypeSchema?: string+ sourceIsArray?: booleantarget: stringtargetType: string+ targetTypeSchema?: string+ targetIsArray?: boolean}diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsxindex a28b9161cf3..20e232c1bb5 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx@@ -1,5 +1,5 @@import * as Sentry from '@sentry/nextjs'-import type { PGColumn, PGTable } from '@supabase/pg-meta'+import type { PGTable } from '@supabase/pg-meta'import { useQueryClient } from '@tanstack/react-query'import { useParams } from 'common'import { isEmpty, isUndefined, noop } from 'lodash'@@ -36,7 +36,10 @@ import { TableEditor } from './TableEditor/TableEditor'import type { ImportContent } from './TableEditor/TableEditor.types'import { useTableRowOperations } from '@/components/grid/hooks/useTableRowOperations'import { useIsQueueOperationsEnabled } from '@/components/interfaces/Account/Preferences/useDashboardSettings'-import { type GeneratedPolicy } from '@/components/interfaces/Auth/Policies/Policies.utils'+import {+ acceptGeneratedPolicy,+ type GeneratedPolicy,+} from '@/components/interfaces/Auth/Policies/Policies.utils'import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'import { databasePoliciesKeys } from '@/data/database-policies/keys'import { useDatabasePublicationCreateMutation } from '@/data/database-publications/database-publications-create-mutation'@@ -63,6 +66,7 @@ import { useUrlState } from '@/hooks/ui/useUrlState'import { useVisibleKey } from '@/hooks/ui/useVisibleKey'import { type ApiPrivilegesByRole } from '@/lib/data-api-types'import { isObjectContainingKeys } from '@/lib/helpers'+import type { SafePostgresTable } from '@/lib/postgres-types'import { useTrack } from '@/lib/telemetry/track'import type { DeepReadonly, Prettify } from '@/lib/type-helpers'import { useTableEditorStateSnapshot, type TableEditorState } from '@/state/table-editor'@@ -170,7 +174,7 @@ const createTableApiAccessHandlerParams = ({export interface SidePanelEditorProps {editable?: boolean- selectedTable?: PGTable+ selectedTable?: SafePostgresTableincludeColumns?: boolean // This is mainly used for invalidating useTablesQuery// Because the panel is shared between grid editor and database pages@@ -377,32 +381,39 @@ export const SidePanelEditor = ({},resolve: any) => {- const selectedColumnToEdit = snap.sidePanel?.type === 'column' && snap.sidePanel.column+ const selectedColumnToEdit =+ snap.sidePanel?.type === 'column' ? snap.sidePanel.column : undefinedconst { primaryKey, foreignKeyRelations, existingForeignKeyRelations } = configurationif (!project || selectedTable === undefined) {return console.error('no project or table selected')}- const response = isNewRecord- ? await createColumn({- projectRef: project?.ref!,- connectionString: project?.connectionString,- payload: payload as CreateColumnPayload,- selectedTable,- primaryKey,- foreignKeyRelations,- })- : await updateColumn({- projectRef: project?.ref!,- connectionString: project?.connectionString,- originalColumn: selectedColumnToEdit as PGColumn,- payload: payload as UpdateColumnPayload,- selectedTable,- primaryKey,- foreignKeyRelations,- existingForeignKeyRelations,- })+ let response+ if (isNewRecord) {+ response = await createColumn({+ projectRef: project.ref,+ connectionString: project.connectionString,+ payload: payload as CreateColumnPayload,+ selectedTable,+ primaryKey,+ foreignKeyRelations,+ })+ } else {+ if (!selectedColumnToEdit) {+ return console.error('no column selected to update')+ }+ response = await updateColumn({+ projectRef: project.ref,+ connectionString: project.connectionString,+ originalColumn: selectedColumnToEdit,+ payload: payload as UpdateColumnPayload,+ selectedTable,+ primaryKey,+ foreignKeyRelations,+ existingForeignKeyRelations,+ })+ }if (response?.error) {toast.error(response.error.message)@@ -658,6 +669,12 @@ export const SidePanelEditor = ({})try {+ // The Save click is the explicit user gesture that promotes generated policy+ // SQL (programmatic or AI) to executable. Programmatic fragments are already+ // SafeSqlFragment; AI fragments are UntrustedSqlFragment — both are accepted+ // here before being passed into createTable.+ const acceptedPolicies = generatedPolicies.map(acceptGeneratedPolicy)+const { table, failedPolicies } = await createTable({projectRef: project?.ref!,connectionString: project?.connectionString,@@ -668,7 +685,7 @@ export const SidePanelEditor = ({isRLSEnabled,importContent,organizationSlug: org?.slug,- generatedPolicies,+ generatedPolicies: acceptedPolicies,onCreatePoliciesSuccess: () => track('rls_generated_policies_created'),})@@ -922,11 +939,7 @@ export const SidePanelEditor = ({)}{!isUndefined(selectedTable) && (<ColumnEditor- column={- snap.sidePanel?.type === 'column'- ? (snap.sidePanel.column as unknown as PGColumn)- : undefined- }+ column={snap.sidePanel?.type === 'column' ? snap.sidePanel.column : undefined}selectedTable={selectedTable}visible={snap.sidePanel?.type === 'column'}closePanel={onClosePanel}diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.tsindex 3b1de59264d..3e05f0f50f0 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts@@ -1,4 +1,4 @@-import type { PGTableRelationship } from '@supabase/pg-meta'+import type { PGTableRelationship, SafeSqlFragment } from '@supabase/pg-meta'import { CreateColumnBody } from '@/data/database-columns/database-column-create-mutation'import { UpdateColumnBody } from '@/data/database-columns/database-column-update-mutation'@@ -46,9 +46,10 @@ export interface ColumnField {name: stringtable: stringschema: string- check: string | null+ check: SafeSqlFragment | nullcomment?: string | nullformat: string+ formatSchema?: stringdefaultValue: string | nullforeignKey?: ExtendedPostgresRelationshipisNullable: booleandiff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.tsindex 2c12f1eea71..d176426ab09 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts@@ -1,4 +1,4 @@-import { FOREIGN_KEY_CASCADE_ACTION } from '@supabase/pg-meta'+import { FOREIGN_KEY_CASCADE_ACTION, safeSql } from '@supabase/pg-meta'import { beforeEach, describe, expect, it, vi } from 'vitest'import type { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'@@ -458,7 +458,7 @@ describe('createTable', () => {createColumnField({name: 'age',format: 'int4',- check: 'age >= 0',+ check: safeSql`age >= 0`,isNullable: false,}),]diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsxindex f9f46bb5ec0..307e83c66af 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx@@ -12,6 +12,7 @@ import pgMeta, {type ForeignKey,} from '@supabase/pg-meta'import type { PGTablePrimaryKey } from '@supabase/pg-meta'+import { joinSqlFragments, safeSql, type SafeSqlFragment } from '@supabase/pg-meta/src/pg-format'import { Query } from '@supabase/pg-meta/src/query'import { chunk, find, isEmpty, isEqual } from 'lodash'import Papa from 'papaparse'@@ -25,7 +26,7 @@ import type { ColumnField, CreateColumnPayload, UpdateColumnPayload } from './Siimport { checkIfRelationChanged } from './TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils'import type { ImportContent } from './TableEditor/TableEditor.types'import type { SupaRow } from '@/components/grid/types'-import { GeneratedPolicy } from '@/components/interfaces/Auth/Policies/Policies.utils'+import { type AcceptedGeneratedPolicy } from '@/components/interfaces/Auth/Policies/Policies.utils'import SparkBar from '@/components/ui/SparkBar'import { createDatabaseColumn } from '@/data/database-columns/database-column-create-mutation'import { deleteDatabaseColumn } from '@/data/database-columns/database-column-delete-mutation'@@ -44,12 +45,7 @@ import { prefetchTableEditor } from '@/data/table-editor/table-editor-query'import { tableRowKeys } from '@/data/table-rows/keys'import { executeWithRetry } from '@/data/table-rows/table-rows-query'import { tableKeys } from '@/data/tables/keys'-import {- getTable,- getTableQuery,- RetrievedTableColumn,- RetrieveTableResult,-} from '@/data/tables/table-retrieve-query'+import { getTable, getTableQuery, RetrieveTableResult } from '@/data/tables/table-retrieve-query'import {UpdateTableBody,updateTable as updateTableMutation,@@ -57,6 +53,7 @@ import {import { getTables } from '@/data/tables/tables-query'import { sendEvent } from '@/data/telemetry/send-event-mutation'import { isObject, isObjectContainingKeys, timeout, tryParseJson } from '@/lib/helpers'+import type { SafePostgresColumn } from '@/lib/postgres-types'import type { DeepReadonly } from '@/lib/type-helpers'import type { SidePanel } from '@/state/table-editor'@@ -173,12 +170,7 @@ const updateForeignKey = async ({table: { schema: string; name: string }foreignKeys: ForeignKey[]}) => {- const query = `- ${getRemoveForeignKeySQL({ table, foreignKeys })}- ${getAddForeignKeySQL({ table, foreignKeys })}- `- .replace(/\s+/g, ' ')- .trim()+ const query = safeSql`${getRemoveForeignKeySQL({ table, foreignKeys })} ${getAddForeignKeySQL({ table, foreignKeys })}`return await executeSql({projectRef: projectRef,connectionString: connectionString,@@ -283,7 +275,7 @@ export const updateColumn = async ({}: {projectRef: stringconnectionString?: string | null- originalColumn: RetrievedTableColumn+ originalColumn: DeepReadonly<SafePostgresColumn>payload: UpdateColumnPayloadselectedTable: RetrieveTableResultprimaryKey?: Constraint@@ -466,14 +458,14 @@ export const createTable = async ({isRLSEnabled: booleanimportContent?: ImportContentorganizationSlug?: string- generatedPolicies?: GeneratedPolicy[]+ generatedPolicies?: AcceptedGeneratedPolicy[]onCreatePoliciesSuccess?: () => void}) => {const queryClient = getQueryClient()// Build all SQL statements for table creation, columns, and constraints// to execute in a single transaction for better performance and atomicity- const sqlStatements: string[] = []+ const sqlStatements: Array<SafeSqlFragment> = []// 1. Create table SQLconst { sql: createTableSql } = pgMeta.tables.create({ ...payload, no_transaction: true })@@ -531,8 +523,8 @@ export const createTable = async ({table: { schema: payload.schema, name: payload.name },foreignKeys: foreignKeyRelations,})- // Remove trailing semicolon since we join with semicolons- sqlStatements.push(fkSql.replace(/;+$/, ''))+ const fkSqlWithoutTrailingSemicolon = fkSql.replace(/;+$/, '') as SafeSqlFragment+ sqlStatements.push(fkSqlWithoutTrailingSemicolon)}// Execute all table creation SQL in a single transaction@@ -545,7 +537,7 @@ export const createTable = async ({await executeSql({projectRef,connectionString,- sql: `BEGIN; ${sqlStatements.join(';\n')}; COMMIT;`,+ sql: safeSql`BEGIN; ${joinSqlFragments(sqlStatements, ';\n')}; COMMIT;`,queryKey: ['table', 'create-with-columns'],})}@@ -555,7 +547,7 @@ export const createTable = async ({// [Joshen] Possible area for optimization to create all policies in a single query call// Can be subsequently added to the table creation SQL as well for a single transaction- const failedPolicies: GeneratedPolicy[] = []+ const failedPolicies: AcceptedGeneratedPolicy[] = []if (generatedPolicies.length > 0 && isRLSEnabled) {await Sentry.startSpan({ name: 'create_table.create_policies', op: 'db.policies.create' },@@ -722,15 +714,16 @@ export const createTable = async ({// For identity columns, manually raise the sequences (batched for performance)const identityColumns = columns.filter((column) => column.isIdentity)if (identityColumns.length > 0) {- const updateSequenceSQL = identityColumns- .map((column) =>+ const updateSequenceSQL = joinSqlFragments(+ identityColumns.map((column) =>getUpdateIdentitySequenceSQL({schema: table.schema,table: table.name,column: column.name,})- )- .join(';\n')+ ),+ ';\n'+ )await executeSql({projectRef,connectionString,@@ -1085,15 +1078,16 @@ export async function insertRowsViaSpreadsheet({return}- const updateSequenceSQL = sequenceColumns- .map((column) =>+ const updateSequenceSQL = joinSqlFragments(+ sequenceColumns.map((column) =>getUpdateIdentitySequenceSQL({schema: table.schema,table: table.name,column: column.name,})- )- .join(';\n')+ ),+ ';\n'+ )executeSql({projectRef,@@ -1185,15 +1179,16 @@ export async function insertTableRows({return { error: insertError }}- const updateSequenceSQL = sequenceColumns- .map((column) =>+ const updateSequenceSQL = joinSqlFragments(+ sequenceColumns.map((column) =>getUpdateIdentitySequenceSQL({schema: table.schema,table: table.name,column: column.name,})- )- .join(';\n')+ ),+ ';\n'+ )try {await executeSql({diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/Column.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/Column.tsxindex 126f6233b75..1f4b16ccd3f 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/Column.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/Column.tsx@@ -12,7 +12,7 @@ import {CommandItem_Shadcn_,CommandList_Shadcn_,CommandSeparator_Shadcn_,- Input_Shadcn_ as Input,+ Input,Popover_Shadcn_,PopoverContent_Shadcn_,PopoverTrigger_Shadcn_,@@ -139,7 +139,7 @@ export const Column = ({disabled={hasImportContent}placeholder="column_name"className={cn(- 'border-r-transparent rounded-r-none',+ '[&>div>div>div>input]:py-1.5 [&>div>div>div>input]:border-r-transparent [&>div>div>div>input]:rounded-r-none',hasImportContent ? 'opacity-50' : '')}onChange={(event) => onUpdateColumn({ name: event.target.value })}@@ -147,7 +147,7 @@ export const Column = ({{relations.filter((r) => !r.toRemove).length === 0 ? (<Buttontype="dashed"- className="rounded-l-none h-[34px] py-0 px-2"+ className="rounded-l-none h-[30px] py-0 px-2"onClick={() => onEditForeignKey()}><Link size={12} />@@ -241,7 +241,7 @@ export const Column = ({<div className="w-[25%]"><div className="w-[95%]"><ColumnType- value={column.format}+ value={{ format: column.format, formatSchema: column.formatSchema }}enumTypes={enumTypes}showLabel={false}className="table-editor-column-type lg:gap-0 "@@ -249,9 +249,9 @@ export const Column = ({description={hasForeignKeys ? 'Column type cannot be changed as it has a foreign key relation' : ''}- onOptionSelect={(format: string) => {+ onOptionSelect={({ format, formatSchema }) => {const defaultValue = format === 'uuid' ? 'gen_random_uuid()' : null- onUpdateColumn({ format, defaultValue })+ onUpdateColumn({ format, formatSchema, defaultValue })}}/></div>@@ -269,7 +269,9 @@ export const Column = ({size="small"value={column.defaultValue ?? ''}disabled={column.format.includes('int') && column.isIdentity}- className={column.format.includes('int') && column.isIdentity ? 'opacity-50' : ''}+ className={`rounded-sm bg-surface-100 lg:gap-0 ${+ column.format.includes('int') && column.isIdentity ? 'opacity-50' : ''+ }`}suggestions={suggestions}suggestionsHeader="Suggested expressions"suggestionsTooltip="Suggested expressions"diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsxindex ec99a679a7f..e276e18af5c 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx@@ -1,11 +1,9 @@-import type { PGTable } from '@supabase/pg-meta'import { isEmpty, noop } from 'lodash'import { useContext, useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'-import { Badge, Checkbox, Input_Shadcn_ as Input, SidePanel } from 'ui'+import { Badge, Checkbox, Input, SidePanel } from 'ui'import { Admonition } from 'ui-patterns'import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { ActionBar } from '../ActionBar'import type { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'@@ -40,6 +38,7 @@ import { useUrlState } from '@/hooks/ui/useUrlState'import { useVisibleKey } from '@/hooks/ui/useVisibleKey'import { useProtectedSchemas } from '@/hooks/useProtectedSchemas'import { DOCS_URL } from '@/lib/constants'+import type { SafePostgresTable } from '@/lib/postgres-types'import { useTrack } from '@/lib/telemetry/track'import { type PlainObject } from '@/lib/type-helpers'import { TableEditorStateContext, useTableEditorStateSnapshot } from '@/state/table-editor'@@ -53,7 +52,7 @@ type SaveTablePayloadFor<Action extends SaveTableParams['action']> =SaveTableParamsFor<Action>['payload']export interface TableEditorProps {- table?: PGTable+ table?: SafePostgresTableisDuplicating: booleantemplateData?: Partial<TableField>visible: boolean@@ -165,7 +164,17 @@ export const TableEditor = ({relation.columns.forEach((column) => {const sourceColumn = tableFields.columns.find((col) => col.name === column.source)if (sourceColumn?.isNewColumn && column.targetType) {- updatedColumns.push({ ...sourceColumn, format: column.targetType })+ const isArray = column.targetIsArray ?? false+ const bareFormat =+ isArray && column.targetType.startsWith('_')+ ? column.targetType.slice(1)+ : column.targetType+ updatedColumns.push({+ ...sourceColumn,+ format: bareFormat,+ formatSchema: column.targetTypeSchema,+ isArray,+ })}})})@@ -348,35 +357,25 @@ export const TableEditor = ({}><SidePanel.Content className="space-y-10 py-6">- <FormItemLayout+ <Input+ data-testid="table-name-input"+ label="Name"id="name"- isReactForm={false}layout="horizontal"- label="Name"+ type="text"error={errors.name ? String(errors.name) : undefined}- >- <Input- data-testid="table-name-input"- id="name"- type="text"- value={tableFields?.name}- onChange={(event) => onUpdateField({ name: event.target.value })}- />- </FormItemLayout>- <FormItemLayout+ value={tableFields?.name}+ onChange={(event) => onUpdateField({ name: event.target.value })}+ />+ <Input+ label="Description"id="description"- isReactForm={false}+ placeholder="Optional"layout="horizontal"- label="Description"- >- <Input- id="description"- placeholder="Optional"- type="text"- value={tableFields?.comment ?? ''}- onChange={(event) => onUpdateField({ comment: event.target.value })}- />- </FormItemLayout>+ type="text"+ value={tableFields?.comment ?? ''}+ onChange={(event) => onUpdateField({ comment: event.target.value })}+ /></SidePanel.Content><SidePanel.Separator />diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.tsindex 15c2e23eb04..469c8d718d6 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts@@ -1,14 +1,14 @@-import type { PGTable } from '@supabase/pg-meta'import { some } from 'lodash'import {generateColumnField,- generateColumnFieldFromPostgresColumn,+ generateColumnFieldFromPGColumn,} from '../ColumnEditor/ColumnEditor.utils'import type { ColumnField } from '../SidePanelEditor.types'import { DEFAULT_COLUMNS } from './TableEditor.constants'import type { ImportContent, TableField } from './TableEditor.types'import type { ForeignKeyConstraint } from '@/data/database/foreign-key-constraints-query'+import type { SafePostgresTable } from '@/lib/postgres-types'type ValidateFieldsReturn = {name?: string@@ -41,7 +41,7 @@ export const generateTableField = (): TableField => {}export const generateTableFieldFromPGTable = (- table: PGTable,+ table: SafePostgresTable,foreignKeys: ForeignKeyConstraint[],isDuplicating = false,isRealtimeEnabled = false@@ -51,7 +51,7 @@ export const generateTableFieldFromPGTable = (name: isDuplicating ? `${table.name}_duplicate` : table.name,comment: isDuplicating ? `This is a duplicate of ${table.name}` : table?.comment,columns: (table.columns ?? []).map((column) => {- return generateColumnFieldFromPostgresColumn(column, table, foreignKeys)+ return generateColumnFieldFromPGColumn(column, table, foreignKeys)}),isRLSEnabled: table.rls_enabled,isRealtimeEnabled,diff --git a/apps/studio/data/ai/sql-policy-mutation.ts b/apps/studio/data/ai/sql-policy-mutation.tsindex a87340c0e1b..fd64608a740 100644--- a/apps/studio/data/ai/sql-policy-mutation.ts+++ b/apps/studio/data/ai/sql-policy-mutation.ts@@ -1,7 +1,7 @@+import { untrustedSql, type UntrustedSqlFragment } from '@supabase/pg-meta'import { useMutation } from '@tanstack/react-query'import { toast } from 'sonner'-import type { CreatePolicyBody } from '@/data/database-policies/database-policy-create-mutation'import { fetchPost } from '@/data/fetchers'import { BASE_PATH } from '@/lib/constants'import { ResponseError, UseCustomMutationOptions } from '@/types'@@ -16,15 +16,29 @@ export type SqlPolicyGenerateVariables = {message?: string}+type RawSqlPolicy = {+ name: string+ table: string+ schema: string+ action: 'PERMISSIVE' | 'RESTRICTIVE'+ roles: string[]+ command?: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'ALL'+ definition?: string+ check?: string+ sql: string+}+/**- * AI-generated policy response extends CreatePolicyBody with required fields and sql for display.+ * AI-generated policy. `definition` and `check` are branded `UntrustedSqlFragment` at the+ * boundary — they originate from third-party AI output and must be promoted via+ * `acceptUntrustedSql` at a user gesture before executing.*/-export type SqlPolicyGenerateResponse = (Required<- Pick<CreatePolicyBody, 'name' | 'table' | 'schema' | 'action' | 'roles'>-> &- Pick<CreatePolicyBody, 'command' | 'definition' | 'check'> & {- sql: string- })[]+export type SqlPolicyGenerateResponse = Array<+ Omit<RawSqlPolicy, 'definition' | 'check'> & {+ definition?: UntrustedSqlFragment+ check?: UntrustedSqlFragment+ }+>export async function generateSqlPolicy({tableName,@@ -35,7 +49,7 @@ export async function generateSqlPolicy({orgSlug,message,}: SqlPolicyGenerateVariables): Promise<SqlPolicyGenerateResponse> {- const result = await fetchPost<SqlPolicyGenerateResponse>(`${BASE_PATH}/api/ai/sql/policy`, {+ const result = await fetchPost<Array<RawSqlPolicy>>(`${BASE_PATH}/api/ai/sql/policy`, {tableName,schema,columns,@@ -46,7 +60,11 @@ export async function generateSqlPolicy({})if ('error' in result) throw new ResponseError((result.error as any).message, 400)- return result as SqlPolicyGenerateResponse+ return (result as Array<RawSqlPolicy>).map((policy) => ({+ ...policy,+ definition: policy.definition === undefined ? undefined : untrustedSql(policy.definition),+ check: policy.check === undefined ? undefined : untrustedSql(policy.check),+ }))}type SqlPolicyGenerateData = Awaited<ReturnType<typeof generateSqlPolicy>>diff --git a/apps/studio/data/database-columns/database-column-create-mutation.ts b/apps/studio/data/database-columns/database-column-create-mutation.tsindex 68150e4c992..e1f8d719775 100644--- a/apps/studio/data/database-columns/database-column-create-mutation.ts+++ b/apps/studio/data/database-columns/database-column-create-mutation.ts@@ -1,4 +1,5 @@-import pgMeta from '@supabase/pg-meta'+import pgMeta, { type SafeSqlFragment } from '@supabase/pg-meta'+import type { ColumnTypeRef } from '@supabase/pg-meta/src/pg-meta-columns'import { useMutation } from '@tanstack/react-query'import { toast } from 'sonner'@@ -9,8 +10,8 @@ export type CreateColumnBody = {schema: stringtable: stringname: string- type: string- check?: string+ type: ColumnTypeRef+ check?: SafeSqlFragmentcomment?: stringdefaultValue?: anydefaultValueFormat?: 'expression' | 'literal'diff --git a/apps/studio/data/table-editor/table-editor-types.ts b/apps/studio/data/table-editor/table-editor-types.tsindex af5c4a49ef1..92995da0a44 100644--- a/apps/studio/data/table-editor/table-editor-types.ts+++ b/apps/studio/data/table-editor/table-editor-types.ts@@ -1,13 +1,8 @@-import type {- PGColumn,- PGMaterializedView,- PGTable,- PGTableRelationship,- PGView,-} from '@supabase/pg-meta'+import type { PGMaterializedView, PGTable, PGTableRelationship, PGView } from '@supabase/pg-meta'import { WRAPPER_HANDLERS } from '@/components/interfaces/Integrations/Wrappers/Wrappers.constants'import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'+import type { SafePostgresColumn, SafePostgresTable } from '@/lib/postgres-types'interface TableRelationship extends PGTableRelationship {deletion_action: 'a' | 'r' | 'c' | 'n' | 'd'@@ -21,28 +16,28 @@ interface TableUniqueIndex {columns: string[]}-export interface Table extends PGTable {+export interface Table extends Omit<PGTable, 'columns'> {entity_type: ENTITY_TYPE.TABLE- columns: PGColumn[]+ columns: SafePostgresColumn[]relationships: TableRelationship[]unique_indexes?: TableUniqueIndex[]}-export interface PartitionedTable extends PGTable {+export interface PartitionedTable extends Omit<PGTable, 'columns'> {entity_type: ENTITY_TYPE.PARTITIONED_TABLE- columns: PGColumn[]+ columns: SafePostgresColumn[]relationships: TableRelationship[]unique_indexes?: TableUniqueIndex[]}export interface View extends PGView {entity_type: ENTITY_TYPE.VIEW- columns: PGColumn[]+ columns: SafePostgresColumn[]}export interface MaterializedView extends PGMaterializedView {entity_type: ENTITY_TYPE.MATERIALIZED_VIEW- columns: PGColumn[]+ columns: SafePostgresColumn[]}export interface ForeignTable {@@ -54,7 +49,7 @@ export interface ForeignTable {foreign_server_name: stringforeign_data_wrapper_name: stringforeign_data_wrapper_handler: string- columns: PGColumn[]+ columns: SafePostgresColumn[]}export type Entity = Table | PartitionedTable | View | MaterializedView | ForeignTable@@ -100,10 +95,10 @@ export function isViewLike(entity?: Entity): entity is View | MaterializedView {return isView(entity) || isMaterializedView(entity)}-export function postgresTableToEntity(table: PGTable): Entity | undefined {+export function postgresTableToEntity(table: SafePostgresTable): Entity | undefined {if (table.columns === undefined || table.relationships === undefined) {console.error(- 'Unable to convert PostgresTable to Entity type: columns and relationships must not be undefined.'+ 'Unable to convert PGTable to Entity type: columns and relationships must not be undefined.')return undefined}diff --git a/apps/studio/data/tables/table-retrieve-query.ts b/apps/studio/data/tables/table-retrieve-query.tsindex 67c82b58236..228b9ebf108 100644--- a/apps/studio/data/tables/table-retrieve-query.ts+++ b/apps/studio/data/tables/table-retrieve-query.ts@@ -4,6 +4,7 @@ import { useQuery } from '@tanstack/react-query'import { tableKeys } from './keys'import { getQueryClient } from '@/data/query-client'import { executeSql } from '@/data/sql/execute-sql-query'+import type { SafePostgresTable } from '@/lib/postgres-types'import type { ResponseError, UseCustomQueryOptions } from '@/types'export type TablesVariables = {@@ -16,7 +17,7 @@ export type TablesVariables = {export async function getTable({ projectRef, connectionString, name, schema }: TablesVariables,signal?: AbortSignal-) {+): Promise<SafePostgresTable> {const { sql, zod } = pgMeta.tables.retrieve({ name, schema })const { result } = await executeSql(@@ -28,7 +29,8 @@ export async function getTable(},signal)- return zod.parse(result[0])+ // pg-meta sources `check` from pg_catalog; treat it as SafeSqlFragment for DDL composition.+ return zod.parse(result[0]) as unknown as SafePostgresTable}export type RetrieveTableResult = Awaited<ReturnType<typeof getTable>>diff --git a/apps/studio/data/tables/tables-query.ts b/apps/studio/data/tables/tables-query.tsindex e1f778b4f30..b03d71816c8 100644--- a/apps/studio/data/tables/tables-query.ts+++ b/apps/studio/data/tables/tables-query.ts@@ -6,6 +6,7 @@ import { useCallback } from 'react'import { tableKeys } from './keys'import { get, handleError } from '@/data/fetchers'+import type { SafePostgresTable } from '@/lib/postgres-types'import type { ResponseError, UseCustomQueryOptions } from '@/types'export type TablesVariables = {@@ -61,10 +62,10 @@ export async function getTables(// Sort the data if the sortByName option is trueif (Array.isArray(data) && sortByProperty) {- return sortBy(data, (t) => t[sortByProperty]) as PGTable[]+ return sortBy(data, (t) => t[sortByProperty]) as SafePostgresTable[]}- return data as PGTable[]+ return data as SafePostgresTable[]}export type TablesData = Awaited<ReturnType<typeof getTables>>diff --git a/apps/studio/pages/project/[ref]/database/tables/index.tsx b/apps/studio/pages/project/[ref]/database/tables/index.tsxindex 4618234c8f6..ddeebe6f27b 100644--- a/apps/studio/pages/project/[ref]/database/tables/index.tsx+++ b/apps/studio/pages/project/[ref]/database/tables/index.tsx@@ -1,4 +1,3 @@-import type { PGTable } from '@supabase/pg-meta'import { LOCAL_STORAGE_KEYS, useParams } from 'common'import { useState } from 'react'import { PageContainer } from 'ui-patterns/PageContainer'@@ -71,7 +70,14 @@ const DatabaseTables: NextPageWithLayout = () => {</TableEditorTableStateContextProvider>)}- <SidePanelEditor includeColumns selectedTable={selectedTableToEdit as PGTable} />+ <SidePanelEditor+ includeColumns+ selectedTable={+ selectedTableToEdit !== undefined && isTableLike(selectedTableToEdit)+ ? selectedTableToEdit+ : undefined+ }+ /></>)}diff --git a/apps/studio/state/table-editor.tsx b/apps/studio/state/table-editor.tsxindex d6e178bb4d5..018059fdfc8 100644--- a/apps/studio/state/table-editor.tsx+++ b/apps/studio/state/table-editor.tsx@@ -20,6 +20,7 @@ import { generateTableChangeKey } from '@/components/grid/utils/queueOperationUtimport { ForeignKey } from '@/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types'import type { EditValue } from '@/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types'import type { TableField } from '@/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types'+import type { SafePostgresColumn } from '@/lib/postgres-types'import type { Dictionary } from '@/types'export const TABLE_EDITOR_DEFAULT_ROWS_PER_PAGE = 100@@ -33,7 +34,7 @@ type ForeignKeyState = {export type SidePanel =| { type: 'cell'; value?: { column: string; row: Dictionary<any> } }| { type: 'row'; row?: Dictionary<any> }- | { type: 'column'; column?: PGColumn }+ | { type: 'column'; column?: SafePostgresColumn }| { type: 'table'; mode: 'new' | 'edit' | 'duplicate'; templateData?: Partial<TableField> }| { type: 'schema'; mode: 'new' | 'edit' }| { type: 'json'; jsonValue: EditValue }@@ -46,7 +47,7 @@ export type SidePanel =export type ConfirmationDialog =| { type: 'table'; isDeleteWithCascade: boolean }- | { type: 'column'; column: PGColumn; isDeleteWithCascade: boolean }+ | { type: 'column'; column: SafePostgresColumn; isDeleteWithCascade: boolean }// [Joshen] Just FYI callback, numRows, allRowsSelected is a temp workaround so that// DeleteConfirmationDialog can trigger dispatch methods after the successful deletion of rows.// Once we deprecate react tracked and move things to valtio, we can remove this.@@ -142,13 +143,13 @@ export const createTableEditorState = () => {sidePanel: { type: 'column' },}},- onEditColumn: (column: PGColumn) => {+ onEditColumn: (column: SafePostgresColumn) => {state.ui = {open: 'side-panel',sidePanel: { type: 'column', column },}},- onDeleteColumn: (column: PGColumn) => {+ onDeleteColumn: (column: SafePostgresColumn) => {state.ui = {open: 'confirmation-dialog',confirmationDialog: { type: 'column', column, isDeleteWithCascade: false },diff --git a/packages/pg-meta/src/pg-meta-columns.ts b/packages/pg-meta/src/pg-meta-columns.tsindex c99c5fc3279..17a0fb35d27 100644--- a/packages/pg-meta/src/pg-meta-columns.ts+++ b/packages/pg-meta/src/pg-meta-columns.ts@@ -2,7 +2,7 @@ import { z } from 'zod'import { DEFAULT_SYSTEM_SCHEMAS } from './constants'import { filterByList } from './helpers'-import { ident, literal, safeSql, type SafeSqlFragment } from './pg-format'+import { ident, keyword, literal, rawSql, safeSql, type SafeSqlFragment } from './pg-format'import { COLUMNS_SQL } from './sql/columns'const pgColumnZod = z.object({@@ -14,6 +14,10 @@ const pgColumnZod = z.object({ordinal_position: z.number(),data_type: z.string(),format: z.string(),+ // Optional at the type level for compatibility with column data sourced from the legacy+ // `/platform/pg-meta/{ref}/tables` REST endpoint, which doesn't include this field. The pg-meta+ // SQL itself always returns format_schema.+ format_schema: z.string().optional(),is_identity: z.boolean(),identity_generation: z.string().nullable(),is_generated: z.boolean(),@@ -106,13 +110,44 @@ function retrieve(identifier: ColumnIdentifier): {}}+export type ColumnTypeRef = {+ schema?: string+ name: string+ isArray?: boolean+}++export interface CreateOptionsBase {+ schema: string+ table: string+ name: string+ type: ColumnTypeRef+ is_identity?: boolean+ identity_generation?: 'BY DEFAULT' | 'ALWAYS'+ is_nullable?: boolean+ is_primary_key?: boolean+ is_unique?: boolean+ comment?: string+ check?: string+ no_transaction?: boolean+}++type CreateOptionsDefaultExpression = {+ default_value_format: 'expression'+ default_value: SafeSqlFragment+} & CreateOptionsBase++type CreateOptionsNotDefaultExpression = {+ default_value_format?: 'literal'+ default_value?: unknown+} & CreateOptionsBase++type CreateOptions = CreateOptionsDefaultExpression | CreateOptionsNotDefaultExpression+function create({schema,table,name,type,- default_value,- default_value_format = 'literal',is_identity = false,identity_generation = 'BY DEFAULT',is_nullable,@@ -121,52 +156,37 @@ function create({comment,check,no_transaction = false,-}: {- schema: string- table: string- name: string- type: string- default_value?: any- default_value_format?: 'expression' | 'literal'- is_identity?: boolean- identity_generation?: 'BY DEFAULT' | 'ALWAYS'- is_nullable?: boolean- is_primary_key?: boolean- is_unique?: boolean- comment?: string- check?: string- no_transaction?: boolean-}): { sql: string } {- let defaultValueClause = ''+ ...defaultOptions+}: CreateOptions): { sql: SafeSqlFragment } {+ let defaultValueClause: SafeSqlFragment = safeSql``if (is_identity) {- if (default_value !== undefined) {+ if (defaultOptions.default_value !== undefined) {throw new Error('Columns cannot both be identity and have a default value')}- defaultValueClause = `GENERATED ${identity_generation} AS IDENTITY`+ defaultValueClause = safeSql`GENERATED ${keyword(identity_generation)} AS IDENTITY`} else {- if (default_value === undefined) {+ if (defaultOptions.default_value === undefined) {// skip- } else if (default_value_format === 'expression') {- defaultValueClause = `DEFAULT ${default_value}`+ } else if (defaultOptions.default_value_format === 'expression') {+ defaultValueClause = safeSql`DEFAULT ${defaultOptions.default_value}`} else {- defaultValueClause = `DEFAULT ${literal(default_value)}`+ defaultValueClause = safeSql`DEFAULT ${literal(defaultOptions.default_value)}`}}- 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 =+ const isNullableClause: SafeSqlFragment =+ is_nullable === undefined ? safeSql`` : is_nullable ? safeSql`NULL` : safeSql`NOT NULL`+ const isPrimaryKeyClause: SafeSqlFragment = is_primary_key ? safeSql`PRIMARY KEY` : safeSql``+ const isUniqueClause: SafeSqlFragment = is_unique ? safeSql`UNIQUE` : safeSql``+ const checkSql: SafeSqlFragment =+ check === undefined ? safeSql`` : safeSql`CHECK (${rawSql(check)})`+ const commentSql: SafeSqlFragment =comment === undefined- ? ''- : `COMMENT ON COLUMN ${ident(schema)}.${ident(table)}.${ident(name)} IS ${literal(comment)}`+ ? safeSql``+ : safeSql`COMMENT ON COLUMN ${ident(schema)}.${ident(table)}.${ident(name)} IS ${literal(comment)}`- const sql = `+ const sql = safeSql`ALTER TABLE ${ident(schema)}.${ident(table)} ADD COLUMN ${ident(name)} ${typeIdent(type)}${defaultValueClause}${isNullableClause}@@ -180,20 +200,19 @@ function create({}return {- sql: `+ sql: safeSql`BEGIN;${sql};COMMIT;`,}}-// 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 typeIdent(type: ColumnTypeRef): SafeSqlFragment {+ const base =+ type.schema !== undefined+ ? safeSql`${ident(type.schema)}.${ident(type.name)}`+ : ident(type.name)+ return type.isArray ? safeSql`${base}[]` : base}function update(@@ -215,7 +234,7 @@ function update(check,}: {name?: string- type?: string+ type?: ColumnTypeRefdrop_default?: booleandefault_value?: anydefault_value_format?: 'expression' | 'literal'@@ -224,36 +243,28 @@ function update(is_nullable?: booleanis_unique?: booleancomment?: string | null- check?: string | null+ check?: SafeSqlFragment | null}-): { sql: string } {- const nameSql =+): { sql: SafeSqlFragment } {+ const nameSql: SafeSqlFragment =name === undefined || name === old.name- ? ''- : `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} RENAME COLUMN ${ident(- old.name- )} TO ${ident(name)};`+ ? safeSql``+ : safeSql`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} RENAME COLUMN ${ident(old.name)} TO ${ident(name)};`// We use USING to allow implicit conversion of incompatible types (e.g. int4 -> text).- const typeSql =+ const typeSql: SafeSqlFragment =type === undefined- ? ''- : `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(- old.name- )} SET DATA TYPE ${typeIdent(type)} USING ${ident(old.name)}::${typeIdent(type)};`+ ? safeSql``+ : safeSql`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(old.name)} SET DATA TYPE ${typeIdent(type)} USING ${ident(old.name)}::${typeIdent(type)};`- let defaultValueSql: string+ let defaultValueSql: SafeSqlFragmentif (drop_default) {- defaultValueSql = `ALTER TABLE ${ident(old.schema)}.${ident(- old.table- )} ALTER COLUMN ${ident(old.name)} DROP DEFAULT;`+ defaultValueSql = safeSql`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(old.name)} DROP DEFAULT;`} else if (default_value === undefined) {- defaultValueSql = ''+ defaultValueSql = safeSql``} else {- const defaultValue =+ const defaultValue: SafeSqlFragment =default_value_format === 'expression' ? default_value : literal(default_value)- defaultValueSql = `ALTER TABLE ${ident(old.schema)}.${ident(- old.table- )} ALTER COLUMN ${ident(old.name)} SET DEFAULT ${defaultValue};`+ defaultValueSql = safeSql`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(old.name)} SET DEFAULT ${defaultValue};`}// What identitySql does vary depending on the old and new values of// is_identity and identity_generation.@@ -263,37 +274,32 @@ function update(// | true | maybe set identity | maybe set identity | drop if exists |// |------------------------+--------------------+--------------------+----------------|// | false | - | add identity | drop if exists |- let identitySql = `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(- old.name- )}`+ const alterColumnPrefix = safeSql`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(old.name)}`+ let identitySql: SafeSqlFragmentif (is_identity === false) {- identitySql += ' DROP IDENTITY IF EXISTS;'+ identitySql = safeSql`${alterColumnPrefix} DROP IDENTITY IF EXISTS;`} else if (old.is_identity === true) {if (identity_generation === undefined) {- identitySql = ''+ identitySql = safeSql``} else {- identitySql += ` SET GENERATED ${identity_generation};`+ identitySql = safeSql`${alterColumnPrefix} SET GENERATED ${keyword(identity_generation)};`}} else if (is_identity === undefined) {- identitySql = ''+ identitySql = safeSql``} else {- identitySql += ` ADD GENERATED ${identity_generation} AS IDENTITY;`+ identitySql = safeSql`${alterColumnPrefix} ADD GENERATED ${keyword(identity_generation)} AS IDENTITY;`}- let isNullableSql: string+ let isNullableSql: SafeSqlFragmentif (is_nullable === undefined) {- isNullableSql = ''+ isNullableSql = safeSql``} else {isNullableSql = is_nullable- ? `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(- old.name- )} DROP NOT NULL;`- : `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(- old.name- )} SET NOT NULL;`+ ? safeSql`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(old.name)} DROP NOT NULL;`+ : safeSql`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(old.name)} SET NOT NULL;`}- let isUniqueSql = ''+ let isUniqueSql: SafeSqlFragment = safeSql``if (old.is_unique === true && is_unique === false) {- isUniqueSql = `+ isUniqueSql = safeSql`DO $$DECLAREr record;@@ -305,29 +311,32 @@ BEGINAND conrelid = ${literal(old.table_id)}AND conkey[1] = ${literal(old.ordinal_position)}LOOP- EXECUTE ${literal(- `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} DROP CONSTRAINT `- )} || quote_ident(r.conname);+ EXECUTE ${literal(`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} DROP CONSTRAINT `)} || quote_ident(r.conname);END LOOP;END-$$;-`+$$;`} else if (old.is_unique === false && is_unique === true) {- isUniqueSql = `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ADD UNIQUE (${ident(- old.name- )});`+ isUniqueSql = safeSql`ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ADD UNIQUE (${ident(old.name)});`}- const commentSql =+ const commentSql: SafeSqlFragment =comment === undefined- ? ''- : `COMMENT ON COLUMN ${ident(old.schema)}.${ident(old.table)}.${ident(- old.name- )} IS ${literal(comment)};`-- const checkSql =- check === undefined- ? ''- : `+ ? safeSql``+ : safeSql`COMMENT ON COLUMN ${ident(old.schema)}.${ident(old.table)}.${ident(old.name)} IS ${literal(comment)};`++ let checkSql: SafeSqlFragment = safeSql``+ if (check !== undefined) {+ const addCheckSql: SafeSqlFragment =+ check !== null+ ? safeSql`+ ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ADD CONSTRAINT ${ident(`${old.table}_${old.name}_check`)} CHECK (${check});++ SELECT conkey into v_conkey FROM pg_constraint WHERE conname = ${literal(`${old.table}_${old.name}_check`)};++ ASSERT v_conkey IS NOT NULL, 'error creating column constraint: check condition must refer to this column';+ ASSERT cardinality(v_conkey) = 1, 'error creating column constraint: check condition cannot refer to multiple columns';+ ASSERT v_conkey[1] = ${literal(old.ordinal_position)}, 'error creating column constraint: check condition cannot refer to other columns';`+ : safeSql``+ checkSql = safeSql`DO $$DECLAREv_conname name;@@ -342,40 +351,19 @@ BEGINLIMIT 1;IF v_conname IS NOT NULL THEN- EXECUTE format('ALTER TABLE ${ident(old.schema)}.${ident(- old.table- )} DROP CONSTRAINT %I', v_conname);+ EXECUTE format('ALTER TABLE ${ident(old.schema)}.${ident(old.table)} DROP CONSTRAINT %I', v_conname);END IF;-- ${- check !== null- ? `- ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ADD CONSTRAINT ${ident(- `${old.table}_${old.name}_check`- )} CHECK (${check});-- SELECT conkey into v_conkey FROM pg_constraint WHERE conname = ${literal(- `${old.table}_${old.name}_check`- )};-- ASSERT v_conkey IS NOT NULL, 'error creating column constraint: check condition must refer to this column';- ASSERT cardinality(v_conkey) = 1, 'error creating column constraint: check condition cannot refer to multiple columns';- ASSERT v_conkey[1] = ${literal(- old.ordinal_position- )}, 'error creating column constraint: check condition cannot refer to other columns';-`- : ''- }+ ${addCheckSql}END-$$;-`+$$;`+ }// TODO: Can't set default if column is previously identity even if// is_identity: false. Must do two separate PATCHes (once to drop identity// and another to set default).// NOTE: nameSql must be last. defaultValueSql must be after typeSql.// identitySql must be after isNullableSql.- const sql = `+ const sql = safeSql`BEGIN;${isNullableSql}${typeSql}diff --git a/packages/pg-meta/src/sql/columns.ts b/packages/pg-meta/src/sql/columns.tsindex cdf6c130ea7..1d81d4d5932 100644--- a/packages/pg-meta/src/sql/columns.ts+++ b/packages/pg-meta/src/sql/columns.ts@@ -29,6 +29,7 @@ SELECTENDEND AS data_type,COALESCE(bt.typname, t.typname) AS format,+ COALESCE(nbt.nspname, nt.nspname) AS format_schema,a.attidentity IN ('a', 'd') AS is_identity,CASEa.attidentitydiff --git a/packages/pg-meta/src/sql/studio/table-editor/table.ts b/packages/pg-meta/src/sql/studio/table-editor/table.tsindex 19cb3b30aad..8b0af9731d9 100644--- a/packages/pg-meta/src/sql/studio/table-editor/table.ts+++ b/packages/pg-meta/src/sql/studio/table-editor/table.ts@@ -1,4 +1,4 @@-import { ident, literal } from '../../../pg-format'+import { ident, joinSqlFragments, literal, safeSql, type SafeSqlFragment } from '../../../pg-format'export const getDuplicateTableSQL = ({comment,@@ -10,13 +10,13 @@ export const getDuplicateTableSQL = ({duplicatedTableName: stringsourceTableName: stringsourceTableSchema: string-}) => {- return [- `CREATE TABLE ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} (LIKE ${ident(sourceTableSchema)}.${ident(sourceTableName)} INCLUDING ALL);`,+}): SafeSqlFragment => {+ const createSql = safeSql`CREATE TABLE ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} (LIKE ${ident(sourceTableSchema)}.${ident(sourceTableName)} INCLUDING ALL);`+ const commentSql =comment != undefined- ? `comment on table ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} is ${literal(comment)};`- : '',- ].join('\n')+ ? safeSql`comment on table ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} is ${literal(comment)};`+ : safeSql``+ return joinSqlFragments([createSql, commentSql], '\n')}export const getDuplicateRowsSQL = ({@@ -27,14 +27,14 @@ export const getDuplicateRowsSQL = ({duplicatedTableName: stringsourceTableName: stringsourceTableSchema: string-}) => {- return `INSERT INTO ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} SELECT * FROM ${ident(sourceTableSchema)}.${ident(sourceTableName)};`+}): SafeSqlFragment => {+ return safeSql`INSERT INTO ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} SELECT * FROM ${ident(sourceTableSchema)}.${ident(sourceTableName)};`}-export const getTableEditorSql = ({ id }: { id?: number }) => {- if (!id) return ''+export const getTableEditorSql = ({ id }: { id?: number }): SafeSqlFragment => {+ if (!id) return safeSql``- return /* SQL */ `+ return safeSql`with base_table_info as (selectc.oid::int8 as id,@@ -55,7 +55,7 @@ export const getTableEditorSql = ({ id }: { id?: number }) => {left join pg_foreign_server fs on fs.oid = ft.ftserverleft join pg_foreign_data_wrapper fdw on fdw.oid = fs.srvfdwleft join pg_proc fdw_handler on fdw.fdwhandler = fdw_handler.oid- where c.oid = ${id}+ where c.oid = ${literal(id)}and not pg_is_other_temp_schema(nc.oid)and (pg_has_role(c.relowner, 'USAGE')@@ -186,15 +186,8 @@ export const getTableEditorSql = ({ id }: { id?: number }) => {else 'USER-DEFINED'endend,- 'format', case- when t.typtype = 'e' then- case- when nt.nspname <> 'public' then concat(nt.nspname, '.', coalesce(bt.typname, t.typname))- else coalesce(bt.typname, t.typname)- end- else- coalesce(bt.typname, t.typname)- end,+ 'format', coalesce(bt.typname, t.typname),+ 'format_schema', coalesce(nbt.nspname, nt.nspname),'is_identity', a.attidentity in ('a', 'd'),'identity_generation', case a.attidentitywhen 'a' then 'ALWAYS'@@ -338,5 +331,5 @@ export const getTableEditorSql = ({ id }: { id?: number }) => {left join primary_keys pk on b.id = pk.table_idleft join unique_indexes ui on b.id = ui.table_idleft join columns c on b.id = c.table_id;- `.trim()+ `}diff --git a/packages/pg-meta/test/columns.test.ts b/packages/pg-meta/test/columns.test.tsindex d7d80726565..0b3ed983d1e 100644--- a/packages/pg-meta/test/columns.test.ts+++ b/packages/pg-meta/test/columns.test.ts@@ -1,6 +1,7 @@import { afterAll, beforeAll, describe, expect, test } from 'vitest'import pgMeta from '../src/index'+import { rawSql } from '../src/pg-format'import { cleanupRoot, createTestDatabase } from './db/utils'beforeAll(async () => {@@ -43,6 +44,7 @@ withTestDatabase('list columns', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": StringMatching /\\^\\\\d\\+\\\\\\.3\\$/,"identity_generation": null,"is_generated": false,@@ -98,6 +100,7 @@ withTestDatabase('list columns from a single table', async ({ executeQuery }) =>"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": StringMatching /\\^\\\\d\\+\\\\\\.\\\\d\\+\\$/,"identity_generation": null,"is_generated": false,@@ -118,6 +121,7 @@ withTestDatabase('list columns from a single table', async ({ executeQuery }) =>"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": StringMatching /\\^\\\\d\\+\\\\\\.\\\\d\\+\\$/,"identity_generation": null,"is_generated": false,@@ -184,7 +188,7 @@ withTestDatabase('retrieve, create, update, delete column', async ({ executeQuerschema: 'public',table: 't',name: 'c',- type: 'int2',+ type: { name: 'int2' },default_value: 42,comment: 'foo',})@@ -210,6 +214,7 @@ withTestDatabase('retrieve, create, update, delete column', async ({ executeQuer"default_value": "42","enums": [],"format": "int2",+ "format_schema": "pg_catalog","id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,"identity_generation": null,"is_generated": false,@@ -229,7 +234,7 @@ withTestDatabase('retrieve, create, update, delete column', async ({ executeQuer// Update columnconst { sql: updateSql } = await pgMeta.columns.update(column!, {name: 'c1',- type: 'int4',+ type: { name: 'int4' },drop_default: true,is_identity: true,identity_generation: 'ALWAYS',@@ -258,6 +263,7 @@ withTestDatabase('retrieve, create, update, delete column', async ({ executeQuer"default_value": null,"enums": [],"format": "int4",+ "format_schema": "pg_catalog","id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,"identity_generation": "ALWAYS","is_generated": false,@@ -309,6 +315,7 @@ withTestDatabase('enum column with quoted name', async ({ executeQuery }) => {"v",],"format": "T",+ "format_schema": "public","id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,"identity_generation": null,"is_generated": false,@@ -335,7 +342,7 @@ withTestDatabase('primary key column', async ({ executeQuery }) => {schema: 'public',table: 't',name: 'c',- type: 'int2',+ type: { name: 'int2' },is_primary_key: true,})await executeQuery(createColumnSql)@@ -368,7 +375,7 @@ withTestDatabase('unique column', async ({ executeQuery }) => {schema: 'public',table: 't',name: 'c',- type: 'int2',+ type: { name: 'int2' },is_unique: true,})await executeQuery(createColumnSql)@@ -403,35 +410,35 @@ describe('array column', async () => {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' },+ { 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' },+ { type: 'json', etype: '_json' },+ { type: 'jsonb', etype: '_jsonb' },// text types- { type: 'text[]', etype: '_text' },- { type: 'varchar[]', etype: '_varchar' },+ { 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' },+ { 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 }) => {+ { 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 valueconst { sql } = pgMeta.columns.create({...id,- type: c.type,+ type: { name: c.type, isArray: true },default_value: null,})await db.executeQuery(sql)@@ -446,6 +453,7 @@ describe('array column', async () => {data_type: 'ARRAY',default_value: null,format: c.etype,+ format_schema: 'pg_catalog',id: expect.stringMatching(/^\d+\.\d+$/),ordinal_position: expect.any(Number),table_id: expect.any(Number),@@ -533,12 +541,16 @@ describe('column with default value', async () => {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',- })+ const { sql } = pgMeta.columns.create(+ c.exp+ ? {+ ...id,+ type: { name: c.type },+ default_value_format: 'expression',+ default_value: rawSql(String(c.value)),+ }+ : { ...id, type: { name: c.type }, default_value_format: 'literal', default_value: c.value }+ )await db.executeQuery(sql)// Retrieve and verify the created column@@ -551,6 +563,7 @@ describe('column with default value', async () => {data_type: c.etype,default_value: c.evalue,format: c.type,+ format_schema: 'pg_catalog',id: expect.stringMatching(/^\d+\.\d+$/),ordinal_position: expect.any(Number),table_id: expect.any(Number),@@ -578,7 +591,7 @@ withTestDatabase('alter column to type with uppercase', async ({ executeQuery })schema: 'public',table: 't',name: 'c',- type: 'text',+ type: { name: 'text' },is_unique: false,})await executeQuery(createSql)@@ -592,7 +605,7 @@ withTestDatabase('alter column to type with uppercase', async ({ executeQuery })const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])// Update column- const { sql: updateSql } = await pgMeta.columns.update(column!, { type: 'T' })+ const { sql: updateSql } = await pgMeta.columns.update(column!, { type: { name: 'T' } })await executeQuery(updateSql)// Verify updated column@@ -616,6 +629,7 @@ withTestDatabase('alter column to type with uppercase', async ({ executeQuery })"default_value": null,"enums": [],"format": "T",+ "format_schema": "public","id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,"identity_generation": null,"is_generated": false,@@ -639,16 +653,16 @@ withTestDatabase('enums are populated in enum array columns', async ({ executeQuawait executeQuery('CREATE TABLE t ()')// Create column- const { sql: createSql } = await pgMeta.columns.create({+ const { sql: createSql } = pgMeta.columns.create({schema: 'public',table: 't',name: 'c',- type: '_test_enum',+ type: { name: 'test_enum', isArray: true },})await executeQuery(createSql)// Verify created column- const { sql: verifySql, zod: verifyZod } = await pgMeta.columns.retrieve({+ const { sql: verifySql, zod: verifyZod } = pgMeta.columns.retrieve({schema: 'public',table: 't',name: 'c',@@ -670,6 +684,7 @@ withTestDatabase('enums are populated in enum array columns', async ({ executeQu"a",],"format": "_test_enum",+ "format_schema": "public","id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,"identity_generation": null,"is_generated": false,@@ -697,7 +712,7 @@ withTestDatabase('drop with cascade', async ({ executeQuery }) => {`)// Retrieve column- const { sql: retrieveSql, zod: retrieveZod } = await pgMeta.columns.retrieve({+ const { sql: retrieveSql, zod: retrieveZod } = pgMeta.columns.retrieve({schema: 'public',table: 't',name: 'id',@@ -705,11 +720,11 @@ withTestDatabase('drop with cascade', async ({ executeQuery }) => {const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])// Remove column with cascade- const { sql: removeSql } = await pgMeta.columns.remove(column!, { cascade: true })+ const { sql: removeSql } = pgMeta.columns.remove(column!, { cascade: true })await executeQuery(removeSql)// Verify original column was removed- const { sql: verifyIdSql, zod: verifyIdZod } = await pgMeta.columns.retrieve({+ const { sql: verifyIdSql, zod: verifyIdZod } = pgMeta.columns.retrieve({schema: 'public',table: 't',name: 'id',@@ -718,7 +733,7 @@ withTestDatabase('drop with cascade', async ({ executeQuery }) => {expect(removedColumn).toBeUndefined()// Verify dependent column was also removed- const { sql: verifyTIdSql, zod: verifyTIdZod } = await pgMeta.columns.retrieve({+ const { sql: verifyTIdSql, zod: verifyTIdZod } = pgMeta.columns.retrieve({schema: 'public',table: 't',name: 't_id',@@ -732,7 +747,7 @@ withTestDatabase('column with multiple checks', async ({ executeQuery }) => {await executeQuery('create table t(c int8 check (c != 0) check (c != -1))')// List columns- const { sql, zod } = await pgMeta.columns.list()+ const { sql, zod } = pgMeta.columns.list()const res = zod.parse(await executeQuery(sql))const columns = res@@ -748,6 +763,7 @@ withTestDatabase('column with multiple checks', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","identity_generation": null,"is_generated": false,"is_identity": false,@@ -784,6 +800,7 @@ withTestDatabase('column with multiple unique constraints', async ({ executeQuer"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","identity_generation": null,"is_generated": false,"is_identity": false,@@ -839,7 +856,7 @@ withTestDatabase('column with fully-qualified type', async ({ executeQuery }) =>schema: 'public',table: 't',name: 'c',- type: 's.my_type',+ type: { schema: 's', name: 'my_type' },})await executeQuery(createColumnSql)@@ -864,6 +881,7 @@ withTestDatabase('column with fully-qualified type', async ({ executeQuery }) =>"default_value": null,"enums": [],"format": "my_type",+ "format_schema": "s","id": StringMatching /\\^\\\\d\\+\\\\\\.1\\$/,"identity_generation": null,"is_generated": false,@@ -880,3 +898,70 @@ withTestDatabase('column with fully-qualified type', async ({ executeQuery }) =>`)})++withTestDatabase('format_schema for built-in type', async ({ executeQuery }) => {+ await executeQuery(`create table t (c int4)`)++ const { sql, zod } = pgMeta.columns.retrieve({ schema: 'public', table: 't', name: 'c' })+ const column = zod.parse((await executeQuery(sql))[0])++ expect(column?.format).toBe('int4')+ expect(column?.format_schema).toBe('pg_catalog')+})++withTestDatabase('format_schema for public-schema enum', async ({ executeQuery }) => {+ await executeQuery(`create type public_enum as enum ('a'); create table t (c public_enum);`)++ const { sql, zod } = pgMeta.columns.retrieve({ schema: 'public', table: 't', name: 'c' })+ const column = zod.parse((await executeQuery(sql))[0])++ expect(column?.format).toBe('public_enum')+ expect(column?.format_schema).toBe('public')+})++withTestDatabase('format_schema for non-public-schema enum', async ({ executeQuery }) => {+ await executeQuery(`+ create schema s;+ create type s.my_enum as enum ('a');+ create table t (c s.my_enum);+ `)++ const { sql, zod } = pgMeta.columns.retrieve({ schema: 'public', table: 't', name: 'c' })+ const column = zod.parse((await executeQuery(sql))[0])++ expect(column?.format).toBe('my_enum')+ expect(column?.format_schema).toBe('s')+})++withTestDatabase('format_schema for array of non-public-schema enum', async ({ executeQuery }) => {+ await executeQuery(`+ create schema s;+ create type s.my_enum as enum ('a');+ create table t (c s.my_enum[]);+ `)++ const { sql, zod } = pgMeta.columns.retrieve({ schema: 'public', table: 't', name: 'c' })+ const column = zod.parse((await executeQuery(sql))[0])++ expect(column?.data_type).toBe('ARRAY')+ expect(column?.format).toBe('_my_enum')+ expect(column?.format_schema).toBe('s')+})++withTestDatabase(+ 'format_schema for domain over non-public-schema base type',+ async ({ executeQuery }) => {+ await executeQuery(`+ create schema s;+ create domain s.my_domain as int4;+ create table t (c s.my_domain);+ `)++ const { sql, zod } = pgMeta.columns.retrieve({ schema: 'public', table: 't', name: 'c' })+ const column = zod.parse((await executeQuery(sql))[0])++ // Domain's `format` resolves to the base type, so `format_schema` follows the base type.+ expect(column?.format).toBe('int4')+ expect(column?.format_schema).toBe('pg_catalog')+ }+)diff --git a/packages/pg-meta/test/foreign-tables.test.ts b/packages/pg-meta/test/foreign-tables.test.tsindex d656e56947a..38da362ede1 100644--- a/packages/pg-meta/test/foreign-tables.test.ts+++ b/packages/pg-meta/test/foreign-tables.test.ts@@ -41,6 +41,7 @@ withTestDatabase('list foreign tables', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16451.1","identity_generation": null,"is_generated": false,@@ -61,6 +62,7 @@ withTestDatabase('list foreign tables', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": "16451.2","identity_generation": null,"is_generated": false,@@ -84,6 +86,7 @@ withTestDatabase('list foreign tables', async ({ executeQuery }) => {"INACTIVE",],"format": "user_status",+ "format_schema": "public","id": "16451.3","identity_generation": null,"is_generated": false,@@ -148,6 +151,7 @@ withTestDatabase('retrieve foreign table by name', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16451.1","identity_generation": null,"is_generated": false,@@ -168,6 +172,7 @@ withTestDatabase('retrieve foreign table by name', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": "16451.2","identity_generation": null,"is_generated": false,@@ -191,6 +196,7 @@ withTestDatabase('retrieve foreign table by name', async ({ executeQuery }) => {"INACTIVE",],"format": "user_status",+ "format_schema": "public","id": "16451.3","identity_generation": null,"is_generated": false,@@ -234,6 +240,7 @@ withTestDatabase('retrieve foreign table by id', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16451.1","identity_generation": null,"is_generated": false,@@ -254,6 +261,7 @@ withTestDatabase('retrieve foreign table by id', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": "16451.2","identity_generation": null,"is_generated": false,@@ -277,6 +285,7 @@ withTestDatabase('retrieve foreign table by id', async ({ executeQuery }) => {"INACTIVE",],"format": "user_status",+ "format_schema": "public","id": "16451.3","identity_generation": null,"is_generated": false,diff --git a/packages/pg-meta/test/materialized-views.test.ts b/packages/pg-meta/test/materialized-views.test.tsindex 616dd626c02..8f1f080cf60 100644--- a/packages/pg-meta/test/materialized-views.test.ts+++ b/packages/pg-meta/test/materialized-views.test.ts@@ -41,6 +41,7 @@ withTestDatabase('list materialized views', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16431.1","identity_generation": null,"is_generated": false,@@ -61,6 +62,7 @@ withTestDatabase('list materialized views', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": "16431.2","identity_generation": null,"is_generated": false,@@ -81,6 +83,7 @@ withTestDatabase('list materialized views', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16431.3","identity_generation": null,"is_generated": false,@@ -141,6 +144,7 @@ withTestDatabase('retrieve materialized view by name', async ({ executeQuery })"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16431.1","identity_generation": null,"is_generated": false,@@ -161,6 +165,7 @@ withTestDatabase('retrieve materialized view by name', async ({ executeQuery })"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": "16431.2","identity_generation": null,"is_generated": false,@@ -181,6 +186,7 @@ withTestDatabase('retrieve materialized view by name', async ({ executeQuery })"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16431.3","identity_generation": null,"is_generated": false,@@ -213,75 +219,78 @@ withTestDatabase('retrieve materialized view by id', async ({ executeQuery }) =>expect(view).toMatchInlineSnapshot({ id: expect.any(Number) },`- {- "columns": [- {- "check": null,- "comment": null,- "data_type": "bigint",- "default_value": null,- "enums": [],- "format": "int8",- "id": "16431.1",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": false,- "name": "id",- "ordinal_position": 1,- "schema": "public",- "table": "todos_matview",- "table_id": 16431,- },- {- "check": null,- "comment": null,- "data_type": "text",- "default_value": null,- "enums": [],- "format": "text",- "id": "16431.2",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": false,- "name": "details",- "ordinal_position": 2,- "schema": "public",- "table": "todos_matview",- "table_id": 16431,- },- {- "check": null,- "comment": null,- "data_type": "bigint",- "default_value": null,- "enums": [],- "format": "int8",- "id": "16431.3",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": false,- "name": "user-id",- "ordinal_position": 3,- "schema": "public",- "table": "todos_matview",- "table_id": 16431,- },- ],- "comment": null,- "id": Any<Number>,- "is_populated": true,- "name": "todos_matview",- "schema": "public",- }- `+ {+ "columns": [+ {+ "check": null,+ "comment": null,+ "data_type": "bigint",+ "default_value": null,+ "enums": [],+ "format": "int8",+ "format_schema": "pg_catalog",+ "id": "16431.1",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": false,+ "name": "id",+ "ordinal_position": 1,+ "schema": "public",+ "table": "todos_matview",+ "table_id": 16431,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "text",+ "default_value": null,+ "enums": [],+ "format": "text",+ "format_schema": "pg_catalog",+ "id": "16431.2",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": false,+ "name": "details",+ "ordinal_position": 2,+ "schema": "public",+ "table": "todos_matview",+ "table_id": 16431,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "bigint",+ "default_value": null,+ "enums": [],+ "format": "int8",+ "format_schema": "pg_catalog",+ "id": "16431.3",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": false,+ "name": "user-id",+ "ordinal_position": 3,+ "schema": "public",+ "table": "todos_matview",+ "table_id": 16431,+ },+ ],+ "comment": null,+ "id": Any<Number>,+ "is_populated": true,+ "name": "todos_matview",+ "schema": "public",+ }+ `)})diff --git a/packages/pg-meta/test/tables.test.ts b/packages/pg-meta/test/tables.test.tsindex 9f13f67cb9c..c5eb3405e79 100644--- a/packages/pg-meta/test/tables.test.ts+++ b/packages/pg-meta/test/tables.test.ts@@ -58,106 +58,109 @@ withTestDatabase('list tables', async ({ executeQuery }) => {size: expect.any(String),},`- {- "bytes": Any<Number>,- "columns": [- {- "check": null,- "comment": null,- "data_type": "bigint",- "default_value": null,- "enums": [],- "format": "int8",- "identity_generation": "BY DEFAULT",- "is_generated": false,- "is_identity": true,- "is_nullable": false,- "is_unique": false,- "is_updatable": true,- "name": "id",- "ordinal_position": 1,- "schema": "public",- "table": "users",- },- {- "check": null,- "comment": null,- "data_type": "text",- "default_value": null,- "enums": [],- "format": "text",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": true,- "name": "name",- "ordinal_position": 2,- "schema": "public",- "table": "users",- },- {- "check": null,- "comment": null,- "data_type": "USER-DEFINED",- "default_value": "'ACTIVE'::user_status",- "enums": [- "ACTIVE",- "INACTIVE",- ],- "format": "user_status",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": true,- "name": "status",- "ordinal_position": 3,- "schema": "public",- "table": "users",- },- ],- "comment": null,- "dead_rows_estimate": Any<Number>,- "id": Any<Number>,- "live_rows_estimate": Any<Number>,- "name": "users",- "primary_keys": [- {- "name": "id",- "schema": "public",- "table_name": "users",- },- ],- "relationships": [- {- "constraint_name": "todos_user-id_fkey",- "source_column_name": "user-id",- "source_schema": "public",- "source_table_name": "todos",- "target_column_name": "id",- "target_table_name": "users",- "target_table_schema": "public",- },- {- "constraint_name": "user_details_user_id_fkey",- "source_column_name": "user_id",- "source_schema": "public",- "source_table_name": "user_details",- "target_column_name": "id",- "target_table_name": "users",- "target_table_schema": "public",- },- ],- "replica_identity": "DEFAULT",- "rls_enabled": false,- "rls_forced": false,- "schema": "public",- "size": Any<String>,- }- `+ {+ "bytes": Any<Number>,+ "columns": [+ {+ "check": null,+ "comment": null,+ "data_type": "bigint",+ "default_value": null,+ "enums": [],+ "format": "int8",+ "format_schema": "pg_catalog",+ "identity_generation": "BY DEFAULT",+ "is_generated": false,+ "is_identity": true,+ "is_nullable": false,+ "is_unique": false,+ "is_updatable": true,+ "name": "id",+ "ordinal_position": 1,+ "schema": "public",+ "table": "users",+ },+ {+ "check": null,+ "comment": null,+ "data_type": "text",+ "default_value": null,+ "enums": [],+ "format": "text",+ "format_schema": "pg_catalog",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": true,+ "name": "name",+ "ordinal_position": 2,+ "schema": "public",+ "table": "users",+ },+ {+ "check": null,+ "comment": null,+ "data_type": "USER-DEFINED",+ "default_value": "'ACTIVE'::user_status",+ "enums": [+ "ACTIVE",+ "INACTIVE",+ ],+ "format": "user_status",+ "format_schema": "public",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": true,+ "name": "status",+ "ordinal_position": 3,+ "schema": "public",+ "table": "users",+ },+ ],+ "comment": null,+ "dead_rows_estimate": Any<Number>,+ "id": Any<Number>,+ "live_rows_estimate": Any<Number>,+ "name": "users",+ "primary_keys": [+ {+ "name": "id",+ "schema": "public",+ "table_name": "users",+ },+ ],+ "relationships": [+ {+ "constraint_name": "todos_user-id_fkey",+ "source_column_name": "user-id",+ "source_schema": "public",+ "source_table_name": "todos",+ "target_column_name": "id",+ "target_table_name": "users",+ "target_table_schema": "public",+ },+ {+ "constraint_name": "user_details_user_id_fkey",+ "source_column_name": "user_id",+ "source_schema": "public",+ "source_table_name": "user_details",+ "target_column_name": "id",+ "target_table_name": "users",+ "target_table_schema": "public",+ },+ ],+ "replica_identity": "DEFAULT",+ "rls_enabled": false,+ "rls_forced": false,+ "schema": "public",+ "size": Any<String>,+ }+ `)})@@ -501,71 +504,73 @@ withTestDatabase('primary keys', async ({ executeQuery }) => {size: expect.any(String),},`- {- "bytes": Any<Number>,- "columns": [- {- "check": null,- "comment": null,- "data_type": "bigint",- "default_value": null,- "enums": [],- "format": "int8",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": false,- "is_unique": false,- "is_updatable": true,- "name": "c",- "ordinal_position": 1,- "schema": "public",- "table": "t",- },- {- "check": null,- "comment": null,- "data_type": "text",- "default_value": null,- "enums": [],- "format": "text",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": false,- "is_unique": false,- "is_updatable": true,- "name": "cc",- "ordinal_position": 2,- "schema": "public",- "table": "t",- },- ],- "comment": null,- "dead_rows_estimate": Any<Number>,- "id": Any<Number>,- "live_rows_estimate": Any<Number>,- "name": "t",- "primary_keys": [- {- "name": "c",- "schema": "public",- "table_name": "t",- },- {- "name": "cc",- "schema": "public",- "table_name": "t",- },- ],- "relationships": [],- "replica_identity": "DEFAULT",- "rls_enabled": false,- "rls_forced": false,- "schema": "public",- "size": Any<String>,- }- `+ {+ "bytes": Any<Number>,+ "columns": [+ {+ "check": null,+ "comment": null,+ "data_type": "bigint",+ "default_value": null,+ "enums": [],+ "format": "int8",+ "format_schema": "pg_catalog",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": false,+ "is_unique": false,+ "is_updatable": true,+ "name": "c",+ "ordinal_position": 1,+ "schema": "public",+ "table": "t",+ },+ {+ "check": null,+ "comment": null,+ "data_type": "text",+ "default_value": null,+ "enums": [],+ "format": "text",+ "format_schema": "pg_catalog",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": false,+ "is_unique": false,+ "is_updatable": true,+ "name": "cc",+ "ordinal_position": 2,+ "schema": "public",+ "table": "t",+ },+ ],+ "comment": null,+ "dead_rows_estimate": Any<Number>,+ "id": Any<Number>,+ "live_rows_estimate": Any<Number>,+ "name": "t",+ "primary_keys": [+ {+ "name": "c",+ "schema": "public",+ "table_name": "t",+ },+ {+ "name": "cc",+ "schema": "public",+ "table_name": "t",+ },+ ],+ "relationships": [],+ "replica_identity": "DEFAULT",+ "rls_enabled": false,+ "rls_forced": false,+ "schema": "public",+ "size": Any<String>,+ }+ `)})@@ -593,6 +598,7 @@ withTestDatabase('retrieve table by id', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": "16510.2","identity_generation": null,"is_generated": false,@@ -613,6 +619,7 @@ withTestDatabase('retrieve table by id', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int4",+ "format_schema": "pg_catalog","id": "16510.3","identity_generation": null,"is_generated": false,@@ -633,6 +640,7 @@ withTestDatabase('retrieve table by id', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "jsonb",+ "format_schema": "pg_catalog","id": "16510.4","identity_generation": null,"is_generated": false,@@ -653,6 +661,7 @@ withTestDatabase('retrieve table by id', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "timestamp",+ "format_schema": "pg_catalog","id": "16510.5","identity_generation": null,"is_generated": false,@@ -673,6 +682,7 @@ withTestDatabase('retrieve table by id', async ({ executeQuery }) => {"default_value": "nextval('memes_id_seq'::regclass)","enums": [],"format": "int4",+ "format_schema": "pg_catalog","id": "16510.1","identity_generation": null,"is_generated": false,@@ -697,6 +707,7 @@ withTestDatabase('retrieve table by id', async ({ executeQuery }) => {"retired",],"format": "meme_status",+ "format_schema": "public","id": "16510.6","identity_generation": null,"is_generated": false,@@ -759,166 +770,172 @@ withTestDatabase('retrieve table by name and schema', async ({ executeQuery }) =size: expect.any(String),},`- {- "bytes": Any<Number>,- "columns": [- {- "check": null,- "comment": null,- "data_type": "text",- "default_value": null,- "enums": [],- "format": "text",- "id": "16510.2",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": false,- "is_unique": false,- "is_updatable": true,- "name": "name",- "ordinal_position": 2,- "schema": "public",- "table": "memes",- "table_id": 16510,- },- {- "check": null,- "comment": null,- "data_type": "integer",- "default_value": null,- "enums": [],- "format": "int4",- "id": "16510.3",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": true,- "name": "category",- "ordinal_position": 3,- "schema": "public",- "table": "memes",- "table_id": 16510,- },- {- "check": null,- "comment": null,- "data_type": "jsonb",- "default_value": null,- "enums": [],- "format": "jsonb",- "id": "16510.4",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": true,- "name": "metadata",- "ordinal_position": 4,- "schema": "public",- "table": "memes",- "table_id": 16510,- },- {- "check": null,- "comment": null,- "data_type": "timestamp without time zone",- "default_value": null,- "enums": [],- "format": "timestamp",- "id": "16510.5",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": false,- "is_unique": false,- "is_updatable": true,- "name": "created_at",- "ordinal_position": 5,- "schema": "public",- "table": "memes",- "table_id": 16510,- },- {- "check": null,- "comment": null,- "data_type": "integer",- "default_value": "nextval('memes_id_seq'::regclass)",- "enums": [],- "format": "int4",- "id": "16510.1",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": false,- "is_unique": false,- "is_updatable": true,- "name": "id",- "ordinal_position": 1,- "schema": "public",- "table": "memes",- "table_id": 16510,- },- {- "check": null,- "comment": null,- "data_type": "USER-DEFINED",- "default_value": "'old'::meme_status",- "enums": [- "new",- "old",- "retired",- ],- "format": "meme_status",- "id": "16510.6",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": true,- "name": "status",- "ordinal_position": 6,- "schema": "public",- "table": "memes",- "table_id": 16510,- },- ],- "comment": null,- "dead_rows_estimate": Any<Number>,- "id": Any<Number>,- "live_rows_estimate": Any<Number>,- "name": "memes",- "primary_keys": [- {- "name": "id",- "schema": "public",- "table_id": 16510,- "table_name": "memes",- },- ],- "relationships": [- {- "constraint_name": "memes_category_fkey",- "id": 16519,- "source_column_name": "category",- "source_schema": "public",- "source_table_name": "memes",- "target_column_name": "id",- "target_table_name": "category",- "target_table_schema": "public",- },- ],- "replica_identity": "DEFAULT",- "rls_enabled": false,- "rls_forced": false,- "schema": "public",- "size": Any<String>,- }- `+ {+ "bytes": Any<Number>,+ "columns": [+ {+ "check": null,+ "comment": null,+ "data_type": "text",+ "default_value": null,+ "enums": [],+ "format": "text",+ "format_schema": "pg_catalog",+ "id": "16510.2",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": false,+ "is_unique": false,+ "is_updatable": true,+ "name": "name",+ "ordinal_position": 2,+ "schema": "public",+ "table": "memes",+ "table_id": 16510,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "integer",+ "default_value": null,+ "enums": [],+ "format": "int4",+ "format_schema": "pg_catalog",+ "id": "16510.3",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": true,+ "name": "category",+ "ordinal_position": 3,+ "schema": "public",+ "table": "memes",+ "table_id": 16510,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "jsonb",+ "default_value": null,+ "enums": [],+ "format": "jsonb",+ "format_schema": "pg_catalog",+ "id": "16510.4",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": true,+ "name": "metadata",+ "ordinal_position": 4,+ "schema": "public",+ "table": "memes",+ "table_id": 16510,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "timestamp without time zone",+ "default_value": null,+ "enums": [],+ "format": "timestamp",+ "format_schema": "pg_catalog",+ "id": "16510.5",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": false,+ "is_unique": false,+ "is_updatable": true,+ "name": "created_at",+ "ordinal_position": 5,+ "schema": "public",+ "table": "memes",+ "table_id": 16510,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "integer",+ "default_value": "nextval('memes_id_seq'::regclass)",+ "enums": [],+ "format": "int4",+ "format_schema": "pg_catalog",+ "id": "16510.1",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": false,+ "is_unique": false,+ "is_updatable": true,+ "name": "id",+ "ordinal_position": 1,+ "schema": "public",+ "table": "memes",+ "table_id": 16510,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "USER-DEFINED",+ "default_value": "'old'::meme_status",+ "enums": [+ "new",+ "old",+ "retired",+ ],+ "format": "meme_status",+ "format_schema": "public",+ "id": "16510.6",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": true,+ "name": "status",+ "ordinal_position": 6,+ "schema": "public",+ "table": "memes",+ "table_id": 16510,+ },+ ],+ "comment": null,+ "dead_rows_estimate": Any<Number>,+ "id": Any<Number>,+ "live_rows_estimate": Any<Number>,+ "name": "memes",+ "primary_keys": [+ {+ "name": "id",+ "schema": "public",+ "table_id": 16510,+ "table_name": "memes",+ },+ ],+ "relationships": [+ {+ "constraint_name": "memes_category_fkey",+ "id": 16519,+ "source_column_name": "category",+ "source_schema": "public",+ "source_table_name": "memes",+ "target_column_name": "id",+ "target_table_name": "category",+ "target_table_schema": "public",+ },+ ],+ "replica_identity": "DEFAULT",+ "rls_enabled": false,+ "rls_forced": false,+ "schema": "public",+ "size": Any<String>,+ }+ `)})diff --git a/packages/pg-meta/test/views.test.ts b/packages/pg-meta/test/views.test.tsindex 3c212b8c949..20f9000fb31 100644--- a/packages/pg-meta/test/views.test.ts+++ b/packages/pg-meta/test/views.test.ts@@ -41,6 +41,7 @@ withTestDatabase('list views', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16423.1","identity_generation": null,"is_generated": false,@@ -61,6 +62,7 @@ withTestDatabase('list views', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": "16423.2","identity_generation": null,"is_generated": false,@@ -81,6 +83,7 @@ withTestDatabase('list views', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16423.3","identity_generation": null,"is_generated": false,@@ -141,6 +144,7 @@ withTestDatabase('retrieve view by name', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16423.1","identity_generation": null,"is_generated": false,@@ -161,6 +165,7 @@ withTestDatabase('retrieve view by name', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "text",+ "format_schema": "pg_catalog","id": "16423.2","identity_generation": null,"is_generated": false,@@ -181,6 +186,7 @@ withTestDatabase('retrieve view by name', async ({ executeQuery }) => {"default_value": null,"enums": [],"format": "int8",+ "format_schema": "pg_catalog","id": "16423.3","identity_generation": null,"is_generated": false,@@ -213,75 +219,78 @@ withTestDatabase('retrieve view by id', async ({ executeQuery }) => {expect(view).toMatchInlineSnapshot({ id: expect.any(Number) },`- {- "columns": [- {- "check": null,- "comment": null,- "data_type": "bigint",- "default_value": null,- "enums": [],- "format": "int8",- "id": "16423.1",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": true,- "name": "id",- "ordinal_position": 1,- "schema": "public",- "table": "todos_view",- "table_id": 16423,- },- {- "check": null,- "comment": null,- "data_type": "text",- "default_value": null,- "enums": [],- "format": "text",- "id": "16423.2",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": true,- "name": "details",- "ordinal_position": 2,- "schema": "public",- "table": "todos_view",- "table_id": 16423,- },- {- "check": null,- "comment": null,- "data_type": "bigint",- "default_value": null,- "enums": [],- "format": "int8",- "id": "16423.3",- "identity_generation": null,- "is_generated": false,- "is_identity": false,- "is_nullable": true,- "is_unique": false,- "is_updatable": true,- "name": "user-id",- "ordinal_position": 3,- "schema": "public",- "table": "todos_view",- "table_id": 16423,- },- ],- "comment": null,- "id": Any<Number>,- "is_updatable": true,- "name": "todos_view",- "schema": "public",- }- `+ {+ "columns": [+ {+ "check": null,+ "comment": null,+ "data_type": "bigint",+ "default_value": null,+ "enums": [],+ "format": "int8",+ "format_schema": "pg_catalog",+ "id": "16423.1",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": true,+ "name": "id",+ "ordinal_position": 1,+ "schema": "public",+ "table": "todos_view",+ "table_id": 16423,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "text",+ "default_value": null,+ "enums": [],+ "format": "text",+ "format_schema": "pg_catalog",+ "id": "16423.2",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": true,+ "name": "details",+ "ordinal_position": 2,+ "schema": "public",+ "table": "todos_view",+ "table_id": 16423,+ },+ {+ "check": null,+ "comment": null,+ "data_type": "bigint",+ "default_value": null,+ "enums": [],+ "format": "int8",+ "format_schema": "pg_catalog",+ "id": "16423.3",+ "identity_generation": null,+ "is_generated": false,+ "is_identity": false,+ "is_nullable": true,+ "is_unique": false,+ "is_updatable": true,+ "name": "user-id",+ "ordinal_position": 3,+ "schema": "public",+ "table": "todos_view",+ "table_id": 16423,+ },+ ],+ "comment": null,+ "id": Any<Number>,+ "is_updatable": true,+ "name": "todos_view",+ "schema": "public",+ }+ `)})