Skip to content

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

feat(logs): brand legacy analytics SQL stack with SafeLogSqlFragment (#46351)

Charisa7d51cdf52f1
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.test.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.test.ts
index ae651686165..5200cdda492 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.test.ts
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.test.ts
@@ -85,7 +85,7 @@ limit 25`)
expect(getSinceLastDeployInvocationCountSql()).toContain(
'SELECT count(*) as count FROM function_edge_logs'
)
- expect(getSinceLastDeployInvocationCountSql()).toContain("(function_id = '__pending__')")
+ expect(getSinceLastDeployInvocationCountSql()).toContain("(`function_id` = '__pending__')")
expect(
getSinceLastDeployInvocationCount([
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
index 38404bff076..5cf09e190c3 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
@@ -2,6 +2,7 @@ import { IS_PLATFORM } from 'common'
import dayjs from 'dayjs'
import type { DatetimeHelper, FilterTableSet, LogTemplate } from './Logs.types'
+import { analyticsLiteral, safeSql, type SafeLogSqlFragment } from '@/data/logs/safe-analytics-sql'
import { DOCS_URL } from '@/lib/constants'
export const LOGS_EXPLORER_DOCS_URL = `${DOCS_URL}/guides/platform/logs#querying-with-the-logs-explorer`
@@ -285,67 +286,71 @@ limit 100;
},
]
-const _SQL_FILTER_COMMON = {
- search_query: (value: string) => `regexp_contains(event_message, '${value}')`,
+type SqlFilterFn = (value: any) => SafeLogSqlFragment
+type SqlFilterEntry = SafeLogSqlFragment | SqlFilterFn
+
+const _SQL_FILTER_COMMON: Record<string, SqlFilterEntry> = {
+ search_query: (value: string) =>
+ safeSql`regexp_contains(event_message, ${analyticsLiteral(value)})`,
}
-export const SQL_FILTER_TEMPLATES: any = {
+export const SQL_FILTER_TEMPLATES: Record<string, Record<string, SqlFilterEntry>> = {
postgres_logs: {
..._SQL_FILTER_COMMON,
- database: (value: string) => `identifier = '${value}'`,
- 'severity.error': `parsed.error_severity in ('ERROR', 'FATAL', 'PANIC')`,
- 'severity.noError': `parsed.error_severity not in ('ERROR', 'FATAL', 'PANIC')`,
- 'severity.log': `parsed.error_severity = 'LOG'`,
+ database: (value: string) => safeSql`identifier = ${analyticsLiteral(value)}`,
+ 'severity.error': safeSql`parsed.error_severity in ('ERROR', 'FATAL', 'PANIC')`,
+ 'severity.noError': safeSql`parsed.error_severity not in ('ERROR', 'FATAL', 'PANIC')`,
+ 'severity.log': safeSql`parsed.error_severity = 'LOG'`,
},
edge_logs: {
..._SQL_FILTER_COMMON,
- database: (value: string) => `identifier = '${value}'`,
- 'status_code.error': `response.status_code between 500 and 599`,
- 'status_code.success': `response.status_code between 200 and 299`,
- 'status_code.warning': `response.status_code between 400 and 499`,
+ database: (value: string) => safeSql`identifier = ${analyticsLiteral(value)}`,
+ 'status_code.error': safeSql`response.status_code between 500 and 599`,
+ 'status_code.success': safeSql`response.status_code between 200 and 299`,
+ 'status_code.warning': safeSql`response.status_code between 400 and 499`,
- 'product.database': `request.path like '/rest/%' or request.path like '/graphql/%'`,
- 'product.storage': `request.path like '/storage/%'`,
- 'product.auth': `request.path like '/auth/%'`,
- 'product.realtime': `request.path like '/realtime/%'`,
+ 'product.database': safeSql`request.path like '/rest/%' or request.path like '/graphql/%'`,
+ 'product.storage': safeSql`request.path like '/storage/%'`,
+ 'product.auth': safeSql`request.path like '/auth/%'`,
+ 'product.realtime': safeSql`request.path like '/realtime/%'`,
- 'method.get': `request.method = 'GET'`,
- 'method.post': `request.method = 'POST'`,
- 'method.put': `request.method = 'PUT'`,
- 'method.patch': `request.method = 'PATCH'`,
- 'method.delete': `request.method = 'DELETE'`,
- 'method.options': `request.method = 'OPTIONS'`,
+ 'method.get': safeSql`request.method = 'GET'`,
+ 'method.post': safeSql`request.method = 'POST'`,
+ 'method.put': safeSql`request.method = 'PUT'`,
+ 'method.patch': safeSql`request.method = 'PATCH'`,
+ 'method.delete': safeSql`request.method = 'DELETE'`,
+ 'method.options': safeSql`request.method = 'OPTIONS'`,
},
function_edge_logs: {
..._SQL_FILTER_COMMON,
- 'status_code.error': `response.status_code between 500 and 599`,
- 'status_code.success': `response.status_code between 200 and 299`,
- 'status_code.warning': `response.status_code between 400 and 499`,
+ 'status_code.error': safeSql`response.status_code between 500 and 599`,
+ 'status_code.success': safeSql`response.status_code between 200 and 299`,
+ 'status_code.warning': safeSql`response.status_code between 400 and 499`,
},
function_logs: {
..._SQL_FILTER_COMMON,
- 'severity.error': `metadata.level = 'error'`,
- 'severity.notError': `metadata.level != 'error'`,
- 'severity.log': `metadata.level = 'log'`,
- 'severity.info': `metadata.level = 'info'`,
- 'severity.debug': `metadata.level = 'debug'`,
- 'severity.warn': `metadata.level = 'warn'`,
+ 'severity.error': safeSql`metadata.level = 'error'`,
+ 'severity.notError': safeSql`metadata.level != 'error'`,
+ 'severity.log': safeSql`metadata.level = 'log'`,
+ 'severity.info': safeSql`metadata.level = 'info'`,
+ 'severity.debug': safeSql`metadata.level = 'debug'`,
+ 'severity.warn': safeSql`metadata.level = 'warn'`,
},
auth_logs: {
..._SQL_FILTER_COMMON,
- 'severity.error': `metadata.level = 'error' or metadata.level = 'fatal'`,
- 'severity.warning': `metadata.level = 'warning'`,
- 'severity.info': `metadata.level = 'info'`,
- 'status_code.server_error': `cast(metadata.status as int64) between 500 and 599`,
- 'status_code.client_error': `cast(metadata.status as int64) between 400 and 499`,
- 'status_code.redirection': `cast(metadata.status as int64) between 300 and 399`,
- 'status_code.success': `cast(metadata.status as int64) between 200 and 299`,
- 'endpoints.admin': `REGEXP_CONTAINS(metadata.path, "/admin")`,
- 'endpoints.signup': `REGEXP_CONTAINS(metadata.path, "/signup|/invite|/verify")`,
- 'endpoints.authentication': `REGEXP_CONTAINS(metadata.path, "/token|/authorize|/callback|/otp|/magiclink")`,
- 'endpoints.recover': `REGEXP_CONTAINS(metadata.path, "/recover")`,
- 'endpoints.user': `REGEXP_CONTAINS(metadata.path, "/user")`,
- 'endpoints.logout': `REGEXP_CONTAINS(metadata.path, "/logout")`,
+ 'severity.error': safeSql`metadata.level = 'error' or metadata.level = 'fatal'`,
+ 'severity.warning': safeSql`metadata.level = 'warning'`,
+ 'severity.info': safeSql`metadata.level = 'info'`,
+ 'status_code.server_error': safeSql`cast(metadata.status as int64) between 500 and 599`,
+ 'status_code.client_error': safeSql`cast(metadata.status as int64) between 400 and 499`,
+ 'status_code.redirection': safeSql`cast(metadata.status as int64) between 300 and 399`,
+ 'status_code.success': safeSql`cast(metadata.status as int64) between 200 and 299`,
+ 'endpoints.admin': safeSql`REGEXP_CONTAINS(metadata.path, "/admin")`,
+ 'endpoints.signup': safeSql`REGEXP_CONTAINS(metadata.path, "/signup|/invite|/verify")`,
+ 'endpoints.authentication': safeSql`REGEXP_CONTAINS(metadata.path, "/token|/authorize|/callback|/otp|/magiclink")`,
+ 'endpoints.recover': safeSql`REGEXP_CONTAINS(metadata.path, "/recover")`,
+ 'endpoints.user': safeSql`REGEXP_CONTAINS(metadata.path, "/user")`,
+ 'endpoints.logout': safeSql`REGEXP_CONTAINS(metadata.path, "/logout")`,
},
realtime_logs: {
..._SQL_FILTER_COMMON,
@@ -355,14 +360,14 @@ export const SQL_FILTER_TEMPLATES: any = {
},
postgrest_logs: {
..._SQL_FILTER_COMMON,
- database: (value: string) => `identifier = '${value}'`,
+ database: (value: string) => safeSql`identifier = ${analyticsLiteral(value)}`,
},
pgbouncer_logs: {
..._SQL_FILTER_COMMON,
},
supavisor_logs: {
..._SQL_FILTER_COMMON,
- database: (value: string) => `m.project like '${value}%'`,
+ database: (value: string) => safeSql`m.project like ${analyticsLiteral(value + '%')}`,
},
pg_upgrade_logs: {
..._SQL_FILTER_COMMON,
@@ -372,7 +377,7 @@ export const SQL_FILTER_TEMPLATES: any = {
},
etl_replication_logs: {
..._SQL_FILTER_COMMON,
- pipeline_id: (value: string | number) => `pipeline_id = ${value}`,
+ pipeline_id: (value: string | number) => safeSql`pipeline_id = ${analyticsLiteral(value)}`,
},
}
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
index 5bcd418f0e0..0636cd65fbf 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
@@ -10,6 +10,13 @@ import { LogsTableName, SQL_FILTER_TEMPLATES } from './Logs.constants'
import type { Filters, LogData, LogsEndpointParams, QueryType } from './Logs.types'
import { convertResultsToCSV } from '@/components/interfaces/SQLEditor/UtilityPanel/Results.utils'
import BackwardIterator from '@/components/ui/CodeEditor/Providers/BackwardIterator'
+import {
+ analyticsLiteral,
+ joinSqlFragments,
+ quotedIdent,
+ safeSql,
+ type SafeLogSqlFragment,
+} from '@/data/logs/safe-analytics-sql'
/**
* Convert a micro timestamp from number/string to iso timestamp
@@ -74,35 +81,36 @@ const getDotKeys = (obj: { [k: string]: unknown }, parent?: string): string[] =>
*
* @returns a where statement with WHERE clause.
*/
-const genWhereStatement = (table: LogsTableName, filters: Filters) => {
+const buildWhereClauses = (table: LogsTableName, filters: Filters): SafeLogSqlFragment[] => {
const keys = Object.keys(filters)
const filterTemplates = SQL_FILTER_TEMPLATES[table]
-
- const _resolveTemplateToStatement = (dotKey: string): string | null => {
+ const _resolveTemplateToStatement = (dotKey: string): SafeLogSqlFragment | null => {
const template = filterTemplates[dotKey]
const value = get(filters, dotKey)
- if (value !== undefined && typeof template === 'function') {
- return template(value)
- } else if (template === undefined) {
- // resolve unknown filters (possibly from filter overrides)
- // no template, set a default
- if (typeof value === 'string') {
- return `${dotKey} = '${value}'`
- } else {
- return `${dotKey} = ${value}`
+
+ if (template === undefined) {
+ // Unknown filter from a filter override — generic equality predicate; drop on bad input.
+ if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
+ return null
+ }
+ try {
+ return safeSql`${quotedIdent(dotKey)} = ${analyticsLiteral(value)}`
+ } catch {
+ return null
}
- } else if (value === undefined && typeof template === 'function') {
- return null
- } else if (template && value === false) {
- // template present, but value is false
- return null
- } else {
- return template
}
+
+ if (typeof template === 'function') {
+ return value !== undefined ? template(value) : null
+ }
+
+ // template is SafeLogSqlFragment — emit unless the filter is explicitly disabled
+ if (!template || value === false) return null
+ return template
}
- const statement = keys
- .map((rootKey) => {
+ return keys
+ .map((rootKey): SafeLogSqlFragment | null => {
if (
filters[rootKey] === undefined ||
(typeof filters[rootKey] === 'string' && (filters[rootKey] as string).length === 0)
@@ -112,128 +120,135 @@ const genWhereStatement = (table: LogsTableName, filters: Filters) => {
// join all statements with an OR
const nestedStatements = getDotKeys(filters[rootKey] as Filters, rootKey)
.map(_resolveTemplateToStatement)
- .filter(Boolean)
+ .filter((s) => s !== null)
if (nestedStatements.length > 0) {
- return `(${nestedStatements.join(' or ')})`
+ return safeSql`(${joinSqlFragments(nestedStatements, ' or ')})`
} else {
return null
}
} else {
const nestedStatement = _resolveTemplateToStatement(rootKey)
if (nestedStatement === null) return null
- return `(${nestedStatement})`
+ return safeSql`(${nestedStatement})`
}
})
- .filter(Boolean)
- // join all root statements with AND
- .join(' and ')
+ .filter((s) => s !== null)
+}
- if (statement) {
- return 'where ' + statement
- } else {
- return ''
- }
+const genWhereStatement = (table: LogsTableName, filters: Filters): SafeLogSqlFragment => {
+ const clauses = buildWhereClauses(table, filters)
+ return clauses.length > 0 ? safeSql`where ${joinSqlFragments(clauses, ' and ')}` : safeSql``
}
-export const genDefaultQuery = (table: LogsTableName, filters: Filters, limit: number = 100) => {
+export const genDefaultQuery = (
+ table: LogsTableName,
+ filters: Filters,
+ limit: number = 100
+): SafeLogSqlFragment => {
const where = genWhereStatement(table, filters)
const joins = genCrossJoinUnnests(table)
- const orderBy = 'order by timestamp desc'
+ const orderBy = safeSql`order by timestamp desc`
+ const limitLit = analyticsLiteral(limit)
switch (table) {
case 'edge_logs':
if (!IS_PLATFORM) {
- return `
+ return safeSql`
-- local dev edge_logs query
select id, edge_logs.timestamp, event_message, request.method, request.path, request.search, response.status_code
from edge_logs
${joins}
${where}
${orderBy}
-limit ${limit};
+limit ${limitLit};
`
}
- return `select id, identifier, timestamp, event_message, request.method, request.path, request.search, response.status_code
- from ${table}
+ return safeSql`select id, identifier, timestamp, event_message, request.method, request.path, request.search, response.status_code
+ from ${LOG_TABLE_SQL[table]}
${joins}
${where}
${orderBy}
- limit ${limit}
+ limit ${limitLit}
`
case 'postgres_logs':
if (!IS_PLATFORM) {
- return `
+ return safeSql`
select postgres_logs.timestamp, id, event_message, parsed.error_severity, parsed.detail, parsed.hint
from postgres_logs
${joins}
${where}
${orderBy}
-limit ${limit}
+limit ${limitLit}
`
}
- return `select identifier, postgres_logs.timestamp, id, event_message, parsed.error_severity, parsed.detail, parsed.hint from ${table}
+ return safeSql`select identifier, postgres_logs.timestamp, id, event_message, parsed.error_severity, parsed.detail, parsed.hint from ${LOG_TABLE_SQL[table]}
${joins}
${where}
${orderBy}
- limit ${limit}
+ limit ${limitLit}
`
case 'function_logs':
- return `select id, ${table}.timestamp, event_message, metadata.event_type, metadata.function_id, metadata.execution_id, metadata.level from ${table}
+ return safeSql`select id, ${LOG_TABLE_SQL[table]}.timestamp, event_message, metadata.event_type, metadata.function_id, metadata.execution_id, metadata.level from ${LOG_TABLE_SQL[table]}
${joins}
${where}
${orderBy}
- limit ${limit}
+ limit ${limitLit}
`
case 'auth_logs':
- return `select id, ${table}.timestamp, event_message, metadata.level, metadata.status, metadata.path, metadata.msg as msg, metadata.error from ${table}
+ return safeSql`select id, ${LOG_TABLE_SQL[table]}.timestamp, event_message, metadata.level, metadata.status, metadata.path, metadata.msg as msg, metadata.error from ${LOG_TABLE_SQL[table]}
${joins}
${where}
${orderBy}
- limit ${limit}
+ limit ${limitLit}
`
case 'function_edge_logs':
if (!IS_PLATFORM) {
- return `
+ return safeSql`
select id, function_edge_logs.timestamp, event_message
from function_edge_logs
${orderBy}
-limit ${limit}
+limit ${limitLit}
`
}
- return `select id, ${table}.timestamp, event_message, response.status_code, request.method, request.pathname, m.function_id, m.execution_id, m.execution_time_ms, m.deployment_id, m.version from ${table}
+ return safeSql`select id, ${LOG_TABLE_SQL[table]}.timestamp, event_message, response.status_code, request.method, request.pathname, m.function_id, m.execution_id, m.execution_time_ms, m.deployment_id, m.version from ${LOG_TABLE_SQL[table]}
${joins}
${where}
${orderBy}
- limit ${limit}
+ limit ${limitLit}
`
+
case 'supavisor_logs':
- return `select id, ${table}.timestamp, event_message from ${table} ${joins} ${where} ${orderBy} limit ${limit}`
+ return safeSql`select id, ${LOG_TABLE_SQL[table]}.timestamp, event_message from ${LOG_TABLE_SQL[table]} ${joins} ${where} ${orderBy} limit ${limitLit}`
case 'pg_upgrade_logs':
- return `select id, ${table}.timestamp, event_message from ${table} ${joins} ${where} ${orderBy} limit 100`
-
- default:
- return `select id, ${table}.timestamp, event_message from ${table}
- ${where}
- ${orderBy}
- limit ${limit}
- `
-
- case 'pg_cron_logs':
- const pgCronWhere = where ? `${basePgCronWhere} AND ${where.substring(6)}` : basePgCronWhere
-
- return `select id, postgres_logs.timestamp, event_message, parsed.error_severity, parsed.query
+ return safeSql`select id, ${LOG_TABLE_SQL[table]}.timestamp, event_message from ${LOG_TABLE_SQL[table]} ${joins} ${where} ${orderBy} limit ${analyticsLiteral(100)}`
+
+ case 'pg_cron_logs': {
+ const userClauses = buildWhereClauses(table, filters)
+ const pgCronWhere =
+ userClauses.length > 0
+ ? safeSql`where ${basePgCronConditions} AND ${joinSqlFragments(userClauses, ' and ')}`
+ : basePgCronWhere
+ return safeSql`select id, postgres_logs.timestamp, event_message, parsed.error_severity, parsed.query
from postgres_logs
${joins}
${pgCronWhere}
${orderBy}
-limit ${limit}
+limit ${limitLit}
`
+ }
+
+ default:
+ return safeSql`select id, ${LOG_TABLE_SQL[table]}.timestamp, event_message from ${LOG_TABLE_SQL[table]}
+ ${where}
+ ${orderBy}
+ limit ${limitLit}
+ `
}
}
@@ -241,42 +256,60 @@ limit ${limit}
* Hardcoded cross join unnests and aliases for each table.
* Should be used together with the getWhereStatements to allow for filtering on aliases
*/
-const genCrossJoinUnnests = (table: LogsTableName) => {
+const genCrossJoinUnnests = (table: LogsTableName): SafeLogSqlFragment => {
switch (table) {
case 'edge_logs':
- return `cross join unnest(metadata) as m
+ return safeSql`cross join unnest(metadata) as m
cross join unnest(m.request) as request
cross join unnest(m.response) as response`
case 'pg_cron_logs':
case 'postgres_logs':
- return `cross join unnest(metadata) as m
+ return safeSql`cross join unnest(metadata) as m
cross join unnest(m.parsed) as parsed`
case 'function_logs':
- return `cross join unnest(metadata) as metadata`
+ return safeSql`cross join unnest(metadata) as metadata`
case 'auth_logs':
- return `cross join unnest(metadata) as metadata`
+ return safeSql`cross join unnest(metadata) as metadata`
case 'function_edge_logs':
- return `cross join unnest(metadata) as m
+ return safeSql`cross join unnest(metadata) as m
cross join unnest(m.response) as response
cross join unnest(m.request) as request`
case 'supavisor_logs':
- return `cross join unnest(metadata) as m`
+ return safeSql`cross join unnest(metadata) as m`
default:
- return ''
+ return safeSql``
}
}
+/** Brand-safe table name literals for analytics SQL. */
+export const LOG_TABLE_SQL: Record<LogsTableName, SafeLogSqlFragment> = {
+ [LogsTableName.EDGE]: safeSql`edge_logs`,
+ [LogsTableName.POSTGRES]: safeSql`postgres_logs`,
+ [LogsTableName.FUNCTIONS]: safeSql`function_logs`,
+ [LogsTableName.FN_EDGE]: safeSql`function_edge_logs`,
+ [LogsTableName.AUTH]: safeSql`auth_logs`,
+ [LogsTableName.AUTH_AUDIT]: safeSql`auth_audit_logs`,
+ [LogsTableName.REALTIME]: safeSql`realtime_logs`,
+ [LogsTableName.STORAGE]: safeSql`storage_logs`,
+ [LogsTableName.POSTGREST]: safeSql`postgrest_logs`,
+ [LogsTableName.SUPAVISOR]: safeSql`supavisor_logs`,
+ [LogsTableName.PGBOUNCER]: safeSql`pgbouncer_logs`,
+ [LogsTableName.PG_UPGRADE]: safeSql`pg_upgrade_logs`,
+ [LogsTableName.PG_CRON]: safeSql`pg_cron_logs`,
+ [LogsTableName.ETL]: safeSql`etl_replication_logs`,
+}
+
/**
* SQL query to retrieve only one log
*/
-export const genSingleLogQuery = (table: LogsTableName, id: string) =>
- `select id, timestamp, event_message, metadata from ${table} where id = '${id}' limit 1`
+export const genSingleLogQuery = (table: LogsTableName, id: string): SafeLogSqlFragment =>
+ safeSql`select id, timestamp, event_message, metadata from ${LOG_TABLE_SQL[table]} where id = ${analyticsLiteral(id)} limit 1`
/**
* Determine if we should show the user an upgrade prompt while browsing logs
@@ -290,16 +323,14 @@ export const maybeShowUpgradePromptIfNotEntitled = (
return day > entitledToDays
}
-export const genCountQuery = (table: LogsTableName, filters: Filters): string => {
+export const genCountQuery = (table: LogsTableName, filters: Filters): SafeLogSqlFragment => {
let where = genWhereStatement(table, filters)
- // pg_cron logs are a subset of postgres logs
- // to calculate the chart, we need to query postgres logs
if (table === LogsTableName.PG_CRON) {
table = LogsTableName.POSTGRES
where = basePgCronWhere
}
const joins = genCrossJoinUnnests(table)
- return `SELECT count(*) as count FROM ${table} ${joins} ${where}`
+ return safeSql`SELECT count(*) as count FROM ${LOG_TABLE_SQL[table]} ${joins} ${where}`
}
/** calculates how much the chart start datetime should be offset given the current datetime filter params */
@@ -325,9 +356,16 @@ const calcChartStart = (
}
// TODO(qiao): workaround for self-hosted cron logs error until logflare is fixed
-const basePgCronWhere = IS_PLATFORM
- ? `where ( parsed.application_name = 'pg_cron' or regexp_contains(event_message, 'cron job') )`
- : `where ( parsed.application_name = 'pg_cron' or event_message::text LIKE '%cron job%' )`
+const basePgCronConditions: SafeLogSqlFragment = IS_PLATFORM
+ ? safeSql`( parsed.application_name = 'pg_cron' or regexp_contains(event_message, 'cron job') )`
+ : safeSql`( parsed.application_name = 'pg_cron' or event_message::text LIKE '%cron job%' )`
+const basePgCronWhere: SafeLogSqlFragment = safeSql`where ${basePgCronConditions}`
+
+const TRUNC_SQL: Record<'minute' | 'hour' | 'day', SafeLogSqlFragment> = {
+ minute: safeSql`minute`,
+ hour: safeSql`hour`,
+ day: safeSql`day`,
+}
/**
*
* generates log event chart query
@@ -336,7 +374,7 @@ export const genChartQuery = (
table: LogsTableName,
params: LogsEndpointParams,
filters: Filters
-) => {
+): SafeLogSqlFragment => {
const [startOffset, trunc] = calcChartStart(params)
let where = genWhereStatement(table, filters)
const errorCondition = getErrorCondition(table)
@@ -349,29 +387,28 @@ export const genChartQuery = (
where = basePgCronWhere
}
- let joins = genCrossJoinUnnests(table)
+ const joins = genCrossJoinUnnests(table)
+ const tsLit = analyticsLiteral(startOffset.toISOString())
+ const whereFragment: SafeLogSqlFragment = where
+ ? safeSql`${where} and t.timestamp > ${tsLit}`
+ : safeSql`where t.timestamp > ${tsLit}`
- const q = `
+ return safeSql`
SELECT
-- log-event-chart
- timestamp_trunc(t.timestamp, ${trunc}) as timestamp,
+ timestamp_trunc(t.timestamp, ${TRUNC_SQL[trunc]}) as timestamp,
count(CASE WHEN NOT (${errorCondition} OR ${warningCondition}) THEN 1 END) as ok_count,
count(CASE WHEN ${errorCondition} THEN 1 END) as error_count,
count(CASE WHEN ${warningCondition} THEN 1 END) as warning_count,
FROM
- ${table} t
+ ${LOG_TABLE_SQL[table]} t
${joins}
- ${
- where
- ? where + ` and t.timestamp > '${startOffset.toISOString()}'`
- : `where t.timestamp > '${startOffset.toISOString()}'`
- }
+ ${whereFragment}
GROUP BY
timestamp
ORDER BY
timestamp ASC
`
- return q
}
type TsPair = [string | '', string | '']
@@ -648,39 +685,39 @@ export function checkForWildcard(query: string) {
return wildcardRegex.test(queryWithoutCount)
}
-function getErrorCondition(table: LogsTableName): string {
+function getErrorCondition(table: LogsTableName): SafeLogSqlFragment {
switch (table) {
case 'edge_logs':
- return 'response.status_code >= 500'
+ return safeSql`response.status_code >= 500`
case 'postgres_logs':
- return "parsed.error_severity IN ('ERROR', 'FATAL', 'PANIC')"
+ return safeSql`parsed.error_severity IN ('ERROR', 'FATAL', 'PANIC')`
case 'auth_logs':
- return "metadata.level = 'error' OR SAFE_CAST(metadata.status AS INT64) >= 400"
+ return safeSql`metadata.level = 'error' OR SAFE_CAST(metadata.status AS INT64) >= 400`
case 'function_edge_logs':
- return 'response.status_code >= 500'
+ return safeSql`response.status_code >= 500`
case 'function_logs':
- return "metadata.level IN ('error', 'fatal')"
+ return safeSql`metadata.level IN ('error', 'fatal')`
case 'pg_cron_logs':
- return "parsed.error_severity IN ('ERROR', 'FATAL', 'PANIC')"
+ return safeSql`parsed.error_severity IN ('ERROR', 'FATAL', 'PANIC')`
default:
- return 'false'
+ return safeSql`false`
}
}
-function getWarningCondition(table: LogsTableName): string {
+function getWarningCondition(table: LogsTableName): SafeLogSqlFragment {
switch (table) {
case 'edge_logs':
- return 'response.status_code >= 400 AND response.status_code < 500'
+ return safeSql`response.status_code >= 400 AND response.status_code < 500`
case 'postgres_logs':
- return "parsed.error_severity IN ('WARNING')"
+ return safeSql`parsed.error_severity IN ('WARNING')`
case 'auth_logs':
- return "metadata.level = 'warning'"
+ return safeSql`metadata.level = 'warning'`
case 'function_edge_logs':
- return 'response.status_code >= 400 AND response.status_code < 500'
+ return safeSql`response.status_code >= 400 AND response.status_code < 500`
case 'function_logs':
- return "metadata.level IN ('warning')"
+ return safeSql`metadata.level IN ('warning')`
default:
- return 'false'
+ return safeSql`false`
}
}
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.bq.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.bq.ts
index 375231d47cd..1351862eab9 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.bq.ts
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.bq.ts
@@ -9,9 +9,9 @@ import dayjs from 'dayjs'
import { DEFAULT_LOG_TYPES } from './UnifiedLogs.constants'
import { QuerySearchParamsType, SearchParamsType } from './UnifiedLogs.types'
import {
- bqIdent,
joinSqlFragments,
analyticsLiteral as lit,
+ quotedIdent,
safeSql,
type SafeLogSqlFragment,
} from '@/data/logs/safe-analytics-sql'
@@ -27,7 +27,7 @@ const EXCLUDED_QUERY_PARAMS = [...PAGINATION_PARAMS, ...SPECIAL_FILTER_PARAMS] a
/**
* Builds WHERE-clause fragments from a search-param map. Identifier-position
- * keys are validated via `bqIdent()` (regex allowlist) and value-position
+ * keys are validated via `quotedIdent()` (regex allowlist) and value-position
* inputs via `analyticsLiteral` — both throw on disallowed input, in which
* case we drop the predicate rather than emit unsafe SQL.
*
@@ -47,11 +47,11 @@ const buildConditions = (
if ((EXCLUDED_QUERY_PARAMS as readonly string[]).includes(key)) return
try {
- // `key` is interpolated as a column identifier. `bqIdent()` rejects
+ // `key` is interpolated as a column identifier. `quotedIdent()` rejects
// anything outside `[A-Za-z_][A-Za-z0-9_]*` (notably no spaces, so a
// crafted URL key like `level OR id IS NOT NULL` is dropped rather
// than emitted into the WHERE clause).
- const col = bqIdent(key)
+ const col = quotedIdent(key)
if (Array.isArray(value) && value.length > 0) {
const inList = joinSqlFragments(
@@ -70,7 +70,7 @@ const buildConditions = (
}
}
} catch {
- // bqIdent() or analyticsLiteral() rejected the input — drop the predicate.
+ // quotedIdent() or analyticsLiteral() rejected the input — drop the predicate.
}
})
@@ -385,17 +385,18 @@ export const getFacetCountCTE = ({
search,
facet,
facetSearch,
+ cteName,
}: {
search: QuerySearchParamsType
facet: string
facetSearch?: string
+ cteName: SafeLogSqlFragment
}): SafeLogSqlFragment => {
const MAX_FACETS_QUANTITY = 20
// `facet` is used both as a column reference and to derive a CTE name;
- // quote each appropriately with bqIdent() to reject non-identifier inputs.
- const facetCol = bqIdent(facet)
- const facetCte = bqIdent(facet + '_count')
+ // quote each appropriately with quotedIdent() to reject non-identifier inputs.
+ const facetCol = quotedIdent(facet)
const baseConditions = buildConditions(search, facet)
const facetSearchClause = facetSearch
? safeSql`AND ${facetCol} LIKE ${lit('%' + facetSearch + '%')}`
@@ -407,7 +408,7 @@ export const getFacetCountCTE = ({
: safeSql`WHERE ${facetCol} IS NOT NULL`
return safeSql`
-${facetCte} AS (
+${cteName} AS (
SELECT ${lit(facet)} as dimension, ${facetCol} as value, COUNT(*) as count
FROM unified_logs
${where}
@@ -552,9 +553,9 @@ level_counts AS (
),
-- Variable facets: open-ended values still need GROUP BY
-${getFacetCountCTE({ search, facet: 'method' })},
-${getFacetCountCTE({ search, facet: 'status' })},
-${getFacetCountCTE({ search, facet: 'pathname' })}
+${getFacetCountCTE({ search, facet: 'method', cteName: safeSql`method_count` })},
+${getFacetCountCTE({ search, facet: 'status', cteName: safeSql`status_count` })},
+${getFacetCountCTE({ search, facet: 'pathname', cteName: safeSql`pathname_count` })}
SELECT 'total' AS dimension, 'all' AS value, total AS count FROM log_type_counts
UNION ALL SELECT 'log_type', 'edge', edge_count FROM log_type_counts
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.test.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.test.ts
index 1b3fb3f5033..03088995abc 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.test.ts
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.test.ts
@@ -179,7 +179,7 @@ describe('UnifiedLogs.queries.bq', () => {
})
it('rejects keys with non-identifier characters', () => {
- // A key like "foo; DROP TABLE" fails the bqIdent regex (the `;` is not
+ // A key like "foo; DROP TABLE" fails the quotedIdent regex (the `;` is not
// in `[A-Za-z_][A-Za-z0-9_]*`), so the predicate is dropped entirely.
const sql = getUnifiedLogsQueryBQ({ ...baseSearch, 'foo; DROP TABLE x': 'y' } as any)
expect(sql).not.toContain('DROP TABLE')
diff --git a/apps/studio/data/logs/execute-analytics-sql.ts b/apps/studio/data/logs/execute-analytics-sql.ts
index 5e3e7a77de7..4fcd36abb1d 100644
--- a/apps/studio/data/logs/execute-analytics-sql.ts
+++ b/apps/studio/data/logs/execute-analytics-sql.ts
@@ -9,11 +9,12 @@
* See .claude/skills/safe-sql-execution/SKILL.md for the full security model.
*/
import type { SafeLogSqlFragment } from './safe-analytics-sql'
-import { handleError, post } from '@/data/fetchers'
+import { get, handleError, post } from '@/data/fetchers'
/**
- * Analytics endpoints that accept a POST body with `{ sql, iso_timestamp_start, iso_timestamp_end }`.
- * Extend this union as additional endpoints are migrated to the safe-analytics-sql pattern.
+ * Analytics endpoints that accept `{ sql, iso_timestamp_start, iso_timestamp_end }`
+ * either as a POST body or GET query string. Extend this union as additional
+ * endpoints are migrated to the safe-analytics-sql pattern.
*/
export type AnalyticsSqlEndpoint =
| '/platform/projects/{ref}/analytics/endpoints/logs.all'
@@ -26,6 +27,8 @@ export interface ExecuteAnalyticsSqlVariables {
sql: SafeLogSqlFragment
iso_timestamp_start: string
iso_timestamp_end: string
+ /** Defaults to 'post'. Use 'get' to preserve wire behavior when migrating legacy GET callers. */
+ method?: 'get' | 'post'
signal?: AbortSignal
headers?: HeadersInit
}
@@ -36,14 +39,30 @@ export async function executeAnalyticsSql({
sql,
iso_timestamp_start,
iso_timestamp_end,
+ method = 'post',
signal,
headers: headersInit,
}: ExecuteAnalyticsSqlVariables) {
+ const headers = headersInit !== undefined ? new Headers(headersInit) : undefined
+
+ if (method === 'get') {
+ const { data, error } = await get(endpoint, {
+ params: {
+ path: { ref: projectRef },
+ query: { sql, iso_timestamp_start, iso_timestamp_end },
+ },
+ signal,
+ headers,
+ })
+ if (error) handleError(error)
+ return data
+ }
+
const { data, error } = await post(endpoint, {
params: { path: { ref: projectRef } },
body: { sql, iso_timestamp_start, iso_timestamp_end },
signal,
- headers: headersInit !== undefined ? new Headers(headersInit) : undefined,
+ headers,
})
if (error) handleError(error)
return data
diff --git a/apps/studio/data/logs/safe-analytics-sql.test.ts b/apps/studio/data/logs/safe-analytics-sql.test.ts
index 358027004ca..376d721e03d 100644
--- a/apps/studio/data/logs/safe-analytics-sql.test.ts
+++ b/apps/studio/data/logs/safe-analytics-sql.test.ts
@@ -1,15 +1,7 @@
import { describe, expect, it } from 'vitest'
import { executeAnalyticsSql } from './execute-analytics-sql'
-import {
- analyticsLiteral,
- bqDottedIdent,
- bqIdent,
- clickhouseDottedIdent,
- clickhouseIdent,
- keyword,
- safeSql,
-} from './safe-analytics-sql'
+import { analyticsLiteral, keyword, quotedIdent, safeSql } from './safe-analytics-sql'
describe('keyword', () => {
it('returns the matching SafeLogSqlFragment from the allow-list', () => {
@@ -35,63 +27,29 @@ describe('keyword', () => {
})
})
-describe('bqDottedIdent', () => {
- it('wraps a single-segment identifier in backticks', () => {
- expect(bqDottedIdent('status')).toBe('`status`')
+describe('quotedIdent', () => {
+ it('backtick-quotes a single-segment identifier', () => {
+ expect(quotedIdent('status')).toBe('`status`')
})
- it('wraps the entire two-part dotted path in a single pair of backticks', () => {
- expect(bqDottedIdent('request.method')).toBe('`request.method`')
+ it('backtick-quotes each segment of a two-part dotted path individually', () => {
+ expect(quotedIdent('request.method')).toBe('`request`.`method`')
})
- it('wraps the entire three-part dotted path in a single pair of backticks', () => {
- expect(bqDottedIdent('a.b.c')).toBe('`a.b.c`')
+ it('backtick-quotes each segment of a three-part dotted path individually', () => {
+ expect(quotedIdent('a.b.c')).toBe('`a`.`b`.`c`')
})
it('throws for an empty string', () => {
- expect(() => bqDottedIdent('')).toThrow('invalid BigQuery dotted identifier')
+ expect(() => quotedIdent('')).toThrow('invalid identifier')
})
it('throws when a segment contains disallowed characters', () => {
- expect(() => bqDottedIdent('request.method; DROP TABLE')).toThrow(
- 'invalid BigQuery dotted identifier'
- )
+ expect(() => quotedIdent('request.method; DROP TABLE')).toThrow('invalid identifier')
})
it('throws for an empty segment (double dot)', () => {
- expect(() => bqDottedIdent('a..b')).toThrow('invalid BigQuery dotted identifier')
- })
-
- it('produces the same result as bqIdent for a single segment', () => {
- expect(bqDottedIdent('col')).toBe(bqIdent('col'))
- })
-})
-
-describe('clickhouseDottedIdent', () => {
- it('quotes a single-segment identifier with double-quotes', () => {
- expect(clickhouseDottedIdent('status')).toBe('"status"')
- })
-
- it('quotes each segment of a two-part dotted identifier', () => {
- expect(clickhouseDottedIdent('request.method')).toBe('"request"."method"')
- })
-
- it('quotes each segment of a three-part dotted identifier', () => {
- expect(clickhouseDottedIdent('a.b.c')).toBe('"a"."b"."c"')
- })
-
- it('throws for an empty string', () => {
- expect(() => clickhouseDottedIdent('')).toThrow('invalid ClickHouse dotted identifier')
- })
-
- it('throws when a segment contains disallowed characters', () => {
- expect(() => clickhouseDottedIdent('col OR 1=1')).toThrow(
- 'invalid ClickHouse dotted identifier'
- )
- })
-
- it('produces the same result as clickhouseIdent for a single segment', () => {
- expect(clickhouseDottedIdent('col')).toBe(clickhouseIdent('col'))
+ expect(() => quotedIdent('a..b')).toThrow('invalid identifier')
})
})
@@ -150,16 +108,10 @@ describe('safeSql template tag — existing helpers still compose', () => {
expect(query).toBe("SELECT 'hello'")
})
- it('bqDottedIdent output is composable via safeSql', () => {
- const col = bqDottedIdent('request.method')
- const query = safeSql`SELECT ${col} FROM logs`
- expect(query).toBe('SELECT `request.method` FROM logs')
- })
-
- it('clickhouseDottedIdent output is composable via safeSql', () => {
- const col = clickhouseDottedIdent('request.method')
+ it('quotedIdent output is composable via safeSql', () => {
+ const col = quotedIdent('request.method')
const query = safeSql`SELECT ${col} FROM logs`
- expect(query).toBe('SELECT "request"."method" FROM logs')
+ expect(query).toBe('SELECT `request`.`method` FROM logs')
})
it('keyword output is composable via safeSql', () => {
diff --git a/apps/studio/data/logs/safe-analytics-sql.ts b/apps/studio/data/logs/safe-analytics-sql.ts
index a26c1cd47d3..409f03cb67c 100644
--- a/apps/studio/data/logs/safe-analytics-sql.ts
+++ b/apps/studio/data/logs/safe-analytics-sql.ts
@@ -41,7 +41,7 @@
*
* Values of this type are either:
* - Static strings in source code (no interpolation) via `rawSql`
- * - Outputs of `analyticsLiteral`, `bqIdent`, or `clickhouseIdent`
+ * - Outputs of `analyticsLiteral` or `quotedIdent`
* - Compositions via the `safeSql` template tag (which only accepts
* `SafeLogSqlFragment` interpolations)
* - Compositions via `joinSqlFragments`
@@ -121,22 +121,6 @@ export function analyticsLiteral(value: string | number | boolean): SafeLogSqlFr
const SAFE_IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/
-/** Quote an identifier for BigQuery using backticks. */
-export function bqIdent(value: string): SafeLogSqlFragment {
- if (typeof value !== 'string' || !SAFE_IDENT_RE.test(value)) {
- throw new Error(`bqIdent: invalid BigQuery identifier "${value}"`)
- }
- return rawSql('`' + value + '`')
-}
-
-/** Quote an identifier for ClickHouse using double-quotes. */
-export function clickhouseIdent(value: string): SafeLogSqlFragment {
- if (typeof value !== 'string' || !SAFE_IDENT_RE.test(value)) {
- throw new Error(`clickhouseIdent: invalid ClickHouse identifier "${value}"`)
- }
- return rawSql('"' + value + '"')
-}
-
/**
* Validates `value` against an allow-list of pre-branded fragments and returns
* the matching fragment. Use for SQL operators or keywords where the permitted
@@ -157,32 +141,18 @@ export function keyword(value: string, allowed: readonly SafeLogSqlFragment[]):
}
/**
- * Quotes a dotted BigQuery identifier by wrapping the entire path in backticks,
- * validating each segment individually.
- * Accepts `a`, `a.b`, or `a.b.c`; each segment must match `[A-Za-z_][A-Za-z0-9_]*`.
- * Example: `bqDottedIdent('request.method')` → `` `request.method` ``
+ * Backtick-quotes each segment of a dotted identifier path, validating each against
+ * `[A-Za-z_][A-Za-z0-9_]*`. Accepts `a`, `a.b`, or `a.b.c`.
+ * Example: `quotedIdent('request.method')` → `` `request`.`method` ``
*
- * BigQuery requires the entire dotted path to be enclosed in a single pair of
- * backticks; individually quoting each segment (`` `request`.`method` ``) is a
- * syntax error in BigQuery's dialect.
- */
-export function bqDottedIdent(value: string): SafeLogSqlFragment {
- const segments = value.split('.')
- if (segments.length === 0 || segments.some((s) => !SAFE_IDENT_RE.test(s))) {
- throw new Error(`bqDottedIdent: invalid BigQuery dotted identifier "${value}"`)
- }
- return rawSql('`' + segments.join('.') + '`')
-}
-
-/**
- * Quotes a dotted ClickHouse identifier using double-quotes, validating each segment.
- * Accepts `a`, `a.b`, or `a.b.c`; each segment must match `[A-Za-z_][A-Za-z0-9_]*`.
- * Example: `clickhouseDottedIdent('request.method')` → `"request"."method"`
+ * Backticks are accepted by both BigQuery and ClickHouse, so this function serves
+ * both engines. Per-segment quoting handles reserved-word segments (e.g. `` `type` ``)
+ * and works for table path references and UNNEST alias field accesses alike.
*/
-export function clickhouseDottedIdent(value: string): SafeLogSqlFragment {
+export function quotedIdent(value: string): SafeLogSqlFragment {
const segments = value.split('.')
if (segments.length === 0 || segments.some((s) => !SAFE_IDENT_RE.test(s))) {
- throw new Error(`clickhouseDottedIdent: invalid ClickHouse dotted identifier "${value}"`)
+ throw new Error(`quotedIdent: invalid identifier "${value}"`)
}
- return rawSql(segments.map((s) => '"' + s + '"').join('.'))
+ return rawSql(segments.map((s) => '`' + s + '`').join('.'))
}
diff --git a/apps/studio/data/logs/unified-logs-facet-count-query.ts b/apps/studio/data/logs/unified-logs-facet-count-query.ts
index 959de605a4c..980f5cd2874 100644
--- a/apps/studio/data/logs/unified-logs-facet-count-query.ts
+++ b/apps/studio/data/logs/unified-logs-facet-count-query.ts
@@ -4,7 +4,7 @@ import { useFlag } from 'common'
import { executeAnalyticsSql } from './execute-analytics-sql'
import { logsKeys } from './keys'
import { logsAllEndpointUrl } from './logs-endpoint'
-import { bqIdent, safeSql } from './safe-analytics-sql'
+import { quotedIdent, safeSql } from './safe-analytics-sql'
import {
getUnifiedLogsISOStartEnd,
UNIFIED_LOGS_QUERY_OPTIONS,
@@ -34,12 +34,14 @@ export async function getUnifiedLogsFacetCount(
}
const { isoTimestampStart, isoTimestampEnd } = getUnifiedLogsISOStartEnd(search)
+ const cteName = quotedIdent(facet.replaceAll('.', '_') + '_count')
+
const sql = useOtel
? getFacetCountQuery({ search, facet, facetSearch })
: safeSql`
${getUnifiedLogsCTE()},
-${getFacetCountCTE({ search, facet, facetSearch })}
-SELECT dimension, value, count from ${bqIdent(facet + '_count')};
+${getFacetCountCTE({ search, facet, facetSearch, cteName })}
+SELECT dimension, value, count from ${cteName};
`
const endpoint = logsAllEndpointUrl(useOtel)
diff --git a/apps/studio/hooks/analytics/useLogsPreview.tsx b/apps/studio/hooks/analytics/useLogsPreview.tsx
index 1f402469bd9..6dc632f4f14 100644
--- a/apps/studio/hooks/analytics/useLogsPreview.tsx
+++ b/apps/studio/hooks/analytics/useLogsPreview.tsx
@@ -24,7 +24,7 @@ import {
genCountQuery,
genDefaultQuery,
} from '@/components/interfaces/Settings/Logs/Logs.utils'
-import { get } from '@/data/fetchers'
+import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'
interface LogsPreviewHook {
logData: LogData[]
@@ -80,16 +80,24 @@ function useLogsPreview({
[JSON.stringify(urlFilters), JSON.stringify(filterOverride), search]
)
- const params: LogsEndpointParams = useMemo(() => {
- const currentSql = genDefaultQuery(table, mergedFilters, limit)
- return {
+ const defaultSql = useMemo(
+ () => genDefaultQuery(table, mergedFilters, limit),
+ [table, mergedFilters, limit]
+ )
+
+ const params: LogsEndpointParams = useMemo(
+ () => ({
iso_timestamp_start: timestampStart,
iso_timestamp_end: timestampEnd,
- sql: currentSql,
- }
- }, [timestampStart, timestampEnd, table, mergedFilters, limit])
+ sql: defaultSql,
+ }),
+ [timestampStart, timestampEnd, defaultSql]
+ )
- const queryKey = useMemo(() => ['projects', projectRef, 'logs', params], [projectRef, params])
+ const queryKey = useMemo(
+ () => ['projects', projectRef, 'logs', params, defaultSql],
+ [projectRef, params, defaultSql]
+ )
const {
data,
@@ -103,20 +111,15 @@ function useLogsPreview({
} = useInfiniteQuery({
queryKey,
queryFn: async ({ signal, pageParam }) => {
- const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {
- params: {
- path: { ref: projectRef },
- query: {
- ...params,
- iso_timestamp_end: pageParam || params.iso_timestamp_end,
- },
- },
+ const data = await executeAnalyticsSql({
+ projectRef,
+ endpoint: '/platform/projects/{ref}/analytics/endpoints/logs.all',
+ sql: defaultSql,
+ iso_timestamp_start: params.iso_timestamp_start ?? '',
+ iso_timestamp_end: (pageParam || params.iso_timestamp_end) ?? '',
+ method: 'get',
signal,
})
- if (error) {
- throw error
- }
-
return data as unknown as Logs
},
refetchOnWindowFocus: false,
@@ -171,21 +174,15 @@ function useLogsPreview({
const { data: countData } = useQuery({
queryKey: countQueryKey,
queryFn: async ({ signal }) => {
- const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {
- params: {
- path: { ref: projectRef },
- query: {
- sql: countQuerySql,
- iso_timestamp_start: latestRefresh,
- iso_timestamp_end: timestampEnd,
- },
- },
+ const data = await executeAnalyticsSql({
+ projectRef,
+ endpoint: '/platform/projects/{ref}/analytics/endpoints/logs.all',
+ sql: countQuerySql,
+ iso_timestamp_start: latestRefresh,
+ iso_timestamp_end: timestampEnd ?? '',
+ method: 'get',
signal,
})
- if (error) {
- throw error
- }
-
return data as unknown as Count
},
refetchOnWindowFocus: false,
@@ -217,21 +214,15 @@ function useLogsPreview({
const { data: eventChartResponse, refetch: refreshEventChart } = useQuery({
queryKey: chartQueryKey,
queryFn: async ({ signal }) => {
- const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {
- params: {
- path: { ref: projectRef },
- query: {
- iso_timestamp_start: timestampStart,
- iso_timestamp_end: timestampEnd,
- sql: chartQuery,
- },
- },
+ const data = await executeAnalyticsSql({
+ projectRef,
+ endpoint: '/platform/projects/{ref}/analytics/endpoints/logs.all',
+ sql: chartQuery,
+ iso_timestamp_start: timestampStart,
+ iso_timestamp_end: timestampEnd ?? '',
+ method: 'get',
signal,
})
- if (error) {
- throw error
- }
-
return data as unknown as EventChart
},
refetchOnWindowFocus: false,
diff --git a/apps/studio/hooks/analytics/useSingleLog.tsx b/apps/studio/hooks/analytics/useSingleLog.tsx
index 005a29cad06..136194cee68 100644
--- a/apps/studio/hooks/analytics/useSingleLog.tsx
+++ b/apps/studio/hooks/analytics/useSingleLog.tsx
@@ -8,7 +8,8 @@ import type {
QueryType,
} from '@/components/interfaces/Settings/Logs/Logs.types'
import { genSingleLogQuery } from '@/components/interfaces/Settings/Logs/Logs.utils'
-import { get } from '@/data/fetchers'
+import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'
+import { safeSql } from '@/data/logs/safe-analytics-sql'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
interface SingleLogHook {
@@ -31,9 +32,7 @@ function useSingleLog({
paramsToMerge,
}: SingleLogParams): SingleLogHook {
const table = queryType ? LOGS_TABLES[queryType] : undefined
- const sql = id && table ? genSingleLogQuery(table, id) : ''
-
- const params: LogsEndpointParams = { ...paramsToMerge, sql }
+ const sql = id && table ? genSingleLogQuery(table, id) : safeSql``
const enabled = Boolean(id && table)
@@ -46,19 +45,28 @@ function useSingleLog({
isRefetching,
refetch,
} = useQuery({
- queryKey: ['projects', projectRef, 'single-log', id, queryType],
+ // id and queryType uniquely identify sql without having to stick the
+ // entire sql in the query key.
+ // eslint-disable-next-line @tanstack/query/exhaustive-deps
+ queryKey: [
+ 'projects',
+ projectRef,
+ 'single-log',
+ id,
+ queryType,
+ paramsToMerge?.iso_timestamp_start,
+ paramsToMerge?.iso_timestamp_end,
+ ],
queryFn: async ({ signal }) => {
- const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {
- params: {
- path: { ref: projectRef },
- query: params,
- },
+ const data = await executeAnalyticsSql({
+ projectRef,
+ endpoint: '/platform/projects/{ref}/analytics/endpoints/logs.all',
+ sql,
+ iso_timestamp_start: paramsToMerge?.iso_timestamp_start ?? '',
+ iso_timestamp_end: paramsToMerge?.iso_timestamp_end ?? '',
+ method: 'get',
signal,
})
- if (error) {
- throw error
- }
-
return data as unknown as Logs
},
enabled,