safe-sql-execution
Skill111k starsChanged 2 months agoApache-2.0View on GitHub
Use whenever code will build, return, fetch, or execute SQL that runs against a user's real Postgres database — even when the request reads like an ordinary feature or bug fix and never says "security," "injection," or "SafeSqlFragment." This covers: writing or editing any pg-meta function, query builder, or endpoint that builds/returns SQL for database objects (tables, views, functions, DB triggers, indexes, RLS policies); interpolating a schema/table/column/search/route-param value into SQL text; storing, fetching, or re-running SQL that round-trips from the database (a policy's definition, a function/view definition, a snippet's saved content); and any "Run"/"Apply"/"Execute" action that sends SQL to a project's database (SQL editor run-selection, policy editor apply, snippet runner). Load this BEFORE writing such code, not only when reviewing a finished diff. Skip only for changes that never touch SQL text or execution — styling, unrelated data hooks, non-SQL form validation, or UI layout work.
Trending
More talk lately.about the whole repository
Who's talking about supabase/supabase
- A Hacker News story“Supabase open sourced their dashboard”Hacker News · Dec 1, 2021 · 331 points
- supabase/postgrest-js“Allow long-running transactions at the client side or do relational inserts”GitHub · Nov 2, 2021 · 121 reactions
- supabase/auth-js“Can't get rid of getUser() warning”GitHub · Mar 31, 2024 · 89 reactions
- supabase/supabase-js“Acquiring an exclusive Navigator LockManager failed”GitHub · Jan 2, 2024 · 69 reactions
- supabase/supabase-js“Still having getSession warning whenever _saveSession is called”GitHub · May 17, 2024 · 68 reactions
The biggest 5 of 80 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 80
Talked about on Bluesky, GitHub and Hacker News (80 times).
On Bluesky · 50
- Nov 26, 2024📦 supabase / supabase ⭐ 74,138 (+62) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social18 likes and reposts · 2 replies
- Mar 2, 2025📦 supabase / supabase ⭐ 78,242 (+49) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social14 likes and reposts
- Nov 15, 2024📦 supabase / supabase ⭐ 73,721 (+77) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social12 likes and reposts
- Oct 5, 2024📦 supabase / supabase ⭐ 72,296 (+45) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social10 likes and reposts
- Sep 2, 2024📦 supabase / supabase ⭐ 71,084 (+33) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social10 likes and reposts · 1 reply
45 more on Bluesky
- Oct 22, 2024📦 supabase / supabase ⭐ 72,893 (+48) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social9 likes and reposts
- Feb 9, 2025📦 supabase / supabase ⭐ 77,109 (+63) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social8 likes and reposts · 1 reply
- Mar 23, 2025📦 supabase / supabase ⭐ 79,628 (+48) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social7 likes and reposts
- Mar 9, 2025📦 supabase / supabase ⭐ 78,642 (+57) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending.bsky.social7 likes and reposts
- Mar 6, 2025📦 supabase / supabase ⭐ 78,475 (+69) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social7 likes and reposts
- Sep 18, 2024📦 supabase / supabase ⭐ 71,657 (+41) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social7 likes and reposts
- Feb 17, 2025📦 supabase / supabase ⭐ 77,500 (+48) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social6 likes and reposts
- Feb 22, 2025📦 supabase / supabase ⭐ 77,818 (+55) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social5 likes and reposts
- Dec 20, 2024📦 supabase / supabase ⭐ 75,163 (+46) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social5 likes and reposts · 1 reply
- Aug 6, 2025📦 supabase / supabase ⭐ 86,619 (+51) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social4 likes and reposts
- May 27, 2025📦 supabase / supabase ⭐ 83,497 (+73) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social4 likes and reposts
- May 18, 2025📦 supabase / supabase ⭐ 82,966 (+65) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social4 likes and reposts
- Mar 31, 2025📦 supabase / supabase ⭐ 80,043 (+57) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social4 likes and reposts
- Sep 11, 2025📦 supabase / supabase ⭐ 88,289 (+76) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending.bsky.social3 likes and reposts
- Sep 9, 2025📦 supabase / supabase ⭐ 88,154 (+38) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social3 likes and reposts
- Jul 10, 2025📦 supabase / supabase ⭐ 85,507 (+84) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social3 likes and reposts
- Nov 4, 2026Postgres plus auth, storage, realtime, edge functions and instant APIs, all open source. 🔗 github.com/supabase/supabase Credits:… — @prosperflowio.bsky.social2 likes and reposts
- Oct 21, 2026🎉 Celebrating! 🎉 (500+ new stars) 📦 supabase / supabase ⭐ 112,619 (+509) 🗒 TypeScript The Postgres development platform. Supabase gives… — @github-trending-js.bsky.social2 likes and reposts · 1 reply
- Oct 15, 2026📦 supabase / supabase ⭐ 111,522 (+98) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social2 likes and reposts
- Sep 16, 2026🔥 Hot Repo! 🔥 (100+ new stars) 📦 supabase / supabase ⭐ 109,394 (+118) 🗒 TypeScript The Postgres development platform. Supabase gives… — @github-trending.bsky.social2 likes and reposts
- Aug 27, 2026📦 supabase / supabase ⭐ 108,421 (+45) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social2 likes and reposts
- Jun 18, 2026📦 supabase / supabase ⭐ 104,439 (+97) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social2 likes and reposts
- Jun 6, 2026🔥 Hot Repo! 🔥 (100+ new stars) 📦 supabase / supabase ⭐ 103,672 (+188) 🗒 TypeScript The Postgres development platform. Supabase gives… — @github-trending-js.bsky.social2 likes and reposts
- Jan 9, 2026📦 supabase / supabase ⭐ 95,874 (+78) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social2 likes and reposts
- Dec 1, 2025Supabase @supabase - your open-source backend. Firebase alternative built on Postgres. Features 👇 - Auth, DB, storage & functions -… — @danshipit.bsky.social2 likes and reposts · 1 reply
- Nov 1, 2025🚀 Skyrocketing! 🚀 (200+ new stars) 📦 supabase / supabase ⭐ 91,288 (+363) 🗒 TypeScript The Postgres development platform. Supabase gives… — @github-trending-js.bsky.social2 likes and reposts · 1 reply
- Sep 25, 2025📦 supabase / supabase ⭐ 89,095 (+61) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social2 likes and reposts
- Aug 13, 2025🔥 Hot Repo! 🔥 (100+ new stars) 📦 supabase / supabase ⭐ 86,968 (+110) 🗒 TypeScript The Postgres development platform. Supabase gives you… — @github-trending-js.bsky.social2 likes and reposts
- May 6, 2025📦 supabase / supabase ⭐ 82,217 (+74) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social2 likes and reposts
- May 2, 2025📦 supabase / supabase ⭐ 81,889 (+61) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social2 likes and reposts
- Apr 26, 2025📦 supabase / supabase ⭐ 81,549 (+78) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social2 likes and reposts
- Sep 22, 2024📦 supabase / supabase ⭐ 71,853 (+60) 🗒 TypeScript The open source Firebase alternative. Supabase gives you a dedicated Postgres database… — @github-trending-js.bsky.social2 likes and reposts
- Jun 11, 2024📦 supabase / supabase ⭐ 67,560 (+38) 🗒 TypeScript The open source Firebase alternative. — @github-trending-js.bsky.social2 likes and reposts
- Feb 8, 2024📦 supabase / supabase ⭐ 62,724 (+45) 🗒 TypeScript The open source Firebase alternative. — @github-trending-js.bsky.social2 likes and reposts
- Sep 2, 2023📦 supabase / supabase ⭐ 56,112 (+43) 🗒 TypeScript The open source Firebase alternative. Follow to stay updated about our public Beta. — @github-trending-js.bsky.social2 likes and reposts
- Jul 10, 2023📦 supabase / supabase ⭐ 52,961 (+37) 🗒 TypeScript The open source Firebase alternative. Follow to stay updated about our public Beta. — @github-trending-js.bsky.social2 likes and reposts
- Nov 13, 2026🔥 Hot Repo! 🔥 (100+ new stars) 📦 supabase / supabase ⭐ 114,916 (+145) 🗒 TypeScript The Postgres development platform. Supabase gives… — @github-trending-js.bsky.social1 likes and repost
- Oct 12, 2026The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications. 🔗… — @vritrasec.bsky.social1 likes and repost
- Jul 12, 2026🔥 Hot Repo! 🔥 (100+ new stars) 📦 supabase / supabase ⭐ 106,150 (+158) 🗒 TypeScript The Postgres development platform. Supabase gives… — @github-trending-js.bsky.social1 likes and repost
- Jul 3, 2026🔥 Hot Repo! 🔥 (100+ new stars) 📦 supabase / supabase ⭐ 105,238 (+145) 🗒 TypeScript The Postgres development platform. Supabase gives… — @github-trending-js.bsky.social1 likes and repost
- Jul 3, 2026🔥 Hot Repo! 🔥 (100+ new stars) 📦 supabase / supabase ⭐ 105,237 (+145) 🗒 TypeScript The Postgres development platform. Supabase gives… — @github-trending.bsky.social1 likes and repost
- Jan 5, 2026github.com/supabase/supabase GitHub - supabase/supabase: The Postgres development platform. Supabase gives you a dedicated Po... — @technews4869.bsky.social1 likes and repost
- Oct 6, 2025📦 supabase / supabase ⭐ 89,606 (+65) 🗒 TypeScript The Postgres development platform. Supabase gives you a dedicated Postgres database to… — @github-trending-js.bsky.social1 likes and repost
- Sep 13, 2025🔥 Hot Repo! 🔥 (100+ new stars) 📦 supabase / supabase ⭐ 88,563 (+143) 🗒 TypeScript The Postgres development platform. Supabase gives you… — @github-trending-js.bsky.social1 likes and repost
- Sep 13, 2025supabase/supabase The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI… — @postgresql.activitypub.awakari.com.ap.brid.gy1 likes and repost
On GitHub · 25
- Nov 2, 2021Allow long-running transactions at the client side or do relational inserts — supabase/postgrest-js121 reactions · 51 comments
- Mar 31, 2024Can't get rid of getUser() warning — supabase/auth-js89 reactions · 122 comments
- Jan 2, 2024Acquiring an exclusive Navigator LockManager failed — supabase/supabase-js69 reactions · 94 comments
- May 17, 2024Still having getSession warning whenever _saveSession is called — supabase/supabase-js68 reactions · 22 comments
- Oct 19, 2023Proposal: throwOnError should be default behavior — supabase/supabase-js50 reactions · 16 comments
20 more on GitHub
- Jul 19, 2023Stack guards not supported in this environment — supabase/auth-js40 reactions · 48 comments
- Jul 4, 2021Filter source table based on the embedded table(inner join) — supabase/postgrest-js39 reactions · 34 comments
- Jul 15, 2023Json type: Type instantiation is excessively deep and possibly infinite. — supabase/supabase-js36 reactions · 30 comments
- Apr 24, 2024user object warning logged, even when not touching `session.user` — supabase/supabase-js35 reactions · 118 comments
- Jul 18, 2021Support multiple columns filter (AND) in realtime channel filter — supabase/realtime-js35 reactions · 48 comments
- Nov 19, 2021Signed urls for upload — supabase/storage33 reactions · 17 comments
- Jun 12, 2021Allow users to BYO S3-compatible storage backend — supabase/storage33 reactions · 22 comments
- Jul 6, 2021Allow configuration of OAuth2 redirect domain in hosted supabase console — supabase/auth31 reactions · 22 comments
- May 29, 2025supabase docker image 15.8.1.094 does not start on local development with CLI — supabase/cli28 reactions · 43 comments
- Jul 16, 2021Allow user to map custom domain to callback url on Sign with OAuth Provider — supabase/auth26 reactions · 1 comment
- Jul 15, 2025Local server unable to start due to analytics bucket — supabase/cli25 reactions · 25 comments
- Aug 4, 2023Wrong type for joins with one-to-one relationships — supabase/postgrest-js25 reactions · 21 comments
- Jan 10, 2022feat: adds support for wildcards in redirect URIs — supabase/auth22 reactions · 7 comments
- Jan 22, 2021feat(v2): Webpack 5, PostCSS 8 — meta/docusaurus14 reactions · 22 comments
- Oct 25, 2023Update images to match official Supabase Docker compose — supabase-community/supabase-kubernetes11 reactions · 46 comments
- Oct 3, 2022feat: Support for OAuth callback proxy. — supabase/auth11 reactions · 23 comments
- Jan 14, 2022feat: add kubernetes support with Helm — supabase-community/supabase-kubernetes8 reactions · 8 comments
- May 14, 2022Allow to override Supabase service URLs in client — supabase/supabase-js6 reactions · 8 comments
- Oct 3, 2022feat: Support for OAuth callback proxy — supabase/auth-js5 reactions · 1 comment
- Sep 12, 2026Make the iPix Supabase skill load reliably and document safer Edge deployments — amoai-tech/ipixai4 reactions · 3 comments
On Hacker News · 5
- Dec 1, 2021Supabase open sourced their dashboard331 points · 39 comments
- Apr 4, 2020Show HN: Realtime Slack clone using Postgres29 points · 4 comments
- Jul 30, 2020Show HN: A Slack Clone Using Postgres Row Level Security6 points · 1 comment
- Jul 28, 2021Supabase: Open-Source Firebase Alternative4 points
- Feb 10, 2025Select Query Returns Empty Array Despite Existing Data with RLS Enabled #334991 point · 1 comment
In this repository32 other files it gives its agents.
- AGENTS.mdAGENTS.md
- apps/docs/AGENTS.mdAGENTS.md
- apps/kb/AGENTS.mdAGENTS.md
- apps/studio/AGENTS.mdAGENTS.md
- apps/docs/CLAUDE.mdCLAUDE.md
- apps/kb/CLAUDE.mdCLAUDE.md
- apps/studio/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- apps/learn/public/llms.txtllms.txt
- api-typesSkill
- ask-the-docsSkill
- clickhouse-logs-queriesSkill
- copywritingSkill
- dev-toolbar-reviewSkill
- edit-the-docsSkill
- pm-the-docsSkill
- react-hook-formSkill
- review-the-docsSkill
- studio-e2e-testsSkill
- studio-error-handlingSkill
- studio-mock-api-testsSkill
- studio-queriesSkill
- studio-shortcutsSkill
- studio-testingSkill
- studio-ui-patternsSkill
- telemetry-standardsSkill
- test-the-docsSkill
- vercel-composition-patternsSkill
- vitestSkill
- write-the-docsSkill
- explorerSkill
The file
Files
Safe SQL execution
Supabase Studio executes SQL statements directly against the user's database. Because this is the authenticated user's own database, our security model is different from most frontend applications: a user should be able to execute any SQL statement, as long as it is proven that they themselves authored it. What we SHOULD NOT ALLOW is execution of SQL statements that can be influenced by an attacker, such as through URL parameters.
Security model
The security model for SQL execution in Supabase Studio is based on the principle of "proven authorship". This means that a user should only be able to execute SQL statements that they have explicitly authored, and not statements that can be influenced by external input.
There are three classes of SQL fragments:
Hardcoded within the application code. These are safe to execute because they cannot be influenced by an attacker. They can be marked with the
safeSqlutility withpg-meta:import { safeSql } from '@supabase/pg-meta' const sql = safeSql` SELECT * FROM users WHERE id = 1 `safeSqlautomatically creates a string of the branded typeSafeSqlFragment. (See Provenance Tracking below.)Third-party influenceable. These are SQL fragments that can be influenced by an attacker, such as through URL parameters or LLM output. These should be marked with the
untrustedSqlutility withpg-meta:import { untrustedSql } from '@supabase/pg-meta' const unsafeQuery = searchParams.get('query') const querySql = untrustedSql(unsafeQuery)untrustedSqlcreates a string of the branded typeUntrustedSqlFragment. (See Provenance Tracking below.)User-authored. These are SQL fragments that are authored by the user themselves within the UI, for example in a text input field. Because the user is the author, these should be considered safe to execute.
However, there is a caveat, where third-party and user-authored code can mix, contaminating the user-authored code (for example, if an input is prefilled from an unsanitized URL parameter). Provenance tracking helps us track these cases.
For example, a safe input component could be implemented as follows by requiring that its placeholder and controlled value are of type
SafeSqlFragment. In this case we can use its onChange to promote the user input toSafeSqlFragmenttype, because we know that the user is the author of the input. An implementation of this is in @apps/studio/components/ui/SafeSqlInput.tsx:import { rawSql, type SafeSqlFragment } from '@supabase/pg-meta' import type { ChangeEvent, ComponentProps } from 'react' import { Input } from 'ui-patterns/DataInputs/Input' type InputProps = ComponentProps<typeof Input> export type SafeSqlInputProps = Omit< InputProps, 'placeholder' | 'value' | 'onChange' > & { placeholder?: SafeSqlFragment value: SafeSqlFragment onChange?: (event: ChangeEvent<HTMLInputElement>, value: SafeSqlFragment) => void } export const SafeSqlInput = ({ onChange, ...props }: SafeSqlInputProps) => ( <Input {...props} onChange={(event) => onChange?.(event, rawSql(event.target.value))} /> )This is pretty much the ONLY VALID USE CASE of the rawSql export from pg-meta, and it should be used with caution.
Provenance tracking
Branded types are used to track the provenance of SQL fragments. The types,
exported from pg-meta, are:
SafeSqlFragment: represents SQL fragments that are safe to execute, because they are either hardcoded in the application or authored by the user themselves.UntrustedSqlFragment: represents SQL fragments that can be influenced by an attacker, such as through URL parameters or LLM output.
These are valid ways to generate a SafeSqlFragment:
- Using the
safeSqlutility frompg-metato create hardcoded SQL fragments. - Using the sanitization utilities from
pg-metato sanitize untrusted input and promote it to aSafeSqlFragment:identliteralkeyword
- Using the safe SQL manipulation utilities:
joinSqlFragments(frompg-meta)trimSafeSqlFragment(fromapps/studio/lib/sql.ts)
UntrustedSqlFragments can be generated from raw strings using
untrustedSql().
There is also a union type, DisplayableSqlFragment, which represents SQL fragments that can be safely displayed in the UI, but not necessarily executed. This includes both SafeSqlFragment and UntrustedSqlFragment.
Security of SQL round-tripped from the user's database
SQL derived directly from catalog tables (e.g., function definitions, RLS expressions, etc.) is considered safe, and it is promoted AT THE POINT OF BEING QUERIED from the database. In most cases, this is in an apps/studio/data/*/.ts file, in the utility function that makes the API or database fetch.
A critical exception to the safety of SQL round-tripped from the database is
user snippets. These must NEVER BE CONSIDERED SAFE because they are both (a)
externally influenceable and (b) auto-saved. The snippet type uses the
unchecked_sql property, which is an UntrustedSqlFragment, to enforce this.
Promoting SQL fragments to SafeSqlFragment type
Given an insecure string or UntrustedSqlFragment, how do we promote it safely
to a SafeSqlFragment?
Sanitization utilities
This is the preferred method when the input is sanitizable, e.g., it is a relation name, a column name, will be compared as a literal, etc.
The pg-meta library provides the following sanitization utilities that can be
used to safely promote untrusted input to SafeSqlFragment:
ident: for sanitizing identifiers such as table names or column names.literal: for sanitizing literal values that will be used in SQL statements.keyword: for sanitizing SQL keywords.
acceptUntrustedSql
Some untrusted SQL fragments cannot be sanitized with the above utilities. For
example, the USING expression in the RLS policy editor is an arbitrary SQL
expression.
In these cases, we can promote the SQL fragment upon explicit user action. User action indicates that the user has seen the SQL and is OK with running it. For example, an explicit user action could be clicking a "Run" button.
The promotion happens with the acceptUntrustedSql utility from pg-meta,
which takes an UntrustedSqlFragment and returns a SafeSqlFragment.
This utility MUST ONLY BE USED IN event handlers. It should NEVER be used in a useQuery, direct in the render body of a component, in a useEffect, or anywhere it could auto-run without explicit user action.
This is safe:
import { acceptUntrustedSql } from '@supabase/pg-meta'
function SafeComponent() {
const { mutate: execute } = useExecuteSqlMutation()
const handleRun = () => {
// ✅ GOOD: Safe because it is in an event handler which requires a user
// click
execute({ sql: acceptUntrustedSql(/* sql */) })
}
return (
<button onClick={handleRun}>Run</button>
)
}This is unsafe:
import { acceptUntrustedSql } from '@supabase/pg-meta'
function UnsafeComponent() {
const { data } = useQuery({
queryKey: ['execute-sql', sql],
queryFn: () => {
// 🛑 BAD: Unsafe because it is in a query which could auto-run without
// explicit user action
return execute({ sql: acceptUntrustedSql(/* sql */) })
},
})
}Type guarantees
SQL run against the user's Postgres database runs through the executeSql
function, which only takes arguments of type SafeSqlFragment for the SQL
parameter. Raw strings or UntrustedSqlFragments will error at compile time.
Examples
Hard-coded SQL
// ✅ GOOD: Automatically safe with `safeSql` utility
const selectStatement = safeSql`select 1`SQL with sanitizable interpolations
// ✅ GOOD: `pg-meta` utilities sanitize the input
const tableName = ident(userInputTableName)
const searchString = literal(userInputSearchString)
const sqlStatement = safeSql`
SELECT *
FROM ${tableName}
WHERE search_column = ${searchString}
`// 🛑 BAD: Passing raw strings will type error
const tableName = 'my_table'
const sqlStatement = safeSql`
SELECT *
FROM ${tableName}
`Non-sanitizable SQL from a user input
// ✅ GOOD: SafeSqlInput only allows a value that is a SafeSqlFragment
import { SafeSqlInput } from '@apps/studio/components/ui/SafeSqlInput'
function MyComponent() {
const [sql, setSql] = useState<SafeSqlFragment>(safeSql``)
return (
<SafeSqlInput
placeholder={safeSql`Enter your SQL query here...`}
value={sql}
onChange={(event, value) => setSql(value)}
/>
)
}// 🛑 BAD: This input mixes SafeSqlFragments and unsafe strings
function MyBadComponent() {
const [sql, setSql] = useState<SafeSqlFragment>(safeSql``)
return (
<Input
// 🛑 BAD: This is unsafe because the placeholder is a raw string
placeholder="Enter your SQL query here..."
value={sql}
onChange={(event) => setSql(event.target.value)}
/>
)
}Round-tripping SQL from the database (NOT snippet content)
// ✅ GOOD: SQL from the database is promoted to SafeSqlFragment at the point
// of fetching
// data/function-definitions.ts
function markFunctionDefinitionSafe(
functionDefinition: FunctionDefinition
): SafeFunctionDefinition {
return {
...functionDefinition,
definition: functionDefinition.definition as SafeSqlFragment,
}
}
// data/function-definitions.ts
function getFunctionDefinitions() {
return GET(`/function-definitions`).then((functionDefinitions) =>
functionDefinitions.map(markFunctionDefinitionSafe)
)
}// 🛑 BAD: Strings are promoted to SafeSqlFragment in a utility function, where
// it is impossible to easily determine the safety of the input
// utils.ts
function markFunctionDefinitionSafe(
functionDefinition: FunctionDefinition
): SafeFunctionDefinition {
return {
...functionDefinition,
definition: functionDefinition.definition as SafeSqlFragment,
}
}
// Component.ts
function MyComponent() {
const { data: functionDefinitions } = useFunctionDefinitions()
const safeFunctionDefinitions = functionDefinitions.map(markFunctionDefinitionSafe)
}Snippet content is ALWAYS UNSAFE
Snippets are auto-persisted to the database and can be created or modified
through externally influenceable channels (e.g., prefilled from URL params).
The unchecked_sql property is typed as UntrustedSqlFragment to enforce this
— it must only be promoted to SafeSqlFragment via acceptUntrustedSql in an
event handler that requires explicit user action.
// 🛑 BAD: Snippet content is executed automatically via useQuery, with no
// explicit user action confirming that the user has reviewed the SQL.
import { acceptUntrustedSql } from '@supabase/pg-meta'
function UnsafeSnippetPreview({ snippet }: { snippet: Snippet }) {
const { data } = useExecuteSqlQuery({
sql: acceptUntrustedSql(snippet.content.unchecked_sql),
})
return <Results data={data} />
}// 🛑 BAD: Casting bypasses the type system entirely. The snippet's
// `unchecked_sql` is `UntrustedSqlFragment` for a reason — never cast it.
function UnsafeSnippetRunner({ snippet }: { snippet: Snippet }) {
const { mutate: execute } = useExecuteSqlMutation()
useEffect(() => {
execute({ sql: snippet.content.unchecked_sql as SafeSqlFragment })
}, [snippet])
}// ✅ GOOD: Snippet content is only promoted to SafeSqlFragment inside an event
// handler, after the user clicks Run. The user has seen the SQL in the editor
// and explicitly chosen to execute it.
import { acceptUntrustedSql } from '@supabase/pg-meta'
function SnippetRunner({ snippet }: { snippet: Snippet }) {
const { mutate: execute } = useExecuteSqlMutation()
const handleRun = () => {
execute({ sql: acceptUntrustedSql(snippet.content.unchecked_sql) })
}
return (
<>
<SnippetEditor snippet={snippet} />
<button onClick={handleRun}>Run</button>
</>
)
}Analytics SQL (BigQuery / ClickHouse)
The same security model applies to analytics queries, which target BigQuery
or ClickHouse via the
/platform/projects/{ref}/analytics/endpoints/logs.all{,.otel} endpoints.
Filter keys and values from URL parameters and UI inputs are spliced into SQL
that runs against the project's logs, so the same injection risk exists.
Analytics SQL uses its own SafeLogSqlFragment brand
(apps/studio/data/logs/safe-analytics-sql.ts), intentionally disjoint
from the pg-meta SafeSqlFragment brand. The brands are kept separate because
escape semantics differ — Postgres-safe E'…' strings, ::jsonb casts, and
double-quoted identifiers are unsafe for BigQuery and/or ClickHouse, and vice
versa. Crossing the brands would silently emit unsafe SQL.
The wire boundary is executeAnalyticsSql in
apps/studio/data/logs/execute-analytics-sql.ts, analogous to pg-meta's
executeSql; it accepts only SafeLogSqlFragment, and an eslint
no-restricted-syntax rule in apps/studio/eslint.config.cjs blocks direct
post()/get() calls to the logs.all endpoints from any other file.
Build fragments with the helpers in safe-analytics-sql.ts:
safeSql— template tag that only acceptsSafeLogSqlFragmentinterpolations; plain strings and PostgresSafeSqlFragments are rejected at compile time.analyticsLiteral(value)— sanitizes string/number/boolean literals.quotedIdent(name)— validates and backtick-quotes dotted identifiers.keyword(value, allowed)— resolves a value against an allow-list of fragments (e.g.AND/OR); never returns the raw input.joinSqlFragments(fragments, separator)— composes already-branded fragments.
import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'
import { analyticsLiteral, quotedIdent, safeSql } from '@/data/logs/safe-analytics-sql'
// ✅ GOOD: every interpolation is sanitized.
const sql = safeSql`
SELECT timestamp, event_message
FROM ${quotedIdent(table)}
WHERE id = ${analyticsLiteral(id)}
`
await executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end })// 🛑 BAD: raw string interpolation. This fails to type-check at the
// executeAnalyticsSql boundary because the result is `string`, not
// `SafeLogSqlFragment`.
const sql = `SELECT * FROM ${table} WHERE id = '${id}'`
await executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end })The only path that runs SQL not built from these helpers is user-authored
editor text: untrustedLogSql(text) marks it UntrustedLogSqlFragment
(displayable and storable, never executable), and acceptUntrustedLogsSql
promotes it to SafeLogSqlFragment. That promotion is a security boundary
— call it only from a run gesture (Run button click, Cmd+Enter) or an
approval-gated tool call (the AI notebook tools). Never from render,
useEffect, or any automatic path. The notebook persist path also promotes
cells because the writable notebook type requires the safe brand; that is
storage typing, not execution approval, and is not precedent for promoting
anywhere else. The same rule as acceptUntrustedSql on the Postgres side.
Endpoint selection, the OTEL query builders, and the rest of the Studio
wiring live in the clickhouse-logs-queries skill
(references/codebase-integration.md).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

