The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: warehouse explorer (#27611)
Jordi Enric003cfd642594
diff --git a/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseAccessToken.tsx b/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseAccessToken.tsxindex 9688ad5a743..af20da05fdd 100644--- a/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseAccessToken.tsx+++ b/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseAccessToken.tsx@@ -1,18 +1,12 @@+import { z } from 'zod'import { zodResolver } from '@hookform/resolvers/zod'-import { PermissionAction } from '@supabase/shared-types/out/constants'import { useForm } from 'react-hook-form'-import { z } from 'zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { FormControl_Shadcn_, FormField_Shadcn_, FormItem_Shadcn_, Form_Shadcn_, Modal } from 'ui'+import { Input } from '@ui/components/shadcn/ui/input'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'-import {- FormControl_Shadcn_,- FormField_Shadcn_,- FormItem_Shadcn_,- Form_Shadcn_,- Input_Shadcn_,- Modal,-} from 'ui'type CreateWarehouseProps = {onSubmit: (values: { description: string }) => void@@ -61,27 +55,44 @@ const CreateWarehouseAccessToken = ({ onSubmit, loading, open, setOpen }: Createvisible={open}alignFooter="right"loading={loading}+ onConfirm={() => {+ form.handleSubmit((data) => {+ onSubmit(data)+ })()++ form.reset()+ }}>- <Modal.Content className="py-4">- <Form_Shadcn_ {...form}>- <form- id="create-access-token-form"- onSubmit={form.handleSubmit((data) => onSubmit(data))}- >+ <Form_Shadcn_ {...form}>+ <form+ onSubmit={(e) => {+ e.preventDefault()+ form.handleSubmit((data) => {+ onSubmit(data)+ })()++ form.reset()+ }}+ id="create-access-token-form"+ >+ <Modal.Content className="py-4">+ <p className="pb-5 text-foreground-light text-sm">+ Enter a unique description to identify this token.+ </p><FormField_Shadcn_control={form.control}name="description"render={({ field }) => (<FormItem_Shadcn_><FormControl_Shadcn_>- <Input_Shadcn_ type="text" {...field} />+ <Input placeholder="Token" type="text" {...field} /></FormControl_Shadcn_></FormItem_Shadcn_>)}/>- </form>- </Form_Shadcn_>- </Modal.Content>+ </Modal.Content>+ </form>+ </Form_Shadcn_></Modal></>)diff --git a/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseCollection.tsx b/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseCollection.tsxindex 17879fac032..224032b4b8c 100644--- a/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseCollection.tsx+++ b/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseCollection.tsx@@ -9,11 +9,12 @@ import { z } from 'zod'import { FormMessage } from '@ui/components/shadcn/ui/form'import { useParams } from 'common'+import { Button, FormControl_Shadcn_, FormField_Shadcn_, Form_Shadcn_, Modal } from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { Input } from '@ui/components/shadcn/ui/input'import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useCreateCollection } from 'data/analytics/warehouse-collections-create-mutation'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'-import { Button, FormControl_Shadcn_, FormField_Shadcn_, Form_Shadcn_, Input, Modal } from 'ui'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'export const CreateWarehouseCollectionModal = () => {const [isOpen, setIsOpen] = useState(false)@@ -24,8 +25,9 @@ export const CreateWarehouseCollectionModal = () => {const { mutate: createCollection, isLoading } = useCreateCollection({onSuccess: (data) => {+ // todo: remove typecast once api types are fixedsetIsOpen(false)- router.push(`/project/${ref}/logs/collections/${data?.token}`)+ router.push(`/project/${ref}/logs/collections/${(data as any).token}`)},onError: (error) => {toast.error(error.message)@@ -74,6 +76,7 @@ export const CreateWarehouseCollectionModal = () => {>New collection</ButtonTooltip>+ {/* <Button onClick={() => setIsOpen(!isOpen)}>Create collection</Button> */}<Modalsize="medium"onCancel={() => setIsOpen(!isOpen)}@@ -96,7 +99,7 @@ export const CreateWarehouseCollectionModal = () => {render={({ field }) => (<FormItemLayout label="Collection name" layout="horizontal"><FormControl_Shadcn_>- <Input {...field} placeholder="Events" />+ <Input placeholder="Events" {...field} /></FormControl_Shadcn_></FormItemLayout>)}diff --git a/apps/studio/components/interfaces/DataWarehouse/WarehouseAccessTokens.tsx b/apps/studio/components/interfaces/DataWarehouse/WarehouseAccessTokens.tsxindex f8444943d10..86a96ce8b77 100644--- a/apps/studio/components/interfaces/DataWarehouse/WarehouseAccessTokens.tsx+++ b/apps/studio/components/interfaces/DataWarehouse/WarehouseAccessTokens.tsx@@ -142,7 +142,7 @@ export const WarehouseAccessTokens = () => {<section className="flex flex-col gap-y-10 py-6 pb-32"><FormHeaderclassName="!mb-0"- title="Warehouse access tokens"+ title="Access tokens"description="Manage your warehouse access tokens for this project."actions={<CreateWarehouseAccessToken@@ -179,7 +179,7 @@ export const WarehouseAccessTokens = () => {<Tablehead={[<Table.th key="description">Description</Table.th>,- <Table.th key="token">Created at</Table.th>,+ <Table.th key="created_at">Created at</Table.th>,<Table.th key="token">Token</Table.th>,<Table.th key="actions" />,]}diff --git a/apps/studio/components/interfaces/DataWarehouse/WarehouseMenuItem.tsx b/apps/studio/components/interfaces/DataWarehouse/WarehouseMenuItem.tsxindex 5db62bee255..e328a432fd6 100644--- a/apps/studio/components/interfaces/DataWarehouse/WarehouseMenuItem.tsx+++ b/apps/studio/components/interfaces/DataWarehouse/WarehouseMenuItem.tsx@@ -81,13 +81,7 @@ export const WarehouseMenuItem = ({ item }: Props) => {resolver: zodResolver(UpdateFormSchema),})- const DeleteFormSchema = z.object({- confirm: z.boolean(),- })-- const deleteForm = useForm<z.infer<typeof DeleteFormSchema>>({- resolver: zodResolver(DeleteFormSchema),- })+ const deleteForm = useForm()return (<>@@ -117,7 +111,7 @@ export const WarehouseMenuItem = ({ item }: Props) => {onClick={(e) => {e.stopPropagation()}}- align="end"+ align="start"className="w-44 *:space-x-2"><Tooltip_Shadcn_>@@ -188,7 +182,7 @@ export const WarehouseMenuItem = ({ item }: Props) => {render={({ field }) => (<FormItemLayout label="Collection name"><FormControl_Shadcn_>- <Input_Shadcn_ type="text" {...field} />+ <Input_Shadcn_ defaultValue={item.name} type="text" {...field} /></FormControl_Shadcn_></FormItemLayout>)}@@ -227,28 +221,11 @@ export const WarehouseMenuItem = ({ item }: Props) => {deleteCollection.mutate({ projectRef, collectionToken: item.token })})}>- <div className="p-3 space-y-4">+ <div className="p-3 px-6 space-y-4"><p className="text-sm text-foreground-light">Are you sure you want to delete the selected collection?<br /> This action cannot be undone.</p>- <div className="flex items-center my-2">- <FormField_Shadcn_- control={deleteForm.control}- name="confirm"- render={({ field }) => (- <FormItemLayout>- <FormControl_Shadcn_>- <Checkbox_Shadcn_ checked={field.value} onCheckedChange={field.onChange} />- </FormControl_Shadcn_>- <FormLabel_Shadcn_ className="p-2">- Yes, I want to delete <span className="font-medium">{item.name}</span>.- </FormLabel_Shadcn_>- <FormMessage />- </FormItemLayout>- )}- />- </div></div><div className="flex gap-2 justify-end p-3 border-t">@@ -262,8 +239,8 @@ export const WarehouseMenuItem = ({ item }: Props) => {>Cancel</Button>- <Button type="primary" htmlType="submit" loading={isLoading}>- Delete+ <Button type="danger" htmlType="submit" loading={isLoading}>+ Yes, delete</Button></div></form>diff --git a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsxindex b0403f9f103..4f3e470409e 100644--- a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx+++ b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx@@ -47,7 +47,6 @@ interface Props {isLoading?: booleanerror?: LogQueryError | nullshowDownload?: boolean- // TODO: move all common params to a context to avoid prop drillingqueryType?: QueryTypeprojectRef: stringparams: LogSelectionProps['params']@@ -57,6 +56,7 @@ interface Props {maxHeight?: stringclassName?: stringcollectionName?: string // Used for warehouse queries+ warehouseError?: stringemptyState?: ReactNodeshowHeader?: booleanshowHistogramToggle?: booleandiff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.types.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.types.tsindex 566e7fa10e6..f9c055618af 100644--- a/apps/studio/components/interfaces/Settings/Logs/Logs.types.ts+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.types.ts@@ -138,3 +138,9 @@ export interface DatetimeHelper {default?: booleandisabled?: boolean}++export interface WarehouseCollection {+ name: string+ id: number+ token: string+}diff --git a/apps/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx b/apps/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsxindex 5c7f8e9982c..525392c468b 100644--- a/apps/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx+++ b/apps/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx@@ -1,11 +1,7 @@-import * as Tooltip from '@radix-ui/react-tooltip'import Link from 'next/link'-import React, { useState } from 'react'+import React, { ReactNode, useState } from 'react'-import Table from 'components/to-be-cleaned/Table'-import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'-import { copyToClipboard } from 'lib/helpers'-import { logConstants } from 'shared-data'+import * as Tooltip from '@radix-ui/react-tooltip'import {Alert,Badge,@@ -14,7 +10,6 @@ import {DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,- IconBookOpen,IconCheck,IconChevronDown,IconClipboard,@@ -25,18 +20,28 @@ import {Tabs,} from 'ui'import DatePickers from './Logs.DatePickers'+import Table from 'components/to-be-cleaned/Table'+import { logConstants } from 'shared-data'+import { copyToClipboard } from 'lib/helpers'+import { BookOpen, ChevronDown } from 'lucide-react'+import { WarehouseQueryTemplate } from './Warehouse.utils'import {EXPLORER_DATEPICKER_HELPERS,LOGS_SOURCE_DESCRIPTION,LogsTableName,} from './Logs.constants'-import type { LogTemplate, LogsWarning } from './Logs.types'+import { LogTemplate, LogsWarning, WarehouseCollection } from './Logs.types'+import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'+import { useFlag } from 'hooks/ui/useFlag'import { IS_PLATFORM } from 'common'+export type SourceType = 'logs' | 'warehouse'export interface LogsQueryPanelProps {templates?: LogTemplate[]+ warehouseTemplates?: WarehouseQueryTemplate[]onSelectTemplate: (template: LogTemplate) => void- onSelectSource: (source: LogsTableName) => void+ onSelectWarehouseTemplate: (template: WarehouseQueryTemplate) => void+ onSelectSource: (source: string) => voidonClear: () => voidonSave?: () => voidhasEditorValue: boolean@@ -45,18 +50,35 @@ export interface LogsQueryPanelProps {defaultTo: stringdefaultFrom: stringwarnings: LogsWarning[]+ warehouseCollections: WarehouseCollection[]+ dataSource: SourceType+ onDataSourceChange: (sourceType: SourceType) => void+}++function DropdownMenuItemContent({ name, desc }: { name: ReactNode; desc?: string }) {+ return (+ <div className="grid gap-1">+ <div className="font-mono font-bold">{name}</div>+ {desc && <div className="text-foreground-light">{desc}</div>}+ </div>+ )}const LogsQueryPanel = ({templates = [],+ warehouseTemplates = [],onSelectTemplate,+ onSelectWarehouseTemplate,onSelectSource,defaultFrom,defaultTo,onDateChange,warnings,+ warehouseCollections,+ dataSource,+ onDataSourceChange,}: LogsQueryPanelProps) => {- const [showReference, setShowReference] = React.useState(false)+ const [showReference, setShowReference] = useState(false)const {projectAuthAll: authEnabled,@@ -64,46 +86,107 @@ const LogsQueryPanel = ({projectEdgeFunctionAll: edgeFunctionsEnabled,} = useIsFeatureEnabled(['project_auth:all', 'project_storage:all', 'project_edge_function:all'])+ const warehouseEnabled = useFlag('warehouse')+const logsTableNames = Object.entries(LogsTableName).filter(([key]) => {if (key === 'AUTH') return authEnabledif (key === 'STORAGE') return storageEnabledif (key === 'FN_EDGE') return edgeFunctionsEnabled+ if (key === 'WAREHOUSE') return falsereturn true}).map(([, value]) => value)return (- <div className="rounded rounded-bl-none rounded-br-none border border-overlay bg-surface-100">+ <div className="border-b bg-surface-100"><div className="flex w-full items-center justify-between px-5 py-2"><div className="flex w-full flex-row items-center justify-between gap-x-4"><div className="flex items-center gap-2">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button type="default" iconRight={<IconChevronDown />}>- Insert source- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent side="bottom" align="start">- {logsTableNames- .sort((a, b) => a.localeCompare(b))- .map((source) => (- <DropdownMenuItem key={source} onClick={() => onSelectSource(source)}>- <div className="flex flex-col gap-1">- <span className="font-mono font-bold">{source}</span>- <span className="text-foreground-light">- {LOGS_SOURCE_DESCRIPTION[source]}+ {warehouseEnabled && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="default" iconRight={<ChevronDown />}>+ Data source <span className="ml-2 font-mono opacity-50">{dataSource}</span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="bottom" align="start">+ <DropdownMenuItem onClick={() => onDataSourceChange('logs')}>+ <DropdownMenuItemContent name="Logs" desc="Logs for all Supabase products" />+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => onDataSourceChange('warehouse')}>+ <DropdownMenuItemContent+ name={+ <span>+ Warehouse <Badge variant="warning">NEW</Badge></span>- </div>+ }+ desc="Query your data warehouse collections"+ />+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}++ {dataSource === 'warehouse' && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="default" iconRight={<ChevronDown />}>+ Templates+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="max-h-96 overflow-auto" side="bottom" align="start">+ {warehouseTemplates.map((template) => (+ <DropdownMenuItem+ key={template.name}+ onClick={() => onSelectWarehouseTemplate(template)}+ >+ <DropdownMenuItemContent name={template.name} desc={template.description} /></DropdownMenuItem>))}- </DropdownMenuContent>- </DropdownMenu>+ {warehouseCollections.length === 0 && (+ <DropdownMenuItem className="hover:bg-transparent cursor-default">+ <DropdownMenuItemContent+ name="No collections found"+ desc="You can create collections in the left sidebar."+ />+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}- {IS_PLATFORM && (+ {dataSource === 'logs' && (<DropdownMenu><DropdownMenuTrigger asChild>- <Button type="default" iconRight={<IconChevronDown />}>+ <Button type="default" iconRight={<ChevronDown />}>+ Insert source+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side="bottom"+ align="start"+ className="max-h-[70vh] overflow-auto"+ >+ {dataSource === 'logs' &&+ logsTableNames+ .sort((a, b) => a.localeCompare(b))+ .map((source) => (+ <DropdownMenuItem key={source} onClick={() => onSelectSource(source)}>+ <DropdownMenuItemContent+ name={source}+ desc={LOGS_SOURCE_DESCRIPTION[source]}+ />+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}++ {dataSource === 'logs' && IS_PLATFORM && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="default" iconRight={<ChevronDown />}>Templates</Button></DropdownMenuTrigger>@@ -122,12 +205,15 @@ const LogsQueryPanel = ({</DropdownMenu>)}- <DatePickers- to={defaultTo}- from={defaultFrom}- onChange={onDateChange}- helpers={EXPLORER_DATEPICKER_HELPERS}- />+ {dataSource === 'logs' && (+ <DatePickers+ to={defaultTo}+ from={defaultFrom}+ onChange={onDateChange}+ helpers={EXPLORER_DATEPICKER_HELPERS}+ />+ )}+<div className="overflow-hidden"><divclassName={` transition-all duration-300 ${@@ -182,7 +268,8 @@ const LogsQueryPanel = ({asChild // ?: we don't want a button inside a buttontype="default"onClick={() => setShowReference(true)}- icon={<IconBookOpen strokeWidth={1.5} />}+ icon={<BookOpen />}+ className="px-2"><span>Field Reference</span></Button>diff --git a/apps/studio/components/interfaces/Settings/Logs/Warehouse.utils.ts b/apps/studio/components/interfaces/Settings/Logs/Warehouse.utils.tsnew file mode 100644index 00000000000..a891844d514--- /dev/null+++ b/apps/studio/components/interfaces/Settings/Logs/Warehouse.utils.ts@@ -0,0 +1,18 @@+export type WarehouseQueryTemplate = {+ query: string+ name: string+ description: string+}++export function createWarehouseQueryTemplates(+ collections: { name: string }[]+): WarehouseQueryTemplate[] {+ return collections.map((collection) => ({+ query:+ 'select id, timestamp, event_message from `' ++ collection.name ++ '`\nwhere timestamp > timestamp_sub(current_timestamp(), interval 7 day)\norder by timestamp desc limit 10',+ name: `${collection.name}`,+ description: `Select last 10 events from ${collection.name} collection`,+ }))+}diff --git a/apps/studio/components/layouts/LogsLayout/LogsLayout.tsx b/apps/studio/components/layouts/LogsLayout/LogsLayout.tsxindex 3b4995d9abb..e27e9bcc79f 100644--- a/apps/studio/components/layouts/LogsLayout/LogsLayout.tsx+++ b/apps/studio/components/layouts/LogsLayout/LogsLayout.tsx@@ -18,6 +18,8 @@ import { Badge, Menu } from 'ui'import { GenericSkeletonLoader } from 'ui-patterns'import ProjectLayout from '../ProjectLayout/ProjectLayout'import { generateLogsMenu } from './LogsMenu.utils'+import Link from 'next/link'+import { ArrowUpRight } from 'lucide-react'interface LogsLayoutProps {title?: string}@@ -36,7 +38,7 @@ const LogsLayout = ({ title, children }: PropsWithChildren<LogsLayoutProps>) =>const showWarehouse = useFlag('warehouse')const project = useSelectedProject()const { ref } = useParams()- const projectRef = ref || 'default'+ const projectRef = ref as stringconst { data: tenant } = useWarehouseTenantQuery({ projectRef },@@ -46,7 +48,7 @@ const LogsLayout = ({ title, children }: PropsWithChildren<LogsLayoutProps>) =>)const { data: collections, isLoading: collectionsLoading } = useWarehouseCollectionsQuery({- projectRef: !tenant ? 'undefined' : projectRef,+ projectRef,},{ enabled: !!tenant })@@ -66,7 +68,7 @@ const LogsLayout = ({ title, children }: PropsWithChildren<LogsLayoutProps>) =>return (<ProjectLayouttitle={title}- product="Logs"+ product="Logs & Analytics"productMenu={<><ProductMenu@@ -79,13 +81,13 @@ const LogsLayout = ({ title, children }: PropsWithChildren<LogsLayoutProps>) =>/>{showWarehouse && (<>- <div className="h-px w-full bg-overlay"></div>+ <div className="h-px w-full bg-border" /><div className="py-6"><div className="px-6 uppercase font-mono"><Menu.Grouptitle={<div>- Events+ Warehouse Events<Badge variant="warning" size="small" className="ml-2">New</Badge>@@ -96,7 +98,7 @@ const LogsLayout = ({ title, children }: PropsWithChildren<LogsLayoutProps>) =><div className="px-3 flex flex-col"><div className="space-y-1"><CreateWarehouseCollectionModal />- <div className="py-3">+ <div className="pt-3">{collectionsLoading ? (<GenericSkeletonLoader />) : (@@ -108,6 +110,21 @@ const LogsLayout = ({ title, children }: PropsWithChildren<LogsLayoutProps>) =></div></div></div>+ <div className="h-px w-full bg-border" />++ <div className="py-6 px-3">+ <Menu.Group+ title={<span className="uppercase font-mono px-3">Configuration</span>}+ />+ <Link href={`/project/${ref}/settings/warehouse`}>+ <Menu.Item rounded>+ <div className="flex px-3 items-center justify-between">+ <p className="truncate">Warehouse Settings</p>+ <ArrowUpRight strokeWidth={1} className="h-4 w-4" />+ </div>+ </Menu.Item>+ </Link>+ </div></>)}</>diff --git a/apps/studio/components/layouts/LogsLayout/LogsMenu.utils.ts b/apps/studio/components/layouts/LogsLayout/LogsMenu.utils.tsindex c7a83990101..80d84450fb0 100644--- a/apps/studio/components/layouts/LogsLayout/LogsMenu.utils.ts+++ b/apps/studio/components/layouts/LogsLayout/LogsMenu.utils.ts@@ -17,7 +17,7 @@ export const generateLogsMenu = (return [{- title: 'Logs Explorer',+ title: 'Explorer',items: ([{ key: 'explorer', name: 'Query', root: true },@@ -33,7 +33,7 @@ export const generateLogsMenu = (})),},{- title: 'Infrastructure',+ title: 'Infrastructure Logs',items: [{name: 'API Gateway',diff --git a/apps/studio/data/analytics/warehouse-access-tokens-create-mutation.ts b/apps/studio/data/analytics/warehouse-access-tokens-create-mutation.tsindex 5e3a3207361..07966b3f0ef 100644--- a/apps/studio/data/analytics/warehouse-access-tokens-create-mutation.ts+++ b/apps/studio/data/analytics/warehouse-access-tokens-create-mutation.ts@@ -12,12 +12,13 @@ async function createWarehouseAccessToken({ref,description,}: WarehouseAccessTokenCreateVariables) {+ // TODO: remove type cast when fetcher fn params are typedconst { data, error } = await post(`/v1/projects/{ref}/analytics/warehouse/access-tokens`, {params: {path: { ref },},body: { description },- } as any) // TODO: remove type cast when fetcher fn params are typed+ } as any)if (error) handleError(error)diff --git a/apps/studio/data/analytics/warehouse-access-tokens-query.ts b/apps/studio/data/analytics/warehouse-access-tokens-query.tsindex 10866103969..004531f5acc 100644--- a/apps/studio/data/analytics/warehouse-access-tokens-query.ts+++ b/apps/studio/data/analytics/warehouse-access-tokens-query.ts@@ -15,6 +15,7 @@ export async function getWarehouseAccessTokens(throw new Error('projectRef is required')}+ // TODO: Remove typecast when codegen types are fixedconst response = await get(`/v1/projects/{ref}/analytics/warehouse/access-tokens`, {params: { path: { ref: projectRef } },signal,diff --git a/apps/studio/data/analytics/warehouse-collections-query.ts b/apps/studio/data/analytics/warehouse-collections-query.tsindex 282a74e14e5..c78ebd5d778 100644--- a/apps/studio/data/analytics/warehouse-collections-query.ts+++ b/apps/studio/data/analytics/warehouse-collections-query.ts@@ -10,10 +10,11 @@ export async function getWarehouseCollections({ projectRef }: WarehouseCollectionsVariables,signal?: AbortSignal) {- if (!projectRef || projectRef === 'undefined') {+ if (!projectRef) {throw new Error('projectRef is required')}+ // TODO: Remove type cast when codegen types are fixedconst { data, error } = await get(`/v1/projects/{ref}/analytics/warehouse/collections`, {params: { path: { ref: projectRef } },signal,@@ -28,12 +29,12 @@ export type WarehouseCollectionsData = Awaited<ReturnType<typeof getWarehouseColexport const useWarehouseCollectionsQuery = ({ projectRef }: WarehouseCollectionsVariables,- { enabled }: { enabled: boolean }+ { enabled }: { enabled: boolean } = { enabled: true }) =>useQuery(analyticsKeys.warehouseCollections(projectRef),({ signal }) => getWarehouseCollections({ projectRef }, signal),{- enabled: !!projectRef || enabled,+ enabled: enabled && !!projectRef,})diff --git a/apps/studio/data/analytics/warehouse-tenant-query.ts b/apps/studio/data/analytics/warehouse-tenant-query.tsindex 57fb3eebc52..1c983f8346a 100644--- a/apps/studio/data/analytics/warehouse-tenant-query.ts+++ b/apps/studio/data/analytics/warehouse-tenant-query.ts@@ -16,7 +16,6 @@ export async function getWarehouseTenant(if (!projectRef) {throw new Error('projectRef is required')}-const { data, error } = await get(`/v1/projects/{ref}/analytics/warehouse/tenant`, {params: { path: { ref: projectRef } },signal,@@ -42,7 +41,7 @@ export const useWarehouseTenantQuery = <TData = WarehouseTenantData>(analyticsKeys.warehouseTenant(projectRef),({ signal }) => getWarehouseTenant({ projectRef }, signal),{- enabled: enabled && typeof projectRef !== 'undefined',+ enabled: enabled && !!projectRef,staleTime: Infinity,// 2H mins cache timecacheTime: 120 * 60 * 1000,diff --git a/apps/studio/hooks/analytics/useLogsQuery.tsx b/apps/studio/hooks/analytics/useLogsQuery.tsxindex 78c6ef96914..84c599c8f68 100644--- a/apps/studio/hooks/analytics/useLogsQuery.tsx+++ b/apps/studio/hooks/analytics/useLogsQuery.tsx@@ -23,11 +23,13 @@ export interface LogsQueryHook {changeQuery: (newQuery?: string) => voidrunQuery: () => voidsetParams: Dispatch<SetStateAction<LogsEndpointParams>>+ enabled?: boolean}const useLogsQuery = (projectRef: string,- initialParams: Partial<LogsEndpointParams> = {}+ initialParams: Partial<LogsEndpointParams> = {},+ enabled = true): LogsQueryHook => {const defaultHelper = getDefaultHelper(EXPLORER_DATEPICKER_HELPERS)const [params, setParams] = useState<LogsEndpointParams>({@@ -41,7 +43,7 @@ const useLogsQuery = (: defaultHelper.calcTo(),})- const enabled = typeof projectRef !== 'undefined' && Boolean(params.sql)+ const _enabled = enabled && typeof projectRef !== 'undefined' && Boolean(params.sql)const queryParams = genQueryParams(params as any)@@ -58,7 +60,7 @@ const useLogsQuery = (signal,}),{- enabled,+ enabled: _enabled,refetchOnWindowFocus: false,})@@ -74,7 +76,7 @@ const useLogsQuery = (return {params,- isLoading: (enabled && isLoading) || isRefetching,+ isLoading: (_enabled && isLoading) || isRefetching,logData: isResponseOk(data) && data.result ? data.result : [],error,changeQuery,diff --git a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx b/apps/studio/pages/project/[ref]/logs/explorer/index.tsxindex a561618b349..cbb4731a1f6 100644--- a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx+++ b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx@@ -4,47 +4,53 @@ import { useRouter } from 'next/router'import { useEffect, useState } from 'react'import toast from 'react-hot-toast'-import LogTable from 'components/interfaces/Settings/Logs/LogTable'import {- LOGS_LARGE_DATE_RANGE_DAYS_THRESHOLD,- LogsTableName,- TEMPLATES,-} from 'components/interfaces/Settings/Logs/Logs.constants'-import type {- DatePickerToFrom,- LogTemplate,- LogsWarning,-} from 'components/interfaces/Settings/Logs/Logs.types'-import {- maybeShowUpgradePrompt,- useEditorHints,-} from 'components/interfaces/Settings/Logs/Logs.utils'-import LogsQueryPanel from 'components/interfaces/Settings/Logs/LogsQueryPanel'+ Button,+ Form,+ Input,+ Modal,+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from 'ui'+import { IS_PLATFORM } from 'common'+import UpgradePrompt from 'components/interfaces/Settings/Logs/UpgradePrompt'-import LogsLayout from 'components/layouts/LogsLayout/LogsLayout'-import CodeEditor from 'components/ui/CodeEditor/CodeEditor'import LoadingOpacity from 'components/ui/LoadingOpacity'import ShimmerLine from 'components/ui/ShimmerLine'import { useContentInsertMutation } from 'data/content/content-insert-mutation'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'import useLogsQuery from 'hooks/analytics/useLogsQuery'-import { useLocalStorage } from 'hooks/misc/useLocalStorage'-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { useUpgradePrompt } from 'hooks/misc/useUpgradePrompt'import { LOCAL_STORAGE_KEYS } from 'lib/constants'import { uuidv4 } from 'lib/helpers'import type { LogSqlSnippets, NextPageWithLayout } from 'types'+import { useWarehouseCollectionsQuery } from 'data/analytics/warehouse-collections-query'+import LogsQueryPanel, { SourceType } from 'components/interfaces/Settings/Logs/LogsQueryPanel'+import { createWarehouseQueryTemplates } from 'components/interfaces/Settings/Logs/Warehouse.utils'import {- Button,- Form,- Input,- Modal,- ResizableHandle,- ResizablePanel,- ResizablePanelGroup,-} from 'ui'-import { IS_PLATFORM } from 'common'+ maybeShowUpgradePrompt,+ useEditorHints,+} from 'components/interfaces/Settings/Logs/Logs.utils'+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'+import {+ DatePickerToFrom,+ LogTemplate,+ LogsWarning,+} from 'components/interfaces/Settings/Logs/Logs.types'+import { useWarehouseQueryQuery } from 'data/analytics/warehouse-query'+import { useLocalStorage } from '@uidotdev/usehooks'+import {+ LOGS_LARGE_DATE_RANGE_DAYS_THRESHOLD,+ LOGS_TABLES,+ TEMPLATES,+} from 'components/interfaces/Settings/Logs/Logs.constants'+import CodeEditor from 'components/ui/CodeEditor/CodeEditor'+import LogTable from 'components/interfaces/Settings/Logs/LogTable'+import LogsLayout from 'components/layouts/LogsLayout/LogsLayout'+const PLACEHOLDER_WAREHOUSE_QUERY =+ '-- Fetch the last 10 logs in the last 7 days \nselect id, timestamp, event_message from `COLLECTION_NAME` \nwhere timestamp > timestamp_sub(current_timestamp(), interval 7 day) \norder by timestamp desc limit 10'const LOCAL_PLACEHOLDER_QUERY ='select\n timestamp, event_message, metadata\n from edge_logs limit 5'@@ -56,24 +62,66 @@ const PLACEHOLDER_QUERY = IS_PLATFORM ? PLATFORM_PLACEHOLDER_QUERY : LOCAL_PLACEexport const LogsExplorerPage: NextPageWithLayout = () => {useEditorHints()const router = useRouter()- const { ref: projectRef, q, ite, its } = useParams()+ const { ref, q, ite, its } = useParams()+ const projectRef = ref as stringconst organization = useSelectedOrganization()const [editorId, setEditorId] = useState<string>(uuidv4())+ const [warehouseEditorId, setWarehouseEditorId] = useState<string>(uuidv4())const [editorValue, setEditorValue] = useState<string>(PLACEHOLDER_QUERY)+ const [warehouseEditorValue, setWarehouseEditorValue] = useState<string>(+ PLACEHOLDER_WAREHOUSE_QUERY+ )const [saveModalOpen, setSaveModalOpen] = useState<boolean>(false)const [warnings, setWarnings] = useState<LogsWarning[]>([])++ const routerSource = router.query.source as SourceType+ const [sourceType, setSourceType] = useState<SourceType>(routerSource || 'logs')+const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })- const { params, logData, error, isLoading, changeQuery, runQuery, setParams } = useLogsQuery(- projectRef as string,+ const {+ params,+ logData,+ error,+ isLoading: logsLoading,+ changeQuery,+ runQuery,+ setParams,+ } = useLogsQuery(+ projectRef,{iso_timestamp_start: its ? (its as string) : undefined,iso_timestamp_end: ite ? (ite as string) : undefined,+ },+ sourceType === 'logs'+ )++ const {+ refetch: runWarehouseQuery,+ data: warehouseResults,+ isFetching: warehouseFetching,+ error: warehouseError,+ } = useWarehouseQueryQuery(+ { ref: projectRef, sql: warehouseEditorValue },+ {+ enabled: false,})++ useEffect(() => {+ if (warehouseError) {+ toast.error(warehouseError.message)+ }+ }, [warehouseError])++ const isLoading = logsLoading || warehouseFetching+const [recentLogs, setRecentLogs] = useLocalStorage<LogSqlSnippets.Content[]>(`project-content-${projectRef}-recent-log-sql`,[])++ const { data: warehouseCollections } = useWarehouseCollectionsQuery({ projectRef })+const addRecentLogSqlSnippet = (snippet: Partial<LogSqlSnippets.Content>) => {const defaults: LogSqlSnippets.Content = {schema_version: '1',@@ -136,9 +184,49 @@ export const LogsExplorerPage: NextPageWithLayout = () => {const handleRun = (value?: string | React.MouseEvent<HTMLButtonElement>) => {const query = typeof value === 'string' ? value || editorValue : editorValue+if (value && typeof value === 'string') {setEditorValue(value)}++ if (sourceType === 'warehouse') {+ const whQuery = warehouseEditorValue++ if (!warehouseCollections?.length) {+ toast.error('You do not have any collections in your warehouse yet.')+ return+ }++ // Check that a collection name is included in the query+ const collectionNames = warehouseCollections?.map((collection) => collection.name)+ const collectionExists = collectionNames?.find((collectionName) =>+ whQuery.includes(collectionName)+ )++ if (!collectionExists) {+ toast.error('Please specify a collection name in the query')+ return+ }++ // Check that the user is not trying to query logs tables and warehouse collections at the same time+ const logsSources = Object.values(LOGS_TABLES)+ const logsSourceExists = logsSources.find((source) => whQuery.includes(source))++ if (logsSourceExists) {+ toast.error(+ 'Cannot query logs tables from a warehouse query. Please remove the logs table from the query.'+ )+ return+ }++ runWarehouseQuery()+ router.push({+ pathname: router.pathname,+ query: { ...router.query, q: query },+ })+ return+ }+changeQuery(query)runQuery()router.push({@@ -151,10 +239,19 @@ export const LogsExplorerPage: NextPageWithLayout = () => {const handleClear = () => {setEditorValue('')setEditorId(uuidv4())+ setWarehouseEditorId(uuidv4())changeQuery('')}- const handleInsertSource = (source: LogsTableName) => {+ const handleInsertSource = (source: string) => {+ if (sourceType === 'warehouse') {+ //TODO: Only one collection can be queried at a time, we need to replace the current collection from the query for the new one++ setWarehouseEditorId(uuidv4())++ return+ }+setEditorValue((prev) => {const index = prev.indexOf('from')if (index === -1) return `${prev}${source}`@@ -214,20 +311,44 @@ export const LogsExplorerPage: NextPageWithLayout = () => {onClear={handleClear}hasEditorValue={Boolean(editorValue)}templates={TEMPLATES.filter((template) => template.mode === 'custom')}+ warehouseCollections={warehouseCollections || []}onSelectTemplate={onSelectTemplate}+ warehouseTemplates={createWarehouseQueryTemplates(warehouseCollections || [])}+ onSelectWarehouseTemplate={(template) => {+ setWarehouseEditorValue(template.query)+ setWarehouseEditorId(uuidv4())+ }}onSave={handleOnSave}isLoading={isLoading}warnings={warnings}+ dataSource={sourceType}+ onDataSourceChange={(srcType) => {+ setSourceType(srcType)+ router.push({+ pathname: router.pathname,+ query: { ...router.query, source: srcType },+ })+ }}/><ShimmerLine active={isLoading} />- <CodeEditor- id={editorId}- language="pgsql"- defaultValue={editorValue}- onInputChange={(v) => setEditorValue(v || '')}- onInputRun={handleRun}- />+ {sourceType === 'warehouse' ? (+ <CodeEditor+ id={warehouseEditorId}+ language="pgsql" // its bq sql but monaco doesn't have a language for it+ defaultValue={warehouseEditorValue}+ onInputChange={(v) => setWarehouseEditorValue(v || '')}+ onInputRun={handleRun}+ />+ ) : (+ <CodeEditor+ id={editorId}+ language="pgsql"+ defaultValue={editorValue}+ onInputChange={(v) => setEditorValue(v || '')}+ onInputRun={handleRun}+ />+ )}</ResizablePanel><ResizableHandle withHandle /><ResizablePanel collapsible minSize={5} className="flex flex-col flex-grow">@@ -238,9 +359,9 @@ export const LogsExplorerPage: NextPageWithLayout = () => {onSave={handleOnSave}hasEditorValue={Boolean(editorValue)}params={params}- data={logData}+ data={sourceType === 'warehouse' ? warehouseResults?.result : logData}error={error}- projectRef={projectRef as string}+ projectRef={projectRef}/></LoadingOpacity><div className="flex flex-row justify-end mt-2">diff --git a/apps/studio/tests/pages/projects/LogsQueryPanel.test.tsx b/apps/studio/tests/pages/projects/LogsQueryPanel.test.tsxindex 40ba4b7bb32..60c4e48994d 100644--- a/apps/studio/tests/pages/projects/LogsQueryPanel.test.tsx+++ b/apps/studio/tests/pages/projects/LogsQueryPanel.test.tsx@@ -18,6 +18,12 @@ test('run and clear', async () => {warnings={[]}onClear={mockClear}hasEditorValue+ warehouseCollections={[]}+ dataSource="logs"+ onDataSourceChange={() => {}}+ templates={[]}+ warehouseTemplates={[]}+ onSelectWarehouseTemplate={() => {}}/>)await expect(screen.findByPlaceholderText(/Search/)).rejects.toThrow()diff --git a/package.json b/package.jsonindex 7e5fb60167b..023c32b5c47 100644--- a/package.json+++ b/package.json@@ -33,7 +33,8 @@"test:playwright": "npm --prefix playwright-tests run test","perf:kong": "ab -t 5 -c 20 -T application/json http://localhost:8000/","perf:meta": "ab -t 5 -c 20 -T application/json http://localhost:5555/tables",- "generate:types": "supabase gen types typescript --local > ./supabase/functions/common/database-types.ts"+ "generate:types": "supabase gen types typescript --local > ./supabase/functions/common/database-types.ts",+ "api:codegen": "cd packages/api-types && npm run codegen"},"devDependencies": {"eslint": "^8.57.0",