Skip to content

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

feat: table definitions

Alaister Young5f89be329b62
diff --git a/package-lock.json b/package-lock.json
index e543f27be8b..32b171c1a65 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -15780,6 +15780,11 @@
"node": ">=8"
}
},
+ "node_modules/discontinuous-range": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz",
+ "integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ=="
+ },
"node_modules/dlv": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
@@ -25792,6 +25797,11 @@
"integrity": "sha512-uhXpYwHFeiTbY9KSgPPRoo1nt8OxNVdMVoTBYHfSEKeRkIkwGpO+gERmhuhBtzfaeOyTkykSrm2+noJBgqt3Hg==",
"peer": true
},
+ "node_modules/moo": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz",
+ "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q=="
+ },
"node_modules/moo-color": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/moo-color/-/moo-color-1.0.3.tgz",
@@ -25942,6 +25952,32 @@
"integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==",
"dev": true
},
+ "node_modules/nearley": {
+ "version": "2.20.1",
+ "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz",
+ "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==",
+ "dependencies": {
+ "commander": "^2.19.0",
+ "moo": "^0.5.0",
+ "railroad-diagrams": "^1.0.0",
+ "randexp": "0.4.6"
+ },
+ "bin": {
+ "nearley-railroad": "bin/nearley-railroad.js",
+ "nearley-test": "bin/nearley-test.js",
+ "nearley-unparse": "bin/nearley-unparse.js",
+ "nearleyc": "bin/nearleyc.js"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://nearley.js.org/#give-to-nearley"
+ }
+ },
+ "node_modules/nearley/node_modules/commander": {
+ "version": "2.20.3",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="
+ },
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@@ -27686,6 +27722,14 @@
"is-reference": "^3.0.0"
}
},
+ "node_modules/pg-minify": {
+ "version": "1.6.3",
+ "resolved": "https://registry.npmjs.org/pg-minify/-/pg-minify-1.6.3.tgz",
+ "integrity": "sha512-NoSsPqXxbkD8RIe+peQCqiea4QzXgosdTKY8p7PsbbGsh2F8TifDj/vJxfuR8qJwNYrijdSs7uf0tAe6WOyCsQ==",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/phenomenon": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/phenomenon/-/phenomenon-1.6.0.tgz",
@@ -30053,6 +30097,11 @@
"resolved": "https://registry.npmjs.org/raf-schd/-/raf-schd-4.0.3.tgz",
"integrity": "sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ=="
},
+ "node_modules/railroad-diagrams": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz",
+ "integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A=="
+ },
"node_modules/ramda": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/ramda/-/ramda-0.28.0.tgz",
@@ -30063,6 +30112,18 @@
"url": "https://opencollective.com/ramda"
}
},
+ "node_modules/randexp": {
+ "version": "0.4.6",
+ "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz",
+ "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==",
+ "dependencies": {
+ "discontinuous-range": "1.0.0",
+ "ret": "~0.1.10"
+ },
+ "engines": {
+ "node": ">=0.12"
+ }
+ },
"node_modules/randomatic": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.1.1.tgz",
@@ -33785,6 +33846,18 @@
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="
},
+ "node_modules/sql-formatter": {
+ "version": "12.2.0",
+ "resolved": "https://registry.npmjs.org/sql-formatter/-/sql-formatter-12.2.0.tgz",
+ "integrity": "sha512-wNsPUdOD6nnN9RUgHlNprQtm+iLW5LTOy/T0/2DDr2UeWSP8mvlQHrx6TY+IG1nfu5Kipq9GaOtS9SVq8s0Vig==",
+ "dependencies": {
+ "argparse": "^2.0.1",
+ "nearley": "^2.20.1"
+ },
+ "bin": {
+ "sql-formatter": "bin/sql-formatter-cli.cjs"
+ }
+ },
"node_modules/sql-parser-cst": {
"version": "0.12.1",
"resolved": "https://registry.npmjs.org/sql-parser-cst/-/sql-parser-cst-0.12.1.tgz",
@@ -38187,6 +38260,7 @@
"papaparse": "^5.3.1",
"parse-numeric-range": "^1.3.0",
"path-to-regexp": "^6.2.0",
+ "pg-minify": "^1.6.3",
"prism-react-renderer": "^1.2.1",
"react": "^17.0.2",
"react-beautiful-dnd": "^13.1.0",
@@ -38210,6 +38284,7 @@
"scheduler": "^0.20.2",
"semver": "^6.3.0",
"shared-data": "*",
+ "sql-formatter": "^12.2.0",
"sqlstring": "^2.3.2",
"ui": "*",
"uniforms-bootstrap4": "^3.6.2",
@@ -50350,6 +50425,11 @@
"path-type": "^4.0.0"
}
},
+ "discontinuous-range": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz",
+ "integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ=="
+ },
"dlv": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
@@ -58270,6 +58350,11 @@
"integrity": "sha512-uhXpYwHFeiTbY9KSgPPRoo1nt8OxNVdMVoTBYHfSEKeRkIkwGpO+gERmhuhBtzfaeOyTkykSrm2+noJBgqt3Hg==",
"peer": true
},
+ "moo": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz",
+ "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q=="
+ },
"moo-color": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/moo-color/-/moo-color-1.0.3.tgz",
@@ -58396,6 +58481,24 @@
"integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==",
"dev": true
},
+ "nearley": {
+ "version": "2.20.1",
+ "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz",
+ "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==",
+ "requires": {
+ "commander": "^2.19.0",
+ "moo": "^0.5.0",
+ "railroad-diagrams": "^1.0.0",
+ "randexp": "0.4.6"
+ },
+ "dependencies": {
+ "commander": {
+ "version": "2.20.3",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="
+ }
+ }
+ },
"negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@@ -59710,6 +59813,11 @@
"is-reference": "^3.0.0"
}
},
+ "pg-minify": {
+ "version": "1.6.3",
+ "resolved": "https://registry.npmjs.org/pg-minify/-/pg-minify-1.6.3.tgz",
+ "integrity": "sha512-NoSsPqXxbkD8RIe+peQCqiea4QzXgosdTKY8p7PsbbGsh2F8TifDj/vJxfuR8qJwNYrijdSs7uf0tAe6WOyCsQ=="
+ },
"phenomenon": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/phenomenon/-/phenomenon-1.6.0.tgz",
@@ -61472,12 +61580,26 @@
"resolved": "https://registry.npmjs.org/raf-schd/-/raf-schd-4.0.3.tgz",
"integrity": "sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ=="
},
+ "railroad-diagrams": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz",
+ "integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A=="
+ },
"ramda": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/ramda/-/ramda-0.28.0.tgz",
"integrity": "sha512-9QnLuG/kPVgWvMQ4aODhsBUFKOUmnbUnsSXACv+NCQZcHbeb+v8Lodp8OVxtRULN1/xOyYLLaL6npE6dMq5QTA==",
"dev": true
},
+ "randexp": {
+ "version": "0.4.6",
+ "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz",
+ "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==",
+ "requires": {
+ "discontinuous-range": "1.0.0",
+ "ret": "~0.1.10"
+ }
+ },
"randomatic": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.1.1.tgz",
@@ -64209,6 +64331,15 @@
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="
},
+ "sql-formatter": {
+ "version": "12.2.0",
+ "resolved": "https://registry.npmjs.org/sql-formatter/-/sql-formatter-12.2.0.tgz",
+ "integrity": "sha512-wNsPUdOD6nnN9RUgHlNprQtm+iLW5LTOy/T0/2DDr2UeWSP8mvlQHrx6TY+IG1nfu5Kipq9GaOtS9SVq8s0Vig==",
+ "requires": {
+ "argparse": "^2.0.1",
+ "nearley": "^2.20.1"
+ }
+ },
"sql-parser-cst": {
"version": "0.12.1",
"resolved": "https://registry.npmjs.org/sql-parser-cst/-/sql-parser-cst-0.12.1.tgz",
@@ -64693,6 +64824,7 @@
"papaparse": "^5.3.1",
"parse-numeric-range": "^1.3.0",
"path-to-regexp": "^6.2.0",
+ "pg-minify": "*",
"postcss": "^8.4.6",
"prettier": "^2.7.1",
"prism-react-renderer": "^1.2.1",
@@ -64718,6 +64850,7 @@
"scheduler": "^0.20.2",
"semver": "^6.3.0",
"shared-data": "*",
+ "sql-formatter": "*",
"sqlstring": "^2.3.2",
"storybook-dark-mode": "^1.0.4",
"tailwindcss": "^3.0.15",
diff --git a/studio/components/interfaces/TableGridEditor/ViewDefinition.tsx b/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
similarity index 56%
rename from studio/components/interfaces/TableGridEditor/ViewDefinition.tsx
rename to studio/components/interfaces/TableGridEditor/TableDefinition.tsx
index 6df9807aa53..75ad83c5e24 100644
--- a/studio/components/interfaces/TableGridEditor/ViewDefinition.tsx
+++ b/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
@@ -1,28 +1,66 @@
-import { useRef } from 'react'
import Editor from '@monaco-editor/react'
-import { timeout } from 'lib/helpers'
-import { useStore } from 'hooks'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import { useViewDefinitionQuery } from 'data/database/view-definition-query'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+import { useTableDefinitionQuery } from 'data/database/table-definition-query'
+import { useViewDefinitionQuery } from 'data/database/view-definition-query'
+import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
+import { useStore } from 'hooks'
+import useEntityType from 'hooks/misc/useEntityType'
+import { timeout } from 'lib/helpers'
+import { observer } from 'mobx-react-lite'
+import { useMemo, useRef } from 'react'
+import { format } from 'sql-formatter'
export interface ViewDefinitionProps {
- name: string
+ id?: number
}
-const ViewDefinition = ({ name }: ViewDefinitionProps) => {
+const ViewDefinition = ({ id }: ViewDefinitionProps) => {
const editorRef = useRef(null)
const monacoRef = useRef(null)
const { ui } = useStore()
const { isDarkTheme } = ui
+ const entityType = useEntityType(id)
+
const { project } = useProjectContext()
- const { data: definition, isLoading } = useViewDefinitionQuery({
- name,
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- })
+ const viewResult = useViewDefinitionQuery(
+ {
+ name: entityType?.name,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ {
+ enabled: entityType?.type === ENTITY_TYPE.VIEW,
+ }
+ )
+
+ const tableResult = useTableDefinitionQuery(
+ {
+ schema: entityType?.schema,
+ name: entityType?.name,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ {
+ enabled: entityType?.type === ENTITY_TYPE.TABLE,
+ }
+ )
+
+ const { data: definition, isLoading } =
+ entityType?.type === ENTITY_TYPE.VIEW ? viewResult : tableResult
+
+ const formattedDefinition = useMemo(
+ () =>
+ definition
+ ? format(definition, {
+ language: 'postgresql',
+ keywordCase: 'lower',
+ })
+ : undefined,
+ [definition]
+ )
const handleEditorOnMount = async (editor: any, monaco: any) => {
editorRef.current = editor
@@ -59,7 +97,7 @@ const ViewDefinition = ({ name }: ViewDefinitionProps) => {
theme={isDarkTheme ? 'vs-dark' : 'vs'}
onMount={handleEditorOnMount}
defaultLanguage="pgsql"
- defaultValue={definition}
+ defaultValue={formattedDefinition}
path={''}
options={{
domReadOnly: true,
@@ -75,4 +113,4 @@ const ViewDefinition = ({ name }: ViewDefinitionProps) => {
)
}
-export default ViewDefinition
+export default observer(ViewDefinition)
diff --git a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index 10cf2915fdd..ffa4a8f5808 100644
--- a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -7,7 +7,8 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { QueryKey, useQueryClient } from '@tanstack/react-query'
import { SchemaView } from 'types'
-import { checkPermissions, useFlag, useStore } from 'hooks'
+import { checkPermissions, useFlag, useStore, useUrlState } from 'hooks'
+import useEntityType from 'hooks/misc/useEntityType'
import { useParams } from 'common/hooks'
import GridHeaderActions from './GridHeaderActions'
import NotFoundState from './NotFoundState'
@@ -24,6 +25,7 @@ import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
import { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
import { JsonEditValue } from './SidePanelEditor/RowEditor/RowEditor.types'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
import {
ForeignKeyConstraint,
useForeignKeyConstraintsQuery,
@@ -31,7 +33,7 @@ import {
import { FOREIGN_KEY_DELETION_ACTION } from 'data/database/database-query-constants'
import { ForeignRowSelectorProps } from './SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector'
import TwoOptionToggle from 'components/ui/TwoOptionToggle'
-import ViewDefinition from './ViewDefinition'
+import TableDefinition from './TableDefinition'
import APIDocumentationPanel from './APIDocumentationPanel'
export interface TableGridEditorProps {
@@ -102,8 +104,14 @@ const TableGridEditor = ({
const [encryptedColumns, setEncryptedColumns] = useState([])
const [apiPreviewPanelOpen, setApiPreviewPanelOpen] = useState(false)
- // When rendering a view in the grid
- const [selectedView, setSelectedView] = useState<'data' | 'definition'>('data')
+ const [{ view: selectedView = 'data' }, setUrlState] = useUrlState()
+ const setSelectedView = (view: string) => {
+ if (view === 'data') {
+ setUrlState({ view: undefined })
+ } else {
+ setUrlState({ view })
+ }
+ }
const isReadOnly =
!checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables') &&
@@ -189,6 +197,8 @@ const TableGridEditor = ({
}
}, [selectedTable?.id])
+ const entityType = useEntityType(selectedTable?.id)
+
// NOTE: DO NOT PUT HOOKS AFTER THIS LINE
if (isUndefined(selectedTable)) {
return <NotFoundState id={Number(id)} />
@@ -196,11 +206,10 @@ const TableGridEditor = ({
const tableId = selectedTable?.id
- // @ts-ignore
- const schema = meta.schemas.list().find((schema) => schema.name === selectedSchema)
- const isViewSelected = !Object.keys(selectedTable).includes('rls_enabled')
- const isForeignTableSelected = meta.foreignTables.byId(selectedTable.id) !== undefined
- const isLocked = meta.excludedSchemas.includes(schema?.name ?? '')
+ const isViewSelected = entityType?.type === ENTITY_TYPE.VIEW
+ const isTableSelected = entityType?.type === ENTITY_TYPE.TABLE
+ const isForeignTableSelected = entityType?.type === ENTITY_TYPE.FOREIGN_TABLE
+ const isLocked = meta.excludedSchemas.includes(entityType?.schema ?? '')
const canUpdateTables = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
const canEditViaTableEditor = !isViewSelected && !isForeignTableSelected && !isLocked
@@ -337,23 +346,28 @@ const TableGridEditor = ({
table={gridTable}
refreshDocs={refreshDocs}
headerActions={
- isViewSelected ? (
- <div>
- <TwoOptionToggle
- width={75}
- options={['definition', 'data']}
- activeOption={selectedView}
- borderOverride="border-gray-500"
- onClickOption={setSelectedView}
- />
- </div>
- ) : canEditViaTableEditor ? (
- <GridHeaderActions
- table={selectedTable as PostgresTable}
- apiPreviewPanelOpen={apiPreviewPanelOpen}
- setApiPreviewPanelOpen={setApiPreviewPanelOpen}
- refreshDocs={refreshDocs}
- />
+ isTableSelected || isViewSelected || canEditViaTableEditor ? (
+ <>
+ {canEditViaTableEditor && (
+ <GridHeaderActions
+ table={selectedTable as PostgresTable}
+ apiPreviewPanelOpen={apiPreviewPanelOpen}
+ setApiPreviewPanelOpen={setApiPreviewPanelOpen}
+ refreshDocs={refreshDocs}
+ />
+ )}
+ {(isTableSelected || isViewSelected) && (
+ <div>
+ <TwoOptionToggle
+ width={75}
+ options={['definition', 'data']}
+ activeOption={selectedView}
+ borderOverride="border-gray-500"
+ onClickOption={setSelectedView}
+ />
+ </div>
+ )}
+ </>
) : null
}
onAddColumn={onAddColumn}
@@ -366,9 +380,9 @@ const TableGridEditor = ({
onSqlQuery={onSqlQuery}
onExpandJSONEditor={onExpandJSONEditor}
onEditForeignKeyColumnValue={onEditForeignKeyColumnValue}
- showCustomChildren={isViewSelected && selectedView === 'definition'}
+ showCustomChildren={(isViewSelected || isTableSelected) && selectedView === 'definition'}
customHeader={
- isViewSelected && selectedView === 'definition' ? (
+ (isViewSelected || isTableSelected) && selectedView === 'definition' ? (
<div className="flex items-center space-x-2">
<p>
SQL Definition of <code className="text-sm">{selectedTable.name}</code>{' '}
@@ -378,7 +392,7 @@ const TableGridEditor = ({
) : null
}
>
- {isViewSelected && <ViewDefinition name={selectedTable.name} />}
+ {(isViewSelected || isTableSelected) && <TableDefinition id={selectedTable?.id} />}
</SupabaseGrid>
{!isUndefined(selectedSchema) && (
diff --git a/studio/data/database/database-query-constants.ts b/studio/data/database/database-query-constants.ts
index b3879a878a5..1030afd2d68 100644
--- a/studio/data/database/database-query-constants.ts
+++ b/studio/data/database/database-query-constants.ts
@@ -1,3 +1,5 @@
+import minify from 'pg-minify'
+
// https://www.postgresql.org/docs/current/catalog-pg-constraint.html
export enum FOREIGN_KEY_DELETION_ACTION {
@@ -16,3 +18,365 @@ export enum CONSTRAINT_TYPE {
CONSTRAINT_TRIGGER = 't',
EXCLUSION_CONSTRAINT = 'x',
}
+
+// Derived from https://github.com/MichaelDBA/pg_get_tabledef
+
+export const CREATE_PG_GET_TABLEDEF_SQL = minify(
+ /* SQL */ `
+ do $$
+ <<first_block>>
+ DECLARE
+ cnt int;
+ BEGIN
+ SELECT count(*) into cnt
+ FROM pg_catalog.pg_type t LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid))
+ AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)
+ AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND pg_catalog.pg_type_is_visible(t.oid)
+ AND pg_catalog.format_type(t.oid, NULL) in ('tabledefs');
+ IF cnt = 0 THEN
+ CREATE TYPE pg_temp.tabledefs AS ENUM ('FKEYS_INTERNAL', 'FKEYS_EXTERNAL', 'FKEYS_COMMENTED', 'FKEYS_NONE', 'INCLUDE_TRIGGERS', 'NO_TRIGGERS');
+ END IF;
+ end first_block $$;
+
+ create
+ or replace function pg_temp.pg_get_tabledef (
+ in_schema varchar,
+ in_table varchar,
+ _verbose boolean,
+ variadic arr pg_temp.tabledefs[] default '{}'::pg_temp.tabledefs[]
+ ) returns text language plpgsql volatile as $$
+ DECLARE
+ v_table_ddl text;
+ v_table_oid int;
+ v_colrec record;
+ v_constraintrec record;
+ v_indexrec record;
+ v_primary boolean := False;
+ v_constraint_name text;
+ v_fkey_defs text;
+ v_trigger text := '';
+ v_partition_key text := '';
+ v_partbound text;
+ v_parent text;
+ v_persist text;
+ v_temp text := '';
+ v_relopts text;
+ v_tablespace text;
+ v_pgversion int;
+ bPartition boolean;
+ bInheritance boolean;
+ bRelispartition boolean;
+ constraintarr text[] := '{}';
+ constraintelement text;
+ bSkip boolean;
+ bVerbose boolean := False;
+
+ -- assume defaults for ENUMs at the getgo
+ fkcnt int := 0;
+ trigcnt int := 0;
+ fktype pg_temp.tabledefs := 'FKEYS_INTERNAL';
+ trigtype pg_temp.tabledefs := 'NO_TRIGGERS';
+ arglen integer;
+ vargs text;
+ avarg pg_temp.tabledefs;
+
+ -- exception variables
+ v_ret text;
+ v_diag1 text;
+ v_diag2 text;
+ v_diag3 text;
+ v_diag4 text;
+ v_diag5 text;
+ v_diag6 text;
+
+ BEGIN
+ IF _verbose THEN bVerbose = True; END IF;
+
+ arglen := array_length($4, 1);
+ IF arglen IS NULL THEN
+ -- nothing to do, so assume defaults
+ NULL;
+ ELSE
+ -- loop thru args
+ -- IF 'NO_TRIGGERS' = ANY ($4)
+ -- select array_to_string($4, ',', '***') INTO vargs;
+ IF bVerbose THEN RAISE NOTICE 'arguments=%', $4; END IF;
+ FOREACH avarg IN ARRAY $4 LOOP
+ IF bVerbose THEN RAISE INFO 'arg=%', avarg; END IF;
+ IF avarg = 'FKEYS_INTERNAL' OR avarg = 'FKEYS_EXTERNAL' OR avarg = 'FKEYS_COMMENTED' THEN
+ fkcnt = fkcnt + 1;
+ fktype = avarg;
+ ELSEIF avarg = 'INCLUDE_TRIGGERS' OR avarg = 'NO_TRIGGERS' THEN
+ trigcnt = trigcnt + 1;
+ trigtype = avarg;
+ END IF;
+ END LOOP;
+ IF fkcnt > 1 THEN
+ RAISE WARNING 'Only one foreign key option can be provided. You provided %', fkcnt;
+ RETURN '';
+ ELSEIF trigcnt > 1 THEN
+ RAISE WARNING 'Only one trigger option can be provided. You provided %', trigcnt;
+ RETURN '';
+ END IF;
+ END IF;
+
+ SELECT c.oid, (select setting from pg_settings where name = 'server_version_num') INTO v_table_oid, v_pgversion FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+ WHERE c.relkind in ('r','p') AND c.relname = in_table AND n.nspname = in_schema;
+ IF bVerbose THEN RAISE NOTICE 'version=%', v_pgversion; END IF;
+
+ -- throw an error if table was not found
+ IF (v_table_oid IS NULL) THEN
+ RAISE EXCEPTION 'table does not exist';
+ END IF;
+
+ -- get user-defined tablespaces if applicable
+ SELECT tablespace INTO v_temp FROM pg_tables WHERE schemaname = in_schema and tablename = in_table and tablespace IS NOT NULL;
+ IF v_temp IS NULL THEN
+ v_tablespace := 'TABLESPACE pg_default';
+ ELSE
+ v_tablespace := 'TABLESPACE ' || v_temp;
+ END IF;
+
+ -- also see if there are any SET commands for this table, ie, autovacuum_enabled=off, fillfactor=70
+ WITH relopts AS (SELECT unnest(c.reloptions) relopts FROM pg_class c, pg_namespace n WHERE n.nspname = in_schema and n.oid = c.relnamespace and c.relname = in_table)
+ SELECT string_agg(r.relopts, ', ') as relopts INTO v_temp from relopts r;
+ IF v_temp IS NULL THEN
+ v_relopts := '';
+ ELSE
+ v_relopts := ' WITH (' || v_temp || ')';
+ END IF;
+
+ -- -----------------------------------------------------------------------------------
+ -- Create table defs for partitions/children using inheritance or declarative methods.
+ -- inheritance: pg_class.relkind = 'r' pg_class.relispartition=false pg_class.relpartbound is NULL
+ -- declarative: pg_class.relkind = 'r' pg_class.relispartition=true pg_class.relpartbound is NOT NULL
+ -- -----------------------------------------------------------------------------------
+ v_partbound := '';
+ bPartition := False;
+ bInheritance := False;
+ IF v_pgversion < 100000 THEN
+ SELECT c2.relname parent INTO v_parent from pg_class c1, pg_namespace n, pg_inherits i, pg_class c2
+ WHERE n.nspname = in_schema and n.oid = c1.relnamespace and c1.relname = in_table and c1.oid = i.inhrelid and i.inhparent = c2.oid and c1.relkind = 'r';
+ IF (v_parent IS NOT NULL) THEN
+ bPartition := True;
+ bInheritance := True;
+ END IF;
+ ELSE
+ SELECT c2.relname parent, c1.relispartition, pg_get_expr(c1.relpartbound, c1.oid, true) INTO v_parent, bRelispartition, v_partbound from pg_class c1, pg_namespace n, pg_inherits i, pg_class c2
+ WHERE n.nspname = in_schema and n.oid = c1.relnamespace and c1.relname = in_table and c1.oid = i.inhrelid and i.inhparent = c2.oid and c1.relkind = 'r';
+ IF (v_parent IS NOT NULL) THEN
+ bPartition := True;
+ IF bRelispartition THEN
+ bInheritance := False;
+ ELSE
+ bInheritance := True;
+ END IF;
+ END IF;
+ END IF;
+
+ IF bPartition THEN
+ IF bInheritance THEN
+ -- inheritance-based
+ v_table_ddl := 'CREATE TABLE ' || in_schema || '.' || in_table || '( '|| E'\\n';
+ -- Jump to constraints section to add the check constraints
+ ELSE
+ -- declarative-based
+ IF v_relopts <> '' THEN
+ v_table_ddl := 'CREATE TABLE ' || in_schema || '.' || in_table || ' PARTITION OF ' || in_schema || '.' || v_parent || ' ' || v_partbound || v_relopts || ' ' || v_tablespace || '; ' || E'\\n';
+ ELSE
+ v_table_ddl := 'CREATE TABLE ' || in_schema || '.' || in_table || ' PARTITION OF ' || in_schema || '.' || v_parent || ' ' || v_partbound || ' ' || v_tablespace || '; ' || E'\\n';
+ END IF;
+ -- Jump to constraints and index section to add the check constraints and indexes and perhaps FKeys
+ END IF;
+ END IF;
+ IF bVerbose THEN RAISE INFO '(1)tabledef so far: %', v_table_ddl; END IF;
+
+ IF NOT bPartition THEN
+ -- see if this is unlogged or temporary table
+ select c.relpersistence into v_persist from pg_class c, pg_namespace n where n.nspname = in_schema and n.oid = c.relnamespace and c.relname = in_table and c.relkind = 'r';
+ IF v_persist = 'u' THEN
+ v_temp := 'UNLOGGED';
+ ELSIF v_persist = 't' THEN
+ v_temp := 'TEMPORARY';
+ ELSE
+ v_temp := '';
+ END IF;
+ END IF;
+
+ -- start the create definition for regular tables unless we are in progress creating an inheritance-based child table
+ IF NOT bPartition THEN
+ v_table_ddl := 'CREATE ' || v_temp || ' TABLE ' || in_schema || '.' || in_table || ' (' || E'\\n';
+ END IF;
+ -- RAISE INFO 'DEBUG2: tabledef so far: %', v_table_ddl;
+ -- define all of the columns in the table unless we are in progress creating an inheritance-based child table
+ IF NOT bPartition THEN
+ FOR v_colrec IN
+ SELECT c.column_name, c.data_type, c.udt_name, c.character_maximum_length, c.is_nullable, c.column_default, c.numeric_precision, c.numeric_scale, c.is_identity, c.identity_generation
+ FROM information_schema.columns c WHERE (table_schema, table_name) = (in_schema, in_table) ORDER BY ordinal_position
+ LOOP
+ v_table_ddl := v_table_ddl || ' ' -- note: two char spacer to start, to indent the column
+ || v_colrec.column_name || ' '
+ -- || CASE WHEN v_colrec.data_type = 'USER-DEFINED' THEN in_schema || '.' || v_colrec.udt_name ELSE v_colrec.data_type END
+ || CASE WHEN v_colrec.udt_name in ('geometry', 'box2d', 'box2df', 'box3d', 'geography', 'geometry_dump', 'gidx', 'spheroid', 'valid_detail')
+ THEN v_colrec.udt_name WHEN v_colrec.data_type = 'USER-DEFINED' THEN in_schema || '.' || v_colrec.udt_name ELSE v_colrec.data_type END
+ || CASE WHEN v_colrec.is_identity = 'YES' THEN CASE WHEN v_colrec.identity_generation = 'ALWAYS' THEN ' GENERATED ALWAYS AS IDENTITY' ELSE ' GENERATED BY DEFAULT AS IDENTITY' END ELSE '' END
+ || CASE WHEN v_colrec.character_maximum_length IS NOT NULL THEN ('(' || v_colrec.character_maximum_length || ')')
+ WHEN v_colrec.numeric_precision > 0 AND v_colrec.numeric_scale > 0 THEN '(' || v_colrec.numeric_precision || ',' || v_colrec.numeric_scale || ')'
+ ELSE '' END || ' '
+ || CASE WHEN v_colrec.is_nullable = 'NO' THEN 'NOT NULL' ELSE 'NULL' END
+ || CASE WHEN v_colrec.column_default IS NOT null THEN (' DEFAULT ' || v_colrec.column_default) ELSE '' END
+ || ',' || E'\n';
+ END LOOP;
+ END IF;
+ IF bVerbose THEN RAISE INFO '(2)tabledef so far: %', v_table_ddl; END IF;
+
+ -- define all the constraints
+ FOR v_constraintrec IN
+ SELECT con.conname as constraint_name, con.contype as constraint_type,
+ CASE
+ WHEN con.contype = 'p' THEN 1 -- primary key constraint
+ WHEN con.contype = 'u' THEN 2 -- unique constraint
+ WHEN con.contype = 'f' THEN 3 -- foreign key constraint
+ WHEN con.contype = 'c' THEN 4
+ ELSE 5
+ END as type_rank,
+ pg_get_constraintdef(con.oid) as constraint_definition
+ FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespace
+ WHERE nsp.nspname = in_schema AND rel.relname = in_table ORDER BY type_rank
+ LOOP
+ IF v_constraintrec.type_rank = 1 THEN
+ v_primary := True;
+ v_constraint_name := v_constraintrec.constraint_name;
+ IF bPartition THEN
+ continue;
+ END IF;
+ END IF;
+ -- RAISE INFO 'DEBUG4: constraint name= %', v_constraintrec.constraint_name;
+ constraintarr := constraintarr || v_constraintrec.constraint_name;
+
+ IF fktype <> 'FKEYS_INTERNAL' AND v_constraintrec.constraint_type = 'f' THEN
+ continue;
+ END IF;
+
+ v_table_ddl := v_table_ddl || ' ' -- note: two char spacer to start, to indent the column
+ || 'CONSTRAINT' || ' '
+ || v_constraintrec.constraint_name || ' '
+ || v_constraintrec.constraint_definition
+ || ',' || E'\\n';
+ END LOOP;
+ IF bVerbose THEN RAISE INFO '(3)tabledef so far: %', v_table_ddl; END IF;
+
+ -- drop the last comma before ending the create statement
+ v_table_ddl = substr(v_table_ddl, 0, length(v_table_ddl) - 1) || E'\\n';
+
+ -- ---------------------------------------------------------------------------
+ -- at this point we have everything up to the last table-enclosing parenthesis
+ -- ---------------------------------------------------------------------------
+ IF bVerbose THEN RAISE INFO '(4)tabledef so far: %', v_table_ddl; END IF;
+
+ -- See if this is an inheritance-based child table and finish up the table create.
+ IF bPartition and bInheritance THEN
+ v_table_ddl := v_table_ddl || ') INHERITS (' || in_schema || '.' || v_parent || ') ' || E'\\n' || v_relopts || ' ' || v_tablespace || ';' || E'\\n';
+ END IF;
+
+ IF v_pgversion >= 100000 AND NOT bPartition and NOT bInheritance THEN
+ -- See if this is a partitioned table (pg_class.relkind = 'p') and add the partitioned key
+ SELECT pg_get_partkeydef(c1.oid) as partition_key INTO v_partition_key FROM pg_class c1 JOIN pg_namespace n ON (n.oid = c1.relnamespace) LEFT JOIN pg_partitioned_table p ON (c1.oid = p.partrelid)
+ WHERE n.nspname = in_schema and n.oid = c1.relnamespace and c1.relname = in_table and c1.relkind = 'p';
+
+ IF v_partition_key IS NOT NULL AND v_partition_key <> '' THEN
+ -- add partition clause
+ -- NOTE: cannot specify default tablespace for partitioned relations
+ -- v_table_ddl := v_table_ddl || ') PARTITION BY ' || v_partition_key || ' ' || v_tablespace || ';' || E'\\n';
+ v_table_ddl := v_table_ddl || ') PARTITION BY ' || v_partition_key || ';' || E'\\n';
+ ELSEIF v_relopts <> '' THEN
+ v_table_ddl := v_table_ddl || ') ' || v_relopts || ' ' || v_tablespace || ';' || E'\\n';
+ ELSE
+ -- end the create definition
+ v_table_ddl := v_table_ddl || ') ' || v_tablespace || ';' || E'\\n';
+ END IF;
+ END IF;
+
+ IF bVerbose THEN RAISE INFO '(5)tabledef so far: %', v_table_ddl; END IF;
+
+ -- Add closing paren for regular tables
+ -- IF NOT bPartition THEN
+ -- v_table_ddl := v_table_ddl || ') ' || v_relopts || ' ' || v_tablespace || E';\\n';
+ -- END IF;
+ -- RAISE NOTICE 'ddlsofar3: %', v_table_ddl;
+
+ -- create indexes
+ FOR v_indexrec IN
+ SELECT indexdef, COALESCE(tablespace, 'pg_default') as tablespace, indexname FROM pg_indexes WHERE (schemaname, tablename) = (in_schema, in_table)
+ LOOP
+ -- RAISE INFO 'DEBUG6: indexname=%', v_indexrec.indexname;
+ -- loop through constraints and skip ones already defined
+ bSkip = False;
+ FOREACH constraintelement IN ARRAY constraintarr
+ LOOP
+ IF constraintelement = v_indexrec.indexname THEN
+ -- RAISE INFO 'DEBUG7: skipping index, %', v_indexrec.indexname;
+ bSkip = True;
+ EXIT;
+ END IF;
+ END LOOP;
+ if bSkip THEN CONTINUE; END IF;
+
+ -- Add IF NOT EXISTS clause so partition index additions will not be created if declarative partition in effect and index already created on parent
+ v_indexrec.indexdef := REPLACE(v_indexrec.indexdef, 'CREATE INDEX', 'CREATE INDEX IF NOT EXISTS');
+ -- RAISE INFO 'DEBUG8: adding index, %', v_indexrec.indexname;
+
+ -- NOTE: cannot specify default tablespace for partitioned relations
+ IF v_partition_key IS NOT NULL AND v_partition_key <> '' THEN
+ v_table_ddl := v_table_ddl || v_indexrec.indexdef || ';' || E'\\n';
+ ELSE
+ v_table_ddl := v_table_ddl || v_indexrec.indexdef || ' TABLESPACE ' || v_indexrec.tablespace || ';' || E'\\n';
+ END IF;
+
+ END LOOP;
+ IF bVerbose THEN RAISE INFO '(6)tabledef so far: %', v_table_ddl; END IF;
+
+ -- Handle external foreign key defs here if applicable.
+ IF fktype = 'FKEYS_EXTERNAL' THEN
+ SELECT 'ALTER TABLE ONLY ' || n.nspname || '.' || c2.relname || ' ADD CONSTRAINT ' || r.conname || ' ' || pg_catalog.pg_get_constraintdef(r.oid, true) || ';' into v_fkey_defs
+ FROM pg_constraint r, pg_class c1, pg_namespace n, pg_class c2 where r.conrelid = c1.oid and r.contype = 'f' and n.nspname = in_schema and n.oid = r.connamespace and r.conrelid = c2.oid and c2.relname = in_table;
+ IF v_fkey_defs IS NOT NULL THEN
+ v_table_ddl := v_table_ddl || v_fkey_defs;
+ END IF;
+ ELSIF fktype = 'FKEYS_COMMENTED' THEN
+ SELECT '-- ALTER TABLE ONLY ' || n.nspname || '.' || c2.relname || ' ADD CONSTRAINT ' || r.conname || ' ' || pg_catalog.pg_get_constraintdef(r.oid, true) || ';' into v_fkey_defs
+ FROM pg_constraint r, pg_class c1, pg_namespace n, pg_class c2 where r.conrelid = c1.oid and r.contype = 'f' and n.nspname = in_schema and n.oid = r.connamespace and r.conrelid = c2.oid and c2.relname = in_table;
+ IF v_fkey_defs IS NOT NULL THEN
+ v_table_ddl := v_table_ddl || v_fkey_defs;
+ END IF;
+ END IF;
+ IF bVerbose THEN RAISE INFO '(7)tabledef so far: %', v_table_ddl; END IF;
+
+ IF trigtype = 'INCLUDE_TRIGGERS' THEN
+ select pg_get_triggerdef(t.oid, True) || ';' INTO v_trigger FROM pg_trigger t, pg_class c, pg_namespace n
+ WHERE n.nspname = in_schema and n.oid = c.relnamespace and c.relname = in_table and c.relkind = 'r' and t.tgrelid = c.oid and NOT t.tgisinternal;
+ IF v_trigger <> '' THEN
+ v_table_ddl := v_table_ddl || v_trigger;
+ END IF;
+ END IF;
+
+ -- add empty line
+ v_table_ddl := v_table_ddl || E'\\n';
+
+ RETURN v_table_ddl;
+
+ EXCEPTION
+ WHEN others THEN
+ BEGIN
+ GET STACKED DIAGNOSTICS v_diag1 = MESSAGE_TEXT, v_diag2 = PG_EXCEPTION_DETAIL, v_diag3 = PG_EXCEPTION_HINT, v_diag4 = RETURNED_SQLSTATE, v_diag5 = PG_CONTEXT, v_diag6 = PG_EXCEPTION_CONTEXT;
+ -- v_ret := 'line=' || v_diag6 || '. '|| v_diag4 || '. ' || v_diag1 || ' .' || v_diag2 || ' .' || v_diag3;
+ v_ret := 'line=' || v_diag6 || '. '|| v_diag4 || '. ' || v_diag1;
+ RAISE EXCEPTION '%', v_ret;
+ -- put additional coding here if necessarY
+ RETURN '';
+ END;
+
+ END;
+ $$;`,
+ { compress: true, removeAll: true }
+)
diff --git a/studio/data/database/foreign-key-constraints-query.ts b/studio/data/database/foreign-key-constraints-query.ts
index d7ec6f5b339..4a218079e88 100644
--- a/studio/data/database/foreign-key-constraints-query.ts
+++ b/studio/data/database/foreign-key-constraints-query.ts
@@ -2,7 +2,7 @@ import { UseQueryOptions } from '@tanstack/react-query'
import { useCallback } from 'react'
import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
-type getForeignKeyConstraintsVariables = {
+type GetForeignKeyConstraintsVariables = {
schema?: string
}
@@ -20,7 +20,7 @@ export type ForeignKeyConstraint = {
target_columns: string
}
-export const getForeignKeyConstraintsQuery = ({ schema }: getForeignKeyConstraintsVariables) => {
+export const getForeignKeyConstraintsQuery = ({ schema }: GetForeignKeyConstraintsVariables) => {
const sql = /* SQL */ `
SELECT
con.oid as id,
@@ -72,7 +72,7 @@ WHERE
return sql
}
-export type ForeignKeyConstraintsVariables = getForeignKeyConstraintsVariables & {
+export type ForeignKeyConstraintsVariables = GetForeignKeyConstraintsVariables & {
projectRef?: string
connectionString?: string
}
diff --git a/studio/data/database/table-definition-query.ts b/studio/data/database/table-definition-query.ts
new file mode 100644
index 00000000000..77b0668b754
--- /dev/null
+++ b/studio/data/database/table-definition-query.ts
@@ -0,0 +1,68 @@
+import { UseQueryOptions } from '@tanstack/react-query'
+import { useCallback } from 'react'
+import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
+import { CREATE_PG_GET_TABLEDEF_SQL } from './database-query-constants'
+
+type GetTableDefinition = {
+ schema?: string
+ name?: string
+}
+
+export const getTableDefinitionQuery = ({ schema = 'public', name }: GetTableDefinition) => {
+ const sql = /* SQL */ `
+ ${CREATE_PG_GET_TABLEDEF_SQL}
+
+ select pg_temp.pg_get_tabledef (
+ '${schema}',
+ '${name}',
+ false,
+ 'FKEYS_INTERNAL',
+ 'INCLUDE_TRIGGERS'
+ ) as definition
+ `.trim()
+
+ return sql
+}
+
+export type TableDefinitionVariables = GetTableDefinition & {
+ projectRef?: string
+ connectionString?: string
+}
+
+export type TableDefinitionData = string
+export type TableDefinitionError = unknown
+
+export const useTableDefinitionQuery = <TData extends TableDefinitionData = TableDefinitionData>(
+ { projectRef, connectionString, name }: TableDefinitionVariables,
+ options: UseQueryOptions<ExecuteSqlData, TableDefinitionError, TData> = {}
+) => {
+ return useExecuteSqlQuery(
+ {
+ projectRef,
+ connectionString,
+ sql: getTableDefinitionQuery({ name }),
+ queryKey: ['table-definition', name],
+ },
+ {
+ select(data) {
+ return data.result[0].definition.trim()
+ },
+ ...options,
+ }
+ )
+}
+
+export const useTableDefinitionQueryPrefetch = () => {
+ const prefetch = useExecuteSqlPrefetch()
+
+ return useCallback(
+ ({ projectRef, connectionString, name }: TableDefinitionVariables) =>
+ prefetch({
+ projectRef,
+ connectionString,
+ sql: getTableDefinitionQuery({ name }),
+ queryKey: ['table-definition', name],
+ }),
+ [prefetch]
+ )
+}
diff --git a/studio/data/database/view-definition-query.ts b/studio/data/database/view-definition-query.ts
index 051b012aac3..99bda076dc5 100644
--- a/studio/data/database/view-definition-query.ts
+++ b/studio/data/database/view-definition-query.ts
@@ -2,7 +2,7 @@ import { UseQueryOptions } from '@tanstack/react-query'
import { useCallback } from 'react'
import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
-type getViewDefinition = {
+type GetViewDefinition = {
name?: string
}
@@ -20,19 +20,20 @@ type ViewDefinition = {
target_columns: string
}
-export const getViewDefinitionQuery = ({ name }: getViewDefinition) => {
+export const getViewDefinitionQuery = ({ name }: GetViewDefinition) => {
const sql = /* SQL */ `
-select pg_get_viewdef('${name}', true) as definition
-`.trim()
+ select pg_get_viewdef('${name}', true) as definition
+ `.trim()
+
return sql
}
-export type ViewDefinitionVariables = getViewDefinition & {
+export type ViewDefinitionVariables = GetViewDefinition & {
projectRef?: string
connectionString?: string
}
-export type ViewDefinitionData = any
+export type ViewDefinitionData = string
export type ViewDefinitionError = unknown
export const useViewDefinitionQuery = <TData extends ViewDefinitionData = ViewDefinitionData>(
diff --git a/studio/package.json b/studio/package.json
index b6af6c9187b..d57c590eef0 100644
--- a/studio/package.json
+++ b/studio/package.json
@@ -65,6 +65,7 @@
"papaparse": "^5.3.1",
"parse-numeric-range": "^1.3.0",
"path-to-regexp": "^6.2.0",
+ "pg-minify": "^1.6.3",
"prism-react-renderer": "^1.2.1",
"react": "^17.0.2",
"react-beautiful-dnd": "^13.1.0",
@@ -88,6 +89,7 @@
"scheduler": "^0.20.2",
"semver": "^6.3.0",
"shared-data": "*",
+ "sql-formatter": "^12.2.0",
"sqlstring": "^2.3.2",
"ui": "*",
"uniforms-bootstrap4": "^3.6.2",