Skip to content

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

feat(logs): enforce a LIMIT clause in the log explorer (#47630)

Jordi Enric27c1850a9a13
diff --git a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx
index e7f65e2e3ee..f1e17d4ec9d 100644
--- a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx
+++ b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx
@@ -34,6 +34,7 @@ import {
} from './Logs.utils'
import LogSelection from './LogSelection'
import { DefaultErrorRenderer } from './LogsErrorRenderers/DefaultErrorRenderer'
+import { MissingLimitErrorRenderer } from './LogsErrorRenderers/MissingLimitErrorRenderer'
import ResourcesExceededErrorRenderer from './LogsErrorRenderers/ResourcesExceededErrorRenderer'
import { LogsTableEmptyState } from './LogsTableEmptyState'
import { MultiSelectActionBar, type LogCopyFormat } from './MultiSelectActionBar'
@@ -530,6 +531,12 @@ export const LogTable = ({
isCustomQuery: queryType ? false : true,
error: error!,
}
+ if (
+ typeof error === 'object' &&
+ error.error?.errors.find((err) => err.reason === 'missingLimit')
+ ) {
+ return <MissingLimitErrorRenderer />
+ }
if (
typeof error === 'object' &&
error.error?.errors.find((err) => err.reason === 'resourcesExceeded')
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts
index 3452209b79e..76da4c9bd25 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts
@@ -4,6 +4,7 @@ import { LogsTableName } from './Logs.constants'
import type { Filters, LogData } from './Logs.types'
import {
buildLogsPrompt,
+ checkForLimitClause,
extractEdgeFunctionName,
formatLogsAsCsv,
formatLogsAsJson,
@@ -295,4 +296,37 @@ describe('Logs.utils', () => {
expect(sql).toContain('NOT (')
})
})
+
+ describe('checkForLimitClause', () => {
+ test('detects a limit clause regardless of casing', () => {
+ expect(checkForLimitClause('select event_message from edge_logs limit 100')).toBe(true)
+ expect(checkForLimitClause('SELECT event_message FROM edge_logs LIMIT 5')).toBe(true)
+ })
+
+ test('detects a limit clause across newlines', () => {
+ expect(checkForLimitClause('select event_message\nfrom edge_logs\nlimit 50')).toBe(true)
+ })
+
+ test('returns false when no limit clause is present', () => {
+ expect(checkForLimitClause('select event_message from edge_logs')).toBe(false)
+ })
+
+ test('returns false for a bare limit keyword without a row count', () => {
+ expect(checkForLimitClause('select event_message from edge_logs limit')).toBe(false)
+ })
+
+ test('ignores a column named like limit', () => {
+ expect(checkForLimitClause('select limit_reached from edge_logs')).toBe(false)
+ })
+
+ test('ignores the word limit inside a string literal', () => {
+ expect(checkForLimitClause("select event_message from edge_logs where s = 'limit 10'")).toBe(
+ false
+ )
+ })
+
+ test('ignores a limit clause that is commented out', () => {
+ expect(checkForLimitClause('select event_message from edge_logs -- limit 10')).toBe(false)
+ })
+ })
})
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
index 44be04b8b07..75bc018d32f 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
@@ -708,6 +708,13 @@ export function checkForILIKEClause(query: string) {
return ilikeClauseRegex.test(queryWithoutComments)
}
+export function checkForLimitClause(query: string) {
+ const queryWithoutComments = query.replace(/--.*$/gm, '').replace(/\/\*[\s\S]*?\*\//gm, '')
+
+ const limitClauseRegex = /\b(LIMIT)\b\s+\d+(?=(?:[^']*'[^']*')*[^']*$)/i
+ return limitClauseRegex.test(queryWithoutComments)
+}
+
export function checkForWildcard(query: string) {
const queryWithoutComments = query.replace(/--.*$/gm, '').replace(/\/\*[\s\S]*?\*\//gm, '')
diff --git a/apps/studio/components/interfaces/Settings/Logs/LogsErrorRenderers/MissingLimitErrorRenderer.tsx b/apps/studio/components/interfaces/Settings/Logs/LogsErrorRenderers/MissingLimitErrorRenderer.tsx
new file mode 100644
index 00000000000..59dc04c8557
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Logs/LogsErrorRenderers/MissingLimitErrorRenderer.tsx
@@ -0,0 +1,9 @@
+export const MissingLimitErrorRenderer = () => (
+ <div className="flex flex-col items-center justify-center gap-2 text-center h-full px-5">
+ <h3 className="text-lg text-foreground">Add a LIMIT to your query</h3>
+ <p className="text-sm max-w-sm text-foreground-lighter">
+ Queries must include a LIMIT clause to avoid scanning large amounts of data. Add a LIMIT (for
+ example, <span className="font-mono">LIMIT 100</span>) and run the query again.
+ </p>
+ </div>
+)
diff --git a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
index c246e2da385..87522878e74 100644
--- a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
+++ b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
@@ -20,9 +20,15 @@ import {
LOGS_LARGE_DATE_RANGE_DAYS_THRESHOLD,
} from '@/components/interfaces/Settings/Logs/Logs.constants'
import { DatePickerValue } from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
-import { LogData, LogsWarning, LogTemplate } from '@/components/interfaces/Settings/Logs/Logs.types'
+import {
+ LogData,
+ LogQueryError,
+ LogsWarning,
+ LogTemplate,
+} from '@/components/interfaces/Settings/Logs/Logs.types'
import { UpdateSavedQueryModal } from '@/components/interfaces/Settings/Logs/Logs.UpdateSavedQueryModal'
import {
+ checkForLimitClause,
maybeShowUpgradePromptIfNotEntitled,
useEditorHints,
} from '@/components/interfaces/Settings/Logs/Logs.utils'
@@ -74,6 +80,15 @@ const OTEL_PLACEHOLDER_QUERY =
const otelSourceQuery = (source: string) =>
`select\n timestamp,\n event_message,\n log_attributes\nfrom logs\nwhere source = '${source}'\norder by timestamp desc\nlimit 100`
+const MISSING_LIMIT_ERROR: LogQueryError = {
+ error: {
+ code: 400,
+ status: 'INVALID_ARGUMENT',
+ message: 'A LIMIT clause is required.',
+ errors: [{ domain: 'logs', reason: 'missingLimit', message: 'A LIMIT clause is required.' }],
+ },
+}
+
export const LogsExplorerPage: NextPageWithLayout = () => {
useEditorHints()
const monaco = useMonaco()
@@ -123,6 +138,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
const [editorValue, setEditorValue] = useState<string>(PLACEHOLDER_QUERY)
const [saveModalOpen, setSaveModalOpen] = useState<boolean>(false)
const [warnings, setWarnings] = useState<LogsWarning[]>([])
+ const [showMissingLimitError, setShowMissingLimitError] = useState<boolean>(false)
const [selectedLog, setSelectedLog] = useState<LogData | null>(null)
const [rewriteProposal, setRewriteProposal] = useState<{
original: string
@@ -285,6 +301,14 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
// keeps the Run button consistent with the Cmd+Enter keybinding.
const liveValue = editorRef.current?.getValue()
const query = typeof value === 'string' ? value || editorValue : (liveValue ?? editorValue)
+
+ if (!checkForLimitClause(query)) {
+ setShowMissingLimitError(true)
+ setSelectedLog(null)
+ return
+ }
+ setShowMissingLimitError(false)
+
const resolvedParams = buildLogQueryParams(datePickerValue, query)
setSelectedLog(null)
@@ -444,11 +468,14 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
text: 'Querying large date ranges can be slow. Consider selecting a smaller date range.',
})
}
- if (editorValue && !editorValue.toLowerCase().includes('limit')) {
- newWarnings.push({ text: 'When querying large date ranges, include a LIMIT clause.' })
- }
setWarnings(newWarnings)
- }, [editorValue, timestampStart, timestampEnd])
+ }, [timestampStart, timestampEnd])
+
+ useEffect(() => {
+ if (showMissingLimitError && checkForLimitClause(editorValue)) {
+ setShowMissingLimitError(false)
+ }
+ }, [editorValue, showMissingLimitError])
// Show the prompt on page load based on query params
useEffect(() => {
@@ -537,8 +564,8 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
onRun={handleRun}
onSave={handleOnSave}
hasEditorValue={Boolean(editorValue)}
- data={results}
- error={error}
+ data={showMissingLimitError ? [] : results}
+ error={showMissingLimitError ? MISSING_LIMIT_ERROR : error}
projectRef={projectRef}
onSelectedLogChange={setSelectedLog}
selectedLog={selectedLog || undefined}