import { Check, ChevronsUpDown, Loader2 } from 'lucide-react' import Link from 'next/link' import { Fragment, useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { Button, cn, Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, Popover, PopoverContent, PopoverTrigger, Select, SelectContent, SelectItem, SelectSeparator, SelectTrigger, SelectValue, SidePanel, } from 'ui' import { Admonition } from 'ui-patterns' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' import { MultiSelector, MultiSelectorContent, MultiSelectorItem, MultiSelectorList, MultiSelectorTrigger, } from 'ui-patterns/multi-select' import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader' import { INDEX_TYPES } from './Indexes.constants' import CodeEditor from '@/components/ui/CodeEditor/CodeEditor' import { DocsButton } from '@/components/ui/DocsButton' import { useDatabaseIndexCreateMutation } from '@/data/database-indexes/index-create-mutation' import { useSchemasQuery } from '@/data/database/schemas-query' import { useTableColumnsQuery } from '@/data/database/table-columns-query' import { useEntityTypesQuery } from '@/data/entity-types/entity-types-infinite-query' import { useIsOrioleDb, useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject' import { DOCS_URL } from '@/lib/constants' interface CreateIndexSidePanelProps { visible: boolean onClose: () => void } export const CreateIndexSidePanel = ({ visible, onClose }: CreateIndexSidePanelProps) => { const { data: project } = useSelectedProjectQuery() const isOrioleDb = useIsOrioleDb() const [selectedSchema, setSelectedSchema] = useState('public') const [selectedEntity, setSelectedEntity] = useState(undefined) const [selectedColumns, setSelectedColumns] = useState([]) const [selectedIndexType, setSelectedIndexType] = useState(INDEX_TYPES[0].value) const [schemaDropdownOpen, setSchemaDropdownOpen] = useState(false) const [tableDropdownOpen, setTableDropdownOpen] = useState(false) const [schemaSearchTerm, setSchemaSearchTerm] = useState('') const [searchTerm, setSearchTerm] = useState('') const { data: schemas } = useSchemasQuery({ projectRef: project?.ref, connectionString: project?.connectionString, }) const { data: entities, isPending: isLoadingEntities } = useEntityTypesQuery({ schemas: [selectedSchema], sort: 'alphabetical', search: searchTerm, projectRef: project?.ref, connectionString: project?.connectionString, }) const { data: tableColumns, isPending: isLoadingTableColumns, isSuccess: isSuccessTableColumns, } = useTableColumnsQuery({ schema: selectedSchema, table: selectedEntity, projectRef: project?.ref, connectionString: project?.connectionString, }) const { mutate: createIndex, isPending: isExecuting } = useDatabaseIndexCreateMutation({ onSuccess: () => { onClose() toast.success(`Successfully created index`) }, }) const entityTypes = useMemo( () => entities?.pages.flatMap((page) => page.data.entities) || [], [entities?.pages] ) function handleSearchChange(value: string) { setSearchTerm(value) } function handleSchemaSelect(schema: string) { setSelectedSchema(schema) setSearchTerm('') setSchemaSearchTerm('') setSchemaDropdownOpen(false) } const columns = tableColumns?.[0]?.columns ?? [] const columnOptions = columns .filter((column): column is NonNullable => column !== null) .map((column) => ({ id: column.attname, value: column.attname, name: column.attname, disabled: false, })) const generatedSQL = ` CREATE INDEX ON "${selectedSchema}"."${selectedEntity}" USING ${selectedIndexType} (${selectedColumns .map((column) => `"${column}"`) .join(', ')}); `.trim() const onSaveIndex = () => { if (!project) return console.error('Project is required') if (!selectedEntity) return console.error('Entity is required') createIndex({ projectRef: project.ref, connectionString: project.connectionString, payload: { schema: selectedSchema, entity: selectedEntity, type: selectedIndexType, columns: selectedColumns, }, }) } useEffect(() => { if (visible) { setSelectedSchema('public') setSelectedEntity('') setSelectedColumns([]) setSelectedIndexType(INDEX_TYPES[0].value) setSchemaSearchTerm('') setSearchTerm('') } }, [visible]) useEffect(() => { setSelectedEntity('') setSelectedColumns([]) setSelectedIndexType(INDEX_TYPES[0].value) setSearchTerm('') }, [selectedSchema]) useEffect(() => { setSelectedColumns([]) setSelectedIndexType(INDEX_TYPES[0].value) }, [selectedEntity]) useEffect(() => { if (!schemaDropdownOpen) setSchemaSearchTerm('') }, [schemaDropdownOpen]) const isSelectEntityDisabled = entityTypes.length === 0 && searchTerm.trim().length === 0 return ( onSaveIndex()} loading={isExecuting} confirmText="Create index" >
7 && 'max-h-[210px]! overflow-y-auto')} onWheel={(event) => event.stopPropagation()} > No schemas found {(schemas ?? []).map((schema) => ( { handleSchemaSelect(schema.name) }} onClick={() => { handleSchemaSelect(schema.name) }} > {schema.name} {selectedSchema === schema.name && ( )} ))} {/* [Terry] shouldFilter context: https://github.com/pacocoursey/cmdk/issues/267#issuecomment-2252717107 */} 7 && 'max-h-[210px]! overflow-y-auto')} onWheel={(event) => event.stopPropagation()} > {isLoadingEntities ? (
Loading...
) : ( 'No tables found' )}
{entityTypes.map((entity) => ( { setSelectedEntity(entity.name) setTableDropdownOpen(false) }} onClick={() => { setSelectedEntity(entity.name) setTableDropdownOpen(false) }} > {entity.name} {selectedEntity === entity.name && ( )} ))}
{selectedEntity && ( {isLoadingTableColumns && } {isSuccessTableColumns && ( {columnOptions.map((option) => ( {option.name} ))} )} )}
{selectedColumns.length > 0 && ( <> {isOrioleDb && ( {/* [Joshen Oriole] Hook up proper docs URL */} )}

Preview of SQL statement

)}
) }