Skip to content

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

Generate policies experiment (#40881)

Saxon Fletcher9f3af6e5025f
diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.utils.test.ts b/apps/studio/components/interfaces/Auth/Policies/Policies.utils.test.ts
new file mode 100644
index 00000000000..25cebe323bb
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.utils.test.ts
@@ -0,0 +1,451 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
+
+// Mock generateSqlPolicy for AI tests
+const mockGenerateSqlPolicy = vi.fn()
+vi.mock('data/ai/sql-policy-mutation', () => ({
+ generateSqlPolicy: (...args: unknown[]) => mockGenerateSqlPolicy(...args),
+}))
+
+// Import after mocks are set up
+import {
+ generateAiPoliciesForTable,
+ generateProgrammaticPoliciesForTable,
+ generateStartingPoliciesForTable,
+ type GeneratedPolicy,
+} from './Policies.utils'
+
+// Helper to create a foreign key constraint
+const createForeignKey = (overrides: Partial<ForeignKeyConstraint> = {}): ForeignKeyConstraint => ({
+ id: 1,
+ constraint_name: 'fk_constraint',
+ source_id: 100,
+ source_schema: 'public',
+ source_table: 'posts',
+ source_columns: ['user_id'],
+ target_id: 200,
+ target_schema: 'auth',
+ target_table: 'users',
+ target_columns: ['id'],
+ deletion_action: 'NO ACTION',
+ update_action: 'NO ACTION',
+ ...overrides,
+})
+
+describe('Policies.utils - Policy Generation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ describe('generateProgrammaticPoliciesForTable', () => {
+ it('should generate 4 CRUD policies for direct FK to auth.users', () => {
+ const foreignKeyConstraints: ForeignKeyConstraint[] = [
+ createForeignKey({
+ source_schema: 'public',
+ source_table: 'posts',
+ source_columns: ['user_id'],
+ target_schema: 'auth',
+ target_table: 'users',
+ target_columns: ['id'],
+ }),
+ ]
+
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ expect(policies).toHaveLength(4)
+
+ const commands = policies.map((p) => p.command)
+ expect(commands).toContain('SELECT')
+ expect(commands).toContain('INSERT')
+ expect(commands).toContain('UPDATE')
+ expect(commands).toContain('DELETE')
+ })
+
+ it('should return empty array when no FK path to auth.users exists', () => {
+ const foreignKeyConstraints: ForeignKeyConstraint[] = [
+ createForeignKey({
+ source_schema: 'public',
+ source_table: 'posts',
+ source_columns: ['category_id'],
+ target_schema: 'public',
+ target_table: 'categories',
+ target_columns: ['id'],
+ }),
+ ]
+
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ expect(policies).toHaveLength(0)
+ })
+
+ it('should return empty array when foreignKeyConstraints is empty', () => {
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints: [],
+ })
+
+ expect(policies).toHaveLength(0)
+ })
+
+ it('should generate policies with EXISTS clause for indirect FK path (2 hops)', () => {
+ // posts -> profiles -> auth.users
+ const foreignKeyConstraints: ForeignKeyConstraint[] = [
+ createForeignKey({
+ id: 1,
+ source_schema: 'public',
+ source_table: 'posts',
+ source_columns: ['profile_id'],
+ target_schema: 'public',
+ target_table: 'profiles',
+ target_columns: ['id'],
+ }),
+ createForeignKey({
+ id: 2,
+ source_schema: 'public',
+ source_table: 'profiles',
+ source_columns: ['user_id'],
+ target_schema: 'auth',
+ target_table: 'users',
+ target_columns: ['id'],
+ }),
+ ]
+
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ expect(policies).toHaveLength(4)
+
+ // Check that the expression contains EXISTS for indirect path
+ const selectPolicy = policies.find((p) => p.command === 'SELECT')
+ expect(selectPolicy?.definition).toContain('exists')
+ expect(selectPolicy?.sql).toContain('exists')
+ })
+
+ describe('policy structure validation', () => {
+ const foreignKeyConstraints: ForeignKeyConstraint[] = [
+ createForeignKey({
+ source_schema: 'public',
+ source_table: 'posts',
+ source_columns: ['user_id'],
+ target_schema: 'auth',
+ target_table: 'users',
+ target_columns: ['id'],
+ }),
+ ]
+
+ it('should include all required fields in generated policies', () => {
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ for (const policy of policies) {
+ expect(policy).toHaveProperty('name')
+ expect(policy).toHaveProperty('sql')
+ expect(policy).toHaveProperty('command')
+ expect(policy).toHaveProperty('table', 'posts')
+ expect(policy).toHaveProperty('schema', 'public')
+ expect(policy).toHaveProperty('action', 'PERMISSIVE')
+ expect(policy).toHaveProperty('roles')
+ expect(policy.roles).toContain('public')
+ }
+ })
+
+ it('SELECT policy should have definition but no check', () => {
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ const selectPolicy = policies.find((p) => p.command === 'SELECT')
+ expect(selectPolicy?.definition).toBeDefined()
+ expect(selectPolicy?.check).toBeUndefined()
+ })
+
+ it('DELETE policy should have definition but no check', () => {
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ const deletePolicy = policies.find((p) => p.command === 'DELETE')
+ expect(deletePolicy?.definition).toBeDefined()
+ expect(deletePolicy?.check).toBeUndefined()
+ })
+
+ it('INSERT policy should have check but no definition', () => {
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ const insertPolicy = policies.find((p) => p.command === 'INSERT')
+ expect(insertPolicy?.definition).toBeUndefined()
+ expect(insertPolicy?.check).toBeDefined()
+ })
+
+ it('UPDATE policy should have both definition and check', () => {
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ const updatePolicy = policies.find((p) => p.command === 'UPDATE')
+ expect(updatePolicy?.definition).toBeDefined()
+ expect(updatePolicy?.check).toBeDefined()
+ })
+
+ it('should generate correct SQL syntax for direct FK', () => {
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ })
+
+ const selectPolicy = policies.find((p) => p.command === 'SELECT')
+ expect(selectPolicy?.sql).toContain('CREATE POLICY')
+ expect(selectPolicy?.sql).toContain('public.posts')
+ expect(selectPolicy?.sql).toContain('AS PERMISSIVE FOR SELECT')
+ expect(selectPolicy?.sql).toContain('TO public')
+ expect(selectPolicy?.sql).toContain('USING')
+ expect(selectPolicy?.sql).toContain('auth.uid()')
+ })
+ })
+
+ it('should handle non-public schema', () => {
+ const foreignKeyConstraints: ForeignKeyConstraint[] = [
+ createForeignKey({
+ source_schema: 'private',
+ source_table: 'documents',
+ source_columns: ['owner_id'],
+ target_schema: 'auth',
+ target_table: 'users',
+ target_columns: ['id'],
+ }),
+ ]
+
+ const policies = generateProgrammaticPoliciesForTable({
+ table: { name: 'documents', schema: 'private' },
+ foreignKeyConstraints,
+ })
+
+ expect(policies).toHaveLength(4)
+ expect(policies[0].schema).toBe('private')
+ expect(policies[0].sql).toContain('private.documents')
+ })
+ })
+
+ describe('generateAiPoliciesForTable', () => {
+ const mockAiPolicies: GeneratedPolicy[] = [
+ {
+ name: 'ai_select_policy',
+ sql: 'CREATE POLICY "ai_select_policy" ON public.posts FOR SELECT USING (true);',
+ command: 'SELECT',
+ table: 'posts',
+ schema: 'public',
+ definition: 'true',
+ action: 'PERMISSIVE',
+ roles: ['public'],
+ },
+ ]
+
+ it('should return policies from AI when called with valid inputs', async () => {
+ mockGenerateSqlPolicy.mockResolvedValue(mockAiPolicies)
+
+ const policies = await generateAiPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ columns: [{ name: 'id' }, { name: 'title' }],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ })
+
+ expect(mockGenerateSqlPolicy).toHaveBeenCalledWith({
+ tableName: 'posts',
+ schema: 'public',
+ columns: ['id', 'title'],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ })
+ expect(policies).toEqual(mockAiPolicies)
+ })
+
+ it('should return empty array when connectionString is null', async () => {
+ const policies = await generateAiPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ columns: [{ name: 'id' }],
+ projectRef: 'test-project',
+ connectionString: null,
+ })
+
+ expect(mockGenerateSqlPolicy).not.toHaveBeenCalled()
+ expect(policies).toEqual([])
+ })
+
+ it('should return empty array when connectionString is undefined', async () => {
+ const policies = await generateAiPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ columns: [{ name: 'id' }],
+ projectRef: 'test-project',
+ connectionString: undefined,
+ })
+
+ expect(mockGenerateSqlPolicy).not.toHaveBeenCalled()
+ expect(policies).toEqual([])
+ })
+
+ it('should handle API errors gracefully and return empty array', async () => {
+ const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ mockGenerateSqlPolicy.mockRejectedValue(new Error('API error'))
+
+ const policies = await generateAiPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ columns: [{ name: 'id' }],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ })
+
+ expect(policies).toEqual([])
+ expect(consoleLogSpy).toHaveBeenCalledWith('AI policy generation failed:', expect.any(Error))
+
+ consoleLogSpy.mockRestore()
+ })
+
+ it('should trim column names before sending to API', async () => {
+ mockGenerateSqlPolicy.mockResolvedValue([])
+
+ await generateAiPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ columns: [{ name: ' id ' }, { name: ' title ' }],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ })
+
+ expect(mockGenerateSqlPolicy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ columns: ['id', 'title'],
+ })
+ )
+ })
+ })
+
+ describe('generateStartingPoliciesForTable', () => {
+ const mockAiPolicies: GeneratedPolicy[] = [
+ {
+ name: 'ai_policy',
+ sql: 'CREATE POLICY "ai_policy" ON public.posts FOR SELECT USING (true);',
+ command: 'SELECT',
+ table: 'posts',
+ schema: 'public',
+ definition: 'true',
+ action: 'PERMISSIVE',
+ roles: ['public'],
+ },
+ ]
+
+ it('should use programmatic policies when FK path exists (does not call AI)', async () => {
+ const foreignKeyConstraints: ForeignKeyConstraint[] = [
+ createForeignKey({
+ source_schema: 'public',
+ source_table: 'posts',
+ source_columns: ['user_id'],
+ target_schema: 'auth',
+ target_table: 'users',
+ target_columns: ['id'],
+ }),
+ ]
+
+ const policies = await generateStartingPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ columns: [{ name: 'id' }],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ enableAi: true,
+ })
+
+ expect(policies).toHaveLength(4)
+ expect(mockGenerateSqlPolicy).not.toHaveBeenCalled()
+ })
+
+ it('should fall back to AI when no FK path exists and enableAi is true', async () => {
+ mockGenerateSqlPolicy.mockResolvedValue(mockAiPolicies)
+
+ const policies = await generateStartingPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints: [],
+ columns: [{ name: 'id' }],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ enableAi: true,
+ })
+
+ expect(mockGenerateSqlPolicy).toHaveBeenCalled()
+ expect(policies).toEqual(mockAiPolicies)
+ })
+
+ it('should return empty array when no FK path exists and enableAi is false', async () => {
+ const policies = await generateStartingPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints: [],
+ columns: [{ name: 'id' }],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ enableAi: false,
+ })
+
+ expect(mockGenerateSqlPolicy).not.toHaveBeenCalled()
+ expect(policies).toEqual([])
+ })
+
+ it('should return empty array when no FK path and AI returns empty', async () => {
+ mockGenerateSqlPolicy.mockResolvedValue([])
+
+ const policies = await generateStartingPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints: [],
+ columns: [{ name: 'id' }],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ enableAi: true,
+ })
+
+ expect(policies).toEqual([])
+ })
+
+ it('should prioritize programmatic over AI even when both could generate policies', async () => {
+ mockGenerateSqlPolicy.mockResolvedValue(mockAiPolicies)
+
+ const foreignKeyConstraints: ForeignKeyConstraint[] = [
+ createForeignKey({
+ source_schema: 'public',
+ source_table: 'posts',
+ source_columns: ['user_id'],
+ target_schema: 'auth',
+ target_table: 'users',
+ target_columns: ['id'],
+ }),
+ ]
+
+ const policies = await generateStartingPoliciesForTable({
+ table: { name: 'posts', schema: 'public' },
+ foreignKeyConstraints,
+ columns: [{ name: 'id' }],
+ projectRef: 'test-project',
+ connectionString: 'postgresql://localhost:5432/test',
+ enableAi: true,
+ })
+
+ // Should return 4 programmatic policies, not 1 AI policy
+ expect(policies).toHaveLength(4)
+ expect(mockGenerateSqlPolicy).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.utils.ts b/apps/studio/components/interfaces/Auth/Policies/Policies.utils.ts
index ebfcc71f43e..128668a8d71 100644
--- a/apps/studio/components/interfaces/Auth/Policies/Policies.utils.ts
+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.utils.ts
@@ -1,5 +1,10 @@
import type { PostgresPolicy } from '@supabase/postgres-meta'
import { has, isEmpty, isEqual } from 'lodash'
+
+import { ident } from '@supabase/pg-meta/src/pg-format'
+import { generateSqlPolicy } from 'data/ai/sql-policy-mutation'
+import type { CreatePolicyBody } from 'data/database-policies/database-policy-create-mutation'
+import type { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import {
PolicyFormField,
PolicyForReview,
@@ -73,7 +78,7 @@ const createSQLStatementForCreatePolicy = (policyFormFields: PolicyFormField): P
return { description, statement }
}
-export const createSQLStatementForUpdatePolicy = (
+const createSQLStatementForUpdatePolicy = (
policyFormFields: PolicyFormField,
fieldsToUpdate: Partial<PolicyFormField>
): PolicyForReview => {
@@ -151,3 +156,287 @@ export const createPayloadForUpdatePolicy = (
return payload
}
+
+// --- Policy Generation ---
+
+/**
+ * Generated policy extends CreatePolicyBody with additional fields for display.
+ * - sql: Full CREATE POLICY SQL statement for preview
+ * - Required fields that are optional in CreatePolicyBody
+ */
+export type GeneratedPolicy = Required<
+ Pick<CreatePolicyBody, 'name' | 'table' | 'schema' | 'action' | 'roles'>
+> &
+ Pick<CreatePolicyBody, 'command' | 'definition' | 'check'> & {
+ sql: string
+ }
+
+type Relationship = {
+ source_schema: string
+ source_table_name: string
+ source_column_name: string
+ target_table_schema: string
+ target_table_name: string
+ target_column_name: string
+}
+
+/**
+ * Gets relationships for a specific table from FK constraints.
+ * Returns relationships where the table is the source.
+ */
+const getRelationshipsForTable = ({
+ schema,
+ table,
+ fkConstraints,
+}: {
+ schema: string
+ table: string
+ fkConstraints: ForeignKeyConstraint[]
+}): Relationship[] => {
+ return fkConstraints
+ .filter((fk) => fk.source_schema === schema && fk.source_table === table)
+ .flatMap((fk) =>
+ fk.source_columns.map((sourceCol, i) => ({
+ source_schema: fk.source_schema,
+ source_table_name: fk.source_table,
+ source_column_name: sourceCol,
+ target_table_schema: fk.target_schema,
+ target_table_name: fk.target_table,
+ target_column_name: fk.target_columns[i],
+ }))
+ )
+}
+
+/**
+ * BFS to find shortest path from table to auth.users via foreign key relationships.
+ * Returns null if no path exists within maxDepth.
+ */
+const findPathToAuthUsers = (
+ startTable: { schema: string; name: string },
+ allForeignKeyConstraints: ForeignKeyConstraint[],
+ maxDepth = 3
+): Relationship[] | null => {
+ const startRelationships = getRelationshipsForTable({
+ schema: startTable.schema,
+ table: startTable.name,
+ fkConstraints: allForeignKeyConstraints,
+ })
+
+ const queue: { table: { schema: string; name: string }; path: Relationship[] }[] = [
+ { table: startTable, path: [] },
+ ]
+ const visited = new Set<string>()
+ visited.add(`${startTable.schema}.${startTable.name}`)
+
+ while (queue.length > 0) {
+ const queueItem = queue.shift()
+ if (!queueItem) continue
+
+ const { table, path } = queueItem
+ if (path.length >= maxDepth) continue
+
+ const relationships =
+ path.length === 0
+ ? startRelationships
+ : getRelationshipsForTable({
+ schema: table.schema,
+ table: table.name,
+ fkConstraints: allForeignKeyConstraints,
+ })
+
+ for (const rel of relationships) {
+ // Found path to auth.users
+ if (
+ rel.target_table_schema === 'auth' &&
+ rel.target_table_name === 'users' &&
+ rel.target_column_name === 'id'
+ ) {
+ return [...path, rel]
+ }
+
+ const targetId = `${rel.target_table_schema}.${rel.target_table_name}`
+ if (visited.has(targetId)) continue
+
+ // Add target table to queue for further exploration
+ queue.push({
+ table: { schema: rel.target_table_schema, name: rel.target_table_name },
+ path: [...path, rel],
+ })
+ visited.add(targetId)
+ }
+ }
+
+ return null
+}
+
+/** Generates SQL expression for RLS policy based on FK path to auth.users */
+const buildPolicyExpression = (path: Relationship[]): string => {
+ if (path.length === 0) return ''
+
+ // Direct FK to auth.users
+ if (path.length === 1) {
+ return `(select auth.uid()) = ${ident(path[0].source_column_name)}`
+ }
+
+ // Indirect path - build EXISTS with JOINs
+ const [first, ...rest] = path
+ const firstTarget = `${ident(first.target_table_schema)}.${ident(first.target_table_name)}`
+ const source = `${ident(first.source_schema)}.${ident(first.source_table_name)}`
+ const last = path[path.length - 1]
+
+ const joins = rest
+ .slice(0, -1)
+ .map((r) => {
+ const targetSchema = ident(r.target_table_schema)
+ const targetTable = ident(r.target_table_name)
+ const targetColumn = ident(r.target_column_name)
+
+ const sourceSchema = ident(r.source_schema)
+ const sourceTable = ident(r.source_table_name)
+ const sourceColumn = ident(r.source_column_name)
+ return `join ${targetSchema}.${targetTable} on ${targetSchema}.${targetTable}.${targetColumn} = ${sourceSchema}.${sourceTable}.${sourceColumn}`
+ })
+ .join('\n ')
+
+ return `exists (
+ select 1 from ${firstTarget}
+ ${joins}
+ where ${firstTarget}.${ident(first.target_column_name)} = ${source}.${ident(first.source_column_name)}
+ and ${ident(last.source_schema)}.${ident(last.source_table_name)}.${ident(last.source_column_name)} = (select auth.uid())
+)`
+}
+
+/** Builds policy SQL for all CRUD operations */
+const buildPoliciesForPath = (
+ table: { name: string; schema: string },
+ path: Relationship[]
+): GeneratedPolicy[] => {
+ const expression = buildPolicyExpression(path)
+ const targetCol = path[0].source_column_name
+
+ return (['SELECT', 'INSERT', 'UPDATE', 'DELETE'] as const).map((command) => {
+ const name = `Enable ${command.toLowerCase()} access for users based on ${ident(targetCol)}`
+ const base = `CREATE POLICY "${name}" ON ${ident(table.schema)}.${ident(table.name)} AS PERMISSIVE FOR ${command} TO public`
+
+ const sql =
+ command === 'INSERT'
+ ? `${base} WITH CHECK (${expression});`
+ : command === 'UPDATE'
+ ? `${base} USING (${expression}) WITH CHECK (${expression});`
+ : `${base} USING (${expression});`
+
+ // Structured data for mutation API
+ const definition = command === 'INSERT' ? undefined : expression
+ const check = command === 'SELECT' || command === 'DELETE' ? undefined : expression
+
+ return {
+ name,
+ sql,
+ command,
+ table: table.name,
+ schema: table.schema,
+ definition,
+ check,
+ action: 'PERMISSIVE' as const,
+ roles: ['public'],
+ }
+ })
+}
+
+/**
+ * Generates RLS policies programmatically based on FK relationships to auth.users.
+ */
+export const generateProgrammaticPoliciesForTable = ({
+ table,
+ foreignKeyConstraints,
+}: {
+ table: { name: string; schema: string }
+ foreignKeyConstraints: ForeignKeyConstraint[]
+}): GeneratedPolicy[] => {
+ try {
+ const path = findPathToAuthUsers(table, foreignKeyConstraints)
+
+ if (path?.length) {
+ return buildPoliciesForPath(table, path)
+ }
+ } catch (error) {
+ // Silently fail - caller will handle empty result
+ }
+
+ return []
+}
+
+/**
+ * Generates RLS policies using AI.
+ */
+export const generateAiPoliciesForTable = async ({
+ table,
+ columns,
+ projectRef,
+ connectionString,
+}: {
+ table: { name: string; schema: string }
+ columns: { name: string }[]
+ projectRef: string
+ connectionString?: string | null
+}): Promise<GeneratedPolicy[]> => {
+ if (!connectionString) return []
+
+ try {
+ const aiPolicies = await generateSqlPolicy({
+ tableName: table.name,
+ schema: table.schema,
+ columns: columns.map((col) => col.name.trim()),
+ projectRef,
+ connectionString: connectionString ?? '',
+ })
+ // AI response now includes all structured fields
+ return aiPolicies as GeneratedPolicy[]
+ } catch (error) {
+ console.log('AI policy generation failed:', error)
+ return []
+ }
+}
+
+/**
+ * Generates RLS policies for a table.
+ * First tries programmatic generation based on FK relationships to auth.users.
+ * Falls back to AI generation if no path exists.
+ */
+export const generateStartingPoliciesForTable = async ({
+ table,
+ foreignKeyConstraints,
+ columns,
+ projectRef,
+ connectionString,
+ enableAi,
+}: {
+ table: { name: string; schema: string }
+ foreignKeyConstraints: ForeignKeyConstraint[]
+ columns: { name: string }[]
+ projectRef: string
+ connectionString?: string | null
+ enableAi: boolean
+}): Promise<GeneratedPolicy[]> => {
+ // Try programmatic generation first
+ const programmaticPolicies = generateProgrammaticPoliciesForTable({
+ table,
+ foreignKeyConstraints,
+ })
+
+ if (programmaticPolicies.length > 0) {
+ return programmaticPolicies
+ }
+
+ // Fall back to AI generation
+ if (enableAi) {
+ return await generateAiPoliciesForTable({
+ table,
+ columns,
+ projectRef,
+ connectionString,
+ })
+ }
+
+ return []
+}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 12d2f525bc2..80a1ba852d5 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -5,6 +5,9 @@ import { useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
+import { type GeneratedPolicy } from 'components/interfaces/Auth/Policies/Policies.utils'
+import { useDatabasePolicyCreateMutation } from 'data/database-policies/database-policy-create-mutation'
+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'
import { useDatabasePublicationUpdateMutation } from 'data/database-publications/database-publications-update-mutation'
@@ -24,6 +27,7 @@ import { getTables } from 'data/tables/tables-query'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useConfirmOnClose, type ConfirmOnCloseModalProps } from 'hooks/ui/useConfirmOnClose'
+import { usePHFlag } from 'hooks/ui/useFlag'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useTrack } from 'lib/telemetry/track'
import { useGetImpersonatedRoleState } from 'state/role-impersonation-state'
@@ -64,6 +68,7 @@ type SaveTableParamsBase = {
columns: ColumnField[]
foreignKeyRelations: ForeignKey[]
resolve: () => void
+ generatedPolicies?: GeneratedPolicy[]
}
type SaveTableParamsNew = SaveTableParamsBase & {
@@ -130,13 +135,20 @@ export const SidePanelEditor = ({
const tabsSnap = useTabsStateSnapshot()
const [_, setParams] = useUrlState({ arrayKeys: ['filter', 'sort'] })
+ const track = useTrack()
const queryClient = useQueryClient()
const { data: project } = useSelectedProjectQuery()
const { data: org } = useSelectedOrganizationQuery()
- const track = useTrack()
+ const getImpersonatedRoleState = useGetImpersonatedRoleState()
+ const generatePoliciesFlag = usePHFlag<boolean>('tableCreateGeneratePolicies')
const [isEdited, setIsEdited] = useState<boolean>(false)
+ const { data: publications } = useDatabasePublicationsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
const { confirmOnClose, modalProps: closeConfirmationModalProps } = useConfirmOnClose({
checkIsDirty: () => isEdited,
onClose: () => {
@@ -161,16 +173,13 @@ export const SidePanelEditor = ({
toast.success('Successfully updated row')
},
})
- const { data: publications } = useDatabasePublicationsQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- })
const { mutateAsync: createPublication } = useDatabasePublicationCreateMutation()
const { mutateAsync: updatePublication } = useDatabasePublicationUpdateMutation({
onError: () => {},
})
-
- const getImpersonatedRoleState = useGetImpersonatedRoleState()
+ const { mutateAsync: createPolicy } = useDatabasePolicyCreateMutation({
+ onError: () => {}, // Errors handled inline
+ })
const isDuplicating = snap.sidePanel?.type === 'table' && snap.sidePanel.mode === 'duplicate'
@@ -472,13 +481,18 @@ export const SidePanelEditor = ({
}
}
- const saveTable = async (params: SaveTableParams) => {
- // action and payload are not destructured here to preserve type
- // narrowing later on
- const { configuration, columns, foreignKeyRelations, resolve } = params
-
+ const saveTable = async ({
+ action,
+ payload,
+ configuration,
+ columns,
+ foreignKeyRelations,
+ generatedPolicies = [],
+ resolve,
+ }: SaveTableParams) => {
let toastId
let saveTableError = false
+
const {
importContent,
isRLSEnabled,
@@ -489,46 +503,75 @@ export const SidePanelEditor = ({
} = configuration
try {
- if (params.action === 'create') {
- toastId = toast.loading(`Creating new table: ${params.payload.name}...`)
+ if (action === 'create') {
+ toastId = toast.loading(`Creating new table: ${payload.name}...`)
- const table = await createTable({
+ const { table, failedPolicies } = await createTable({
projectRef: project?.ref!,
connectionString: project?.connectionString,
toastId,
- payload: params.payload,
+ payload,
columns,
foreignKeyRelations,
isRLSEnabled,
importContent,
organizationSlug: org?.slug,
+ generatedPolicies,
+ onCreatePoliciesSuccess: () => track('rls_generated_policies_created'),
})
+
if (isRealtimeEnabled) await updateTableRealtime(table, true)
+ // Invalidate queries for table creation
await Promise.all([
queryClient.invalidateQueries({
queryKey: tableKeys.list(project?.ref, table.schema, includeColumns),
}),
queryClient.invalidateQueries({ queryKey: entityTypeKeys.list(project?.ref) }),
+ queryClient.invalidateQueries({ queryKey: databasePoliciesKeys.list(project?.ref) }),
])
- toast.success(`Table ${table.name} is good to go!`, { id: toastId })
+ // Show success toast after everything is complete
+ if (failedPolicies.length > 0) {
+ toast.success(
+ `Table ${table.name} is created successfully, but we ran into issues creating ${failedPolicies.length} policie${failedPolicies.length > 1 ? 's' : ''}`,
+ {
+ id: toastId,
+ description: (
+ <ul className="list-disc pl-6">
+ {failedPolicies.map((x) => (
+ <li key={x.name}>{x.name}</li>
+ ))}
+ </ul>
+ ),
+ }
+ )
+ } else {
+ toast.success(`Table ${table.name} is good to go!`, { id: toastId })
+ }
+
+ // Track experiment conversion if user is in the experiment
+ if (generatePoliciesFlag !== undefined) {
+ track('table_create_generate_policies_experiment_converted', {
+ experiment_id: 'tableCreateGeneratePolicies',
+ variant: generatePoliciesFlag ? 'treatment' : 'control',
+ has_rls_enabled: isRLSEnabled,
+ has_rls_policies: generatedPolicies.length > 0,
+ has_generated_policies: generatedPolicies.length > 0,
+ })
+ }
+
onTableCreated(table)
- } else if (params.action === 'duplicate' && !!selectedTable) {
+ } else if (action === 'duplicate' && !!selectedTable) {
const tableToDuplicate = selectedTable
toastId = toast.loading(`Duplicating table: ${tableToDuplicate.name}...`)
- const table = await duplicateTable(
- project?.ref!,
- project?.connectionString,
- params.payload,
- {
- isRLSEnabled,
- isDuplicateRows,
- duplicateTable: tableToDuplicate,
- foreignKeyRelations,
- }
- )
+ const table = await duplicateTable(project?.ref!, project?.connectionString, payload, {
+ isRLSEnabled,
+ isDuplicateRows,
+ duplicateTable: tableToDuplicate,
+ foreignKeyRelations,
+ })
if (isRealtimeEnabled) await updateTableRealtime(table, isRealtimeEnabled)
await Promise.all([
@@ -543,7 +586,7 @@ export const SidePanelEditor = ({
{ id: toastId }
)
onTableCreated(table)
- } else if (params.action === 'update' && selectedTable) {
+ } else if (action === 'update' && selectedTable) {
toastId = toast.loading(`Updating table: ${selectedTable.name}...`)
const { table, hasError } = await updateTable({
@@ -551,7 +594,7 @@ export const SidePanelEditor = ({
connectionString: project?.connectionString,
toastId,
table: selectedTable,
- payload: params.payload,
+ payload,
columns,
foreignKeyRelations,
existingForeignKeyRelations,
@@ -571,10 +614,10 @@ export const SidePanelEditor = ({
`Table ${table.name} has been updated but there were some errors. Please check these errors separately.`
)
} else {
- if (ref && params.payload.name) {
+ if (ref && payload.name) {
// [Joshen] Only table entities can be updated via the dashboard
const tabId = createTabId(ENTITY_TYPE.TABLE, { id: selectedTable.id })
- tabsSnap.updateTab(tabId, { label: params.payload.name })
+ tabsSnap.updateTab(tabId, { label: payload.name })
}
toast.success(`Successfully updated ${table.name}!`, { id: toastId })
}
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 9041b931c92..1c09396321b 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
@@ -141,6 +141,7 @@ describe('createTable', () => {
event: {
action: 'table_created',
properties: {
+ has_generated_policies: false,
method: 'table_editor',
schema_name: 'public',
table_name: 'test_table',
@@ -160,7 +161,10 @@ describe('createTable', () => {
})
)
- expect(result).toStrictEqual(mockTableResult)
+ expect(result).toStrictEqual({
+ failedPolicies: [],
+ table: mockTableResult,
+ })
})
it('should create a table with RLS enabled', async () => {
@@ -355,7 +359,10 @@ describe('createTable', () => {
isRLSEnabled: false,
})
- expect(result).toStrictEqual(mockTableResult)
+ expect(result).toStrictEqual({
+ failedPolicies: [],
+ table: mockTableResult,
+ })
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Failed to track table creation event:',
expect.any(Error)
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index 675c64b1223..54a4831deaf 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -5,10 +5,12 @@ import Papa from 'papaparse'
import { toast } from 'sonner'
import { Query } from '@supabase/pg-meta/src/query'
+import { GeneratedPolicy } from 'components/interfaces/Auth/Policies/Policies.utils'
import SparkBar from 'components/ui/SparkBar'
import { createDatabaseColumn } from 'data/database-columns/database-column-create-mutation'
import { deleteDatabaseColumn } from 'data/database-columns/database-column-delete-mutation'
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'
@@ -496,6 +498,8 @@ export const createTable = async ({
isRLSEnabled,
importContent,
organizationSlug,
+ generatedPolicies = [],
+ onCreatePoliciesSuccess,
}: {
projectRef: string
connectionString?: string | null
@@ -510,6 +514,8 @@ export const createTable = async ({
isRLSEnabled: boolean
importContent?: ImportContent
organizationSlug?: string
+ generatedPolicies?: GeneratedPolicy[]
+ onCreatePoliciesSuccess?: () => void
}) => {
const queryClient = getQueryClient()
@@ -583,6 +589,39 @@ export const createTable = async ({
queryKey: ['table', 'create-with-columns'],
})
+ // 6. Create generated RLS policies if any
+ // [Joshen] Possible area for optimization to create all policies in a single query call
+ // Can be subsequently added to the table creation SQL as well for a single transaction
+
+ const failedPolicies: GeneratedPolicy[] = []
+ if (generatedPolicies.length > 0 && isRLSEnabled) {
+ toast.loading(`Creating ${generatedPolicies.length} policies for table...`, { id: toastId })
+ await Promise.all(
+ generatedPolicies.map(async (policy) => {
+ try {
+ return await createDatabasePolicy({
+ projectRef,
+ connectionString,
+ payload: {
+ name: policy.name,
+ table: policy.table,
+ schema: policy.schema,
+ definition: policy.definition,
+ check: policy.check,
+ action: policy.action,
+ command: policy.command,
+ roles: policy.roles,
+ },
+ })
+ } catch (error: any) {
+ console.error('Failed to generate policy', error.message)
+ failedPolicies.push(policy)
+ }
+ })
+ )
+ onCreatePoliciesSuccess?.()
+ }
+
// Track table creation event (fire-and-forget to avoid blocking)
sendEvent({
event: {
@@ -591,6 +630,7 @@ export const createTable = async ({
method: 'table_editor',
schema_name: payload.schema,
table_name: payload.name,
+ has_generated_policies: generatedPolicies.length > 0 && isRLSEnabled,
},
groups: {
project: projectRef,
@@ -681,7 +721,6 @@ export const createTable = async ({
type="horizontal"
barClass="bg-brand"
labelBottom={`Adding ${importContent.rows.length.toLocaleString()} rows to ${table.name}`}
- labelBottomClass=""
labelTop={`${progress.toFixed(2)}%`}
labelTopClass="tabular-nums"
/>
@@ -721,7 +760,7 @@ export const createTable = async ({
})
// Finally, return the created table
- return table
+ return { table, failedPolicies }
}
/** TODO: Refactor to do in a single transaction */
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSDisableModal.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSDisableModal.tsx
index b9f18ae1d18..abc9c488d59 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSDisableModal.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSDisableModal.tsx
@@ -5,7 +5,7 @@ import { useCustomContent } from 'hooks/custom-content/useCustomContent'
import { DOCS_URL } from 'lib/constants'
import { Alert } from 'ui'
-export default function RLSDisableModalContent() {
+export function RLSDisableModalContent() {
const { docsRowLevelSecurityGuidePath } = useCustomContent(['docs:row_level_security_guide_path'])
return (
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyList.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyList.tsx
new file mode 100644
index 00000000000..f40562843e8
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyList.tsx
@@ -0,0 +1,105 @@
+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
new file mode 100644
index 00000000000..4477cc88d23
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/PolicyListEmptyState.tsx
@@ -0,0 +1,242 @@
+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
new file mode 100644
index 00000000000..278d455c5d3
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/RLSManagement.tsx
@@ -0,0 +1,200 @@
+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
+ generatedPolicies?: GeneratedPolicy[]
+ onRLSUpdate?: (isEnabled: boolean) => void
+ onGeneratedPoliciesChange?: (policies: GeneratedPolicy[]) => void
+}
+
+export const RLSManagement = ({
+ table,
+ tableFields,
+ foreignKeyRelations = [],
+ isNewRecord,
+ isDuplicating,
+ 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 ? '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
new file mode 100644
index 00000000000..41ed4a52835
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/RLSManagement/ToggleRLSButton.tsx
@@ -0,0 +1,70 @@
+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 0533e95c1ba..66c325dd7c4 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -1,8 +1,9 @@
import type { PostgresTable } from '@supabase/postgres-meta'
-import { isEmpty, isUndefined, noop } from 'lodash'
+import { isEmpty, noop } from 'lodash'
import { useContext, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
+import type { GeneratedPolicy } from 'components/interfaces/Auth/Policies/Policies.utils'
import { DocsButton } from 'components/ui/DocsButton'
import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'
import { CONSTRAINT_TYPE, useTableConstraintsQuery } from 'data/database/constraints-query'
@@ -14,6 +15,7 @@ import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { RealtimeButtonVariant, useRealtimeExperiment } from 'hooks/misc/useRealtimeExperiment'
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'
@@ -32,7 +34,8 @@ import { SpreadsheetImport } from '../SpreadsheetImport/SpreadsheetImport'
import ColumnManagement from './ColumnManagement'
import { ForeignKeysManagement } from './ForeignKeysManagement/ForeignKeysManagement'
import { HeaderTitle } from './HeaderTitle'
-import RLSDisableModalContent from './RLSDisableModal'
+import { RLSDisableModalContent } from './RLSDisableModal'
+import { RLSManagement } from './RLSManagement/RLSManagement'
import { DEFAULT_COLUMNS } from './TableEditor.constants'
import type { ImportContent, TableField } from './TableEditor.types'
import {
@@ -69,24 +72,34 @@ export const TableEditor = ({
saveChanges = noop,
updateEditorDirty = noop,
}: TableEditorProps) => {
- const tableEditorApi = useContext(TableEditorStateContext)
+ const track = useTrack()
const snap = useTableEditorStateSnapshot()
+ const tableEditorApi = useContext(TableEditorStateContext)
+ const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])
+ const { docsRowLevelSecurityGuidePath } = useCustomContent(['docs:row_level_security_guide_path'])
+ const [params, setParams] = useUrlState()
const { data: project } = useSelectedProjectQuery()
const { selectedSchema } = useQuerySchemaState()
- const isNewRecord = isUndefined(table)
- const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])
- const track = useTrack()
- const { docsRowLevelSecurityGuidePath } = useCustomContent(['docs:row_level_security_guide_path'])
+ const isNewRecord = table === undefined
+ const visibleChanged = useChanged(visible)
- const [params, setParams] = useUrlState()
- useEffect(() => {
- if (params.create === 'table' && snap.ui.open === 'none') {
- tableEditorApi.onAddTable()
- setParams({ ...params, create: undefined })
- }
- }, [tableEditorApi, setParams, snap.ui.open, params])
+ const [errors, setErrors] = useState<PlainObject>({})
+ const [tableFields, setTableFields] = useState<TableField>()
+ const [fkRelations, setFkRelations] = useState<ForeignKey[]>([])
+
+ const [isDuplicateRows, setIsDuplicateRows] = useState<boolean>(false)
+ const [importContent, setImportContent] = useState<ImportContent>()
+ 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,
@@ -115,15 +128,6 @@ export const TableEditor = ({
isRealtimeEnabled,
})
- const [errors, setErrors] = useState<PlainObject>({})
- const [tableFields, setTableFields] = useState<TableField>()
- const [fkRelations, setFkRelations] = useState<ForeignKey[]>([])
-
- const [isDuplicateRows, setIsDuplicateRows] = useState<boolean>(false)
- const [importContent, setImportContent] = useState<ImportContent>()
- const [isImportingSpreadsheet, setIsImportingSpreadsheet] = useState<boolean>(false)
- const [rlsConfirmVisible, setRlsConfirmVisible] = useState<boolean>(false)
-
const { data: constraints } = useTableConstraintsQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
@@ -134,11 +138,16 @@ export const TableEditor = ({
)
const { data: foreignKeyMeta, isSuccess: isSuccessForeignKeyMeta } =
- useForeignKeyConstraintsQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- schema: table?.schema,
- })
+ useForeignKeyConstraintsQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: table?.schema,
+ },
+ {
+ enabled: !isNewRecord && !!table?.schema,
+ }
+ )
const foreignKeys = useMemo(
() =>
(foreignKeyMeta ?? []).filter(
@@ -186,15 +195,11 @@ export const TableEditor = ({
setFkRelations(relations)
}
- const onSaveChanges = (resolve: () => void) => {
+ const onSaveChanges = async (resolve: () => void) => {
if (tableFields) {
const errors = validateFields(tableFields)
- if (errors.name) {
- toast.error(errors.name)
- }
- if (errors.columns) {
- toast.error(errors.columns)
- }
+ if (errors.name) toast.error(errors.name)
+ if (errors.columns) toast.error(errors.columns)
setErrors(errors)
const isNameChanged = tableFields.name.trim() !== table?.name
@@ -228,6 +233,7 @@ export const TableEditor = ({
columns,
foreignKeyRelations: fkRelations,
resolve,
+ generatedPolicies,
})
} else if (isDuplicating) {
const payload: SaveTablePayloadFor<'duplicate'> = {
@@ -241,6 +247,7 @@ export const TableEditor = ({
columns,
foreignKeyRelations: fkRelations,
resolve,
+ generatedPolicies: [],
})
} else {
const payload: SaveTablePayloadFor<'update'> = {
@@ -255,6 +262,7 @@ export const TableEditor = ({
columns,
foreignKeyRelations: fkRelations,
resolve,
+ generatedPolicies: [],
})
}
} else {
@@ -263,12 +271,19 @@ export const TableEditor = ({
}
}
- const visibleChanged = useChanged(visible)
+ useEffect(() => {
+ if (params.create === 'table' && snap.ui.open === 'none') {
+ tableEditorApi.onAddTable()
+ setParams({ ...params, create: undefined })
+ }
+ }, [tableEditorApi, setParams, snap.ui.open, params])
+
useEffect(() => {
if (visibleChanged && visible) {
setErrors({})
setImportContent(undefined)
setIsDuplicateRows(false)
+ setGeneratedPolicies([])
if (isNewRecord) {
const tableFields = generateTableField()
if (templateData) {
@@ -362,88 +377,96 @@ export const TableEditor = ({
onChange={(event: any) => onUpdateField({ comment: event.target.value })}
/>
</SidePanel.Content>
+
<SidePanel.Separator />
- <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}`}
+ {!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"
/>
- </Admonition>
- )}
- {activeRealtimeVariant !== RealtimeButtonVariant.HIDE_BUTTON && 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>
+ {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>
+ )}
+
+ {activeRealtimeVariant !== RealtimeButtonVariant.HIDE_BUTTON && 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 && (
@@ -487,19 +510,21 @@ export const TableEditor = ({
closePanel={() => setIsImportingSpreadsheet(false)}
/>
- <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>
+ {!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>
+ )}
</SidePanel.Content>
{!isDuplicating && (
@@ -516,6 +541,26 @@ export const TableEditor = ({
</SidePanel.Content>
</>
)}
+
+ {/* [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 && (
+ <>
+ <SidePanel.Separator />
+ <SidePanel.Content className="space-y-10 py-6">
+ <RLSManagement
+ table={table}
+ tableFields={tableFields}
+ foreignKeyRelations={isNewRecord ? fkRelations : undefined}
+ isNewRecord={isNewRecord}
+ isDuplicating={isDuplicating}
+ generatedPolicies={generatedPolicies}
+ onGeneratedPoliciesChange={setGeneratedPolicies}
+ onRLSUpdate={(value) => onUpdateField({ isRLSEnabled: value })}
+ />
+ </SidePanel.Content>
+ </>
+ )}
</SidePanel>
)
}
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIOptInModal.tsx b/apps/studio/components/ui/AIAssistantPanel/AIOptInModal.tsx
index 70f7a913602..d539c9eba1a 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIOptInModal.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIOptInModal.tsx
@@ -43,7 +43,7 @@ export const AIOptInModal = ({ visible, onCancel }: AIOptInModalProps) => {
return (
<Dialog open={visible} onOpenChange={onOpenChange}>
- <DialogContent size="large">
+ <DialogContent size="large" aria-describedby={undefined}>
<Form_Shadcn_ {...form}>
<form id="ai-opt-in-form" onSubmit={form.handleSubmit(onSubmit)}>
<DialogHeader padding="small">
diff --git a/apps/studio/data/ai/sql-policy-mutation.ts b/apps/studio/data/ai/sql-policy-mutation.ts
new file mode 100644
index 00000000000..fde77f775cb
--- /dev/null
+++ b/apps/studio/data/ai/sql-policy-mutation.ts
@@ -0,0 +1,76 @@
+import { useMutation } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import type { CreatePolicyBody } from 'data/database-policies/database-policy-create-mutation'
+import { fetchPost } from 'data/fetchers'
+import { BASE_PATH } from 'lib/constants'
+import { ResponseError, UseCustomMutationOptions } from 'types'
+
+export type SqlPolicyGenerateVariables = {
+ tableName: string
+ schema?: string
+ columns?: string[]
+ projectRef: string
+ connectionString: string
+ orgSlug?: string
+ message?: string
+}
+
+/**
+ * AI-generated policy response extends CreatePolicyBody with required fields and sql for display.
+ */
+export type SqlPolicyGenerateResponse = (Required<
+ Pick<CreatePolicyBody, 'name' | 'table' | 'schema' | 'action' | 'roles'>
+> &
+ Pick<CreatePolicyBody, 'command' | 'definition' | 'check'> & {
+ sql: string
+ })[]
+
+export async function generateSqlPolicy({
+ tableName,
+ schema,
+ columns,
+ projectRef,
+ connectionString,
+ orgSlug,
+ message,
+}: SqlPolicyGenerateVariables): Promise<SqlPolicyGenerateResponse> {
+ const result = await fetchPost<SqlPolicyGenerateResponse>(`${BASE_PATH}/api/ai/sql/policy`, {
+ tableName,
+ schema,
+ columns,
+ projectRef,
+ connectionString,
+ orgSlug,
+ message,
+ })
+
+ if ('error' in result) throw new ResponseError((result.error as any).message, 400)
+ return result as SqlPolicyGenerateResponse
+}
+
+type SqlPolicyGenerateData = Awaited<ReturnType<typeof generateSqlPolicy>>
+
+export const useSqlPolicyGenerateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<SqlPolicyGenerateData, ResponseError, SqlPolicyGenerateVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<SqlPolicyGenerateResponse, ResponseError, SqlPolicyGenerateVariables>({
+ mutationFn: (vars) => generateSqlPolicy(vars),
+ async onSuccess(data, variables, context) {
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to generate policy: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/database-policies/database-policy-create-mutation.ts b/apps/studio/data/database-policies/database-policy-create-mutation.ts
index b1012f086e1..a952aeda8f0 100644
--- a/apps/studio/data/database-policies/database-policy-create-mutation.ts
+++ b/apps/studio/data/database-policies/database-policy-create-mutation.ts
@@ -6,7 +6,7 @@ import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError, UseCustomMutationOptions } from 'types'
import { databasePoliciesKeys } from './keys'
-type CreatePolicyBody = {
+export type CreatePolicyBody = {
name: string
table: string
schema?: string
diff --git a/apps/studio/data/database/foreign-key-constraints-query.ts b/apps/studio/data/database/foreign-key-constraints-query.ts
index 8494a43e82e..797d09ffd20 100644
--- a/apps/studio/data/database/foreign-key-constraints-query.ts
+++ b/apps/studio/data/database/foreign-key-constraints-query.ts
@@ -1,8 +1,8 @@
import { QueryClient, useQuery } from '@tanstack/react-query'
+import { UseCustomQueryOptions } from 'types'
import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'
import { databaseKeys } from './keys'
-import { UseCustomQueryOptions } from 'types'
type GetForeignKeyConstraintsVariables = {
schema?: string
@@ -39,9 +39,7 @@ export type ForeignKeyConstraint = {
}
export const getForeignKeyConstraintsSql = ({ schema }: GetForeignKeyConstraintsVariables) => {
- if (!schema) {
- throw new Error('schema is required')
- }
+ if (!schema) throw new Error('schema is required')
const sql = /* SQL */ `
SELECT
@@ -139,7 +137,11 @@ export const useForeignKeyConstraintsQuery = <TData = ForeignKeyConstraintsData>
queryKey: databaseKeys.foreignKeyConstraints(projectRef, schema),
queryFn: ({ signal }) =>
getForeignKeyConstraints({ projectRef, connectionString, schema }, signal),
- enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined',
+ enabled:
+ enabled &&
+ typeof projectRef !== 'undefined' &&
+ typeof schema !== 'undefined' &&
+ schema.length > 0,
...options,
})
diff --git a/apps/studio/hooks/misc/useTableCreateGeneratePolicies.ts b/apps/studio/hooks/misc/useTableCreateGeneratePolicies.ts
new file mode 100644
index 00000000000..92cf14dee2d
--- /dev/null
+++ b/apps/studio/hooks/misc/useTableCreateGeneratePolicies.ts
@@ -0,0 +1,76 @@
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+import { useEffect, useMemo, useRef } from 'react'
+
+import { usePHFlag } from 'hooks/ui/useFlag'
+import { IS_PLATFORM } from 'lib/constants'
+import { useTrack } from 'lib/telemetry/track'
+
+dayjs.extend(utc)
+
+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 track = useTrack()
+ const tableCreateGeneratePoliciesFlag = usePHFlag<boolean>('tableCreateGeneratePolicies')
+ const hasTrackedExposure = useRef(false)
+
+ const enabled = useMemo(() => {
+ if (!IS_PLATFORM) return false
+ if (!tableCreateGeneratePoliciesFlag) return false
+ return true
+ }, [tableCreateGeneratePoliciesFlag])
+
+ useEffect(() => {
+ if (!IS_PLATFORM) return
+ if (hasTrackedExposure.current) return
+ if (!isNewRecord) return
+ if (tableCreateGeneratePoliciesFlag === undefined) return
+ if (!projectInsertedAt) return
+
+ try {
+ const insertedDate = dayjs.utc(projectInsertedAt)
+ if (!insertedDate.isValid()) return
+
+ const daysSinceCreation = dayjs.utc().diff(insertedDate, 'day')
+ track('table_create_generate_policies_experiment_exposed', {
+ experiment_id: 'tableCreateGeneratePolicies',
+ variant: tableCreateGeneratePoliciesFlag ? 'treatment' : 'control',
+ days_since_project_creation: daysSinceCreation,
+ })
+ hasTrackedExposure.current = true
+ } catch {
+ hasTrackedExposure.current = false
+ }
+ }, [isNewRecord, tableCreateGeneratePoliciesFlag, projectInsertedAt, track])
+
+ return {
+ enabled,
+ }
+}
diff --git a/apps/studio/pages/api/ai/sql/policy.ts b/apps/studio/pages/api/ai/sql/policy.ts
new file mode 100644
index 00000000000..d403e9b6b35
--- /dev/null
+++ b/apps/studio/pages/api/ai/sql/policy.ts
@@ -0,0 +1,166 @@
+import { Output, generateText, stepCountIs } from 'ai'
+import { IS_PLATFORM } from 'common'
+import { source } from 'common-tags'
+import { NextApiRequest, NextApiResponse } from 'next'
+import { z } from 'zod'
+
+import type { AiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'
+import { getModel } from 'lib/ai/model'
+import { getOrgAIDetails } from 'lib/ai/org-ai-details'
+import { RLS_PROMPT } from 'lib/ai/prompts'
+import { getTools } from 'lib/ai/tools'
+import apiWrapper from 'lib/api/apiWrapper'
+
+const policySchema = z.object({
+ sql: z.string().describe('The generated Postgres CREATE POLICY statement.'),
+ name: z.string().describe('The name of the policy.'),
+ command: z
+ .enum(['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'ALL'])
+ .describe('The SQL command this policy applies to.'),
+ definition: z
+ .string()
+ .optional()
+ .describe('The USING clause expression (for SELECT, UPDATE, DELETE).'),
+ check: z.string().optional().describe('The WITH CHECK clause expression (for INSERT, UPDATE).'),
+ action: z
+ .enum(['PERMISSIVE', 'RESTRICTIVE'])
+ .default('PERMISSIVE')
+ .describe('Whether the policy is PERMISSIVE or RESTRICTIVE.'),
+ roles: z.array(z.string()).default(['public']).describe('The roles this policy applies to.'),
+})
+
+const requestBodySchema = z.object({
+ tableName: z.string().min(1),
+ schema: z.string().default('public'),
+ columns: z.array(z.string()).optional(),
+ projectRef: z.string().min(1),
+ connectionString: z.string().min(1),
+ orgSlug: z.string().optional(),
+ message: z.string().optional(),
+})
+
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ const { method } = req
+
+ switch (method) {
+ case 'POST':
+ return handlePost(req, res)
+ default:
+ res.setHeader('Allow', ['POST'])
+ res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
+ }
+}
+
+export async function handlePost(req: NextApiRequest, res: NextApiResponse) {
+ const authorization = req.headers.authorization
+ const accessToken = authorization?.replace('Bearer ', '')
+
+ if (IS_PLATFORM && !accessToken) {
+ return res.status(401).json({ error: 'Authorization token is required' })
+ }
+
+ const body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
+ const { data, error: parseError } = requestBodySchema.safeParse(body)
+
+ if (parseError) {
+ return res.status(400).json({ error: 'Invalid request body', issues: parseError.issues })
+ }
+
+ const { tableName, schema, columns = [], projectRef, connectionString, orgSlug, message } = data
+
+ let aiOptInLevel: AiOptInLevel = 'disabled'
+
+ if (!IS_PLATFORM) {
+ aiOptInLevel = 'schema'
+ }
+
+ if (IS_PLATFORM && orgSlug && authorization) {
+ try {
+ const { aiOptInLevel: orgAIOptInLevel } = await getOrgAIDetails({
+ orgSlug,
+ authorization,
+ projectRef,
+ })
+
+ aiOptInLevel = orgAIOptInLevel
+ } catch (error) {
+ return res.status(400).json({
+ error: 'There was an error fetching your organization details',
+ })
+ }
+ }
+
+ try {
+ const { model, error: modelError } = await getModel({
+ provider: 'openai',
+ routingKey: 'sql-policy',
+ })
+
+ if (modelError) {
+ return res.status(500).json({ error: modelError.message })
+ }
+
+ const tools = await getTools({
+ projectRef,
+ connectionString,
+ authorization,
+ aiOptInLevel,
+ accessToken,
+ })
+
+ const { experimental_output } = await generateText({
+ model,
+ stopWhen: stepCountIs(5),
+ prompt: source`
+ You are a Postgres RLS (Row Level Security) expert.
+ Determine the most appropriate policies for the "${schema}"."${tableName}" table within a Supabase project.
+
+ ${columns.length > 0 ? `Table columns: ${columns.join(', ')}` : 'No column metadata provided.'}
+
+ ${message ? `User request: ${message}` : ''}
+
+ RLS Guide: ${RLS_PROMPT}
+
+ Requirements:
+ - Use the available planning and schema tools (like "list_policies" or "list_tables") to inspect the "${schema}" schema and existing policies before generating new ones.
+ - Ensure policies strictly adhere to the existing schema
+ - Return a curated list of recommended CREATE POLICY statements as JSON.
+ - Each policy must include: name, sql, command (SELECT/INSERT/UPDATE/DELETE/ALL), action (PERMISSIVE/RESTRICTIVE), roles (array of role names).
+ - Include "definition" (USING clause expression without the USING keyword) for SELECT, UPDATE, DELETE policies.
+ - Include "check" (WITH CHECK clause expression without the WITH CHECK keywords) for INSERT, UPDATE policies.
+ - Avoid duplicating existing policies and reference the public schema and typical Supabase best practices when deciding the coverage.
+ - Prefer PERMISSIVE policies unless a RESTRICTIVE policy is explicitly required
+ `,
+ tools,
+ experimental_output: Output.object({
+ schema: z.object({
+ policies: z.array(policySchema),
+ }),
+ }),
+ })
+
+ // Add table and schema to each policy from the request
+ const policies = (experimental_output?.policies ?? []).map((policy) => ({
+ ...policy,
+ table: tableName,
+ schema,
+ }))
+
+ return res.json(policies)
+ } catch (error) {
+ if (error instanceof Error) {
+ console.error(`AI policy generation failed: ${error.message}`)
+ return res.status(500).json({
+ error: 'Failed to generate policy. Please try again.',
+ })
+ }
+ return res.status(500).json({
+ error: 'An unknown error occurred.',
+ })
+ }
+}
+
+const wrapper = (req: NextApiRequest, res: NextApiResponse) =>
+ apiWrapper(req, res, handler, { withAuth: true })
+
+export default wrapper
diff --git a/apps/studio/proxy.ts b/apps/studio/proxy.ts
index 124d6aa3126..9f8c75aabc3 100644
--- a/apps/studio/proxy.ts
+++ b/apps/studio/proxy.ts
@@ -8,6 +8,7 @@ export const config = {
// [Joshen] Return 404 for all next.js API endpoints EXCEPT the ones we use in hosted:
const HOSTED_SUPPORTED_API_URLS = [
'/ai/sql/generate-v4',
+ '/ai/sql/policy',
'/ai/feedback/rate',
'/ai/code/complete',
'/ai/sql/cron-v2',
diff --git a/packages/common/telemetry-constants.ts b/packages/common/telemetry-constants.ts
index 92c7ce67b61..664b0a4f50e 100644
--- a/packages/common/telemetry-constants.ts
+++ b/packages/common/telemetry-constants.ts
@@ -1933,6 +1933,10 @@ export interface TableCreatedEvent {
* Name of the table created
*/
table_name?: string
+ /**
+ * Whether RLS policies were generated and saved with the table
+ */
+ has_generated_policies?: boolean
}
groups: Partial<TelemetryGroups>
}
@@ -1989,6 +1993,104 @@ export interface TableRLSEnabledEvent {
groups: Partial<TelemetryGroups>
}
+/**
+ * User clicked the generate policies button in the table editor.
+ *
+ * @group Events
+ * @source studio
+ * @page /dashboard/project/{ref}/editor
+ */
+export interface RLSGeneratePoliciesClickedEvent {
+ action: 'rls_generate_policies_clicked'
+ groups: TelemetryGroups
+}
+
+/**
+ * User removed a generated policy from the table editor.
+ *
+ * @group Events
+ * @source studio
+ * @page /dashboard/project/{ref}/editor
+ */
+export interface RLSGeneratedPolicyRemovedEvent {
+ action: 'rls_generated_policy_removed'
+ groups: TelemetryGroups
+}
+
+/**
+ * User successfully created generated RLS policies for a table.
+ *
+ * @group Events
+ * @source studio
+ * @page /dashboard/project/{ref}/editor
+ */
+export interface RLSGeneratedPoliciesCreatedEvent {
+ action: 'rls_generated_policies_created'
+ groups: TelemetryGroups
+}
+
+/**
+ * Conversion event for the generate policies experiment.
+ * Fires when a user in the experiment creates a new table via table editor.
+ * This is separate from TableCreatedEvent to keep experiment tracking isolated.
+ *
+ * @group Events
+ * @source studio
+ * @page /dashboard/project/{ref}/editor
+ */
+export interface TableCreateGeneratePoliciesExperimentConvertedEvent {
+ action: 'table_create_generate_policies_experiment_converted'
+ properties: {
+ /**
+ * Experiment identifier for tracking
+ */
+ experiment_id: 'tableCreateGeneratePolicies'
+ /**
+ * Experiment variant: 'control' (feature disabled) or 'treatment' (feature enabled)
+ */
+ variant: 'control' | 'treatment'
+ /**
+ * Whether RLS was enabled on the table
+ */
+ has_rls_enabled: boolean
+ /**
+ * Whether the table was created with any RLS policies (manual or generated)
+ */
+ has_rls_policies: boolean
+ /**
+ * Whether AI-generated policies were used (only possible in treatment)
+ */
+ has_generated_policies: boolean
+ }
+ groups: TelemetryGroups
+}
+
+/**
+ * User was exposed to the generate policies experiment (shown or not shown the Generate Policies button).
+ *
+ * @group Events
+ * @source studio
+ * @page /dashboard/project/{ref}/editor
+ */
+export interface TableCreateGeneratePoliciesExperimentExposedEvent {
+ action: 'table_create_generate_policies_experiment_exposed'
+ properties: {
+ /**
+ * Experiment identifier for tracking
+ */
+ experiment_id: 'tableCreateGeneratePolicies'
+ /**
+ * Experiment variant: 'control' (feature disabled) or 'treatment' (feature enabled)
+ */
+ variant: 'control' | 'treatment'
+ /**
+ * Days since project creation (to segment by new user cohorts)
+ */
+ days_since_project_creation: number
+ }
+ groups: TelemetryGroups
+}
+
/**
* User opened API docs panel.
*
@@ -2607,6 +2709,11 @@ export type TelemetryEvent =
| TableCreatedEvent
| TableDataAddedEvent
| TableRLSEnabledEvent
+ | RLSGeneratePoliciesClickedEvent
+ | RLSGeneratedPolicyRemovedEvent
+ | RLSGeneratedPoliciesCreatedEvent
+ | TableCreateGeneratePoliciesExperimentExposedEvent
+ | TableCreateGeneratePoliciesExperimentConvertedEvent
| TableQuickstartOpenedEvent
| TableQuickstartAIPromptSubmittedEvent
| TableQuickstartAIGenerationCompletedEvent