Skip to content

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

Chore/shift manual table editor queries into pg meta (#43848)

Gildas Garcia57fee30b6149
diff --git a/apps/studio/components/grid/components/grid/ColumnHeader.tsx b/apps/studio/components/grid/components/grid/ColumnHeader.tsx
index aa4492882b5..68145498442 100644
--- a/apps/studio/components/grid/components/grid/ColumnHeader.tsx
+++ b/apps/studio/components/grid/components/grid/ColumnHeader.tsx
@@ -1,12 +1,12 @@
+import { FOREIGN_KEY_CASCADE_ACTION } from '@supabase/pg-meta'
+import { getForeignKeyCascadeAction } from 'components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils'
import type { XYCoord } from 'dnd-core'
import { ArrowRight, Key, Lightbulb, Link, Lock } from 'lucide-react'
import { useEffect, useRef } from 'react'
import { useDrag, useDrop } from 'react-dnd'
-
-import { getForeignKeyCascadeAction } from 'components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import { useTableEditorTableStateSnapshot } from 'state/table-editor-table'
import { Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+
import {
useColumnHasIndexSuggestion,
useTableIndexAdvisor,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
index ed358d6cf2c..cd3550e1dee 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
@@ -1,12 +1,12 @@
+import { FOREIGN_KEY_CASCADE_ACTION } from '@supabase/pg-meta'
import type { PostgresColumn } from '@supabase/postgres-meta'
-import { isNull } from 'lodash'
-import type { Dictionary } from 'types'
-
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import type { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import type { RetrievedTableColumn, RetrieveTableResult } from 'data/tables/table-retrieve-query'
import { uuidv4 } from 'lib/helpers'
+import { isNull } from 'lodash'
import { toast } from 'sonner'
+import type { Dictionary } from 'types'
+
import {
ColumnField,
CreateColumnPayload,
@@ -32,7 +32,9 @@ const isSQLExpression = (input: string) => {
return false
}
-export const generateColumnField = (field: any = {}): ColumnField => {
+export const generateColumnField = (
+ field: { name?: string; table?: string; schema?: string; format?: string } = {}
+): ColumnField => {
const { name, table, schema, format } = field
return {
id: uuidv4(),
@@ -173,7 +175,7 @@ export const generateUpdateColumnPayload = (
}
export const validateFields = (field: ColumnField) => {
- const errors = {} as Dictionary<any>
+ const errors = {} as Dictionary<string>
if (field.name.length === 0) {
errors['name'] = `Please assign a name for your column`
toast.error(errors['name'])
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.constants.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.constants.ts
index 17f218bce48..be40005ae41 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.constants.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.constants.ts
@@ -1,9 +1,29 @@
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
+import { FOREIGN_KEY_CASCADE_ACTION } from '@supabase/pg-meta'
export const FOREIGN_KEY_CASCADE_OPTIONS = [
- { key: 'no-action', label: 'No action', value: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION },
- { key: 'cascade', label: 'Cascade', value: FOREIGN_KEY_CASCADE_ACTION.CASCADE },
- { key: 'restrict', label: 'Restrict', value: FOREIGN_KEY_CASCADE_ACTION.RESTRICT },
- { key: 'set-default', label: 'Set default', value: FOREIGN_KEY_CASCADE_ACTION.SET_DEFAULT },
- { key: 'set-null', label: 'Set NULL', value: FOREIGN_KEY_CASCADE_ACTION.SET_NULL },
+ {
+ key: 'no-action',
+ label: 'No action',
+ value: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
+ },
+ {
+ key: 'cascade',
+ label: 'Cascade',
+ value: FOREIGN_KEY_CASCADE_ACTION.CASCADE,
+ },
+ {
+ key: 'restrict',
+ label: 'Restrict',
+ value: FOREIGN_KEY_CASCADE_ACTION.RESTRICT,
+ },
+ {
+ key: 'set-default',
+ label: 'Set default',
+ value: FOREIGN_KEY_CASCADE_ACTION.SET_DEFAULT,
+ },
+ {
+ key: 'set-null',
+ label: 'Set NULL',
+ value: FOREIGN_KEY_CASCADE_ACTION.SET_NULL,
+ },
]
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
index 11c008d3839..54649a19879 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
@@ -1,26 +1,26 @@
+import { FOREIGN_KEY_CASCADE_ACTION } from '@supabase/pg-meta'
import type { PostgresTable } from '@supabase/postgres-meta'
+import { DocsButton } from 'components/ui/DocsButton'
+import InformationBox from 'components/ui/InformationBox'
+import { useSchemasQuery } from 'data/database/schemas-query'
+import { useTableQuery } from 'data/tables/table-retrieve-query'
+import { useTablesQuery } from 'data/tables/tables-query'
+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import { DOCS_URL } from 'lib/constants'
+import { uuidv4 } from 'lib/helpers'
import { sortBy } from 'lodash'
import { ArrowRight, Database, HelpCircle, Loader2, Table, X } from 'lucide-react'
import { Fragment, useEffect, useState } from 'react'
import {
+ Alert_Shadcn_,
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
- Alert_Shadcn_,
Button,
Listbox,
SidePanel,
} from 'ui'
-import { DocsButton } from 'components/ui/DocsButton'
-import InformationBox from 'components/ui/InformationBox'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
-import { useSchemasQuery } from 'data/database/schemas-query'
-import { useTableQuery } from 'data/tables/table-retrieve-query'
-import { useTablesQuery } from 'data/tables/tables-query'
-import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { DOCS_URL } from 'lib/constants'
-import { uuidv4 } from 'lib/helpers'
import { ActionBar } from '../ActionBar'
import { NUMERICAL_TYPES, TEXT_TYPES } from '../SidePanelEditor.constants'
import type { ColumnField } from '../SidePanelEditor.types'
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils.tsx
index fcb10df4f84..787eccb9aff 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils.tsx
@@ -1,7 +1,8 @@
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
+import { FOREIGN_KEY_CASCADE_ACTION } from '@supabase/pg-meta'
import type { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import { HelpCircle } from 'lucide-react'
import { Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+
import { getForeignKeyCascadeAction } from '../ColumnEditor/ColumnEditor.utils'
import type { ForeignKey } from './ForeignKeySelector.types'
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts
index 1c09396321b..7cb3ff80328 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,8 +1,9 @@
+import { FOREIGN_KEY_CASCADE_ACTION } from '@supabase/pg-meta'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import type { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'
import type { ColumnField } from './SidePanelEditor.types'
+import { createTable } from './SidePanelEditor.utils'
// Define mock functions at module level
const mockExecuteSql = vi.fn()
@@ -51,9 +52,6 @@ vi.mock('components/ui/SparkBar', () => ({
default: () => null,
}))
-// Import after mocks are set up
-import { createTable } from './SidePanelEditor.utils'
-
// Helper to create a column field with defaults
const createColumnField = (overrides: Partial<ColumnField> = {}): ColumnField => ({
id: 'col-1',
@@ -306,7 +304,7 @@ describe('createTable', () => {
const sqlCall = mockExecuteSql.mock.calls[0][0]
expect(sqlCall.sql).toContain('ADD FOREIGN KEY')
expect(sqlCall.sql).toContain('REFERENCES')
- expect(sqlCall.sql).toContain('"users"')
+ expect(sqlCall.sql).toContain('users')
expect(sqlCall.sql).toContain('ON DELETE CASCADE')
})
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index a828d212864..e838e486e24 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -1,5 +1,16 @@
import * as Sentry from '@sentry/nextjs'
-import pgMeta from '@supabase/pg-meta'
+import pgMeta, {
+ getAddForeignKeySQL,
+ getAddPrimaryKeySQL,
+ getDropConstraintSQL,
+ getDuplicateIdentitySequenceSQL,
+ getDuplicateRowsSQL,
+ getDuplicateTableSQL,
+ getEnableRLSSQL,
+ getRemoveForeignKeySQL,
+ getUpdateIdentitySequenceSQL,
+ type ForeignKey,
+} from '@supabase/pg-meta'
import { Query } from '@supabase/pg-meta/src/query'
import type { PostgresPrimaryKey } from '@supabase/postgres-meta'
import type { SupaRow } from 'components/grid/types'
@@ -10,7 +21,6 @@ import { deleteDatabaseColumn } from 'data/database-columns/database-column-dele
import { updateDatabaseColumn } from 'data/database-columns/database-column-update-mutation'
import { createDatabasePolicy } from 'data/database-policies/database-policy-create-mutation'
import type { Constraint } from 'data/database/constraints-query'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import { databaseKeys } from 'data/database/keys'
import { entityTypeKeys } from 'data/entity-types/keys'
@@ -24,10 +34,10 @@ import { tableRowKeys } from 'data/table-rows/keys'
import { executeWithRetry } from 'data/table-rows/table-rows-query'
import { tableKeys } from 'data/tables/keys'
import {
- RetrieveTableResult,
- RetrievedTableColumn,
getTable,
getTableQuery,
+ RetrievedTableColumn,
+ RetrieveTableResult,
} from 'data/tables/table-retrieve-query'
import {
UpdateTableBody,
@@ -45,7 +55,6 @@ import {
generateCreateColumnPayload,
generateUpdateColumnPayload,
} from './ColumnEditor/ColumnEditor.utils'
-import type { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'
import type { ColumnField, CreateColumnPayload, UpdateColumnPayload } from './SidePanelEditor.types'
import { checkIfRelationChanged } from './TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils'
import type { ImportContent } from './TableEditor/TableEditor.types'
@@ -81,23 +90,6 @@ export function getRowFromSidePanel(
}
}
-/**
- * The functions below are basically just queries but may be supported directly
- * from the pg-meta library in the future
- */
-const getAddPrimaryKeySQL = ({
- schema,
- table,
- columns,
-}: {
- schema: string
- table: string
- columns: string[]
-}) => {
- const primaryKeyColumns = columns.map((col) => `"${col}"`).join(', ')
- return `ALTER TABLE "${schema}"."${table}" ADD PRIMARY KEY (${primaryKeyColumns})`
-}
-
const addPrimaryKey = async (
projectRef: string,
connectionString: string | undefined | null,
@@ -121,7 +113,7 @@ const dropConstraint = async (
table: string,
name: string
) => {
- const query = `ALTER TABLE "${schema}"."${table}" DROP CONSTRAINT "${name}"`
+ const query = getDropConstraintSQL({ schema, table, name })
return await executeSql({
projectRef: projectRef,
connectionString: connectionString,
@@ -130,49 +122,6 @@ const dropConstraint = async (
})
}
-const getAddForeignKeySQL = ({
- table,
- foreignKeys,
-}: {
- table: { schema: string; name: string }
- foreignKeys: ForeignKey[]
-}) => {
- const getOnDeleteSql = (action: string) =>
- action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
- ? 'ON DELETE CASCADE'
- : action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
- ? 'ON DELETE RESTRICT'
- : action === FOREIGN_KEY_CASCADE_ACTION.SET_DEFAULT
- ? 'ON DELETE SET DEFAULT'
- : action === FOREIGN_KEY_CASCADE_ACTION.SET_NULL
- ? 'ON DELETE SET NULL'
- : ''
- const getOnUpdateSql = (action: string) =>
- action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
- ? 'ON UPDATE CASCADE'
- : action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
- ? 'ON UPDATE RESTRICT'
- : ''
- return (
- foreignKeys
- .map((relation) => {
- const { deletionAction, updateAction } = relation
- const onDeleteSql = getOnDeleteSql(deletionAction)
- const onUpdateSql = getOnUpdateSql(updateAction)
- return `
- ALTER TABLE "${table.schema}"."${table.name}"
- ADD FOREIGN KEY (${relation.columns.map((column) => `"${column.source}"`).join(',')})
- REFERENCES "${relation.schema}"."${relation.table}" (${relation.columns.map((column) => `"${column.target}"`).join(',')})
- ${onUpdateSql}
- ${onDeleteSql}
- `
- .replace(/\s+/g, ' ')
- .trim()
- })
- .join(';') + ';'
- )
-}
-
const addForeignKey = async ({
projectRef,
connectionString,
@@ -193,27 +142,6 @@ const addForeignKey = async ({
})
}
-const getRemoveForeignKeySQL = ({
- table,
- foreignKeys,
-}: {
- table: { schema: string; name: string }
- foreignKeys: ForeignKey[]
-}) => {
- return (
- foreignKeys
- .map((relation) =>
- `
-ALTER TABLE IF EXISTS "${table.schema}"."${table.name}"
-DROP CONSTRAINT IF EXISTS "${relation.name}"
-`
- .replace(/\s+/g, ' ')
- .trim()
- )
- .join(';') + ';'
- )
-}
-
const removeForeignKey = async ({
projectRef,
connectionString,
@@ -259,22 +187,6 @@ const updateForeignKey = async ({
})
}
-const getUpdateIdentitySequenceSQL = ({
- schema,
- table,
- column,
-}: {
- schema: string
- table: string
- column: string
-}) => {
- return `SELECT setval('"${schema}"."${table}_${column}_seq"', (SELECT COALESCE(MAX("${column}"), 1) FROM "${schema}"."${table}"))`
-}
-
-const getEnableRLSSQL = ({ schema, table }: { schema: string; table: string }) => {
- return `ALTER TABLE "${schema}"."${table}" ENABLE ROW LEVEL SECURITY`
-}
-
/**
* The methods below involve several contexts due to the UI flow of the
* dashboard and hence do not sit within their own stores
@@ -350,7 +262,7 @@ export const createColumn = async ({
toast.success(`Successfully created column "${formattedPayload.name}"`, { id: toastId })
}
return { error: undefined }
- } catch (error: any) {
+ } catch (error) {
toast.error(`An error occurred while creating the column "${payload.name}"`, { id: toastId })
return { error }
}
@@ -458,12 +370,12 @@ export const duplicateTable = async (
await executeSql({
projectRef,
connectionString,
- sql: [
- `CREATE TABLE "${sourceTableSchema}"."${duplicatedTableName}" (LIKE "${sourceTableSchema}"."${sourceTableName}" INCLUDING ALL);`,
- payload.comment != undefined
- ? `comment on table "${sourceTableSchema}"."${duplicatedTableName}" is '${payload.comment}';`
- : '',
- ].join('\n'),
+ sql: getDuplicateTableSQL({
+ sourceTableName,
+ sourceTableSchema,
+ duplicatedTableName,
+ comment: payload.comment,
+ }),
})
await queryClient.invalidateQueries({ queryKey: tableKeys.list(projectRef, sourceTableSchema) })
@@ -482,7 +394,11 @@ export const duplicateTable = async (
await executeSql({
projectRef,
connectionString,
- sql: `INSERT INTO "${sourceTableSchema}"."${duplicatedTableName}" SELECT * FROM "${sourceTableSchema}"."${sourceTableName}";`,
+ sql: getDuplicateRowsSQL({
+ sourceTableName,
+ sourceTableSchema,
+ duplicatedTableName,
+ }),
})
// Insert into does not copy over auto increment sequences, so we manually do it next if any
@@ -492,7 +408,12 @@ export const duplicateTable = async (
await executeSql({
projectRef,
connectionString,
- sql: `SELECT setval('"${sourceTableSchema}"."${duplicatedTableName}_${column.name}_seq"', (SELECT MAX("${column.name}") FROM "${sourceTableSchema}"."${sourceTableName}"));`,
+ sql: getDuplicateIdentitySequenceSQL({
+ sourceTableName,
+ sourceTableSchema,
+ duplicatedTableName,
+ columnName: column.name,
+ }),
})
})
}
@@ -560,7 +481,10 @@ export const createTable = async ({
// 2. Enable RLS if configured
if (isRLSEnabled) {
- const enableRLSSQL = getEnableRLSSQL({ schema: payload.schema, table: payload.name })
+ const enableRLSSQL = getEnableRLSSQL({
+ schema: payload.schema,
+ table: payload.name,
+ })
sqlStatements.push(enableRLSSQL)
}
diff --git a/packages/pg-meta/src/index.ts b/packages/pg-meta/src/index.ts
index 8a5e8a29d7b..c5692818611 100644
--- a/packages/pg-meta/src/index.ts
+++ b/packages/pg-meta/src/index.ts
@@ -19,16 +19,20 @@ import views from './pg-meta-views'
import * as query from './query/index'
// Studio SQL queries
-export { getUserSQL } from './sql/studio/auth/get-user'
-export { getIndexStatusesSQL, USER_SEARCH_INDEXES } from './sql/studio/auth/get-index-statuses'
-export { getIndexWorkerStatusSQL } from './sql/studio/auth/get-index-worker-status'
-export { type OptimizedSearchColumns } from './sql/studio/auth/get-users-types'
-export { getPaginatedUsersSQL, type UsersCursor } from './sql/studio/auth/get-users-paginated'
-export { getUsersCountSQL } from './sql/studio/auth/get-users-count'
+export {
+ getUserSQL,
+ getIndexStatusesSQL,
+ getUsersCountSQL,
+ getPaginatedUsersSQL,
+ getIndexWorkerStatusSQL,
+ USER_SEARCH_INDEXES,
+ type OptimizedSearchColumns,
+ type UsersCursor,
+} from './sql/studio/auth'
export {
getLargestSizeLimitBucketsSqlUnoptimized,
LARGEST_SIZE_LIMIT_BUCKETS_COUNT,
-} from './sql/studio/storage/get-largest-size-limit-buckets'
+} from './sql/studio/storage'
export {
getExposedTablesSql,
getExposedTableCountsSql,
@@ -39,16 +43,30 @@ export {
buildDefaultPrivilegesSql,
getDefaultPrivilegesStateSql,
} from './sql/studio/privileges'
-export { getIndexesSQL } from './sql/studio/database/indexes'
-export { getDatabaseExtensionDefaultSchemaSQL } from './sql/studio/database/extensions'
export {
+ getIndexesSQL,
+ getDatabaseExtensionDefaultSchemaSQL,
getCronJobsMinimalSql,
getCronJobsSql,
getJobRunDetailsPageCountSql,
getDeleteOldCronJobRunDetailsByCtidSql,
getScheduleDeleteCronJobRunDetailsSql,
-} from './sql/studio/database/cron-jobs'
-export { getTableRowsCountSql } from './sql/studio/database/rows'
+ getTableRowsCountSql,
+} from './sql/studio/database'
+export {
+ type ForeignKey,
+ FOREIGN_KEY_CASCADE_ACTION,
+ getAddPrimaryKeySQL,
+ getDropConstraintSQL,
+ getAddForeignKeySQL,
+ getRemoveForeignKeySQL,
+ getUpdateIdentitySequenceSQL,
+ getDuplicateIdentitySequenceSQL,
+ getDuplicateTableSQL,
+ getDuplicateRowsSQL,
+ getEnableRLSSQL,
+} from './sql/studio/table-editor'
+
export { getLiveTupleEstimate } from './sql/studio/get-live-tuple-estimate'
export default {
diff --git a/packages/pg-meta/src/sql/studio/auth/index.ts b/packages/pg-meta/src/sql/studio/auth/index.ts
new file mode 100644
index 00000000000..040b51b5d54
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/auth/index.ts
@@ -0,0 +1,7 @@
+export * from './get-index-statuses'
+export * from './get-index-worker-status'
+export * from './get-user'
+export * from './get-users-common'
+export * from './get-users-count'
+export * from './get-users-paginated'
+export * from './get-users-types'
diff --git a/packages/pg-meta/src/sql/studio/database/index.ts b/packages/pg-meta/src/sql/studio/database/index.ts
new file mode 100644
index 00000000000..ef3bfe8ad23
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/database/index.ts
@@ -0,0 +1,4 @@
+export * from './cron-jobs'
+export * from './extensions'
+export * from './indexes'
+export * from './rows'
diff --git a/packages/pg-meta/src/sql/studio/storage/index.ts b/packages/pg-meta/src/sql/studio/storage/index.ts
new file mode 100644
index 00000000000..3b6feef9a28
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/storage/index.ts
@@ -0,0 +1 @@
+export * from './get-largest-size-limit-buckets'
diff --git a/packages/pg-meta/src/sql/studio/table-editor/constraints.ts b/packages/pg-meta/src/sql/studio/table-editor/constraints.ts
new file mode 100644
index 00000000000..82354ee2474
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/table-editor/constraints.ts
@@ -0,0 +1,11 @@
+import { ident } from '../../../pg-format'
+
+export const getDropConstraintSQL = ({
+ schema,
+ table,
+ name,
+}: {
+ schema: string
+ table: string
+ name: string
+}) => `ALTER TABLE ${ident(schema)}.${ident(table)} DROP CONSTRAINT ${ident(name)}`
diff --git a/packages/pg-meta/src/sql/studio/table-editor/foreign-keys.ts b/packages/pg-meta/src/sql/studio/table-editor/foreign-keys.ts
new file mode 100644
index 00000000000..617d0cde241
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/table-editor/foreign-keys.ts
@@ -0,0 +1,86 @@
+import { ident } from '../../../pg-format'
+
+export const getAddForeignKeySQL = ({
+ table,
+ foreignKeys,
+}: {
+ table: { schema: string; name: string }
+ foreignKeys: ForeignKey[]
+}) => {
+ const getOnDeleteSql = (action: string) =>
+ action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
+ ? 'ON DELETE CASCADE'
+ : action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
+ ? 'ON DELETE RESTRICT'
+ : action === FOREIGN_KEY_CASCADE_ACTION.SET_DEFAULT
+ ? 'ON DELETE SET DEFAULT'
+ : action === FOREIGN_KEY_CASCADE_ACTION.SET_NULL
+ ? 'ON DELETE SET NULL'
+ : ''
+ const getOnUpdateSql = (action: string) =>
+ action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
+ ? 'ON UPDATE CASCADE'
+ : action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
+ ? 'ON UPDATE RESTRICT'
+ : ''
+ return (
+ foreignKeys
+ .map((relation) => {
+ const { deletionAction, updateAction } = relation
+ const onDeleteSql = getOnDeleteSql(deletionAction)
+ const onUpdateSql = getOnUpdateSql(updateAction)
+ return `
+ ALTER TABLE ${ident(table.schema)}.${ident(table.name)}
+ ADD FOREIGN KEY (${relation.columns.map((column) => ident(column.source)).join(', ')})
+ REFERENCES ${ident(relation.schema)}.${ident(relation.table)} (${relation.columns.map((column) => ident(column.target)).join(', ')})
+ ${onUpdateSql}
+ ${onDeleteSql}
+ `
+ .replace(/\s+/g, ' ')
+ .trim()
+ })
+ .join(';') + ';'
+ )
+}
+
+export const getRemoveForeignKeySQL = ({
+ table,
+ foreignKeys,
+}: {
+ table: { schema: string; name: string }
+ foreignKeys: ForeignKey[]
+}) => {
+ return (
+ foreignKeys
+ .map((relation) =>
+ `
+ALTER TABLE IF EXISTS ${ident(table.schema)}.${ident(table.name)}
+DROP CONSTRAINT IF EXISTS ${ident(relation.name)}
+`
+ .replace(/\s+/g, ' ')
+ .trim()
+ )
+ .join(';') + ';'
+ )
+}
+
+export interface ForeignKey {
+ id?: number | string
+ name?: string
+ tableId?: number
+
+ schema: string
+ table: string
+ columns: { source: string; sourceType?: string; target: string; targetType?: string }[]
+ deletionAction: string
+ updateAction: string
+ toRemove?: boolean
+}
+
+export enum FOREIGN_KEY_CASCADE_ACTION {
+ NO_ACTION = 'a',
+ RESTRICT = 'r',
+ CASCADE = 'c',
+ SET_NULL = 'n',
+ SET_DEFAULT = 'd',
+}
diff --git a/packages/pg-meta/src/sql/studio/table-editor/identity.ts b/packages/pg-meta/src/sql/studio/table-editor/identity.ts
new file mode 100644
index 00000000000..c25c97efe91
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/table-editor/identity.ts
@@ -0,0 +1,27 @@
+import { ident } from '../../../pg-format'
+
+export const getUpdateIdentitySequenceSQL = ({
+ schema,
+ table,
+ column,
+}: {
+ schema: string
+ table: string
+ column: string
+}) => {
+ return `SELECT setval('${ident(schema)}.${ident(`${table}_${column}_seq`)}', (SELECT COALESCE(MAX(${ident(column)}), 1) FROM ${ident(schema)}.${ident(table)}))`
+}
+
+export const getDuplicateIdentitySequenceSQL = ({
+ columnName,
+ duplicatedTableName,
+ sourceTableName,
+ sourceTableSchema,
+}: {
+ columnName: string
+ duplicatedTableName: string
+ sourceTableName: string
+ sourceTableSchema: string
+}) => {
+ return `SELECT setval('${ident(sourceTableSchema)}.${ident(`${duplicatedTableName}_${columnName}_seq`)}', (SELECT COALESCE(MAX(${ident(columnName)}), 1) FROM ${ident(sourceTableSchema)}.${ident(sourceTableName)}));`
+}
diff --git a/packages/pg-meta/src/sql/studio/table-editor/index.ts b/packages/pg-meta/src/sql/studio/table-editor/index.ts
new file mode 100644
index 00000000000..25e6f5d6c98
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/table-editor/index.ts
@@ -0,0 +1,6 @@
+export * from './constraints'
+export * from './identity'
+export * from './foreign-keys'
+export * from './primary-keys'
+export * from './rls'
+export * from './table'
diff --git a/packages/pg-meta/src/sql/studio/table-editor/primary-keys.ts b/packages/pg-meta/src/sql/studio/table-editor/primary-keys.ts
new file mode 100644
index 00000000000..53fc0185d05
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/table-editor/primary-keys.ts
@@ -0,0 +1,18 @@
+import { ident } from '../../../pg-format'
+
+/**
+ * The functions below are basically just queries but may be supported directly
+ * from the pg-meta library in the future
+ */
+export const getAddPrimaryKeySQL = ({
+ schema,
+ table,
+ columns,
+}: {
+ schema: string
+ table: string
+ columns: string[]
+}) => {
+ const primaryKeyColumns = columns.map((col) => ident(col)).join(', ')
+ return `ALTER TABLE ${ident(schema)}.${ident(table)} ADD PRIMARY KEY (${primaryKeyColumns})`
+}
diff --git a/packages/pg-meta/src/sql/studio/table-editor/rls.ts b/packages/pg-meta/src/sql/studio/table-editor/rls.ts
new file mode 100644
index 00000000000..1d142971025
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/table-editor/rls.ts
@@ -0,0 +1,5 @@
+import { ident } from '../../../pg-format'
+
+export const getEnableRLSSQL = ({ schema, table }: { schema: string; table: string }) => {
+ return `ALTER TABLE ${ident(schema)}.${ident(table)} ENABLE ROW LEVEL SECURITY`
+}
diff --git a/packages/pg-meta/src/sql/studio/table-editor/table.ts b/packages/pg-meta/src/sql/studio/table-editor/table.ts
new file mode 100644
index 00000000000..87f4240f681
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/table-editor/table.ts
@@ -0,0 +1,32 @@
+import { ident, literal } from '../../../pg-format'
+
+export const getDuplicateTableSQL = ({
+ comment,
+ duplicatedTableName,
+ sourceTableName,
+ sourceTableSchema,
+}: {
+ comment?: string | null
+ duplicatedTableName: string
+ sourceTableName: string
+ sourceTableSchema: string
+}) => {
+ return [
+ `CREATE TABLE ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} (LIKE ${ident(sourceTableSchema)}.${ident(sourceTableName)} INCLUDING ALL);`,
+ comment != undefined
+ ? `comment on table ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} is ${literal(comment)};`
+ : '',
+ ].join('\n')
+}
+
+export const getDuplicateRowsSQL = ({
+ duplicatedTableName,
+ sourceTableName,
+ sourceTableSchema,
+}: {
+ duplicatedTableName: string
+ sourceTableName: string
+ sourceTableSchema: string
+}) => {
+ return `INSERT INTO ${ident(sourceTableSchema)}.${ident(duplicatedTableName)} SELECT * FROM ${ident(sourceTableSchema)}.${ident(sourceTableName)};`
+}