The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/fix unified logs (#36650)
Joshen Limec43e11c1177
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.constants.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.constants.tsxindex 996d6290e59..2eeaf8a7bff 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.constants.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.constants.tsx@@ -34,7 +34,7 @@ export const CHART_CONFIG = {} satisfies ChartConfigexport const REGIONS = ['ams', 'fra', 'gru', 'hkg', 'iad', 'syd'] as const-export const METHODS = ['GET', 'POST', 'PUT', 'DELETE'] as const+export const METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'] as constexport const LOG_TYPES = ['auth','edge',@@ -86,5 +86,5 @@ export const SEARCH_PARAMS_PARSER = {live: parseAsBoolean.withDefault(false),// REQUIRED FOR SELECTION- uuid: parseAsString,+ id: parseAsString,}diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsxindex 11ff66d6d83..71c79e47759 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx@@ -31,7 +31,7 @@ export const filterFields = [const value = props.value as (typeof LEVELS)[number]return (<div className="flex w-full max-w-28 items-center justify-between gap-2 font-mono">- <span className="capitalize text-foreground/70 group-hover:text-accent-foreground">+ <span className="capitalize text-foreground/70 group-hover:text-accent-foreground text-xs">{props.label}</span><div className="flex items-center gap-2">@@ -51,7 +51,7 @@ export const filterFields = [component: (props: Option) => {return (<div className="flex w-full items-center justify-between gap-2 font-mono">- <span className="capitalize text-foreground/70 group-hover:text-accent-foreground">+ <span className="capitalize text-foreground/70 group-hover:text-accent-foreground text-xs">{props.label}</span><span className="text-xs text-muted-foreground/70">{props.value}</span>@@ -106,7 +106,7 @@ export const filterFields = [export const sheetFields = [{- id: 'uuid',+ id: 'id',label: 'Request ID',type: 'readonly',skeletonClassName: 'w-64',diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.schema.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.schema.tsindex 6e7459128dd..a6037e1270b 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.schema.ts+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.schema.ts@@ -10,7 +10,6 @@ import { LOG_TYPES, METHODS, REGIONS } from './UnifiedLogs.constants'export const columnSchema = z.object({id: z.string(),log_type: z.enum(LOG_TYPES),- uuid: z.string(),method: z.enum(METHODS),host: z.string(),pathname: z.string(),diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsxindex ed6128be00c..911f62f9cf8 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx@@ -45,7 +45,7 @@ import {TabsList_Shadcn_ as TabsList,TabsTrigger_Shadcn_ as TabsTrigger,} from 'ui'-import { COLUMNS } from './components/Columns'+import { UNIFIED_LOGS_COLUMNS } from './components/Columns'import { MemoizedDataTableSheetContent } from './components/DataTableSheetContent'import { FunctionLogsTab } from './components/FunctionLogsTab'import { CHART_CONFIG, SEARCH_PARAMS_PARSER } from './UnifiedLogs.constants'@@ -54,19 +54,16 @@ import { useLiveMode, useResetFocus } from './UnifiedLogs.hooks'import { QuerySearchParamsType } from './UnifiedLogs.types'import { getFacetedUniqueValues, getLevelRowClassName, logEventBus } from './UnifiedLogs.utils'-// Debug mode flag - set to true to enable detailed logs-const DEBUG_FILTER_PROCESSING = false-export const UnifiedLogs = () => {useResetFocus()const { ref: projectRef } = useParams()const [search, setSearch] = useQueryStates(SEARCH_PARAMS_PARSER)- const { sort, start, size, uuid, cursor, direction, live, ...filter } = search+ const { sort, start, size, id, cursor, direction, live, ...filter } = searchconst defaultColumnSorting = sort ? [sort] : []const defaultColumnVisibility = { uuid: false }- const defaultRowSelection = search.uuid ? { [search.uuid]: true } : {}+ const defaultRowSelection = search.id ? { [search.id]: true } : {}const defaultColumnFilters = Object.entries(filter).map(([key, value]) => ({ id: key, value })).filter(({ value }) => value ?? undefined)@@ -86,11 +83,11 @@ export const UnifiedLogs = () => {[])- // Create a stable query key object by removing nulls/undefined, uuid, and live+ // Create a stable query key object by removing nulls/undefined, id, and live// Mainly to prevent the react queries from unnecessarily re-fetchingconst searchParameters = Object.entries(search).reduce((acc, [key, value]) => {- if (!['uuid', 'live'].includes(key) && value !== null && value !== undefined) {+ if (!['id', 'live'].includes(key) && value !== null && value !== undefined) {acc[key] = value}return acc@@ -107,24 +104,28 @@ export const UnifiedLogs = () => {fetchNextPage,fetchPreviousPage,} = useUnifiedLogsInfiniteQuery({ projectRef, search: searchParameters })- const { data: counts } = useUnifiedLogsCountQuery({ projectRef, search: searchParameters })+ const { data: counts, isLoading: isLoadingCounts } = useUnifiedLogsCountQuery({+ projectRef,+ search: searchParameters,+ })const { data: unifiedLogsChart = [] } = useUnifiedLogsChartQuery({projectRef,search: searchParameters,})- const flatData = useMemo(() => {+ const rawFlatData = useMemo(() => {return unifiedLogsData?.pages?.flatMap((page) => page.data ?? []) ?? []}, [unifiedLogsData?.pages])+ // [Joshen] Refer to unified-logs-infinite-query on why the need to deupe+ const flatData = useMemo(() => {+ return rawFlatData.filter((value, idx) => {+ return idx === rawFlatData.findIndex((x) => x.id === value.id)+ })+ }, [rawFlatData])const liveMode = useLiveMode(flatData)- // REMINDER: meta data is always the same for all pages as filters do not change(!)- const lastPage = unifiedLogsData?.pages?.[unifiedLogsData?.pages.length - 1]-- // Use the totalCount from chartDataResult which gives us the actual count of logs in the time period- // instead of the hardcoded 10000 valueconst totalDBRowCount = counts?.totalRowCount- const filterDBRowCount = lastPage?.meta?.filterRowCount+ const filterDBRowCount = flatData.lengthconst facets = counts?.facetsconst totalFetched = flatData?.length@@ -143,12 +144,12 @@ export const UnifiedLogs = () => {const rowTimestamp = row.original.timestampconst isPast = rowTimestamp <= (liveMode.timestamp || -1)const levelClassName = getLevelRowClassName(row.original.level as any)- return cn(levelClassName, isPast ? 'opacity-50' : 'opacity-100')+ return cn(levelClassName, isPast ? 'opacity-50' : 'opacity-100', 'h-[30px]')}const table = useReactTable({data: flatData,- columns: COLUMNS,+ columns: UNIFIED_LOGS_COLUMNS,state: {columnFilters,sorting,@@ -160,7 +161,7 @@ export const UnifiedLogs = () => {columnResizeMode: 'onChange',filterFns: { inDateRange, arrSome },meta: { getRowClassName },- getRowId: (row) => row.uuid,+ getRowId: (row) => row.id,onColumnVisibilityChange: setColumnVisibility,onColumnFiltersChange: setColumnFilters,onRowSelectionChange: setRowSelection,@@ -207,37 +208,14 @@ export const UnifiedLogs = () => {}, [facets])useEffect(() => {- if (DEBUG_FILTER_PROCESSING) console.log('========== FILTER CHANGE DETECTED ==========')- if (DEBUG_FILTER_PROCESSING) console.log('Raw columnFilters:', JSON.stringify(columnFilters))-- // Check for level filters specifically- const levelColumnFilter = columnFilters.find((filter) => filter.id === 'level')- if (DEBUG_FILTER_PROCESSING) console.log('Level column filter:', levelColumnFilter)-const columnFiltersWithNullable = filterFields.map((field) => {const filterValue = columnFilters.find((filter) => filter.id === field.value)- if (DEBUG_FILTER_PROCESSING) console.log(`Processing field ${field.value}:`, filterValue)if (!filterValue) return { id: field.value, value: null }return { id: field.value, value: filterValue.value }})- // Debug level filter specifically- const levelFilter = columnFiltersWithNullable.find((f) => f.id === 'level')- if (DEBUG_FILTER_PROCESSING) console.log('Level filter after mapping:', levelFilter)-- if (DEBUG_FILTER_PROCESSING)- console.log('All column filters after mapping:', columnFiltersWithNullable)-const search = columnFiltersWithNullable.reduce((prev, curr) => {- if (DEBUG_FILTER_PROCESSING)- console.log(`Processing filter for URL: ${curr.id}`, {- value: curr.value,- type: Array.isArray(curr.value) ? 'array' : typeof curr.value,- isEmpty: Array.isArray(curr.value) && curr.value.length === 0,- isNull: curr.value === null,- })-// Add to search parametersprev[curr.id as string] = curr.valuereturn prev@@ -245,14 +223,7 @@ export const UnifiedLogs = () => {{} as Record<string, unknown>)- if (DEBUG_FILTER_PROCESSING) console.log('Final search object to be set in URL:', search)- if (DEBUG_FILTER_PROCESSING) console.log('Level value in final search:', search.level)- if (DEBUG_FILTER_PROCESSING) console.log('Is level in search object:', 'level' in search)-- // Set the search state without any console logs- if (DEBUG_FILTER_PROCESSING) console.log('CALLING setSearch with:', JSON.stringify(search))setSearch(search)- if (DEBUG_FILTER_PROCESSING) console.log('========== END FILTER PROCESSING ==========')// eslint-disable-next-line react-hooks/exhaustive-deps}, [columnFilters])@@ -265,10 +236,10 @@ export const UnifiedLogs = () => {useEffect(() => {if (isLoading || isFetching) returnif (Object.keys(rowSelection)?.length && !selectedRow) {- setSearch({ uuid: null })+ setSearch({ id: null })setRowSelection({})} else {- setSearch({ uuid: Object.keys(rowSelection)?.[0] || null })+ setSearch({ id: Object.keys(rowSelection)?.[0] || null })}// eslint-disable-next-line react-hooks/exhaustive-deps}, [rowSelection, selectedRow, isLoading, isFetching])@@ -287,7 +258,7 @@ export const UnifiedLogs = () => {return (<DataTableProvidertable={table}- columns={COLUMNS}+ columns={UNIFIED_LOGS_COLUMNS}filterFields={filterFields}columnFilters={columnFilters}sorting={sorting}@@ -295,7 +266,9 @@ export const UnifiedLogs = () => {columnOrder={columnOrder}columnVisibility={columnVisibility}enableColumnOrdering={true}- isLoading={isFetching || isLoading}+ isFetching={isFetching}+ isLoading={isLoading}+ isLoadingCounts={isLoadingCounts}getFacetedUniqueValues={getFacetedUniqueValues(facets)}><DataTableSideBarLayout topBarHeight={topBarHeight}>@@ -329,26 +302,22 @@ export const UnifiedLogs = () => {<ResizablePanel defaultSize={selectedRowKey ? 60 : 100} minSize={30} className="h-full"><ResizablePanelGroup key="main-logs" direction="vertical" className="h-full"><ResizablePanel defaultSize={100} minSize={30}>- <div className="h-full overflow-auto">- <DataTableInfinite- columns={COLUMNS}- totalRows={totalDBRowCount}- filterRows={filterDBRowCount}- totalRowsFetched={totalFetched}- isFetching={isFetching}- isLoading={isLoading}- fetchNextPage={fetchNextPage}- hasNextPage={hasNextPage}- renderLiveRow={(props) => {- if (!liveMode.timestamp) return null- if ((props?.row as any).original.uuid !== liveMode?.row?.uuid) return null- return <LiveRow colSpan={COLUMNS.length - 1} />- }}- setColumnOrder={setColumnOrder}- setColumnVisibility={setColumnVisibility}- searchParamsParser={SEARCH_PARAMS_PARSER}- />- </div>+ <DataTableInfinite+ columns={UNIFIED_LOGS_COLUMNS}+ totalRows={totalDBRowCount}+ filterRows={filterDBRowCount}+ totalRowsFetched={totalFetched}+ fetchNextPage={fetchNextPage}+ hasNextPage={hasNextPage}+ renderLiveRow={(props) => {+ if (!liveMode.timestamp) return null+ if (props?.row?.original.id !== liveMode?.row?.id) return null+ return <LiveRow colSpan={UNIFIED_LOGS_COLUMNS.length - 1} />+ }}+ setColumnOrder={setColumnOrder}+ setColumnVisibility={setColumnVisibility}+ searchParamsParser={SEARCH_PARAMS_PARSER}+ /></ResizablePanel>{selectedRow?.original?.logs && selectedRow?.original?.logs?.length > 0 && (<>diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsxindex f49f017179f..49334f1b61b 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx@@ -10,7 +10,7 @@ import { HoverCardTimestamp } from './HoverCardTimestamp'import { LogTypeIcon } from './LogTypeIcon'import { TextWithTooltip } from './TextWithTooltip'-export const COLUMNS: ColumnDef<ColumnSchema>[] = [+export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [{accessorKey: 'level',header: '',@@ -39,9 +39,9 @@ export const COLUMNS: ColumnDef<ColumnSchema>[] = [},filterFn: (row, columnId, filterValue) => true,enableResizing: false,- size: 190,- minSize: 190,- maxSize: 190,+ size: 130,+ minSize: 130,+ maxSize: 130,meta: {headerClassName:'w-[--header-date-size] max-w-[--header-date-size] min-w-[--header-date-size]',@@ -55,16 +55,16 @@ export const COLUMNS: ColumnDef<ColumnSchema>[] = [cell: ({ row }) => {const logType = row.getValue<ColumnSchema['log_type']>('log_type')return (- <div className="absolute right-0 top-1/2 -translate-y-1/2 text-right flex items-center gap-1">+ <div className="flex items-center justify-end gap-1"><LogTypeIcon type={logType} size={16} className="text-foreground/70" /></div>)},enableHiding: false,filterFn: (row, columnId, filterValue) => true,- size: 48,- minSize: 48,- maxSize: 48,+ size: 40,+ minSize: 40,+ maxSize: 40,enableResizing: false,meta: {headerClassName:@@ -83,8 +83,8 @@ export const COLUMNS: ColumnDef<ColumnSchema>[] = [return <span className="text-foreground-lighter">{value}</span>},enableResizing: false,- size: 69,- minSize: 69,+ size: 70,+ minSize: 70,meta: {cellClassName:'font-mono text-muted-foreground w-[--col-method-size] max-w-[--col-method-size] min-w-[--col-method-size]',@@ -113,8 +113,8 @@ export const COLUMNS: ColumnDef<ColumnSchema>[] = [},filterFn: (row, columnId, filterValue) => true,enableResizing: false,- size: 60,- minSize: 60,+ size: 50,+ minSize: 50,meta: {headerClassName:'w-[--header-status-size] max-w-[--header-status-size] min-w-[--header-status-size]',@@ -181,8 +181,8 @@ export const COLUMNS: ColumnDef<ColumnSchema>[] = [)},enableResizing: true,- size: 400,- minSize: 400,+ size: 200,+ minSize: 200,meta: {headerClassName:'w-[--header-event_message-size] max-w-[--header-event_message-size] min-w-[--header-event_message-size]',diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/FunctionLogsTab.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/FunctionLogsTab.tsxindex 3607f940d9b..a9998ffe56b 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/FunctionLogsTab.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/components/FunctionLogsTab.tsx@@ -27,7 +27,6 @@ export const FunctionLogsTab = ({ logs = [] }: FunctionLogsTabProps) => {<div className="text-sm font-mono">{logs.map((log) => {const date = new Date(Number(log.timestamp) / 1000)- // Map the log level to our standard levelsreturn (<div key={log.id} className="py-1 border-b border-border last:border-0">@@ -40,7 +39,6 @@ export const FunctionLogsTab = ({ logs = [] }: FunctionLogsTabProps) => {level={log.level}className="min-w-20"/>- {/* <span className="text-foreground">{log.event_type || 'Log'}</span> */}</div><div className="mt-1 whitespace-pre-wrap break-all pl-2 text-[0.8rem]">{log.event_message}diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogTypeIcon.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/LogTypeIcon.tsxindex a14bb8bbd45..5f9d067407a 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/LogTypeIcon.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogTypeIcon.tsx@@ -44,7 +44,7 @@ export const LogTypeIcon = ({<IconComponent /></TooltipTrigger><TooltipContent side="left">- <div className="text-sm">{type}</div>+ <div className="text-xs">{type}</div></TooltipContent></Tooltip>)diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckbox.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckbox.tsxindex 26fbbdc57d3..94cca02970c 100644--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckbox.tsx+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckbox.tsx@@ -4,7 +4,7 @@ import { useState } from 'react'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 '../InputWithAddons'+import { InputWithAddons } from '../primitives/InputWithAddons'import { useDataTable } from '../providers/DataTableProvider'export function DataTableFilterCheckbox<TData>({@@ -14,7 +14,9 @@ export function DataTableFilterCheckbox<TData>({}: DataTableCheckboxFilterField<TData>) {const value = _value as stringconst [inputValue, setInputValue] = useState('')- const { table, columnFilters, isLoading, getFacetedUniqueValues } = useDataTable()+ const { table, columnFilters, isLoading, isLoadingCounts, getFacetedUniqueValues } =+ useDataTable()+const column = table.getColumn(value)// REMINDER: avoid using column?.getFilterValue()const filterValue = columnFilters.find((i) => i.id === value)?.value@@ -33,7 +35,7 @@ export function DataTableFilterCheckbox<TData>({// REMINDER: if no options are defined, while fetching data, we should show a skeletonif (isLoading && !filterOptions?.length)return (- <div className="grid divide-y rounded-lg border border-border">+ <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" />@@ -51,13 +53,13 @@ export function DataTableFilterCheckbox<TData>({<InputWithAddonsplaceholder="Search"leading={<Search className="mt-0.5 h-4 w-4" />}- containerClassName="h-9 rounded-lg"+ containerClassName="h-9 rounded"value={inputValue}onChange={(e) => setInputValue(e.target.value)}/>) : null}{/* FIXME: due to the added max-h and overflow-y-auto, the hover state and border is laying on top of the scroll bar */}- <div className="max-h-[200px] overflow-y-auto rounded-lg border border-border empty:border-none">+ <div className="max-h-[200px] overflow-y-auto rounded border border-border empty:border-none">{filterOptions// TODO: we shoudn't sort the options here, instead filterOptions should be sorted by default// .sort((a, b) => a.label.localeCompare(b.label))@@ -92,7 +94,7 @@ export function DataTableFilterCheckbox<TData>({<span className="truncate font-normal">{option.label}</span>)}<span className="ml-auto flex items-center justify-center font-mono text-xs">- {isLoading ? (+ {isLoadingCounts ? (<Skeleton className="h-4 w-4" />) : facetedValue?.has(option.value) ? (formatCompactNumber(facetedValue.get(option.value) || 0)diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterInput.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterInput.tsxindex 21d3e217d5f..a41cc5d9656 100644--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterInput.tsx+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterInput.tsx@@ -4,7 +4,7 @@ import { useEffect, useState } from 'react'import { Label_Shadcn_ as Label } from 'ui'import type { DataTableInputFilterField } from '../DataTable.types'import { useDebounce } from '../hooks/useDebounce'-import { InputWithAddons } from '../InputWithAddons'+import { InputWithAddons } from '../primitives/InputWithAddons'import { useDataTable } from '../providers/DataTableProvider'function getFilter(filterValue: unknown) {@@ -40,8 +40,8 @@ export function DataTableFilterInput<TData>({ value: _value }: DataTableInputFil</Label><InputWithAddonsplaceholder="Search"- leading={<Search className="mt-0.5 h-4 w-4" />}- containerClassName="h-9 rounded-lg"+ leading={<Search className="h-4 w-4" />}+ containerClassName="h-9 rounded"name={value}id={value}value={input || ''}diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterSlider.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterSlider.tsxindex 14d8d23d6bc..8882c6fe91d 100644--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterSlider.tsx+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterSlider.tsx@@ -4,7 +4,7 @@ import { Label_Shadcn_ as Label } from 'ui'import type { DataTableSliderFilterField } from '../DataTable.types'import { isArrayOfNumbers } from '../DataTable.utils'import { useDebounce } from '../hooks/useDebounce'-import { InputWithAddons } from '../InputWithAddons'+import { InputWithAddons } from '../primitives/InputWithAddons'import { Slider } from '../primitives/Slider'import { useDataTable } from '../providers/DataTableProvider'@@ -60,7 +60,7 @@ export function DataTableFilterSlider<TData>({<InputWithAddonsplaceholder="from"trailing="ms"- containerClassName="mb-2 h-9 rounded-lg"+ containerClassName="mb-2 h-9 rounded"type="number"name={`min-${value}`}id={`min-${value}`}@@ -77,7 +77,7 @@ export function DataTableFilterSlider<TData>({<InputWithAddonsplaceholder="to"trailing="ms"- containerClassName="mb-2 h-9 rounded-lg"+ containerClassName="mb-2 h-9 rounded"type="number"name={`max-${value}`}id={`max-${value}`}diff --git a/apps/studio/components/ui/DataTable/DataTableInfinite.tsx b/apps/studio/components/ui/DataTable/DataTableInfinite.tsxindex 7546227e637..8dec475c052 100644--- a/apps/studio/components/ui/DataTable/DataTableInfinite.tsx+++ b/apps/studio/components/ui/DataTable/DataTableInfinite.tsx@@ -30,11 +30,10 @@ export interface DataTableInfiniteProps<TData, TValue, TMeta> {searchParamsParser: any}+// [Joshen] JFYI this component is NOT virtualized and hence will struggle handling many data pointsexport function DataTableInfinite<TData, TValue, TMeta>({columns,defaultColumnVisibility = {},- isFetching,- isLoading,fetchNextPage,hasNextPage,totalRows = 0,@@ -45,10 +44,12 @@ export function DataTableInfinite<TData, TValue, TMeta>({setColumnVisibility,searchParamsParser,}: DataTableInfiniteProps<TData, TValue, TMeta>) {- const { table } = useDataTable()+ const { table, isLoading, isFetching } = useDataTable()const tableRef = useRef<HTMLTableElement>(null)const headerGroups = table.getHeaderGroups()+ const headers = headerGroups[0].headers+ const rows = table.getRowModel().rows ?? []const onScroll = useCallback((e: UIEvent<HTMLElement>) => {@@ -56,11 +57,11 @@ export function DataTableInfinite<TData, TValue, TMeta>({Math.ceil(e.currentTarget.scrollTop + e.currentTarget.clientHeight) >=e.currentTarget.scrollHeight- if (onPageBottom && !isFetching && totalRowsFetched < filterRows) {+ if (onPageBottom && !isFetching && totalRows > totalRowsFetched) {fetchNextPage()}},- [fetchNextPage, isFetching, filterRows, totalRowsFetched]+ [fetchNextPage, isFetching, totalRows, totalRowsFetched])useHotKey(() => {@@ -69,118 +70,103 @@ export function DataTableInfinite<TData, TValue, TMeta>({}, 'u')return (- <>- <Table- containerProps={{- onScroll,- }}- ref={tableRef} // REMINDER: https://stackoverflow.com/questions/50361698/border-style-do-not-work-with-sticky-position-element- className="z-0"- >- <TableHeader>- {headerGroups.map((headerGroup) => (- <TableRow key={headerGroup.id} className="bg-surface-75">- {headerGroup.headers.map((header) => {- const sort = header.column.getIsSorted()- const canResize = header.column.getCanResize()- const onResize = header.getResizeHandler()- const headerClassName = (header.column.columnDef.meta as any)?.headerClassName+ <Table ref={tableRef} onScroll={onScroll}>+ <TableHeader>+ <TableRow className="bg-surface-75">+ {headers.map((header) => {+ const sort = header.column.getIsSorted()+ const canResize = header.column.getCanResize()+ const onResize = header.getResizeHandler()+ const headerClassName = (header.column.columnDef.meta as any)?.headerClassName- return (- <TableHead- key={header.id}- className={headerClassName}- aria-sort={- sort === 'asc' ? 'ascending' : sort === 'desc' ? 'descending' : 'none'- }- >- {header.isPlaceholder- ? null- : flexRender(header.column.columnDef.header, header.getContext())}- {canResize && (- <div- onDoubleClick={() => header.column.resetSize()}- onMouseDown={onResize}- onTouchStart={onResize}- className={cn(- 'user-select-none absolute -right-2 top-0 z-10 flex h-full w-4 cursor-col-resize touch-none justify-center',- 'before:absolute before:inset-y-0 before:w-px before:translate-x-px before:bg-border'- )}- />+ return (+ <TableHead+ key={header.id}+ className={headerClassName}+ aria-sort={sort === 'asc' ? 'ascending' : sort === 'desc' ? 'descending' : 'none'}+ >+ {header.isPlaceholder+ ? null+ : flexRender(header.column.columnDef.header, header.getContext())}+ {canResize && (+ <div+ onDoubleClick={() => header.column.resetSize()}+ onMouseDown={onResize}+ onTouchStart={onResize}+ className={cn(+ 'user-select-none absolute -right-2 top-0 z-10 flex h-full w-4 cursor-col-resize touch-none justify-center',+ 'before:absolute before:inset-y-0 before:w-px before:translate-x-px before:bg-border')}- </TableHead>- )- })}- </TableRow>- ))}- </TableHeader>- <TableBody- id="content"- tabIndex={-1}- // REMINDER: avoids scroll (skipping the table header) when using skip to content- style={{ scrollMarginTop: 'calc(var(--top-bar-height))' }}- >- {table.getRowModel().rows?.length ? (- table.getRowModel().rows.map((row) => (- // REMINDER: if we want to add arrow navigation https://github.com/TanStack/table/discussions/2752#discussioncomment-192558- <Fragment key={row.id}>- {renderLiveRow?.({ row: row as any })}- <MemoizedRow- row={row}- table={table}- searchParamsParser={searchParamsParser}- selected={row.getIsSelected()}- />- </Fragment>- ))- ) : (- <Fragment>- {renderLiveRow?.()}- <TableRow>- <TableCell colSpan={columns.length} className="h-24 text-center">- No results.- </TableCell>- </TableRow>+ />+ )}+ </TableHead>+ )+ })}+ </TableRow>+ </TableHeader>+ <TableBody+ id="content"+ tabIndex={-1}+ // REMINDER: avoids scroll (skipping the table header) when using skip to content+ style={{ scrollMarginTop: 'calc(var(--top-bar-height))' }}+ >+ {rows.length ? (+ rows.map((row) => (+ // REMINDER: if we want to add arrow navigation https://github.com/TanStack/table/discussions/2752#discussioncomment-192558+ <Fragment key={row.id}>+ {renderLiveRow?.({ row: row as any })}+ <DataTableRow+ row={row}+ table={table}+ searchParamsParser={searchParamsParser}+ selected={row.getIsSelected()}+ /></Fragment>- )}- <TableRow className="hover:bg-transparent data-[state=selected]:bg-transparent">- <TableCell colSpan={columns.length} className="text-center">- {hasNextPage || isFetching || isLoading ? (- <div className="flex flex-col items-center gap-2">- <Button- disabled={isFetching || isLoading}- onClick={() => fetchNextPage()}- size="small"- type="outline"- icon={- isFetching ? <LoaderCircle className="mr-2 h-4 w-4 animate-spin" /> : null- }- >- Load More- </Button>- <p className="text-xs text-foreground-lighter">- Showing{' '}- <span className="font-mono font-medium">- {formatCompactNumber(totalRowsFetched)}- </span>{' '}- of{' '}- <span className="font-mono font-medium">{formatCompactNumber(totalRows)}</span>{' '}- rows- </p>- </div>- ) : (- <p className="text-sm text-foreground-lighter py-4">- No more data to load (- <span className="font-mono font-medium">{formatCompactNumber(filterRows)}</span>{' '}+ ))+ ) : (+ <Fragment>+ {renderLiveRow?.()}+ <TableRow>+ <TableCell colSpan={columns.length} className="h-24 text-center">+ {isLoading ? 'Retrieving logs...' : 'No results'}+ </TableCell>+ </TableRow>+ </Fragment>+ )}+ <TableRow className="hover:bg-transparent data-[state=selected]:bg-transparent">+ <TableCell colSpan={columns.length} className="text-center !py-2">+ {hasNextPage || isFetching || isLoading ? (+ <div className="flex flex-col items-center gap-2">+ <Button+ disabled={isFetching || isLoading}+ onClick={() => fetchNextPage()}+ size="small"+ type="outline"+ icon={isFetching ? <LoaderCircle className="mr-2 h-4 w-4 animate-spin" /> : null}+ >+ Load more+ </Button>+ <p className="text-xs text-foreground-lighter">+ Showing{' '}+ <span className="font-mono font-medium">+ {formatCompactNumber(totalRowsFetched)}+ </span>{' '}of <span className="font-mono font-medium">{formatCompactNumber(totalRows)}</span>{' '}- rows)+ rows</p>- )}- </TableCell>- </TableRow>- </TableBody>- </Table>- </>+ </div>+ ) : (+ <p className="text-xs text-foreground-lighter">+ No more data to load (+ <span className="font-mono font-medium">{formatCompactNumber(filterRows)}</span> of{' '}+ <span className="font-mono font-medium">{formatCompactNumber(totalRows)}</span>{' '}+ rows)+ </p>+ )}+ </TableCell>+ </TableRow>+ </TableBody>+ </Table>)}@@ -201,10 +187,9 @@ function DataTableRow<TData>({selected?: booleansearchParamsParser: any}) {- // REMINDER: rerender the row when live mode is toggled - used to opacity the row- // via the `getRowClassName` prop - but for some reasons it wil render the row on data fetchuseQueryState('live', searchParamsParser.live)const rowClassName = (table.options.meta as any)?.getRowClassName?.(row)+ const cells = row.getVisibleCells()return (<TableRow@@ -220,7 +205,7 @@ function DataTableRow<TData>({}}className={cn(rowClassName)}>- {row.getVisibleCells().map((cell) => {+ {cells.map((cell) => {const cellClassName = (cell.column.columnDef.meta as any)?.cellClassNamereturn (<TableCell key={cell.id} className={cn(cellClassName)}>@@ -232,6 +217,7 @@ function DataTableRow<TData>({)}+// [Joshen] Using MemoizedRow will cause the column visibility to break as the rows aren't getting re-renderedconst MemoizedRow = memo(DataTableRow,(prev, next) => prev.row.id === next.row.id && prev.selected === next.selecteddiff --git a/apps/studio/components/ui/DataTable/DataTableSheetRowAction.tsx b/apps/studio/components/ui/DataTable/DataTableSheetRowAction.tsxindex 47f02763d75..d1cec2acbfe 100644--- a/apps/studio/components/ui/DataTable/DataTableSheetRowAction.tsx+++ b/apps/studio/components/ui/DataTable/DataTableSheetRowAction.tsx@@ -55,7 +55,6 @@ export function DataTableSheetRowAction<TData, TFields extends DataTableFilterFireturn (<DropdownMenuItemonClick={() => {- // FIXME:const filterValue = column?.getFilterValue() as undefined | Array<unknown>const newValue = filterValue?.includes(value)? filterValuediff --git a/apps/studio/components/ui/DataTable/DataTableSideBarLayout.tsx b/apps/studio/components/ui/DataTable/DataTableSideBarLayout.tsxindex ec9162a8fed..5898566d139 100644--- a/apps/studio/components/ui/DataTable/DataTableSideBarLayout.tsx+++ b/apps/studio/components/ui/DataTable/DataTableSideBarLayout.tsx@@ -1,4 +1,4 @@-import { ReactNode, useMemo } from 'react'+import { CSSProperties, ReactNode, useMemo } from 'react'import { cn } from 'ui'import { useDataTable } from './providers/DataTableProvider'@@ -42,23 +42,9 @@ export function DataTableSideBarLayout({return (<div- className={cn(- 'flex flex-row w-full h-full',- // 'min-h-screen w-full flex-col sm:flex-row',- className- )}- style={- {- '--top-bar-height': `${- // topBarHeight is the height of the chart and search bar- topBarHeight +- // 64px is the height of the top bar- 64- //- }px`,- ...columnSizeVars,- } as React.CSSProperties- }+ className={cn('flex flex-row w-full h-full', className)}+ // topBarHeight is the height of the chart and search bar, and 64px is the height of the top bar+ style={{ '--top-bar-height': `${topBarHeight + 64}px`, ...columnSizeVars } as CSSProperties}>{children}</div>diff --git a/apps/studio/components/ui/DataTable/DataTableViewOptions.tsx b/apps/studio/components/ui/DataTable/DataTableViewOptions.tsxindex 069cd02d143..24fc9a6641a 100644--- a/apps/studio/components/ui/DataTable/DataTableViewOptions.tsx+++ b/apps/studio/components/ui/DataTable/DataTableViewOptions.tsx@@ -1,9 +1,9 @@-import { Check, GripVertical, Settings2 } from 'lucide-react'+import { GripVertical, Settings2 } from 'lucide-react'import { useMemo, useState } from 'react'import {Button,- cn,+ Checkbox_Shadcn_,Command_Shadcn_ as Command,CommandEmpty_Shadcn_ as CommandEmpty,CommandGroup_Shadcn_ as CommandGroup,@@ -45,9 +45,9 @@ export function DataTableViewOptions() {icon={<Settings2 className="text-foreground" />}/></PopoverTrigger>- <PopoverContent side="bottom" align="end" className="w-[200px] p-0">+ <PopoverContent portal side="bottom" align="end" className="w-[200px] p-0"><Command>- <CommandInput value={search} onValueChange={setSearch} placeholder="Search options..." />+ <CommandInput value={search} onValueChange={setSearch} placeholder="Search columns..." /><CommandList><CommandEmpty>No option found.</CommandEmpty><CommandGroup>@@ -68,19 +68,10 @@ export function DataTableViewOptions() {<CommandItemvalue={column.id}onSelect={() => column.toggleVisibility(!column.getIsVisible())}- className={'capitalize'}+ className="capitalize p-1"disabled={drag}>- <div- className={cn(- 'mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary',- column.getIsVisible()- ? 'bg-primary text-primary-foreground'- : 'opacity-50 [&_svg]:invisible'- )}- >- <Check className={cn('h-4 w-4')} />- </div>+ <Checkbox_Shadcn_ checked={column.getIsVisible()} className="mr-2" /><span>{(column.columnDef.meta as any)?.label || column.id}</span>{enableColumnOrdering && !search ? (<SortableDragHandlediff --git a/apps/studio/components/ui/DataTable/Table.tsx b/apps/studio/components/ui/DataTable/Table.tsxindex 655e0df400c..efd78e2613a 100644--- a/apps/studio/components/ui/DataTable/Table.tsx+++ b/apps/studio/components/ui/DataTable/Table.tsx@@ -13,17 +13,15 @@ import {// Only create a custom component for Table with the added propsconst Table = forwardRef<HTMLTableElement, ComponentPropsWithRef<typeof ShadcnTable>>(- ({ className, ...props }, ref) => (+ ({ className, onScroll, ...props }, ref) => (<ShadcnTableref={ref}{...props}- className={cn('', className)}+ className={cn(className)}containerProps={{- className:- 'table-fixed min-w-max caption-bottom text-sm max-h-[calc(100vh_-_var(--top-bar-height))]',- ...props.containerProps,+ onScroll,+ className: 'h-full w-full overflow-auto table-fixed min-w-max caption-bottom text-sm',}}- // REMINDER: we are not scrolling the table, but the container/>))@@ -33,7 +31,7 @@ const TableHeader = forwardRef<HTMLTableSectionElement,ComponentPropsWithRef<typeof ShadcnTableHeader>>(({ className, ...props }, ref) => (- <ShadcnTableHeader ref={ref} className={cn('sticky top-0', className)} {...props} />+ <ShadcnTableHeader ref={ref} className={cn('sticky top-0 z-[1]', className)} {...props} />))TableHeader.displayName = 'TableHeader'@@ -63,12 +61,7 @@ const TableRow = forwardRef<HTMLTableRowElement, ComponentPropsWithRef<typeof Sh({ className, ...props }, ref) => (<ShadcnTableRowref={ref}- className={cn(- 'bg-background hover:bg-muted/50',- // '[&>*]:border-t [&>:not(:last-child)]:border-r',- 'border-b-0',- className- )}+ className={cn('bg-background hover:bg-surface-100 border-b-0', className)}{...props}/>)@@ -95,10 +88,7 @@ const TableCell = forwardRef<HTMLTableCellElement, ComponentPropsWithRef<typeof({ className, ...props }, ref) => (<ShadcnTableCellref={ref}- className={cn(- 'text-[0.8rem] !py-1 p-2 [&>[role=checkbox]]:translate-y-[2px] truncate',- className- )}+ className={cn('text-xs !py-1 p-2 [&>[role=checkbox]]:translate-y-[2px] truncate', className)}{...props}/>)diff --git a/apps/studio/components/ui/DataTable/InputWithAddons.tsx b/apps/studio/components/ui/DataTable/primitives/InputWithAddons.tsxsimilarity index 55%rename from apps/studio/components/ui/DataTable/InputWithAddons.tsxrename to apps/studio/components/ui/DataTable/primitives/InputWithAddons.tsxindex 0b27280f9c8..bc08b4fe97f 100644--- a/apps/studio/components/ui/DataTable/InputWithAddons.tsx+++ b/apps/studio/components/ui/DataTable/primitives/InputWithAddons.tsx@@ -8,21 +8,25 @@ export interface InputWithAddonsProps extends InputHTMLAttributes<HTMLInputElemecontainerClassName?: string}-const InputWithAddons = forwardRef<HTMLInputElement, InputWithAddonsProps>(+export const InputWithAddons = forwardRef<HTMLInputElement, InputWithAddonsProps>(({ leading, trailing, containerClassName, className, ...props }, ref) => {return (<divclassName={cn(- 'border-input ring-offset-background focus-within:ring-ring group flex h-10 w-full rounded-md border bg-transparent text-sm focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 overflow-hidden',+ 'group border-input ring-offset-background flex h-10 w-full rounded border bg-transparent text-sm overflow-hidden',+ 'focus-within:ring-ring focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2',containerClassName)}>{leading ? (- <div className="border-input bg-muted/50 border-r px-3 py-2">{leading}</div>+ <div className="border-input bg-muted/50 border-r px-2.5 py-2 flex items-center justify-center">+ {leading}+ </div>) : null}<inputclassName={cn(- 'placeholder:text-muted-foreground bg-background w-full rounded-md px-3 py-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50',+ 'bg-background w-full px-3 py-2 focus:outline-none border-0 placeholder:text-muted-foreground ',+ 'disabled:cursor-not-allowed disabled:opacity-50 text-sm',className)}ref={ref}@@ -36,5 +40,3 @@ const InputWithAddons = forwardRef<HTMLInputElement, InputWithAddonsProps>(})InputWithAddons.displayName = 'InputWithAddons'--export { InputWithAddons }diff --git a/apps/studio/components/ui/DataTable/providers/DataTableProvider.tsx b/apps/studio/components/ui/DataTable/providers/DataTableProvider.tsxindex f351dfe2981..ff1abe4f0cb 100644--- a/apps/studio/components/ui/DataTable/providers/DataTableProvider.tsx+++ b/apps/studio/components/ui/DataTable/providers/DataTableProvider.tsx@@ -29,7 +29,9 @@ interface DataTableBaseContextType<TData = unknown, TValue = unknown> {table: Table<TData>filterFields: DataTableFilterField<TData>[]columns: ColumnDef<TData, TValue>[]+ isFetching?: booleanisLoading?: boolean+ isLoadingCounts?: booleangetFacetedUniqueValues?: (table: Table<TData>, columnId: string) => Map<string, number>getFacetedMinMaxValues?: (table: Table<TData>, columnId: string) => undefined | [number, number]}diff --git a/apps/studio/data/logs/unified-logs-chart-query.ts b/apps/studio/data/logs/unified-logs-chart-query.tsindex de215cf36ea..295078c2c44 100644--- a/apps/studio/data/logs/unified-logs-chart-query.ts+++ b/apps/studio/data/logs/unified-logs-chart-query.ts@@ -4,7 +4,7 @@ import { getLogsChartQuery } from 'components/interfaces/UnifiedLogs/UnifiedLogsimport { handleError, post } from 'data/fetchers'import { ExecuteSqlError } from 'data/sql/execute-sql-query'import { logsKeys } from './keys'-import { UNIFIED_LOGS_STALE_TIME, UnifiedLogsVariables } from './unified-logs-infinite-query'+import { UNIFIED_LOGS_QUERY_OPTIONS, UnifiedLogsVariables } from './unified-logs-infinite-query'export async function getUnifiedLogsChart({ projectRef, search }: UnifiedLogsVariables,@@ -150,7 +150,7 @@ export const useUnifiedLogsChartQuery = <TData = UnifiedLogsChartData>(({ signal }) => getUnifiedLogsChart({ projectRef, search }, signal),{enabled: enabled && typeof projectRef !== 'undefined',- staleTime: UNIFIED_LOGS_STALE_TIME,+ ...UNIFIED_LOGS_QUERY_OPTIONS,...options,})diff --git a/apps/studio/data/logs/unified-logs-count-query.ts b/apps/studio/data/logs/unified-logs-count-query.tsindex cca71aa39fc..7bd0d1dca2f 100644--- a/apps/studio/data/logs/unified-logs-count-query.ts+++ b/apps/studio/data/logs/unified-logs-count-query.ts@@ -7,7 +7,7 @@ import { ExecuteSqlError } from 'data/sql/execute-sql-query'import { logsKeys } from './keys'import {getUnifiedLogsISOStartEnd,- UNIFIED_LOGS_STALE_TIME,+ UNIFIED_LOGS_QUERY_OPTIONS,UnifiedLogsVariables,} from './unified-logs-infinite-query'@@ -88,7 +88,7 @@ export const useUnifiedLogsCountQuery = <TData = UnifiedLogsCountData>(({ signal }) => getUnifiedLogsCount({ projectRef, search }, signal),{enabled: enabled && typeof projectRef !== 'undefined',- staleTime: UNIFIED_LOGS_STALE_TIME,+ ...UNIFIED_LOGS_QUERY_OPTIONS,...options,})diff --git a/apps/studio/data/logs/unified-logs-infinite-query.ts b/apps/studio/data/logs/unified-logs-infinite-query.tsindex c7afe83a21d..ff2f8cba4b4 100644--- a/apps/studio/data/logs/unified-logs-infinite-query.ts+++ b/apps/studio/data/logs/unified-logs-infinite-query.ts@@ -11,7 +11,14 @@ import { logsKeys } from './keys'const LOGS_PAGE_LIMIT = 50type LogLevel = 'success' | 'warning' | 'error'-export const UNIFIED_LOGS_STALE_TIME = 1000 * 60 * 5 // 5 minutes++export const UNIFIED_LOGS_QUERY_OPTIONS = {+ refetchOnWindowFocus: false,+ refetchOnMount: false,+ refetchOnReconnect: false,+ refetchInterval: 0,+ staleTime: 1000 * 60 * 5, // 5 minutes,+}export type UnifiedLogsData = anyexport type UnifiedLogsError = ResponseError@@ -26,7 +33,6 @@ export const getUnifiedLogsISOStartEnd = (search: QuerySearchParamsType) => {isoTimestampStart = new Date(search.date[0]).toISOString()isoTimestampEnd = new Date(search.date[1]).toISOString()} else {- // Default to last hourconst now = new Date()isoTimestampEnd = now.toISOString()const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000)@@ -36,12 +42,6 @@ export const getUnifiedLogsISOStartEnd = (search: QuerySearchParamsType) => {return { isoTimestampStart, isoTimestampEnd }}-/**- * Refactor notes- * - Shouldn't need to handle "direction", we store all data as it gets infinitely feteched- * - Shouldn't need to handle fetching previous too i think- */-async function getUnifiedLogs({ projectRef, search, pageParam }: UnifiedLogsVariables & { pageParam: PageParam },signal?: AbortSignal@@ -49,62 +49,70 @@ async function getUnifiedLogs(if (typeof projectRef === 'undefined')throw new Error('projectRef is required for getUnifiedLogs')- const cursorValue = pageParam?.cursor // Already in microseconds- const direction = pageParam?.direction- const isPagination = pageParam !== undefined- const sql = `${getUnifiedLogsQuery(search)} ORDER BY timestamp DESC, id DESC LIMIT ${LOGS_PAGE_LIMIT}`+ /**+ * [Joshen] RE infinite loading pagination logic for unified logs, these all really should live in the API+ * but for now we're doing these on the FE to move quickly while figuring out what data we need before we+ * migrate this logic to the BE. Just thought to leave a small explanation on the logic here:+ *+ * We're leveraging on the log's timestamp to essentially fetch the next page+ * Given that the logs are ordered descending (latest logs come first, and we're fetching older logs as we scroll down)+ * Hence why the cursor is basically the last row's timestamp from the latest page+ *+ * iso_timestamp_start will always be the current timestamp+ * iso_timestamp_end will default to the last hour for the first page, followed by the last row's timestamp from+ * the previous page.+ *+ * However, just note that this isn't a perfect solution as there's always the edge case where by there's multiple rows+ * with identical timestamps, hence why FE will need a de-duping logic (in UnifiedLogs.tsx) unless we can figure a cleaner+ * solution when we move all this logic to the BE (e.g using composite columns for the cursor like timestamp + id)+ *+ */const { isoTimestampStart, isoTimestampEnd } = getUnifiedLogsISOStartEnd(search)+ const sql = `${getUnifiedLogsQuery(search)} ORDER BY timestamp DESC, id DESC LIMIT ${LOGS_PAGE_LIMIT}`++ const cursorValue = pageParam?.cursor+ const cursorDirection = pageParam?.directionlet timestampStart: stringlet timestampEnd: string- if (isPagination && direction === 'prev') {+ if (cursorDirection === 'prev') {// Live mode: fetch logs newer than the cursortimestampStart = cursorValue- ? new Date(Number(cursorValue) / 1000).toISOString() // Convert microseconds to ISO for API+ ? new Date(Number(cursorValue) / 1000).toISOString(): isoTimestampStart- timestampEnd = new Date().toISOString() // Current time as ISO for API- } else if (isPagination && direction === 'next') {+ timestampEnd = new Date().toISOString()+ } else if (cursorDirection === 'next') {// Regular pagination: fetch logs older than the cursortimestampStart = isoTimestampStarttimestampEnd = cursorValue- ? new Date(Number(cursorValue) / 1000).toISOString() // Convert microseconds to ISO for API+ ? new Date(Number(cursorValue) / 1000).toISOString(): isoTimestampEnd} else {- // Initial load: use the original date rangetimestampStart = isoTimestampStarttimestampEnd = isoTimestampEnd}const { data, error } = await post(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {params: { path: { ref: projectRef } },- body: { iso_timestamp_start: timestampStart, iso_timestamp_end: timestampEnd, sql },+ body: { iso_timestamp_start: isoTimestampStart, iso_timestamp_end: timestampEnd, sql },signal,})if (error) handleError(error)- const resultData = data?.result || []+ const resultData = data?.result ?? []- // Transform results to expected schemaconst result = resultData.map((row: any) => {- // Create a unique ID using the timestamp- const uniqueId = `${row.id || 'id'}-${row.timestamp}-${new Date().getTime()}`-// Create a date object for display purposes- // The timestamp is in microseconds, need to convert to milliseconds for JS Dateconst date = new Date(Number(row.timestamp) / 1000)- // Use the level directly from SQL rather than determining it in TypeScript- const level = row.level as LogLevel-return {- id: uniqueId,- uuid: uniqueId,- date, // Date object for display purposes- timestamp: row.timestamp, // Original timestamp from the database- level,+ id: row.id,+ date,+ timestamp: row.timestamp,+ level: row.level as LogLevel,status: row.status || 200,method: row.method,host: row.host,@@ -121,25 +129,20 @@ async function getUnifiedLogs(}})- // Just use the row timestamps directly for cursors- const lastRow = result.length > 0 ? result[result.length - 1] : nullconst firstRow = result.length > 0 ? result[0] : null- const nextCursor = lastRow ? lastRow.timestamp : null+ const lastRow = result.length > 0 ? result[result.length - 1] : null+ const hasMore = result.length >= LOGS_PAGE_LIMIT - 1+ const nextCursor = lastRow ? lastRow.timestamp : null+ // FIXED: Always provide prevCursor like DataTableDemo does// This ensures live mode never breaks the infinite query chain// DataTableDemo uses milliseconds, but our timestamps are in microsecondsconst prevCursor = result.length > 0 ? firstRow!.timestamp : new Date().getTime() * 1000- // HACK: Backend uses "timestamp > cursor" which can exclude records with identical timestamps- // THIS CAN SOMETIMES CAUSE 49 RECORDS INSTEAD OF 50 TO BE RETURNED- // TODO: Revisit this - ideally the backend should use composite cursors (timestamp+id) for proper pagination- // For now, we consider either 49 or 50 records as a "full page" to ensure pagination works correctly- const hasMore = result.length >= LOGS_PAGE_LIMIT - 1-return {data: result,- prevCursor,nextCursor: hasMore ? nextCursor : null,+ prevCursor,}}@@ -157,17 +160,16 @@ export const useUnifiedLogsInfiniteQuery = <TData = UnifiedLogsData>(},{enabled: enabled && typeof projectRef !== 'undefined',- getNextPageParam(lastPage, pages) {- // Only return a cursor if we actually have more data to fetch+ getPreviousPageParam: (firstPage) => {+ if (!firstPage.prevCursor) return null+ const result = { cursor: firstPage.prevCursor, direction: 'prev' } as PageParam+ return result+ },+ getNextPageParam(lastPage) {if (!lastPage.nextCursor || lastPage.data.length === 0) return null- // Only trigger fetch when specifically requested, not during column resizingreturn { cursor: lastPage.nextCursor, direction: 'next' } as PageParam},- refetchOnWindowFocus: false,- refetchOnMount: false,- refetchOnReconnect: false,- refetchInterval: 0,- staleTime: UNIFIED_LOGS_STALE_TIME,+ ...UNIFIED_LOGS_QUERY_OPTIONS,...options,})