The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/ai realtime (#39145)
Saxon Fletcher54ad0b7495e6
diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsxindex 3d6f2287f0a..9160a211ca5 100644--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx@@ -1,7 +1,7 @@import { PostgresTrigger } from '@supabase/postgres-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'import { noop } from 'lodash'-import { Plus, Search } from 'lucide-react'+import { DatabaseZap, FunctionSquare, Plus, Search, Shield } from 'lucide-react'import { useState } from 'react'import AlphaPreview from 'components/to-be-cleaned/AlphaPreview'@@ -19,7 +19,10 @@ import { useIsProtectedSchema, useProtectedSchemas } from 'hooks/useProtectedSchimport { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import {AiIconAnimation,+ Button,Card,+ CardContent,+ cn,Input,Table,TableBody,@@ -29,6 +32,7 @@ import {} from 'ui'import { ProtectedSchemaWarning } from '../../ProtectedSchemaWarning'import TriggerList from './TriggerList'+import Link from 'next/link'interface TriggersListProps {createTrigger: () => void@@ -79,146 +83,159 @@ const TriggersList = ({return <AlertError error={error} subject="Failed to retrieve database triggers" />}+ const schemaTriggers = triggers.filter((x) => x.schema == selectedSchema)+return (- <>- {(triggers ?? []).length === 0 ? (- <div className="flex h-full w-full items-center justify-center">- <ProductEmptyState- title="Triggers"- ctaButtonLabel="Create a new trigger"- onClickCta={() => createTrigger()}- >- <AlphaPreview />- <p className="text-sm text-foreground-light">- A PostgreSQL trigger is a function invoked automatically whenever an event associated- with a table occurs.- </p>- <p className="text-sm text-foreground-light">- An event could be any of the following: INSERT, UPDATE, DELETE. A trigger is a special- user-defined function associated with a table.- </p>- </ProductEmptyState>+ <div className="space-y-4">+ <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-2 flex-wrap">+ <div className="flex flex-col lg:flex-row lg:items-center gap-2">+ <SchemaSelector+ className="w-full lg:w-[180px]"+ size="tiny"+ showError={false}+ selectedSchemaName={selectedSchema}+ onSelectSchema={setSelectedSchema}+ />+ <Input+ placeholder="Search for a trigger"+ size="tiny"+ icon={<Search size="14" />}+ value={filterString}+ className="w-full lg:w-52"+ onChange={(e) => setFilterString(e.target.value)}+ /></div>- ) : (- <div className="space-y-4">- <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-2 flex-wrap">- <div className="flex flex-col lg:flex-row lg:items-center gap-2">- <SchemaSelector- className="w-full lg:w-[180px]"- size="tiny"- showError={false}- selectedSchemaName={selectedSchema}- onSelectSchema={setSelectedSchema}- />- <Input- placeholder="Search for a trigger"- size="tiny"- icon={<Search size="14" />}- value={filterString}- className="w-full lg:w-52"- onChange={(e) => setFilterString(e.target.value)}- />- </div>- {!isSchemaLocked && (- <div className="flex items-center gap-x-2">- <ButtonTooltip- disabled={!hasTables || !canCreateTriggers}- icon={<Plus />}- onClick={() => createTrigger()}- className="flex-grow"- tooltip={{- content: {- side: 'bottom',- text: !hasTables- ? 'Create a table first before creating triggers'- : !canCreateTriggers- ? 'You need additional permissions to create triggers'- : undefined,- },- }}- >- New trigger- </ButtonTooltip>-- {hasTables && (- <ButtonTooltip- type="default"- disabled={!hasTables || !canCreateTriggers}- className="px-1 pointer-events-auto"- icon={<AiIconAnimation size={16} />}- onClick={() =>- aiSnap.newChat({- name: 'Create new trigger',- open: true,- initialInput: `Create a new trigger for the schema ${selectedSchema} that does ...`,- suggestions: {- title:- 'I can help you create a new trigger, here are a few example prompts to get you started:',- prompts: [- {- label: 'Log Changes',- description: 'Create a trigger that logs changes to the users table',- },- {- label: 'Update Timestamp',- description: 'Create a trigger that updates updated_at timestamp',- },- {- label: 'Validate Email',- description:- 'Create a trigger that validates email format before insert',- },- ],+ {!isSchemaLocked && (+ <div className="flex items-center gap-x-2">+ <ButtonTooltip+ disabled={!hasTables || !canCreateTriggers}+ icon={<Plus />}+ onClick={() => createTrigger()}+ className="flex-grow"+ tooltip={{+ content: {+ side: 'bottom',+ text: !hasTables+ ? 'Create a table first before creating triggers'+ : !canCreateTriggers+ ? 'You need additional permissions to create triggers'+ : undefined,+ },+ }}+ >+ New trigger+ </ButtonTooltip>++ {hasTables && (+ <ButtonTooltip+ type="default"+ disabled={!hasTables || !canCreateTriggers}+ className="px-1 pointer-events-auto"+ icon={<AiIconAnimation size={16} />}+ onClick={() =>+ aiSnap.newChat({+ name: 'Create new trigger',+ open: true,+ initialInput: `Create a new trigger for the schema ${selectedSchema} that does ...`,+ suggestions: {+ title:+ 'I can help you create a new trigger, here are a few example prompts to get you started:',+ prompts: [+ {+ label: 'Log Changes',+ description: 'Create a trigger that logs changes to the users table',+ },+ {+ label: 'Update Timestamp',+ description: 'Create a trigger that updates updated_at timestamp',},- })- }- tooltip={{- content: {- side: 'bottom',- text: !canCreateTriggers- ? 'You need additional permissions to create triggers'- : 'Create with Supabase Assistant',- },- }}- />- )}- </div>+ {+ label: 'Validate Email',+ description: 'Create a trigger that validates email format before insert',+ },+ ],+ },+ })+ }+ tooltip={{+ content: {+ side: 'bottom',+ text: !canCreateTriggers+ ? 'You need additional permissions to create triggers'+ : 'Create with Supabase Assistant',+ },+ }}+ />)}</div>+ )}+ </div>- {isSchemaLocked && <ProtectedSchemaWarning schema={selectedSchema} entity="triggers" />}-- <div className="w-full overflow-hidden overflow-x-auto">- <Card>- <Table>- <TableHeader>- <TableRow>- <TableHead key="name">Name</TableHead>- <TableHead key="table">Table</TableHead>- <TableHead key="function">Function</TableHead>- <TableHead key="events">Events</TableHead>- <TableHead key="orientation">Orientation</TableHead>- <TableHead key="enabled" className="w-20">- Enabled- </TableHead>- <TableHead key="buttons" className="w-1/12"></TableHead>- </TableRow>- </TableHeader>- <TableBody>- <TriggerList- schema={selectedSchema}- filterString={filterString}- isLocked={isSchemaLocked}- editTrigger={editTrigger}- deleteTrigger={deleteTrigger}- />- </TableBody>- </Table>- </Card>+ {isSchemaLocked && <ProtectedSchemaWarning schema={selectedSchema} entity="triggers" />}++ {!isSchemaLocked && (schemaTriggers ?? []).length === 0 ? (+ <Card className="grid grid-cols-1 @xl:grid-cols-3 bg divide-x @container">+ <div className="flex flex-col h-full p-6">+ <div className="flex items-center gap-3 mb-2">+ <DatabaseZap strokeWidth={1.5} size={16} className="text-foreground-light" />+ <h3 className="heading-default">Create realtime experiences</h3>+ </div>+ <p className="text-foreground-light text-sm flex-1">+ Keep your application in sync by automatically updating when data changes+ </p>+ </div>++ <div className="flex flex-col h-full p-6">+ <div className="flex items-center gap-3 mb-2">+ <FunctionSquare strokeWidth={1.5} size={16} className="text-foreground-light" />+ <h3 className="heading-default">Trigger an edge function</h3>+ </div>+ <p className="text-foreground-light text-sm flex-1">+ Automatically invoke edge functions when database events occur+ </p>+ </div>++ <div className="flex flex-col h-full p-6">+ <div className="flex items-center gap-3 mb-2">+ <Shield strokeWidth={1.5} size={16} className="text-foreground-light" />+ <h3 className="heading-default">Validate data</h3>+ </div>+ <p className="text-foreground-light text-sm flex-1">+ Ensure data meets your requirements before it is inserted into the database+ </p></div>+ </Card>+ ) : (+ <div className="w-full overflow-hidden overflow-x-auto">+ <Card>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead key="name">Name</TableHead>+ <TableHead key="table">Table</TableHead>+ <TableHead key="function">Function</TableHead>+ <TableHead key="events">Events</TableHead>+ <TableHead key="orientation">Orientation</TableHead>+ <TableHead key="enabled" className="w-20">+ Enabled+ </TableHead>+ <TableHead key="buttons" className="w-1/12"></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ <TriggerList+ schema={selectedSchema}+ filterString={filterString}+ isLocked={isSchemaLocked}+ editTrigger={editTrigger}+ deleteTrigger={deleteTrigger}+ />+ </TableBody>+ </Table>+ </Card></div>)}- </>+ </div>)}diff --git a/apps/studio/components/interfaces/Realtime/Inspector/AnimatedCursors.tsx b/apps/studio/components/interfaces/Realtime/Inspector/AnimatedCursors.tsxnew file mode 100644index 00000000000..de4bd3abaed--- /dev/null+++ b/apps/studio/components/interfaces/Realtime/Inspector/AnimatedCursors.tsx@@ -0,0 +1,61 @@+import { useState, useEffect } from 'react'+import { motion } from 'framer-motion'+import { MousePointer2 } from 'lucide-react'++export const AnimatedCursors = () => {+ const [cursor1Position, setCursor1Position] = useState({ x: 20, y: 20 })+ const [cursor2Position, setCursor2Position] = useState({ x: 180, y: 80 })++ useEffect(() => {+ const animateCursors = () => {+ const newCursor1Position = {+ x: Math.random() * 160 + 20,+ y: Math.random() * 80 + 20,+ }+ const newCursor2Position = {+ x: Math.random() * 160 + 20,+ y: Math.random() * 80 + 20,+ }++ setCursor1Position(newCursor1Position)+ setCursor2Position(newCursor2Position)+ }++ const initialTimer = setTimeout(animateCursors, 1000)++ const interval = setInterval(animateCursors, 3000)++ return () => {+ clearTimeout(initialTimer)+ clearInterval(interval)+ }+ }, [])++ return (+ <div className="relative w-48 h-32 mx-auto mb-8">+ <motion.div+ className="absolute text-warning"+ animate={{ x: cursor1Position.x, y: cursor1Position.y }}+ transition={{+ duration: 1.2,+ ease: 'easeInOut',+ }}+ style={{ width: 20, height: 20 }}+ >+ <MousePointer2 size={20} />+ </motion.div>+ <motion.div+ className="absolute text-brand"+ animate={{ x: cursor2Position.x, y: cursor2Position.y }}+ transition={{+ duration: 1.2,+ ease: 'easeInOut',+ delay: 0.2,+ }}+ style={{ width: 20, height: 20 }}+ >+ <MousePointer2 size={20} />+ </motion.div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Realtime/Inspector/EmptyRealtime.tsx b/apps/studio/components/interfaces/Realtime/Inspector/EmptyRealtime.tsxnew file mode 100644index 00000000000..8bed6a1596c--- /dev/null+++ b/apps/studio/components/interfaces/Realtime/Inspector/EmptyRealtime.tsx@@ -0,0 +1,101 @@+import { AiIconAnimation, Button, Card, cn } from 'ui'+import Link from 'next/link'+import { AnimatedCursors } from './AnimatedCursors'+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'++/**+ * Acts as a container component for the entire log display+ */+export const EmptyRealtime = ({ projectRef }: { projectRef: string }) => {+ const aiSnap = useAiAssistantStateSnapshot()++ const handleCreateTriggerWithAssistant = () => {+ aiSnap.newChat({+ name: `Realtime`,+ open: true,+ initialInput: `Help me set up a realtime experience for my project`,+ })+ }++ return (+ <div className="flex grow items-center justify-center p-12 border-t @container">+ <div className="w-full max-w-4xl flex flex-col items-center gap-0">+ <div className="text-center mb-12">+ <AnimatedCursors />+ <h2 className="heading-section mb-1">Create realtime experiences</h2>+ <p className="text-foreground-light mb-6">+ Send your first realtime message from your database, application code or edge function+ </p>+ <Button+ type="default"+ icon={<AiIconAnimation />}+ onClick={handleCreateTriggerWithAssistant}+ >+ Set up realtime for me+ </Button>+ </div>++ <Card className="grid grid-cols-1 @xl:grid-cols-3 bg divide-x mb-8">+ <div className="flex flex-col h-full p-6">+ <div className="flex items-center gap-3 mb-2">+ <span+ className={cn(+ 'text-xs shrink-0 font-mono text-foreground-light w-7 h-7 bg border flex items-center justify-center rounded-md'+ )}+ >+ 1+ </span>+ <h3 className="heading-default">Broadcast messages</h3>+ </div>+ <p className="text-foreground-light text-sm mb-4 flex-1">+ Send messages to a channel from your client application or database via triggers.+ </p>+ <Button type="default" className="w-full">+ <Link href={`/project/${projectRef}/database/triggers`}>Create a trigger</Link>+ </Button>+ </div>++ <div className="flex flex-col h-full p-6">+ <div className="flex items-center gap-3 mb-2">+ <span+ className={cn(+ 'text-xs shrink-0 font-mono text-foreground-light w-7 h-7 bg border flex items-center justify-center rounded-md'+ )}+ >+ 2+ </span>+ <h3 className="heading-default">Write policies</h3>+ </div>+ <p className="text-foreground-light text-sm mb-4 flex-1">+ Set up Row Level Security policies to control who can see messages within a channel+ </p>+ <Button type="default">+ <Link href={`/project/${projectRef}/realtime/policies`}>Write a policy</Link>+ </Button>+ </div>++ <div className="flex flex-col h-full p-6">+ <div className="flex items-center gap-3 mb-2">+ <span+ className={cn(+ 'text-xs shrink-0 font-mono text-foreground-light w-7 h-7 bg border flex items-center justify-center rounded-md'+ )}+ >+ 3+ </span>+ <h3 className="heading-default">Subscribe to a channel</h3>+ </div>+ <p className="text-foreground-light text-sm mb-4 flex-1">+ Receive realtime messages in your application by listening to a channel+ </p>+ <Button type="default" asChild>+ <Link href="https://supabase.com/docs/guides/realtime/subscribing-to-database-changes#listening-on-client-side">+ Read the guide+ </Link>+ </Button>+ </div>+ </Card>+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Realtime/Inspector/index.tsx b/apps/studio/components/interfaces/Realtime/Inspector/index.tsxindex 28b616b7735..116ce210093 100644--- a/apps/studio/components/interfaces/Realtime/Inspector/index.tsx+++ b/apps/studio/components/interfaces/Realtime/Inspector/index.tsx@@ -1,5 +1,7 @@import { useParams } from 'common'-import { useState } from 'react'+import { useState, useEffect } from 'react'+import { motion } from 'framer-motion'+import { MousePointer2 } from 'lucide-react'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'@@ -7,6 +9,7 @@ import { Header } from './Header'import MessagesTable from './MessagesTable'import { SendMessageModal } from './SendMessageModal'import { RealtimeConfig, useRealtimeMessages } from './useRealtimeMessages'+import { EmptyRealtime } from './EmptyRealtime'/*** Acts as a container component for the entire log display@@ -40,12 +43,16 @@ export const RealtimeInspector = () => {<Header config={realtimeConfig} onChangeConfig={setRealtimeConfig} /><div className="relative flex flex-col grow"><div className="flex grow">- <MessagesTable- hasChannelSet={realtimeConfig.channelName.length > 0}- enabled={realtimeConfig.enabled}- data={logData}- showSendMessage={() => setSendMessageShown(true)}- />+ {(logData ?? []).length > 0 ? (+ <MessagesTable+ hasChannelSet={realtimeConfig.channelName.length > 0}+ enabled={realtimeConfig.enabled}+ data={logData}+ showSendMessage={() => setSendMessageShown(true)}+ />+ ) : (+ <EmptyRealtime projectRef={ref!} />+ )}</div></div><SendMessageModaldiff --git a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsxindex 1d17ad0eb9f..a2a99dfcd3e 100644--- a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx@@ -1,14 +1,15 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { Lock, MousePointer2, PlusCircle, Unlock } from 'lucide-react'import Link from 'next/link'-import { useState } from 'react'+import { useMemo, useState } from 'react'import { toast } from 'sonner'-import { useParams } from 'common'+import { useParams, useFlag } from 'common'import { RefreshButton } from 'components/grid/components/header/RefreshButton'import { getEntityLintDetails } from 'components/interfaces/TableGridEditor/TableEntity.utils'import { APIDocsButton } from 'components/ui/APIDocsButton'import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useDatabaseTriggersQuery } from 'data/database-triggers/database-triggers-query'import { useDatabasePoliciesQuery } from 'data/database-policies/database-policies-query'import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'import { useDatabasePublicationUpdateMutation } from 'data/database-publications/database-publications-update-mutation'@@ -68,6 +69,7 @@ export const GridHeaderActions = ({ table, isRefetching }: GridHeaderActionsPropconst isView = isTableLikeView(table)const isMaterializedView = isTableLikeMaterializedView(table)+ const triggersInsteadOfRealtime = useFlag<boolean>('triggersInsteadOfRealtime')const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])const { isSchemaLocked } = useIsProtectedSchema({ schema: table.schema })@@ -116,6 +118,21 @@ export const GridHeaderActions = ({ table, isRefetching }: GridHeaderActionsProp},})+ const { data: triggersData } = useDatabaseTriggersQuery(+ {+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ },+ {+ enabled: isTable,+ }+ )+ const tableTriggers = (triggersData ?? []).filter(+ (trigger) => trigger.schema === table.schema && trigger.table === table.name+ )++ const tableTriggersCount = tableTriggers.length+const { can: canSqlWriteTables, isLoading: isLoadingPermissions } = useAsyncCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE,'tables'@@ -147,6 +164,8 @@ export const GridHeaderActions = ({ table, isRefetching }: GridHeaderActionsPropconst { mutate: sendEvent } = useSendEventMutation()+ const manageTriggersHref = `/project/${ref}/database/triggers?schema=${table.schema}`+const toggleRealtime = async () => {if (!project) return console.error('Project is required')if (!realtimePublication) return console.error('Unable to find realtime publication')@@ -325,6 +344,55 @@ export const GridHeaderActions = ({ table, isRefetching }: GridHeaderActionsProp)) : null}+ {isTable && triggersInsteadOfRealtime ? (+ <Button+ asChild+ type={'default'}+ size="tiny"+ icon={+ <div+ className={cn(+ 'flex items-center justify-center rounded-full bg-border-stronger h-[16px]',+ tableTriggersCount > 9 ? 'px-1' : 'w-[16px]'+ )}+ >+ <span className="text-[11px] text-foreground font-mono text-center">+ {tableTriggersCount}+ </span>+ </div>+ }+ >+ <Link href={manageTriggersHref}>+ {tableTriggersCount === 1 ? 'Trigger' : 'Triggers'}+ </Link>+ </Button>+ ) : (+ realtimeEnabled && (+ <ButtonTooltip+ type="default"+ size="tiny"+ icon={+ <MousePointer2+ strokeWidth={1.5}+ className={isRealtimeEnabled ? 'text-brand' : 'text-foreground-muted'}+ />+ }+ onClick={() => setShowEnableRealtime(true)}+ className={cn(isRealtimeEnabled && 'w-7 h-7 p-0 text-brand hover:text-brand-hover')}+ tooltip={{+ content: {+ side: 'bottom',+ text: isRealtimeEnabled+ ? 'Click to disable realtime for this table'+ : 'Click to enable realtime for this table',+ },+ }}+ >+ {!isRealtimeEnabled && 'Enable Realtime'}+ </ButtonTooltip>+ )+ )}+{isView && viewHasLints && (<Popover_Shadcn_ modal={false} open={showWarning} onOpenChange={setShowWarning}><PopoverTrigger_Shadcn_ asChild>@@ -459,31 +527,6 @@ export const GridHeaderActions = ({ table, isRefetching }: GridHeaderActionsProp<RoleImpersonationPopover serviceRoleLabel="postgres" />- {isTable && realtimeEnabled && (- <ButtonTooltip- type="default"- size="tiny"- icon={- <MousePointer2- strokeWidth={1.5}- className={isRealtimeEnabled ? 'text-brand' : 'text-foreground-muted'}- />- }- onClick={() => setShowEnableRealtime(true)}- className={cn(isRealtimeEnabled && 'w-7 h-7 p-0 text-brand hover:text-brand-hover')}- tooltip={{- content: {- side: 'bottom',- text: isRealtimeEnabled- ? 'Click to disable realtime for this table'- : 'Click to enable realtime for this table',- },- }}- >- {!isRealtimeEnabled && 'Enable Realtime'}- </ButtonTooltip>- )}-{doesHaveAutoGeneratedAPIDocs && <APIDocsButton section={['entities', table.name]} />}<RefreshButton tableId={table.id} isRefetching={isRefetching} />diff --git a/apps/studio/lib/ai/prompts.ts b/apps/studio/lib/ai/prompts.tsindex 83b00581dc0..887832b66a3 100644--- a/apps/studio/lib/ai/prompts.ts+++ b/apps/studio/lib/ai/prompts.ts@@ -287,6 +287,281 @@ export const PG_BEST_PRACTICES = `- Use \`create or replace function\` whenever possible.`+export const REALTIME_PROMPT = `+# Supabase Realtime Implementation Guide++## Core Rules++### Do+- Use \`broadcast\` for all realtime events (database changes via triggers, messaging, notifications, game state)+- Use \`presence\` sparingly for user state tracking (online status, user counters)+- Create indexes for all columns used in RLS policies+- Use topic names that correlate with concepts and tables: \`scope:entity\` (e.g., \`room:123:messages\`)+- Use snake_case for event names: \`entity_action\` (e.g., \`message_created\`)+- Include unsubscribe/cleanup logic in all implementations+- Set \`private: true\` for channels using database triggers or RLS policies+- Prefer private channels over public channels for better security and control+- Implement proper error handling and reconnection logic++### Don't+- Use \`postgres_changes\` for new applications (single-threaded, doesn't scale well)+- Create multiple subscriptions without proper cleanup+- Write complex RLS queries without proper indexing+- Use generic event names like "update" or "change"+- Subscribe directly in render functions without state management+- Use database functions (\`realtime.send\`, \`realtime.broadcast_changes\`) in client code++## Function Selection+- **Custom payloads with business logic:** Use \`broadcast\`+- **Database change notifications:** Use \`broadcast\` via database triggers+- **High-frequency updates:** Use \`broadcast\` with minimal payload+- **User presence/status tracking:** Use \`presence\` (sparingly)+- **Client to client communication:** Use \`broadcast\` without triggers++**Note:** Avoid \`postgres_changes\` due to scalability limitations. Use \`broadcast\` with database triggers for all database change notifications.++## Naming Conventions++### Topics (Channels)+- **Pattern:** \`scope:entity\` or \`scope:entity:id\`+- **Examples:** \`room:123:messages\`, \`game:456:moves\`, \`user:789:notifications\`+- **One topic per room/user/organization for better performance and scalability**++### Events+- **Pattern:** \`entity_action\` (snake_case)+- **Examples:** \`message_created\`, \`user_joined\`, \`game_ended\`, \`status_changed\`++## Database Triggers++### Using realtime.broadcast_changes (Recommended for database changes)+\`\`\`sql+CREATE OR REPLACE FUNCTION room_messages_broadcast_trigger()+RETURNS TRIGGER AS $$+SECURITY DEFINER+LANGUAGE plpgsql+AS $$+BEGIN+ PERFORM realtime.broadcast_changes(+ 'room:' || COALESCE(NEW.room_id, OLD.room_id)::text,+ TG_OP,+ TG_OP,+ TG_TABLE_NAME,+ TG_TABLE_SCHEMA,+ NEW,+ OLD+ );+ RETURN COALESCE(NEW, OLD);+END;+$$;++CREATE TRIGGER messages_broadcast_trigger+ AFTER INSERT OR UPDATE OR DELETE ON messages+ FOR EACH ROW EXECUTE FUNCTION room_messages_broadcast_trigger();+\`\`\`++**Note:** \`realtime.broadcast_changes\` requires private channels by default.++### Using realtime.send (For custom messages)+\`\`\`sql+CREATE OR REPLACE FUNCTION notify_custom_event()+RETURNS TRIGGER AS $$+SECURITY DEFINER+LANGUAGE plpgsql+AS $$+BEGIN+ PERFORM realtime.send(+ 'room:' || NEW.room_id::text,+ 'status_changed',+ jsonb_build_object('id', NEW.id, 'status', NEW.status),+ false -- set to true for private channels+ );+ RETURN NEW;+END;+$$;+\`\`\`++### Conditional Broadcasting+\`\`\`sql+-- Only broadcast significant changes+IF TG_OP = 'UPDATE' AND OLD.status IS DISTINCT FROM NEW.status THEN+ PERFORM realtime.broadcast_changes(+ 'room:' || NEW.room_id::text,+ TG_OP,+ TG_OP,+ TG_TABLE_NAME,+ TG_TABLE_SCHEMA,+ NEW,+ OLD+ );+END IF;+\`\`\`++## Authorization Setup++### RLS Policies on realtime.messages++#### Allow Users to Receive Broadcasts (SELECT)+\`\`\`sql+CREATE POLICY "room_members_can_read" ON realtime.messages+FOR SELECT TO authenticated+USING (+ topic LIKE 'room:%' AND+ EXISTS (+ SELECT 1 FROM room_members+ WHERE user_id = auth.uid()+ AND room_id = SPLIT_PART(topic, ':', 2)::uuid+ )+);++-- Required index for performance+CREATE INDEX idx_room_members_user_room ON room_members(user_id, room_id);+\`\`\`++#### Allow Users to Send Broadcasts (INSERT)+\`\`\`sql+CREATE POLICY "room_members_can_write" ON realtime.messages+FOR INSERT TO authenticated+WITH CHECK (+ topic LIKE 'room:%' AND+ EXISTS (+ SELECT 1 FROM room_members+ WHERE user_id = auth.uid()+ AND room_id = SPLIT_PART(topic, ':', 2)::uuid+ )+);+\`\`\`++## Client Implementation++### Broadcasting from Client+You can send broadcast messages using the Supabase client libraries:++\`\`\`javascript+const myChannel = supabase.channel('room:123:messages', {+ config: { private: true }+})++// Sending before subscribing uses HTTP+myChannel.send({+ type: 'broadcast',+ event: 'message_created',+ payload: { message: 'Hello', user_id: 123 },+})++// Sending after subscribing uses WebSockets (recommended)+myChannel.subscribe((status) => {+ if (status !== 'SUBSCRIBED') return++ myChannel.send({+ type: 'broadcast',+ event: 'message_created',+ payload: { message: 'Hello', user_id: 123 },+ })+})+\`\`\`++**Note:** Sending messages after subscribing uses WebSockets and is more efficient than HTTP for real-time communication.++### React Pattern+\`\`\`javascript+const channelRef = useRef(null)++useEffect(() => {+ // Check if already subscribed to prevent multiple subscriptions+ if (channelRef.current?.state === 'subscribed') return++ const channel = supabase.channel('room:123:messages', {+ config: { private: true }+ })+ channelRef.current = channel++ // Set auth before subscribing+ await supabase.realtime.setAuth()++ channel+ .on('broadcast', { event: 'message_created' }, handleMessage)+ .subscribe()++ return () => {+ if (channelRef.current) {+ supabase.removeChannel(channelRef.current)+ channelRef.current = null+ }+ }+}, [roomId])+\`\`\`++### Channel Configuration+\`\`\`javascript+const channel = supabase.channel('room:123:messages', {+ config: {+ broadcast: { self: true, ack: true },+ presence: { key: 'user-session-id' },+ private: true // Required for RLS authorization+ }+})+\`\`\`++## Best Practices++### Scalability+- **Use dedicated, granular topics** - Messages only reach interested clients+- **One topic per room:** \`room:123:messages\`+- **One topic per user:** \`user:456:notifications\`+- **Avoid broad topics** that broadcast to all users++### Security+- **Enable private-only channels** in Realtime Settings for production+- **Always use \`private: true\`** for database-triggered channels+- **Create separate RLS policies** for SELECT (receive) and INSERT (send) operations+- **Index columns used in RLS policies** for performance++### Performance+- **Check channel state before subscribing** to prevent duplicate subscriptions+- **Include cleanup logic** - Always unsubscribe when component unmounts+- **Use \`SECURITY DEFINER\`** for trigger functions+- **Add conditional logic** to broadcast only significant changes++## Migration from postgres_changes++### Replace Client Code+\`\`\`javascript+// ❌ Old: postgres_changes+const oldChannel = supabase+ .channel('changes')+ .on('postgres_changes', { event: '*', schema: 'public', table: 'messages' }, callback)++// ✅ New: broadcast+const newChannel = supabase+ .channel(\`messages:\${room_id}:changes\`, { config: { private: true } })+ .on('broadcast', { event: 'INSERT' }, callback)+ .on('broadcast', { event: 'UPDATE' }, callback)+ .on('broadcast', { event: 'DELETE' }, callback)+\`\`\`++### Add Database Trigger+\`\`\`sql+CREATE TRIGGER messages_broadcast_trigger+ AFTER INSERT OR UPDATE OR DELETE ON messages+ FOR EACH ROW EXECUTE FUNCTION room_messages_broadcast_trigger();+\`\`\`++### Setup Authorization+\`\`\`sql+CREATE POLICY "users_can_receive_broadcasts" ON realtime.messages+ FOR SELECT TO authenticated USING (true);+\`\`\`++## Implementation Workflow+1. Understand the use case (messaging, notifications, game state, etc.)+2. Determine if database triggers are needed or client-only messaging+3. Create RLS policies on \`realtime.messages\` for SELECT and INSERT+4. If using database triggers, create trigger functions using \`realtime.broadcast_changes\` or \`realtime.send\`+5. Add indexes for columns used in RLS policies+6. Implement client code with proper cleanup and state management+7. Enable private-only channels in Realtime Settings for production+`+export const GENERAL_PROMPT = `# Role and ObjectiveAct as a Supabase Postgres expert to assist users in efficiently managing their Supabase projects.diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.tsindex e67c7d2ffc3..006da3a2ccd 100644--- a/apps/studio/pages/api/ai/sql/generate-v4.ts+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts@@ -15,6 +15,7 @@ import {GENERAL_PROMPT,PG_BEST_PRACTICES,RLS_PROMPT,+ REALTIME_PROMPT,SECURITY_PROMPT,LIMITATIONS_PROMPT,} from 'lib/ai/prompts'@@ -177,6 +178,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {${PG_BEST_PRACTICES}${RLS_PROMPT}${EDGE_FUNCTION_PROMPT}+ ${REALTIME_PROMPT}${SECURITY_PROMPT}${LIMITATIONS_PROMPT}`diff --git a/apps/studio/styles/typography.scss b/apps/studio/styles/typography.scssindex 55a5ca29ace..ab28b715c71 100644--- a/apps/studio/styles/typography.scss+++ b/apps/studio/styles/typography.scss@@ -72,6 +72,6 @@/* Link */.text-link {- @apply text-foreground-light underline underline-offset-4 decoration-border hover:decoration-foreground transition-colors hover:text-foreground;+ @apply text-foreground-light underline underline-offset-4 decoration-inherit hover:decoration-foreground transition-colors hover:text-foreground;}}