Skip to content

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

Chore/async filters for unified logs (#37200)

Joshen Lim22f937c954b1
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx
index a2ab7ee4912..d16449090a6 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx
@@ -3,7 +3,7 @@ import { User } from 'lucide-react'
import { LEVELS } from 'components/ui/DataTable/DataTable.constants'
import { DataTableFilterField, Option } from 'components/ui/DataTable/DataTable.types'
-import { getLevelColor, getStatusColor } from 'components/ui/DataTable/DataTable.utils'
+import { getLevelColor } from 'components/ui/DataTable/DataTable.utils'
import { cn } from 'ui'
import { LOG_TYPES, METHODS, STATUS_CODE_LABELS } from './UnifiedLogs.constants'
import { ColumnSchema } from './UnifiedLogs.schema'
@@ -41,11 +41,8 @@ export const filterFields = [
value: 'status',
type: 'checkbox',
defaultOpen: true,
- options: [
- { label: '2xx', value: 200 },
- { label: '4xx', value: 400 },
- { label: '4xx', value: 500 },
- ], // REMINDER: this is a placeholder to set the type in the client.tsx
+ options: [],
+ hasDynamicOptions: true,
component: (props: Option) => {
if (typeof props.value === 'boolean') return null
if (typeof props.value === 'undefined') return null
@@ -53,10 +50,6 @@ export const filterFields = [
const statusValue = String(props.value)
const statusLabel = STATUS_CODE_LABELS[statusValue as keyof typeof STATUS_CODE_LABELS]
- // Convert string status codes to numbers for HTTP status styling
- const statusCode = typeof props.value === 'string' ? parseInt(props.value, 10) : props.value
- const isHttpStatus = !isNaN(statusCode) && statusCode >= 100 && statusCode < 600
-
return (
<div className="flex items-center gap-2 w-full min-w-0">
<span className="flex-shrink-0 text-foreground">{statusValue}</span>
@@ -110,7 +103,9 @@ export const filterFields = [
value: 'host',
type: 'checkbox',
defaultOpen: false,
- options: [], // Will be populated dynamically from facets
+ options: [],
+ hasDynamicOptions: true,
+ hasAsyncSearch: true,
component: (props: Option) => {
return (
<span className="truncate block text-[0.75rem]" title={props.value as string}>
@@ -123,8 +118,10 @@ export const filterFields = [
label: 'Pathname',
value: 'pathname',
type: 'checkbox',
- defaultOpen: true,
- options: [], // Will be populated dynamically from facets
+ defaultOpen: false,
+ options: [],
+ hasDynamicOptions: true,
+ hasAsyncSearch: true,
component: (props: Option) => {
return (
<span className="truncate block w-full text-[0.75rem]" title={props.value as string}>
@@ -138,7 +135,9 @@ export const filterFields = [
value: 'auth_user',
type: 'checkbox',
defaultOpen: false,
- options: [], // Will be populated dynamically from facets
+ options: [],
+ hasDynamicOptions: true,
+ hasAsyncSearch: true,
component: (props: Option) => {
return (
<div className="flex items-center gap-2 min-w-0">
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.ts
index 4d9cba79b51..984be6580c8 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.ts
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.ts
@@ -459,7 +459,7 @@ const getSupabaseStorageLogsQuery = () => {
/**
* Combine all log sources to create the unified logs CTE
*/
-const getUnifiedLogsCTE = () => {
+export const getUnifiedLogsCTE = () => {
return `
WITH unified_logs AS (
${getPostgrestLogsQuery()}
@@ -510,39 +510,72 @@ ${finalWhere}
* Get a count query for the total logs within the timeframe
* Uses proper faceted search behavior where facets show "what would I get if I selected ONLY this option"
*/
-export const getLogsCountQuery = (search: QuerySearchParamsType): string => {
- const { finalWhere } = buildQueryConditions(search)
- // Helper function to build WHERE clause excluding a specific field
- const buildFacetWhere = (excludeField: string): string => {
- const conditions: string[] = []
+// Helper function to build WHERE clause excluding a specific field
+const buildFacetWhere = (search: QuerySearchParamsType, excludeField: string): string => {
+ const conditions: string[] = []
- Object.entries(search).forEach(([key, value]) => {
- if (key === excludeField) return // Skip the field we're getting facets for
- if (EXCLUDED_QUERY_PARAMS.includes(key as any)) return // Skip pagination and special params
+ Object.entries(search).forEach(([key, value]) => {
+ if (key === excludeField) return // Skip the field we're getting facets for
+ if (EXCLUDED_QUERY_PARAMS.includes(key as any)) return // Skip pagination and special params
- // Handle array filters (IN clause)
- if (Array.isArray(value) && value.length > 0) {
- conditions.push(`${key} IN (${value.map((v) => `'${v}'`).join(',')})`)
- return
- }
+ // Handle array filters (IN clause)
+ if (Array.isArray(value) && value.length > 0) {
+ conditions.push(`${key} IN (${value.map((v) => `'${v}'`).join(',')})`)
+ return
+ }
- // Handle scalar values
- if (value !== null && value !== undefined) {
- if (['host', 'pathname'].includes(key)) {
- conditions.push(`${key} LIKE '%${value}%'`)
- } else {
- conditions.push(`${key} = '${value}'`)
- }
+ // Handle scalar values
+ if (value !== null && value !== undefined) {
+ if (['host', 'pathname'].includes(key)) {
+ conditions.push(`${key} LIKE '%${value}%'`)
+ } else {
+ conditions.push(`${key} = '${value}'`)
}
- })
+ }
+ })
- return conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
- }
+ return conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
+}
+
+export const getFacetCountCTE = ({
+ search,
+ facet,
+ facetSearch,
+}: {
+ search: QuerySearchParamsType
+ facet: string
+ facetSearch?: string
+}) => {
+ const MAX_FACETS_QUANTITY = 20
+
+ return `
+${facet}_count AS (
+ SELECT '${facet}' as dimension, ${facet} as value, COUNT(*) as count
+ FROM unified_logs
+ ${buildFacetWhere(search, `${facet}`) || `WHERE ${facet} IS NOT NULL`}
+ ${buildFacetWhere(search, `${facet}`) ? ` AND ${facet} IS NOT NULL` : ''}
+ ${!!facetSearch ? `AND ${facet} LIKE '%${facetSearch}%'` : ''}
+ GROUP BY ${facet}
+ LIMIT ${MAX_FACETS_QUANTITY}
+)
+`.trim()
+}
+
+export const getLogsCountQuery = (search: QuerySearchParamsType): string => {
+ const { finalWhere } = buildQueryConditions(search)
// Create a count query using the same unified logs CTE
const sql = `
-${getUnifiedLogsCTE()}
+${getUnifiedLogsCTE()},
+${getFacetCountCTE({ search, facet: 'log_type' })},
+${getFacetCountCTE({ search, facet: 'method' })},
+${getFacetCountCTE({ search, facet: 'level' })},
+${getFacetCountCTE({ search, facet: 'status' })},
+${getFacetCountCTE({ search, facet: 'host' })},
+${getFacetCountCTE({ search, facet: 'pathname' })},
+${getFacetCountCTE({ search, facet: 'auth_user' })}
+
-- Get total count
SELECT 'total' as dimension, 'all' as value, COUNT(*) as count
FROM unified_logs
@@ -551,65 +584,37 @@ ${finalWhere}
UNION ALL
-- Get counts by log_type (exclude log_type filter to avoid self-filtering)
-SELECT 'log_type' as dimension, log_type as value, COUNT(*) as count
-FROM unified_logs
-${buildFacetWhere('log_type') || 'WHERE log_type IS NOT NULL'}
-${buildFacetWhere('log_type') ? ' AND log_type IS NOT NULL' : ''}
-GROUP BY log_type
+SELECT dimension, value, count from log_type_count
UNION ALL
-- Get counts by method (exclude method filter to avoid self-filtering)
-SELECT 'method' as dimension, method as value, COUNT(*) as count
-FROM unified_logs
-${buildFacetWhere('method') || 'WHERE method IS NOT NULL'}
-${buildFacetWhere('method') ? ' AND method IS NOT NULL' : ''}
-GROUP BY method
+SELECT dimension, value, count from method_count
UNION ALL
-- Get counts by level (exclude level filter to avoid self-filtering)
-SELECT 'level' as dimension, level as value, COUNT(*) as count
-FROM unified_logs
-${buildFacetWhere('level') || 'WHERE level IS NOT NULL'}
-${buildFacetWhere('level') ? ' AND level IS NOT NULL' : ''}
-GROUP BY level
+SELECT dimension, value, count from level_count
UNION ALL
-- Get counts by status (exclude status filter to avoid self-filtering)
-SELECT 'status' as dimension, status as value, COUNT(*) as count
-FROM unified_logs
-${buildFacetWhere('status') || 'WHERE status IS NOT NULL'}
-${buildFacetWhere('status') ? ' AND status IS NOT NULL' : ''}
-GROUP BY status
+SELECT dimension, value, count from status_count
UNION ALL
-- Get counts by host (exclude host filter to avoid self-filtering)
-SELECT 'host' as dimension, host as value, COUNT(*) as count
-FROM unified_logs
-${buildFacetWhere('host') || 'WHERE host IS NOT NULL'}
-${buildFacetWhere('host') ? ' AND host IS NOT NULL' : ''}
-GROUP BY host
+SELECT dimension, value, count from host_count
UNION ALL
-- Get counts by pathname (exclude pathname filter to avoid self-filtering)
-SELECT 'pathname' as dimension, pathname as value, COUNT(*) as count
-FROM unified_logs
-${buildFacetWhere('pathname') || 'WHERE pathname IS NOT NULL'}
-${buildFacetWhere('pathname') ? ' AND pathname IS NOT NULL' : ''}
-GROUP BY pathname
+SELECT dimension, value, count from pathname_count
UNION ALL
-- Get counts by auth_user (exclude auth_user filter to avoid self-filtering)
-SELECT 'auth_user' as dimension, auth_user as value, COUNT(*) as count
-FROM unified_logs
-${buildFacetWhere('auth_user') || 'WHERE auth_user IS NOT NULL'}
-${buildFacetWhere('auth_user') ? ' AND auth_user IS NOT NULL' : ''}
-GROUP BY auth_user
+SELECT dimension, value, count from auth_user_count
`
return sql
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
index 36490a091ff..6683e4db27c 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
@@ -71,8 +71,6 @@ export const UnifiedLogs = () => {
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>(defaultColumnFilters)
const [rowSelection, setRowSelection] = useState<RowSelectionState>(defaultRowSelection)
- const [showBottomLogsPanel, setShowBottomLogsPanelState] = useState(false)
-
const [columnVisibility, setColumnVisibility] = useLocalStorageQuery<VisibilityState>(
'data-table-visibility',
defaultColumnVisibility
@@ -203,7 +201,11 @@ export const UnifiedLogs = () => {
}, [isLoading, isFetching, flatData.length, table, selectedRowKey])
// REMINDER: this is currently needed for the cmdk search
+ // [Joshen] This is where facets are getting dynamically loaded
// TODO: auto search via API when the user changes the filter instead of hardcoded
+
+ // Will need to refactor this bit
+ // - Each facet just handles its own state, rather than getting passed down like this
const filterFields = useMemo(() => {
return defaultFilterFields.map((field) => {
const facetsField = facets?.[field.value]
@@ -289,6 +291,7 @@ export const UnifiedLogs = () => {
rowSelection={rowSelection}
columnOrder={columnOrder}
columnVisibility={columnVisibility}
+ searchParameters={searchParameters}
enableColumnOrdering={true}
isFetching={isFetching}
isLoading={isLoading}
diff --git a/apps/studio/components/ui/DataTable/DataTable.types.ts b/apps/studio/components/ui/DataTable/DataTable.types.ts
index 8bea320ad0f..19d2b5d77f3 100644
--- a/apps/studio/components/ui/DataTable/DataTable.types.ts
+++ b/apps/studio/components/ui/DataTable/DataTable.types.ts
@@ -50,6 +50,8 @@ export type Base<TData> = {
* Defines if the command input is disabled for this field
*/
commandDisabled?: boolean
+ hasDynamicOptions?: boolean
+ hasAsyncSearch?: boolean
}
export type DataTableCheckboxFilterField<TData> = Base<TData> & Checkbox
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckbox.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckbox.tsx
index a514895a2b2..02d284968ae 100644
--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckbox.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckbox.tsx
@@ -6,6 +6,7 @@ import type { DataTableCheckboxFilterField } from '../DataTable.types'
import { formatCompactNumber } from '../DataTable.utils'
import { InputWithAddons } from '../primitives/InputWithAddons'
import { useDataTable } from '../providers/DataTableProvider'
+import { DataTableFilterCheckboxLoader } from './DataTableFilterCheckboxLoader'
export function DataTableFilterCheckbox<TData>({
value: _value,
@@ -34,31 +35,13 @@ export function DataTableFilterCheckbox<TData>({
const filters = filterValue ? (Array.isArray(filterValue) ? filterValue : [filterValue]) : []
// REMINDER: if no options are defined, while fetching data, we should show a skeleton
- if (isLoading && !filterOptions?.length)
- return (
- <div className="grid divide-y rounded border border-border">
- {Array.from({ length: 3 }).map((_, index) => (
- <div key={index} className="flex items-center justify-between gap-2 px-2 py-2.5">
- <Skeleton className="h-4 w-4 rounded-sm" />
- <Skeleton className="h-4 w-full rounded-sm" />
- </div>
- ))}
- </div>
- )
+ if (isLoading && !filterOptions?.length) return <DataTableFilterCheckboxLoader />
// Show empty state when no original options are available (not due to search filtering)
if (!options?.length)
return (
- <div className="flex items-center justify-center px-2 py-6 text-center">
- <div className="flex flex-col items-center gap-2">
- <div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center">
- <Search className="h-4 w-4 text-muted-foreground" />
- </div>
- <div className="space-y-1">
- <p className="text-sm text-muted-foreground">No options available</p>
- <p className="text-xs text-muted-foreground/70">Try adjusting your filters</p>
- </div>
- </div>
+ <div className="flex items-center justify-center px-2 py-4 text-center border border-border rounded">
+ <p className="text-xs text-foreground-light">No options available</p>
</div>
)
@@ -77,9 +60,9 @@ export function DataTableFilterCheckbox<TData>({
<div className="max-h-[200px] overflow-y-auto rounded border border-border empty:border-none">
{filterOptions.length === 0 && inputValue !== '' ? (
<div className="flex items-center justify-center px-2 py-4 text-center">
- <div className="space-y-1">
- <p className="text-sm text-muted-foreground">No results found</p>
- <p className="text-xs text-muted-foreground/70">Try a different search term</p>
+ <div className="space-y-0.5">
+ <p className="text-xs text-foreground">No results found</p>
+ <p className="text-xs text-foreground-lighter">Try a different search term</p>
</div>
</div>
) : (
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxAsync.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxAsync.tsx
new file mode 100644
index 00000000000..79ad290266d
--- /dev/null
+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxAsync.tsx
@@ -0,0 +1,136 @@
+import { useDebounce } from '@uidotdev/usehooks'
+import { Loader2, Search } from 'lucide-react'
+import { useState } from 'react'
+
+import { useParams } from 'common'
+import { useUnifiedLogsFacetCountQuery } from 'data/logs/unified-logs-facet-count-query'
+import { Checkbox_Shadcn_ as Checkbox, cn, Label_Shadcn_ as Label, Skeleton } from 'ui'
+import type { DataTableCheckboxFilterField } from '../DataTable.types'
+import { formatCompactNumber } from '../DataTable.utils'
+import { InputWithAddons } from '../primitives/InputWithAddons'
+import { useDataTable } from '../providers/DataTableProvider'
+
+export function DataTableFilterCheckboxAsync<TData>({
+ value: _value,
+ options,
+ component: Component,
+}: DataTableCheckboxFilterField<TData>) {
+ const value = _value as string
+ const [inputValue, setInputValue] = useState('')
+
+ const { table, searchParameters, columnFilters, isLoadingCounts, getFacetedUniqueValues } =
+ useDataTable()
+
+ // [Joshen] JFYI for simplicity currently, i'm adding UnifiedLogs logic into this file
+ // despite this supposedly being a reusable component - tbh really, this doesn't need to
+ // be reusable perhaps unless we plan for this to be used in another area of the dashboard
+ // but its too early to say for sure atm.
+ const { ref: projectRef } = useParams()
+ const debouncedSearch = useDebounce(inputValue, 700)
+ const { data: filterOptions = [], isFetching: isFetchingFacetCount } =
+ useUnifiedLogsFacetCountQuery(
+ {
+ projectRef,
+ search: searchParameters,
+ facet: value,
+ facetSearch: debouncedSearch,
+ },
+ {
+ keepPreviousData: true,
+ enabled: debouncedSearch.length > 0,
+ initialData: debouncedSearch.length === 0 ? options : undefined,
+ }
+ )
+
+ const column = table.getColumn(value)
+ const filterValue = columnFilters.find((i) => i.id === value)?.value
+ const facetedValue = getFacetedUniqueValues?.(table, value) || column?.getFacetedUniqueValues()
+ const filters = filterValue ? (Array.isArray(filterValue) ? filterValue : [filterValue]) : []
+
+ if (!options?.length)
+ return (
+ <div className="flex items-center justify-center px-2 py-4 text-center border border-border rounded">
+ <p className="text-xs text-foreground-light">No options available</p>
+ </div>
+ )
+
+ return (
+ <div className="grid gap-2">
+ <InputWithAddons
+ placeholder="Search"
+ leading={<Search size={14} className="text-foreground-lighter" />}
+ containerClassName="h-8 rounded"
+ value={inputValue}
+ trailing={isFetchingFacetCount ? <Loader2 size={12} className="animate-spin" /> : undefined}
+ onChange={(e) => setInputValue(e.target.value)}
+ />
+
+ <div className="max-h-[200px] overflow-y-auto rounded border border-border empty:border-none">
+ {filterOptions.length === 0 ? (
+ <div className="flex items-center justify-center px-2 py-3 text-center">
+ <div className="space-y-0.5">
+ <p className="text-xs text-foreground">No results found</p>
+ <p className="text-xs text-foreground-lighter">Try a different search term</p>
+ </div>
+ </div>
+ ) : (
+ filterOptions.map((option, index) => {
+ const checked = filters.includes(option.value)
+
+ return (
+ <div
+ key={String(option.value)}
+ className={cn(
+ 'group relative flex items-center space-x-2 px-2 py-2 hover:bg-accent/50',
+ index !== filterOptions.length - 1 ? 'border-b' : undefined
+ )}
+ >
+ <Checkbox
+ id={`${value}-${option.value}`}
+ checked={checked}
+ onCheckedChange={(checked) => {
+ const newValue = checked
+ ? [...(filters || []), option.value]
+ : filters?.filter((value) => option.value !== value)
+ column?.setFilterValue(newValue?.length ? newValue : undefined)
+ }}
+ />
+ <Label
+ htmlFor={`${value}-${option.value}`}
+ className="flex w-full items-center justify-between gap-2 text-foreground/70 group-hover:text-accent-foreground text-[0.8rem] min-w-0"
+ >
+ <div className="flex-1 min-w-0 overflow-hidden">
+ {Component ? (
+ <Component {...option} />
+ ) : (
+ <span className="truncate font-normal block">{option.label}</span>
+ )}
+ </div>
+ <span className="flex-shrink-0 flex items-center justify-center font-mono text-xs">
+ {isLoadingCounts ? (
+ <Skeleton className="h-4 w-4" />
+ ) : facetedValue?.has(option.value) ? (
+ formatCompactNumber(facetedValue.get(option.value) || 0)
+ ) : ['log_type', 'method', 'level'].includes(value) ? (
+ '0'
+ ) : null}
+ </span>
+ <button
+ type="button"
+ onClick={() => column?.setFilterValue([option.value])}
+ className={cn(
+ 'absolute inset-y-0 right-0 hidden font-normal text-muted-foreground backdrop-blur-sm hover:text-foreground group-hover:block',
+ 'rounded-md ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2'
+ )}
+ >
+ <span className="px-2">only</span>
+ </button>
+ </Label>
+ </div>
+ )
+ })
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxLoader.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxLoader.tsx
new file mode 100644
index 00000000000..3c74d3ce878
--- /dev/null
+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxLoader.tsx
@@ -0,0 +1,14 @@
+import { Skeleton } from 'ui'
+
+export const DataTableFilterCheckboxLoader = () => {
+ return (
+ <div className="grid divide-y rounded border border-border">
+ {Array.from({ length: 3 }).map((_, index) => (
+ <div key={index} className="flex items-center justify-between gap-2 px-2 py-2.5">
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ <Skeleton className="h-4 w-full rounded-sm" />
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx
index 628ba8a49f9..2f69d227226 100644
--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx
@@ -13,6 +13,8 @@ import { DataTableFilterTimerange } from './DataTableFilterTimerange'
import { DateRangeDisabled } from '../DataTable.types'
import { useDataTable } from '../providers/DataTableProvider'
+import { DataTableFilterCheckboxAsync } from './DataTableFilterCheckboxAsync'
+import { DataTableFilterCheckboxLoader } from './DataTableFilterCheckboxLoader'
// FIXME: use @container (especially for the slider element) to restructure elements
@@ -24,7 +26,7 @@ interface DataTableFilterControls {
}
export function DataTableFilterControls({ dateRangeDisabled }: DataTableFilterControls) {
- const { filterFields } = useDataTable()
+ const { filterFields, isLoadingCounts } = useDataTable()
return (
<Accordion
type="multiple"
@@ -51,7 +53,15 @@ export function DataTableFilterControls({ dateRangeDisabled }: DataTableFilterCo
{(() => {
switch (field.type) {
case 'checkbox': {
- return <DataTableFilterCheckbox {...field} />
+ // [Joshen] Loader here so that CheckboxAsync can retrieve the data
+ // immediately to be set in its react query state
+ if (field.hasDynamicOptions && isLoadingCounts) {
+ return <DataTableFilterCheckboxLoader />
+ } else if (field.hasAsyncSearch) {
+ return <DataTableFilterCheckboxAsync {...field} />
+ } else {
+ return <DataTableFilterCheckbox {...field} />
+ }
}
case 'slider': {
return <DataTableFilterSlider {...field} />
diff --git a/apps/studio/components/ui/DataTable/primitives/InputWithAddons.tsx b/apps/studio/components/ui/DataTable/primitives/InputWithAddons.tsx
index 2848c0e3cc3..974dde4b670 100644
--- a/apps/studio/components/ui/DataTable/primitives/InputWithAddons.tsx
+++ b/apps/studio/components/ui/DataTable/primitives/InputWithAddons.tsx
@@ -31,7 +31,9 @@ export const InputWithAddons = forwardRef<HTMLInputElement, InputWithAddonsProps
{...props}
/>
{trailing ? (
- <div className="border-input bg-muted/50 border-l px-3 py-2">{trailing}</div>
+ <div className="border-input bg-muted/50 border-l px-3 py-2 flex items-center justify-center">
+ {trailing}
+ </div>
) : null}
</div>
)
diff --git a/apps/studio/components/ui/DataTable/providers/DataTableProvider.tsx b/apps/studio/components/ui/DataTable/providers/DataTableProvider.tsx
index ff1abe4f0cb..2515c748a59 100644
--- a/apps/studio/components/ui/DataTable/providers/DataTableProvider.tsx
+++ b/apps/studio/components/ui/DataTable/providers/DataTableProvider.tsx
@@ -9,6 +9,7 @@ import type {
} from '@tanstack/react-table'
import { createContext, ReactNode, useContext, useMemo } from 'react'
+import { QuerySearchParamsType } from 'components/interfaces/UnifiedLogs/UnifiedLogs.types'
import { DataTableFilterField } from '../DataTable.types'
import { ControlsProvider } from './ControlsProvider'
@@ -23,6 +24,7 @@ interface DataTableStateContextType {
columnVisibility: VisibilityState
pagination: PaginationState
enableColumnOrdering: boolean
+ searchParameters: QuerySearchParamsType
}
interface DataTableBaseContextType<TData = unknown, TValue = unknown> {
@@ -59,6 +61,7 @@ export function DataTableProvider<TData, TValue>({
columnVisibility: props.columnVisibility ?? {},
pagination: props.pagination ?? { pageIndex: 0, pageSize: 10 },
enableColumnOrdering: props.enableColumnOrdering ?? false,
+ searchParameters: props.searchParameters ?? ({} as any),
}),
[props]
)
diff --git a/apps/studio/data/logs/keys.ts b/apps/studio/data/logs/keys.ts
index a079740b2c8..af62b1e3116 100644
--- a/apps/studio/data/logs/keys.ts
+++ b/apps/studio/data/logs/keys.ts
@@ -34,6 +34,21 @@ export const logsKeys = {
'chart-data',
...(searchParams ? [searchParams].filter(Boolean) : []),
] as const,
+ unifiedLogsFacetCount: (
+ projectRef: string | undefined,
+ facet: string,
+ facetSearch: string | undefined,
+ searchParams: QuerySearchParamsType | undefined
+ ) =>
+ [
+ 'projects',
+ projectRef,
+ 'unified-logs',
+ 'count-data',
+ facet,
+ facetSearch,
+ ...(searchParams ? [searchParams].filter(Boolean) : []),
+ ] as const,
serviceFlow: (
projectRef: string | undefined,
searchParams: QuerySearchParamsType | undefined,
diff --git a/apps/studio/data/logs/unified-logs-facet-count-query.ts b/apps/studio/data/logs/unified-logs-facet-count-query.ts
new file mode 100644
index 00000000000..dea0d5a885c
--- /dev/null
+++ b/apps/studio/data/logs/unified-logs-facet-count-query.ts
@@ -0,0 +1,64 @@
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+
+import {
+ getFacetCountCTE,
+ getUnifiedLogsCTE,
+} from 'components/interfaces/UnifiedLogs/UnifiedLogs.queries'
+import { Option } from 'components/ui/DataTable/DataTable.types'
+import { handleError, post } from 'data/fetchers'
+import { ExecuteSqlError } from 'data/sql/execute-sql-query'
+import { logsKeys } from './keys'
+import {
+ getUnifiedLogsISOStartEnd,
+ UNIFIED_LOGS_QUERY_OPTIONS,
+ UnifiedLogsVariables,
+} from './unified-logs-infinite-query'
+
+type UnifiedLogsFacetCountVariables = UnifiedLogsVariables & {
+ facet: string
+ facetSearch?: string
+}
+
+export async function getUnifiedLogsFacetCount(
+ { projectRef, search, facet, facetSearch }: UnifiedLogsFacetCountVariables,
+ signal?: AbortSignal
+) {
+ if (typeof projectRef === 'undefined') {
+ throw new Error('projectRef is required for getUnifiedLogsFacetCount')
+ }
+
+ const { isoTimestampStart, isoTimestampEnd } = getUnifiedLogsISOStartEnd(search)
+ const sql = `
+${getUnifiedLogsCTE()},
+${getFacetCountCTE({ search, facet, facetSearch })}
+SELECT dimension, value, count from ${facet}_count;
+`.trim()
+ const { data, error } = await post(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {
+ params: { path: { ref: projectRef } },
+ body: { iso_timestamp_start: isoTimestampStart, iso_timestamp_end: isoTimestampEnd, sql },
+ signal,
+ })
+
+ if (error) handleError(error)
+ return (data.result ?? []) as Option[]
+}
+
+export type UnifiedLogsFacetCountData = Awaited<ReturnType<typeof getUnifiedLogsFacetCount>>
+export type UnifiedLogsFacetCountError = ExecuteSqlError
+
+export const useUnifiedLogsFacetCountQuery = <TData = UnifiedLogsFacetCountData>(
+ { projectRef, search, facet, facetSearch }: UnifiedLogsFacetCountVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<UnifiedLogsFacetCountData, UnifiedLogsFacetCountError, TData> = {}
+) =>
+ useQuery<UnifiedLogsFacetCountData, UnifiedLogsFacetCountError, TData>(
+ logsKeys.unifiedLogsFacetCount(projectRef, facet, facetSearch, search),
+ ({ signal }) => getUnifiedLogsFacetCount({ projectRef, search, facet, facetSearch }, signal),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ ...UNIFIED_LOGS_QUERY_OPTIONS,
+ ...options,
+ }
+ )