Skip to content

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

remove tableCreateGeneratePolicies experiment (failed variant) (#43498)

Sean Oliver0aa23980bb43
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index bcef46ef901..a35ecec53af 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -7,6 +7,7 @@ import {
} from 'components/grid/utils/queueOperationUtils'
import { useIsQueueOperationsEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { 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'
import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'
@@ -28,9 +29,7 @@ import { RetrieveTableResult } from 'data/tables/table-retrieve-query'
import { getTables } from 'data/tables/tables-query'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { isValidExperimentVariant } from 'hooks/misc/useTableCreateGeneratePolicies'
import { useConfirmOnClose } from 'hooks/ui/useConfirmOnClose'
-import { usePHFlag } from 'hooks/ui/useFlag'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useTrack } from 'lib/telemetry/track'
import { isEmpty, isUndefined, noop } from 'lodash'
@@ -41,7 +40,6 @@ import { useTableEditorStateSnapshot, type TableEditorState } from 'state/table-
import { createTabId, useTabsStateSnapshot } from 'state/tabs'
import type { Dictionary } from 'types'
import { SonnerProgress } from 'ui'
-import { DiscardChangesConfirmationDialog } from 'components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
import { ColumnEditor } from './ColumnEditor/ColumnEditor'
import type { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'
@@ -206,7 +204,6 @@ export const SidePanelEditor = ({
const getImpersonatedRoleState = useGetImpersonatedRoleState()
const isApiGrantTogglesEnabled = useDataApiGrantTogglesEnabled()
- const generatePoliciesFlag = usePHFlag<string>('tableCreateGeneratePolicies')
const isQueueOperationsEnabled = useIsQueueOperationsEnabled()
const [isEdited, setIsEdited] = useState<boolean>(false)
@@ -739,17 +736,6 @@ export const SidePanelEditor = ({
toast.success(`Table ${table.name} is good to go!`, { id: toastId })
}
- // Track experiment conversion if user is in the experiment
- if (isValidExperimentVariant(generatePoliciesFlag)) {
- track('table_create_generate_policies_experiment_converted', {
- experiment_id: 'tableCreateGeneratePolicies',
- variant: generatePoliciesFlag,
- has_rls_enabled: isRLSEnabled,
- has_rls_policies: generatedPolicies.length > 0,
- has_generated_policies: generatedPolicies.length > 0,
- })
- }
-
onTableCreated(table)
} else if (action === 'duplicate' && !!selectedTable) {
const tableToDuplicate = selectedTable
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyList.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyList.tsx
deleted file mode 100644
index f40562843e8..00000000000
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyList.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { X } from 'lucide-react'
-
-import {
- Badge,
- Card,
- cn,
- HoverCard_Shadcn_,
- HoverCardContent_Shadcn_,
- HoverCardTrigger_Shadcn_,
- SimpleCodeBlock,
-} from 'ui'
-
-export interface PolicyListItemData {
- name: string
- command?: string | null
- sql?: string | null
- isNew?: boolean
-}
-
-interface PolicyListItemProps {
- policy: PolicyListItemData
- onRemove?: () => void
-}
-
-/**
- * A shared component for displaying policy items with hover preview
- * Used in RLSManagement and policy creation toast notifications
- */
-export const PolicyListItem = ({ policy, onRemove }: PolicyListItemProps) => {
- return (
- <HoverCard_Shadcn_ openDelay={200} closeDelay={100}>
- <HoverCardTrigger_Shadcn_ asChild>
- <div
- className={cn(
- 'flex items-center justify-between text-sm text-foreground py-2 px-3 hover:bg-surface-100 transition-colors',
- 'border-b border-default last:border-b-0'
- )}
- >
- <code className="text-xs truncate flex-1">{policy.name}</code>
-
- <div className="flex items-center gap-2">
- {policy.command && <Badge variant="default">{policy.command}</Badge>}
- {policy.isNew && <Badge variant="success">New</Badge>}
- {!!onRemove && policy.isNew && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation()
- onRemove()
- }}
- className="flex items-center justify-center hover:bg-surface-200 rounded p-0.5 transition-colors"
- aria-label="Remove policy"
- >
- <X size={16} strokeWidth={1.5} className="text-foreground-lighter" />
- </button>
- )}
- </div>
- </div>
- </HoverCardTrigger_Shadcn_>
- <HoverCardContent_Shadcn_ className="w-96" side="left">
- {policy.sql ? (
- <SimpleCodeBlock className="language-sql" showCopy={false}>
- {policy.sql}
- </SimpleCodeBlock>
- ) : (
- <p className="text-xs text-foreground-lighter">No definition available.</p>
- )}
- </HoverCardContent_Shadcn_>
- </HoverCard_Shadcn_>
- )
-}
-
-interface PolicyListProps {
- disabled?: boolean
- policies: PolicyListItemData[]
- className?: string
- onRemove?: (index: number) => void
-}
-
-/**
- * A list of policies with hover previews
- * Used in RLSManagement and toast notifications
- */
-export const PolicyList = ({
- disabled = false,
- policies,
- className,
- onRemove,
-}: PolicyListProps) => {
- return (
- <Card aria-disabled={disabled} className={cn(disabled && 'opacity-50 pointer-events-none')}>
- <div
- className={`rounded border border-default overflow-hidden bg-surface-100 ${className ?? ''}`}
- >
- {policies.map((policy, idx) => (
- <PolicyListItem
- key={`${policy.name}-${idx}`}
- policy={policy}
- onRemove={onRemove ? () => onRemove(idx) : undefined}
- />
- ))}
- </div>
- </Card>
- )
-}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyListEmptyState.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyListEmptyState.tsx
deleted file mode 100644
index 4477cc88d23..00000000000
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyListEmptyState.tsx
+++ /dev/null
@@ -1,242 +0,0 @@
-import { useMemo, useState } from 'react'
-import { toast } from 'sonner'
-
-import {
- type GeneratedPolicy,
- generateStartingPoliciesForTable,
-} from 'components/interfaces/Auth/Policies/Policies.utils'
-import { AIOptInModal } from 'components/ui/AIAssistantPanel/AIOptInModal'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import {
- ForeignKeyConstraint,
- useForeignKeyConstraintsQuery,
-} from 'data/database/foreign-key-constraints-query'
-import { useOrgAiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { useTrack } from 'lib/telemetry/track'
-import { Button, Card, CardContent, cn } from 'ui'
-import type { ForeignKey } from '../../ForeignKeySelector/ForeignKeySelector.types'
-import { ColumnField } from '../../SidePanelEditor.types'
-
-interface PolicyListEmptyStateProps {
- schema: string
- tableName?: string
- columns: ColumnField[]
- foreignKeyRelations: ForeignKey[]
- isNewRecord: boolean
- isRLSEnabled: boolean
- isDuplicating: boolean
- onGeneratedPoliciesChange?: (policies: GeneratedPolicy[]) => void
-}
-
-export const PolicyListEmptyState = ({
- schema,
- tableName,
- columns,
- foreignKeyRelations,
- isNewRecord,
- isRLSEnabled,
- isDuplicating,
- onGeneratedPoliciesChange,
-}: PolicyListEmptyStateProps) => {
- const track = useTrack()
- const { data: project } = useSelectedProjectQuery()
- const { includeSchemaMetadata } = useOrgAiOptInLevel()
-
- const [isGenerating, setIsGenerating] = useState(false)
- const [generateFailed, setGenerateFailed] = useState(false)
- const [isOptInModalOpen, setIsOptInModalOpen] = useState(false)
-
- // Fetch foreign key constraints for policy generation BFS traversal
- const { data: schemaForeignKeys } = useForeignKeyConstraintsQuery(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- schema: schema,
- },
- {
- enabled: isNewRecord && !isDuplicating && !!schema,
- }
- )
-
- const emptyStateMessage = useMemo(() => {
- if (!generateFailed) {
- return {
- title: 'Generate starting policies',
- description: (
- <>
- Starter policies are generated from your table relationships to{' '}
- <code className="text-code-inline">auth.users</code> or, if none exist, using AI.
- </>
- ),
- }
- }
-
- if (!includeSchemaMetadata) {
- return {
- title: 'Unable to generate policies',
- description: (
- <>
- <p>We couldn't detect any relationships to auth.users to suggest policies.</p>
- <p>Enable schema metadata sharing to use our AI-assisted policy generator.</p>
- </>
- ),
- }
- }
-
- return {
- title: 'We could not generate policies for this table',
- description:
- "Automatic policy generation wasn't possible for this table. Update the schema and try again, or add policies manually after creating the table.",
- }
- }, [generateFailed, includeSchemaMetadata])
-
- const { title, description } = emptyStateMessage
- const showPermissionButton = generateFailed && !includeSchemaMetadata
- const allowPolicyGeneration = isNewRecord && !isDuplicating
-
- const convertForeignKeysToConstraints = (fks: ForeignKey[]): ForeignKeyConstraint[] => {
- if (!tableName || !schema) {
- return []
- }
-
- return fks
- .filter((fk) => fk.columns && fk.columns.length > 0) // Only include FKs with columns
- .map((fk) => ({
- id: typeof fk.id === 'number' ? fk.id : 0,
- constraint_name: fk.name || '',
- source_id: typeof fk.tableId === 'number' ? fk.tableId : 0,
- source_schema: schema.trim(),
- source_table: tableName.trim(),
- source_columns: fk.columns.map((col: { source: string; target: string }) =>
- col.source.trim()
- ),
- target_id: 0,
- target_schema: fk.schema.trim(),
- target_table: fk.table.trim(),
- target_columns: fk.columns.map((col: { source: string; target: string }) =>
- col.target.trim()
- ),
- deletion_action: fk.deletionAction || 'NO ACTION',
- update_action: fk.updateAction || 'NO ACTION',
- }))
- }
-
- const handleGeneratePolicies = async () => {
- if (!project?.ref || !tableName || columns.length === 0) {
- return toast.error(
- 'Unable to generate policies. Please ensure table name and columns are set.'
- )
- }
-
- track('rls_generate_policies_clicked')
-
- setIsGenerating(true)
- try {
- const trimmedTableName = tableName.trim()
- const trimmedSchema = schema.trim()
-
- const newTableForeignKeys = convertForeignKeysToConstraints(foreignKeyRelations)
-
- const allForeignKeys = [
- ...newTableForeignKeys,
- ...(schemaForeignKeys ?? []).filter(
- (existingFk) =>
- !(
- existingFk.source_schema === trimmedSchema &&
- existingFk.source_table === trimmedTableName
- )
- ),
- ]
-
- const tableColumns = columns.map((col) => ({ name: col.name.trim() }))
-
- const policies = await generateStartingPoliciesForTable({
- table: { name: trimmedTableName, schema: trimmedSchema },
- foreignKeyConstraints: allForeignKeys,
- columns: tableColumns,
- projectRef: project.ref,
- connectionString: project.connectionString,
- enableAi: includeSchemaMetadata,
- })
-
- if (policies.length === 0) {
- setGenerateFailed(true)
- } else {
- setGenerateFailed(false)
- onGeneratedPoliciesChange?.(policies)
- }
- } catch (error: any) {
- console.error('Failed to generate policies:', error)
- toast.error(error.message || 'Failed to generate policies')
- } finally {
- setIsGenerating(false)
- }
- }
-
- if (allowPolicyGeneration) {
- return (
- <>
- <Card>
- <CardContent className="flex flex-col items-center justify-center py-8">
- <div
- className={cn(
- 'flex flex-col items-center gap-4 text-center',
- !generateFailed && 'max-w-sm'
- )}
- >
- <div className="flex flex-col gap-1">
- <h4 className="text-sm text-foreground">{title}</h4>
- <p className="text-sm text-foreground-lighter">{description}</p>
- </div>
- <div className="flex items-center gap-2">
- <ButtonTooltip
- type="default"
- size="tiny"
- onClick={handleGeneratePolicies}
- loading={isGenerating}
- disabled={isGenerating || !isRLSEnabled || !tableName || columns.length === 0}
- tooltip={{
- content: {
- side: 'bottom',
- text: !tableName
- ? 'Provide a name for your table first before generating policies'
- : columns.length === 0
- ? 'Create at least one column first before generating policies'
- : undefined,
- },
- }}
- >
- {isGenerating
- ? 'Generating policies...'
- : generateFailed
- ? 'Try generating again'
- : 'Generate policies'}
- </ButtonTooltip>
- {showPermissionButton && (
- <Button
- type="default"
- size="tiny"
- onClick={() => setIsOptInModalOpen(true)}
- disabled={isGenerating}
- >
- Permission settings
- </Button>
- )}
- </div>
- </div>
- </CardContent>
- </Card>
- <AIOptInModal visible={isOptInModalOpen} onCancel={() => setIsOptInModalOpen(false)} />
- </>
- )
- }
-
- return (
- <Card>
- <CardContent>
- <p className="text-sm text-foreground-lighter">No policies exist for this table</p>
- </CardContent>
- </Card>
- )
-}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/RLSManagement.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/RLSManagement.tsx
deleted file mode 100644
index 6bbcfd08456..00000000000
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/RLSManagement.tsx
+++ /dev/null
@@ -1,205 +0,0 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
-import { ExternalLink } from 'lucide-react'
-import Link from 'next/link'
-import { useMemo } from 'react'
-
-import { type GeneratedPolicy } from 'components/interfaces/Auth/Policies/Policies.utils'
-import { generatePolicyUpdateSQL } from 'components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRow.utils'
-import { DocsButton } from 'components/ui/DocsButton'
-import { useDatabasePoliciesQuery } from 'data/database-policies/database-policies-query'
-import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { DOCS_URL } from 'lib/constants'
-import { useTrack } from 'lib/telemetry/track'
-import { Button, cn } from 'ui'
-import { Admonition } from 'ui-patterns/admonition'
-import type { ForeignKey } from '../../ForeignKeySelector/ForeignKeySelector.types'
-import { TableField } from '../TableEditor.types'
-import { PolicyList, type PolicyListItemData } from './PolicyList'
-import { PolicyListEmptyState } from './PolicyListEmptyState'
-import { ToggleRLSButton } from './ToggleRLSButton'
-
-interface RLSManagementProps {
- table?: PostgresTable
- tableFields: TableField // Fields within the form
- foreignKeyRelations?: ForeignKey[] // For new tables
- isNewRecord: boolean
- isDuplicating: boolean
- isExposed?: boolean
- generatedPolicies?: GeneratedPolicy[]
- onRLSUpdate?: (isEnabled: boolean) => void
- onGeneratedPoliciesChange?: (policies: GeneratedPolicy[]) => void
-}
-
-export const RLSManagement = ({
- table,
- tableFields,
- foreignKeyRelations = [],
- isNewRecord,
- isDuplicating,
- isExposed,
- generatedPolicies = [],
- onRLSUpdate,
- onGeneratedPoliciesChange,
-}: RLSManagementProps) => {
- const track = useTrack()
- const { data: project } = useSelectedProjectQuery()
- const { selectedSchema } = useQuerySchemaState()
-
- const { name: tableName, columns, isRLSEnabled } = tableFields
- const schema = table?.schema ?? selectedSchema
-
- const isExistingTable = !!table && !isNewRecord && !isDuplicating
- const generatedPoliciesTargetTable = generatedPolicies[0]?.table
- const policiesNotRelevantDueToTableNameChange =
- isNewRecord && tableName !== generatedPoliciesTargetTable
- const disablePoliciesList =
- (isExistingTable && !isRLSEnabled) || policiesNotRelevantDueToTableNameChange
-
- const { data: policies } = useDatabasePoliciesQuery(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- },
- {
- enabled: !isNewRecord && !isDuplicating,
- }
- )
-
- const tablePolicies = (policies ?? []).filter(
- (policy) => policy.schema === table?.schema && policy.table === table?.name
- )
-
- const existingPoliciesList = useMemo<PolicyListItemData[]>(
- () =>
- (tablePolicies ?? []).map((policy) => ({
- name: policy.name,
- command: policy.action ?? policy.command,
- sql: generatePolicyUpdateSQL(policy),
- isNew: false,
- })),
- [tablePolicies]
- )
-
- // Convert generated policies to PolicyListItemData format
- const generatedPoliciesList = useMemo<PolicyListItemData[]>(
- () =>
- generatedPolicies.map((policy) => ({
- name: policy.name,
- command: policy.command,
- sql: policy.sql,
- isNew: true,
- })),
- [generatedPolicies]
- )
-
- const allPoliciesList = useMemo<PolicyListItemData[]>(
- () => [...existingPoliciesList, ...generatedPoliciesList],
- [existingPoliciesList, generatedPoliciesList]
- )
-
- const hasPolicies = allPoliciesList.length > 0
-
- const handleRemoveGeneratedPolicy = (index: number) => {
- // Find the index in generatedPoliciesList that corresponds to the allPoliciesList index
- const generatedIndex = index - existingPoliciesList.length
- if (generatedIndex >= 0 && generatedIndex < generatedPolicies.length) {
- const updatedPolicies = generatedPolicies.filter((_, i) => i !== generatedIndex)
- onGeneratedPoliciesChange?.(updatedPolicies)
-
- // Track policy removal
- if (project?.ref) track('rls_generated_policy_removed')
- }
- }
-
- return (
- <div className="flex flex-col gap-y-4">
- <div className="flex items-center justify-between">
- <div>
- <h5>Policies</h5>
- <p className="text-sm text-foreground-lighter">
- Set rules around who can read and write data to this table
- </p>
- </div>
- {!isNewRecord && (
- <Button asChild type="default" icon={<ExternalLink />}>
- <Link
- target="_blank"
- rel="noopener noreferrer"
- href={`/project/${project?.ref}/auth/policies`}
- >
- Manage policies
- </Link>
- </Button>
- )}
- </div>
-
- {generatedPolicies.length > 0 && policiesNotRelevantDueToTableNameChange && (
- <Admonition
- type="warning"
- title="Update generated policies with new table name"
- description={`These policies were previously generated for the table name "${generatedPoliciesTargetTable}"`}
- actions={
- <Button
- type="default"
- className="w-min mt-3"
- onClick={() => {
- const updatedPolicies = generatedPolicies.map((policy) => {
- return {
- ...policy,
- table: tableName,
- name: policy.name.replaceAll(generatedPoliciesTargetTable, tableName),
- sql: policy.sql.replaceAll(generatedPoliciesTargetTable, tableName),
- }
- })
- onGeneratedPoliciesChange?.(updatedPolicies)
- }}
- >
- Update policies
- </Button>
- }
- />
- )}
-
- <Admonition
- // [Joshen] Using CSS to determine visibility here as the onSuccess within ToggleRLSButton doesn't get triggered
- // if we dynamically render this component, since this admonition gets unmounted from the DOM once RLS is updated
- className={cn(
- 'mb-0',
- !isNewRecord && !isRLSEnabled && isExposed !== false ? 'block' : 'hidden'
- )}
- type="warning"
- title="Row Level Security is currently disabled"
- description="Your table is currently accessible by anyone on the internet. We recommend enabling RLS to restrict access."
- actions={
- <div className="flex items-center gap-x-2 mt-3">
- <ToggleRLSButton table={table} isRLSEnabled={isRLSEnabled} onSuccess={onRLSUpdate} />
- <DocsButton href={`${DOCS_URL}/guides/database/postgres/row-level-security`} />
- </div>
- }
- />
-
- {!hasPolicies ? (
- <PolicyListEmptyState
- schema={schema}
- tableName={tableName}
- columns={columns}
- foreignKeyRelations={foreignKeyRelations}
- isNewRecord={isNewRecord}
- isDuplicating={isDuplicating}
- isRLSEnabled={isRLSEnabled}
- onGeneratedPoliciesChange={(policies) => {
- onGeneratedPoliciesChange?.(policies)
- }}
- />
- ) : (
- <PolicyList
- policies={allPoliciesList}
- disabled={disablePoliciesList}
- className="border-0 rounded-none"
- onRemove={isNewRecord && !isDuplicating ? handleRemoveGeneratedPolicy : undefined}
- />
- )}
- </div>
- )
-}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/ToggleRLSButton.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/ToggleRLSButton.tsx
deleted file mode 100644
index 41ed4a52835..00000000000
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/ToggleRLSButton.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { PostgresTable } from '@supabase/postgres-meta'
-import { useTableUpdateMutation } from 'data/tables/table-update-mutation'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { useState } from 'react'
-import { toast } from 'sonner'
-
-import { Button } from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-
-interface ToggleRLSButtonProps {
- table?: PostgresTable
- isRLSEnabled?: boolean
- onSuccess?: (value: boolean) => void
-}
-
-export const ToggleRLSButton = ({
- table,
- isRLSEnabled = false,
- onSuccess,
-}: ToggleRLSButtonProps) => {
- const { data: project } = useSelectedProjectQuery()
- const [showConfirmation, setShowConfirmation] = useState(false)
-
- const action = isRLSEnabled ? 'Disable' : 'Enable'
-
- const { mutate: updateTable, isPending } = useTableUpdateMutation()
-
- const onConfirm = () => {
- if (!project) return console.error('Project is required')
- if (!table) return console.error('Table is missing')
-
- updateTable(
- {
- id: table.id,
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- schema: table.schema,
- name: table.name,
- payload: { rls_enabled: !isRLSEnabled },
- },
- {
- onSuccess: () => {
- toast.success(`Row Level Security has been ${action.toLowerCase()} for this table.`)
- onSuccess?.(!isRLSEnabled)
- setShowConfirmation(false)
- },
- onError: (error) => {
- toast.error(`Failed to ${action.toLowerCase()} RLS: ${error.message}`)
- },
- }
- )
- }
-
- return (
- <>
- <Button type="default" className="w-min" onClick={() => setShowConfirmation(true)}>
- {action} RLS
- </Button>
- <ConfirmationModal
- visible={showConfirmation}
- loading={isPending}
- title={`Confirm to ${action.toLowerCase()} Row Level Security`}
- description={`Are you sure you want to ${action.toLowerCase()} Row Level Security for this table?`}
- confirmLabel={`${action} RLS`}
- onCancel={() => setShowConfirmation(false)}
- onConfirm={onConfirm}
- />
- </>
- )
-}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index f1f946b4509..5c10d88a481 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -10,7 +10,6 @@ import { useChanged } from 'hooks/misc/useChanged'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { useTableCreateGeneratePolicies } from 'hooks/misc/useTableCreateGeneratePolicies'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useProtectedSchemas } from 'hooks/useProtectedSchemas'
import { DOCS_URL } from 'lib/constants'
@@ -35,7 +34,6 @@ import ColumnManagement from './ColumnManagement'
import { ForeignKeysManagement } from './ForeignKeysManagement/ForeignKeysManagement'
import { HeaderTitle } from './HeaderTitle'
import { RLSDisableModalContent } from './RLSDisableModal'
-import { RLSManagement } from './RLSManagement/RLSManagement'
import { DEFAULT_COLUMNS } from './TableEditor.constants'
import type { ImportContent, TableField } from './TableEditor.types'
import {
@@ -100,13 +98,6 @@ export const TableEditor = ({
const [isImportingSpreadsheet, setIsImportingSpreadsheet] = useState<boolean>(false)
const [rlsConfirmVisible, setRlsConfirmVisible] = useState<boolean>(false)
- const [generatedPolicies, setGeneratedPolicies] = useState<GeneratedPolicy[]>([])
-
- const { enabled: generatePoliciesEnabled } = useTableCreateGeneratePolicies({
- isNewRecord,
- projectInsertedAt: project?.inserted_at,
- })
-
const { data: types } = useEnumeratedTypesQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
@@ -233,7 +224,7 @@ export const TableEditor = ({
columns,
foreignKeyRelations: fkRelations,
resolve,
- generatedPolicies,
+ generatedPolicies: [],
})
} else if (isDuplicating) {
const payload: SaveTablePayloadFor<'duplicate'> = {
@@ -283,7 +274,6 @@ export const TableEditor = ({
setErrors({})
setImportContent(undefined)
setIsDuplicateRows(false)
- setGeneratedPolicies([])
if (isNewRecord) {
const tableFields = generateTableField()
if (templateData) {
@@ -339,7 +329,6 @@ export const TableEditor = ({
if (!tableFields) return null
- const isApiAccessAndPoliciesSectionShown = isApiGrantTogglesEnabled || generatePoliciesEnabled
const isExposed = isApiGrantTogglesEnabled
? !!apiAccessToggleHandler.data?.schemaExposed &&
checkDataApiPrivilegesNonEmpty(apiAccessToggleHandler.data.privileges)
@@ -387,93 +376,89 @@ export const TableEditor = ({
<SidePanel.Separator />
- {!generatePoliciesEnabled && (
- <>
- <SidePanel.Content className="space-y-10 py-6">
- <Checkbox
- id="enable-rls"
- // @ts-ignore
- label={
- <div className="flex items-center space-x-2">
- <span>Enable Row Level Security (RLS)</span>
- <Badge>Recommended</Badge>
- </div>
- }
- description="Restrict access to your table by enabling RLS and writing Postgres policies."
- checked={tableFields.isRLSEnabled}
- onChange={() => {
- // if isEnabled, show confirm modal to turn off
- // if not enabled, allow turning on without modal confirmation
- tableFields.isRLSEnabled
- ? setRlsConfirmVisible(true)
- : onUpdateField({ isRLSEnabled: !tableFields.isRLSEnabled })
- }}
- size="medium"
+ <SidePanel.Content className="space-y-10 py-6">
+ <Checkbox
+ id="enable-rls"
+ // @ts-ignore
+ label={
+ <div className="flex items-center space-x-2">
+ <span>Enable Row Level Security (RLS)</span>
+ <Badge>Recommended</Badge>
+ </div>
+ }
+ description="Restrict access to your table by enabling RLS and writing Postgres policies."
+ checked={tableFields.isRLSEnabled}
+ onChange={() => {
+ // if isEnabled, show confirm modal to turn off
+ // if not enabled, allow turning on without modal confirmation
+ tableFields.isRLSEnabled
+ ? setRlsConfirmVisible(true)
+ : onUpdateField({ isRLSEnabled: !tableFields.isRLSEnabled })
+ }}
+ size="medium"
+ />
+
+ {tableFields.isRLSEnabled ? (
+ <Admonition
+ type="default"
+ className="!mt-3"
+ title="Policies are required to query data"
+ description={
+ <>
+ You need to create an access policy before you can query data from this table.
+ Without a policy, querying this table will return an{' '}
+ <u className="text-foreground">empty array</u> of results.{' '}
+ {isNewRecord ? 'You can create policies after saving this table.' : ''}
+ </>
+ }
+ >
+ <DocsButton
+ abbrev={false}
+ className="mt-2"
+ href={`${DOCS_URL}${docsRowLevelSecurityGuidePath}`}
+ />
+ </Admonition>
+ ) : (
+ <Admonition
+ type="warning"
+ className="!mt-3"
+ title="You are allowing anonymous access to your table"
+ description={
+ <>
+ {tableFields.name ? `The table ${tableFields.name}` : 'Your table'} will be publicly
+ writable and readable
+ </>
+ }
+ >
+ <DocsButton
+ abbrev={false}
+ className="mt-2"
+ href={`${DOCS_URL}${docsRowLevelSecurityGuidePath}`}
/>
+ </Admonition>
+ )}
- {tableFields.isRLSEnabled ? (
- <Admonition
- type="default"
- className="!mt-3"
- title="Policies are required to query data"
- description={
- <>
- You need to create an access policy before you can query data from this table.
- Without a policy, querying this table will return an{' '}
- <u className="text-foreground">empty array</u> of results.{' '}
- {isNewRecord ? 'You can create policies after saving this table.' : ''}
- </>
- }
- >
- <DocsButton
- abbrev={false}
- className="mt-2"
- href={`${DOCS_URL}${docsRowLevelSecurityGuidePath}`}
- />
- </Admonition>
- ) : (
- <Admonition
- type="warning"
- className="!mt-3"
- title="You are allowing anonymous access to your table"
- description={
- <>
- {tableFields.name ? `The table ${tableFields.name}` : 'Your table'} will be
- publicly writable and readable
- </>
- }
- >
- <DocsButton
- abbrev={false}
- className="mt-2"
- href={`${DOCS_URL}${docsRowLevelSecurityGuidePath}`}
- />
- </Admonition>
- )}
-
- {realtimeEnabled && (
- <Checkbox
- id="enable-realtime"
- label="Enable Realtime"
- description="Broadcast changes on this table to authorized subscribers"
- checked={tableFields.isRealtimeEnabled}
- onChange={() => {
- track('realtime_toggle_table_clicked', {
- newState: tableFields.isRealtimeEnabled ? 'disabled' : 'enabled',
- origin: 'tableSidePanel',
- })
- onUpdateField({
- isRealtimeEnabled: !tableFields.isRealtimeEnabled,
- })
- }}
- size="medium"
- />
- )}
- </SidePanel.Content>
+ {realtimeEnabled && (
+ <Checkbox
+ id="enable-realtime"
+ label="Enable Realtime"
+ description="Broadcast changes on this table to authorized subscribers"
+ checked={tableFields.isRealtimeEnabled}
+ onChange={() => {
+ track('realtime_toggle_table_clicked', {
+ newState: tableFields.isRealtimeEnabled ? 'disabled' : 'enabled',
+ origin: 'tableSidePanel',
+ })
+ onUpdateField({
+ isRealtimeEnabled: !tableFields.isRealtimeEnabled,
+ })
+ }}
+ size="medium"
+ />
+ )}
+ </SidePanel.Content>
- <SidePanel.Separator />
- </>
- )}
+ <SidePanel.Separator />
<SidePanel.Content className="space-y-10 py-6">
{!isDuplicating && (
@@ -517,21 +502,19 @@ export const TableEditor = ({
closePanel={() => setIsImportingSpreadsheet(false)}
/>
- {!generatePoliciesEnabled && (
- <ConfirmationModal
- visible={rlsConfirmVisible}
- title="Turn off Row Level Security"
- confirmLabel="Confirm"
- size="medium"
- onCancel={() => setRlsConfirmVisible(false)}
- onConfirm={() => {
- onUpdateField({ isRLSEnabled: !tableFields.isRLSEnabled })
- setRlsConfirmVisible(false)
- }}
- >
- <RLSDisableModalContent />
- </ConfirmationModal>
- )}
+ <ConfirmationModal
+ visible={rlsConfirmVisible}
+ title="Turn off Row Level Security"
+ confirmLabel="Confirm"
+ size="medium"
+ onCancel={() => setRlsConfirmVisible(false)}
+ onConfirm={() => {
+ onUpdateField({ isRLSEnabled: !tableFields.isRLSEnabled })
+ setRlsConfirmVisible(false)
+ }}
+ >
+ <RLSDisableModalContent />
+ </ConfirmationModal>
</SidePanel.Content>
{!isDuplicating && (
@@ -549,37 +532,19 @@ export const TableEditor = ({
</>
)}
- {isApiAccessAndPoliciesSectionShown && (
+ {isApiGrantTogglesEnabled && (
<>
<SidePanel.Separator />
<SidePanel.Content className="py-6 space-y-6">
- {isApiGrantTogglesEnabled && (
- <ApiAccessToggle
- projectRef={project?.ref}
- schemaName={isNewRecord ? selectedSchema : table?.schema}
- tableName={
- isNewRecord || isDuplicating ? tableFields.name : tableFields.name || table?.name
- }
- isNewRecord={isNewRecord || isDuplicating}
- handler={apiAccessToggleHandler}
- />
- )}
-
- {/* [Joshen] Temporarily hide this section if duplicating, as we aren't duplicating policies atm when duplicating tables */}
- {/* We should do this thought, but let's do this in another PR as the current one is already quite big */}
- {generatePoliciesEnabled && !isDuplicating && (
- <RLSManagement
- table={table}
- tableFields={tableFields}
- foreignKeyRelations={isNewRecord ? fkRelations : undefined}
- isNewRecord={isNewRecord}
- isDuplicating={isDuplicating}
- isExposed={isExposed}
- generatedPolicies={generatedPolicies}
- onGeneratedPoliciesChange={setGeneratedPolicies}
- onRLSUpdate={(value) => onUpdateField({ isRLSEnabled: value })}
- />
- )}
+ <ApiAccessToggle
+ projectRef={project?.ref}
+ schemaName={isNewRecord ? selectedSchema : table?.schema}
+ tableName={
+ isNewRecord || isDuplicating ? tableFields.name : tableFields.name || table?.name
+ }
+ isNewRecord={isNewRecord || isDuplicating}
+ handler={apiAccessToggleHandler}
+ />
</SidePanel.Content>
</>
)}
diff --git a/apps/studio/hooks/misc/useTableCreateGeneratePolicies.ts b/apps/studio/hooks/misc/useTableCreateGeneratePolicies.ts
deleted file mode 100644
index fe13743b1d9..00000000000
--- a/apps/studio/hooks/misc/useTableCreateGeneratePolicies.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import dayjs from 'dayjs'
-import utc from 'dayjs/plugin/utc'
-import { useTrackExperimentExposure } from 'hooks/misc/useTrackExperimentExposure'
-import { usePHFlag } from 'hooks/ui/useFlag'
-import { IS_PLATFORM } from 'lib/constants'
-import { useMemo } from 'react'
-
-dayjs.extend(utc)
-
-export type TableCreateGeneratePoliciesVariant = 'control' | 'variation'
-
-const VALID_VARIANTS: TableCreateGeneratePoliciesVariant[] = ['control', 'variation']
-
-export function isValidExperimentVariant(
- value: unknown
-): value is TableCreateGeneratePoliciesVariant {
- return (
- typeof value === 'string' &&
- VALID_VARIANTS.includes(value as TableCreateGeneratePoliciesVariant)
- )
-}
-
-interface UseTableCreateGeneratePoliciesOptions {
- /**
- * Whether this is a new table being created
- */
- isNewRecord?: boolean
- /**
- * Project creation timestamp
- */
- projectInsertedAt?: string
-}
-
-interface UseTableCreateGeneratePoliciesResult {
- /**
- * Whether the generate policies feature is enabled
- */
- enabled: boolean
-}
-
-/**
- * Hook to manage the table create generate policies feature flag.
- * Handles feature flag determination and exposure tracking.
- *
- * @param options Configuration for feature targeting
- * @returns Feature state including whether it's enabled
- */
-export function useTableCreateGeneratePolicies({
- isNewRecord = false,
- projectInsertedAt,
-}: UseTableCreateGeneratePoliciesOptions): UseTableCreateGeneratePoliciesResult {
- const tableCreateGeneratePoliciesFlag = usePHFlag<string>('tableCreateGeneratePolicies')
-
- const enabled = useMemo(() => {
- if (!IS_PLATFORM) return false
- if (tableCreateGeneratePoliciesFlag !== 'variation') return false
- return true
- }, [tableCreateGeneratePoliciesFlag])
-
- const daysSinceCreation = useMemo(() => {
- if (!projectInsertedAt) return undefined
- const insertedDate = dayjs.utc(projectInsertedAt)
- if (!insertedDate.isValid()) return undefined
- return dayjs.utc().diff(insertedDate, 'day')
- }, [projectInsertedAt])
-
- const shouldTrack =
- IS_PLATFORM &&
- isNewRecord &&
- isValidExperimentVariant(tableCreateGeneratePoliciesFlag) &&
- daysSinceCreation !== undefined
-
- useTrackExperimentExposure(
- 'table_create_generate_policies',
- shouldTrack ? tableCreateGeneratePoliciesFlag : undefined,
- { days_since_project_creation: daysSinceCreation }
- )
-
- return {
- enabled,
- }
-}