The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Midway implementing sort filter through URL state
Joshen Limd9600377080a
diff --git a/studio/components/grid/SupabaseGrid.tsx b/studio/components/grid/SupabaseGrid.tsxindex 6a09b66a572..b580b32b07b 100644--- a/studio/components/grid/SupabaseGrid.tsx+++ b/studio/components/grid/SupabaseGrid.tsx@@ -3,18 +3,21 @@ import { createPortal } from 'react-dom'import { useMonaco } from '@monaco-editor/react'import { DndProvider } from 'react-dnd'import { HTML5Backend } from 'react-dnd-html5-backend'-import { Dictionary, SupabaseGridProps, SupabaseGridRef } from './types'import { DataGridHandle } from '@supabase/react-data-grid'-import { RowContextMenu } from './components/menu'++import { Dictionary, SupabaseGridProps, SupabaseGridRef } from './types'import { StoreProvider, useDispatch, useTrackedState } from './store'import { fetchCount, fetchPage, refreshPageDebounced } from './utils'import { REFRESH_PAGE_IMMEDIATELY, TOTAL_ROWS_RESET } from './constants'-import { Grid } from './components/grid'import { Shortcuts } from './components/common'+import { Grid } from './components/grid'import Header from './components/header'import Footer from './components/footer'+import { RowContextMenu } from './components/menu'import { cleanupProps, initTable, saveStorageDebounced } from './SupabaseGrid.utils'+import { useUrlState } from 'hooks'+/*** Supabase Grid.*@@ -60,6 +63,10 @@ const SupabaseGridLayout = forwardRef<SupabaseGridRef, SupabaseGridProps>((propsconst gridRef = useRef<DataGridHandle>(null)const [mounted, setMount] = useState(false)+ const [{ sort: sorts, filter: filters }, setParams] = useUrlState({+ arrayKeys: ['sort', 'filter'],+ })+useImperativeHandle(ref, () => ({rowAdded(row: Dictionary<any>) {dispatch({@@ -79,6 +86,16 @@ const SupabaseGridLayout = forwardRef<SupabaseGridRef, SupabaseGridProps>((propsif (!mounted) setMount(true)}, [])+ // [Joshen] This where we refetch the data is say a sort or filter was updated+ useEffect(() => {+ if (state.refreshPageFlag == REFRESH_PAGE_IMMEDIATELY) {+ console.log('Refresh page')+ fetchPage(state, dispatch)+ } else if (state.refreshPageFlag != 0) {+ refreshPageDebounced(state, dispatch)+ }+ }, [state.refreshPageFlag])+useEffect(() => {if (state.isInitialComplete && storageRef && state.table) {saveStorageDebounced(state, storageRef)@@ -92,14 +109,6 @@ const SupabaseGridLayout = forwardRef<SupabaseGridRef, SupabaseGridProps>((propsstorageRef,])- useEffect(() => {- if (state.refreshPageFlag == REFRESH_PAGE_IMMEDIATELY) {- fetchPage(state, dispatch)- } else if (state.refreshPageFlag != 0) {- refreshPageDebounced(state, dispatch)- }- }, [state.refreshPageFlag])-useEffect(() => {if (state.totalRows === TOTAL_ROWS_RESET) {fetchCount(state, dispatch)@@ -130,7 +139,7 @@ const SupabaseGridLayout = forwardRef<SupabaseGridRef, SupabaseGridProps>((props(typeof props.table != 'string' &&JSON.stringify(props.table) !== JSON.stringify(state.table))) {- initTable(props, state, dispatch)+ initTable(props, state, dispatch, sorts as string[], filters as string[])}}, [state.metaService, state.table, props.table, props.schema])diff --git a/studio/components/grid/SupabaseGrid.utils.ts b/studio/components/grid/SupabaseGrid.utils.tsindex d3f65bf7833..f371b31c556 100644--- a/studio/components/grid/SupabaseGrid.utils.ts+++ b/studio/components/grid/SupabaseGrid.utils.ts@@ -1,12 +1,14 @@-import AwesomeDebouncePromise from 'awesome-debounce-promise';-import { STORAGE_KEY_PREFIX } from './constants';-import { IMetaService } from './services/meta';-import { InitialStateType } from './store/reducers';-import { Dictionary, SupabaseGridProps, SupaColumn, SupaTable } from './types';-import { getGridColumns } from './utils/gridColumns';+import AwesomeDebouncePromise from 'awesome-debounce-promise'+import { uuidv4 } from 'lib/helpers'+import { STORAGE_KEY_PREFIX } from './constants'+import { IMetaService } from './services/meta'+import { InitialStateType } from './store/reducers'+import { Dictionary, SupabaseGridProps, SupaColumn, SupaTable } from './types'+import { getGridColumns } from './utils/gridColumns'+import { FilterOperatorOptions } from './components/header/filter'export function defaultErrorHandler(error: any) {- console.log('Supabase grid error: ', error);+ console.log('Supabase grid error: ', error)}/**@@ -14,7 +16,7 @@ export function defaultErrorHandler(error: any) {* to prevent rare-case bugs with the UI*/export function cleanupProps(props: SupabaseGridProps) {- const { editable } = props;+ const { editable } = propsif (!editable) {return {...props,@@ -23,29 +25,64 @@ export function cleanupProps(props: SupabaseGridProps) {onEditColumn: undefined,onDeleteColumn: undefined,onEditRow: undefined,- };+ }} else {- return props;+ return props}}export function initTable(props: SupabaseGridProps,state: InitialStateType,- dispatch: (value: any) => void+ dispatch: (value: any) => void,+ sort?: string[], // Come directly from URL param+ filter?: string[] // Come directly from URL param) {function onInitTable(table: SupaTable, props: SupabaseGridProps) {const gridColumns = getGridColumns(table, {editable: props.editable,defaultWidth: props.gridProps?.defaultColumnWidth,onAddColumn: props.editable ? props.onAddColumn : undefined,- });-- let savedState;+ })++ // [JOSHEN WE LEFT OFF HERE TO FIGURE OUT HOW TO REPLACE EXISTING FILTER AND SORT]+ const sorts = Array.isArray(sort)+ ? sort+ .map((s) => {+ const [column, order] = s.split(':')+ // Reject any possible malformed sort param+ if (!column || !order) return undefined+ else return { column, ascending: order === 'asc' }+ })+ .filter((s) => s !== undefined)+ : []++ const filters = Array.isArray(filter)+ ? filter+ .map((f) => {+ const [column, operatorAbbrev, value] = f.split(':')+ const operator = FilterOperatorOptions.find(+ (option) => option.abbrev === operatorAbbrev+ )+ // Reject any possible malformed filter param+ if (!column || !operatorAbbrev || !operator || !value) return undefined+ else return { id: uuidv4(), column, operator: operator.value, value }+ })+ .filter((f) => f !== undefined)+ : []++ let savedStateif (props.storageRef) {- savedState = onLoadStorage(props.storageRef, table.name, table.schema);+ savedState = onLoadStorage(props.storageRef, table.name, table.schema)}+ console.log('initTable', savedState, {+ sort,+ sorts,+ filter,+ filters,+ })+dispatch({type: 'INIT_TABLE',payload: {@@ -57,24 +94,24 @@ export function initTable(onSqlQuery: props.onSqlQuery,onError: props.onError ?? defaultErrorHandler,},- });+ })}if (typeof props.table === 'string') {const fetchMethod = props.editable? fetchEditableInfo(state.metaService!, props.table, props.schema)- : fetchReadOnlyInfo(state.metaService!, props.table, props.schema);+ : fetchReadOnlyInfo(state.metaService!, props.table, props.schema)fetchMethod.then((res) => {- if (res) onInitTable(res, props);+ if (res) onInitTable(res, props)else {if (props.onError) {- props.onError({ message: 'fetch table info failed' });+ props.onError({ message: 'fetch table info failed' })}}- });+ })} else {- onInitTable(props.table, props);+ onInitTable(props.table, props)}}@@ -83,10 +120,10 @@ async function fetchEditableInfo(tableName: string,schema?: string): Promise<SupaTable | null> {- const resTable = await service.fetchInfo(tableName, schema);- const resColumns = await service.fetchColumns(tableName, schema);- const resPrimaryKeys = await service.fetchPrimaryKeys(tableName, schema);- const resRelationships = await service.fetchRelationships(tableName, schema);+ const resTable = await service.fetchInfo(tableName, schema)+ const resColumns = await service.fetchColumns(tableName, schema)+ const resPrimaryKeys = await service.fetchPrimaryKeys(tableName, schema)+ const resRelationships = await service.fetchRelationships(tableName, schema)if (resTable.data &&resColumns.data &&@@ -99,10 +136,10 @@ async function fetchEditableInfo(columns: resColumns.data,primaryKeys: resPrimaryKeys.data,relationships: resRelationships.data,- });- return supaTable;+ })+ return supaTable}- return null;+ return null}async function fetchReadOnlyInfo(@@ -110,7 +147,7 @@ async function fetchReadOnlyInfo(name: string,schema?: string): Promise<SupaTable | null> {- const { data } = await service.fetchColumns(name, schema);+ const { data } = await service.fetchColumns(name, schema)if (data) {const supaColumns: SupaColumn[] = data.map((x, index) => {@@ -120,25 +157,25 @@ async function fetchReadOnlyInfo(format: x.format,position: index,isUpdatable: false,- };- });+ }+ })return {name: name,schema: schema,columns: supaColumns,- };+ }}- return null;+ return null}export function parseSupaTable(data: {- table: Dictionary<any>;- columns: Dictionary<any>[];- primaryKeys: Dictionary<any>[];- relationships: Dictionary<any>[];+ table: Dictionary<any>+ columns: Dictionary<any>[]+ primaryKeys: Dictionary<any>[]+ relationships: Dictionary<any>[]}): SupaTable {- const { table, columns, primaryKeys, relationships } = data;+ const { table, columns, primaryKeys, relationships } = dataconst supaColumns: SupaColumn[] = columns.map((x) => {const temp = {position: x.ordinal_position,@@ -156,68 +193,63 @@ export function parseSupaTable(data: {targetTableSchema: null,targetTableName: null,targetColumnName: null,- };- const primaryKey = primaryKeys.find((pk) => pk.name == x.name);- temp.isPrimaryKey = !!primaryKey;+ }+ const primaryKey = primaryKeys.find((pk) => pk.name == x.name)+ temp.isPrimaryKey = !!primaryKeyconst relationship = relationships.find((r) => {- return r.source_column_name == x.name;- });+ return r.source_column_name == x.name+ })if (relationship) {- temp.targetTableSchema = relationship.target_table_schema;- temp.targetTableName = relationship.target_table_name;- temp.targetColumnName = relationship.target_column_name;+ temp.targetTableSchema = relationship.target_table_schema+ temp.targetTableName = relationship.target_table_name+ temp.targetColumnName = relationship.target_column_name}- return temp;- });+ return temp+ })return {name: table.name,comment: table.comment,schema: table.schema,columns: supaColumns,- };+ }}-export function onLoadStorage(- storageRef: string,- tableName: string,- schema?: string | null-) {- const storageKey = getStorageKey(STORAGE_KEY_PREFIX, storageRef);- const jsonStr = localStorage.getItem(storageKey);- if (!jsonStr) return;- const json = JSON.parse(jsonStr);- const tableKey =- !schema || schema == 'public' ? tableName : `${schema}.${tableName}`;- return json[tableKey];+export function onLoadStorage(storageRef: string, tableName: string, schema?: string | null) {+ const storageKey = getStorageKey(STORAGE_KEY_PREFIX, storageRef)+ const jsonStr = localStorage.getItem(storageKey)+ if (!jsonStr) return+ const json = JSON.parse(jsonStr)+ const tableKey = !schema || schema == 'public' ? tableName : `${schema}.${tableName}`+ return json[tableKey]}-export const saveStorageDebounced = AwesomeDebouncePromise(saveStorage, 500);+export const saveStorageDebounced = AwesomeDebouncePromise(saveStorage, 500)function saveStorage(state: InitialStateType, storageRef: string) {- if (!state.table) return;+ if (!state.table) returnconst config = {gridColumns: state.gridColumns,sorts: state.sorts,filters: state.filters,- };- const storageKey = getStorageKey(STORAGE_KEY_PREFIX, storageRef);- const savedStr = localStorage.getItem(storageKey);+ }+ const storageKey = getStorageKey(STORAGE_KEY_PREFIX, storageRef)+ const savedStr = localStorage.getItem(storageKey)- let savedJson;- const { name, schema } = state.table;- const tableKey = !schema || schema == 'public' ? name : `${schema}.${name}`;+ let savedJson+ const { name, schema } = state.table+ const tableKey = !schema || schema == 'public' ? name : `${schema}.${name}`if (savedStr) {- savedJson = JSON.parse(savedStr);- savedJson = { ...savedJson, [tableKey]: config };+ savedJson = JSON.parse(savedStr)+ savedJson = { ...savedJson, [tableKey]: config }} else {- savedJson = { [tableKey]: config };+ savedJson = { [tableKey]: config }}- localStorage.setItem(storageKey, JSON.stringify(savedJson));+ localStorage.setItem(storageKey, JSON.stringify(savedJson))}function getStorageKey(prefix: string, ref: string) {- return `${prefix}_${ref}`;+ return `${prefix}_${ref}`}diff --git a/studio/components/grid/components/header/Header.tsx b/studio/components/grid/components/header/Header.tsxindex 502a6b2c2d7..7c98dc217a3 100644--- a/studio/components/grid/components/header/Header.tsx+++ b/studio/components/grid/components/header/Header.tsx@@ -43,11 +43,7 @@ const DefaultHeader: React.FC<DefaultHeaderProps> = ({ onAddColumn, onAddRow })const renderNewColumn = (onAddColumn?: () => void) => {if (!onAddColumn) return nullreturn (- <Button- type="text"- onClick={onAddColumn}- // style={{ padding: '4px 8px' }}- >+ <Button type="text" onClick={onAddColumn}>New Column</Button>)@@ -56,12 +52,7 @@ const DefaultHeader: React.FC<DefaultHeaderProps> = ({ onAddColumn, onAddRow })const renderAddRow = (onAddRow?: () => void) => {if (!onAddRow) return nullreturn (- <Button- size="tiny"- // style={{ padding: '4px 8px' }}- icon={<IconPlus size={14} strokeWidth={2} />}- onClick={onAddRow}- >+ <Button size="tiny" icon={<IconPlus size={14} strokeWidth={2} />} onClick={onAddRow}>Insert row</Button>)diff --git a/studio/components/grid/components/header/filter/Filter.constants.ts b/studio/components/grid/components/header/filter/Filter.constants.tsindex 7e651635fc9..7a31a236f36 100644--- a/studio/components/grid/components/header/filter/Filter.constants.ts+++ b/studio/components/grid/components/header/filter/Filter.constants.ts@@ -1,16 +1,17 @@export const FilterOperatorOptions = [- { value: '=', label: 'equals', preLabel: '[ = ]' },- { value: '<>', label: 'not equal', preLabel: '[ <> ]' },- { value: '>', label: 'greater than', preLabel: '[ > ]' },- { value: '<', label: 'less than', preLabel: '[ < ]' },- { value: '>=', label: 'greater than or equal', preLabel: '[ >= ]' },- { value: '<=', label: 'less than or equal', preLabel: '[ <= ]' },- { value: '~~', label: 'like operator', preLabel: '[ ~~ ]' },- { value: '~~*', label: 'ilike operator', preLabel: '[ ~~* ]' },- { value: 'in', label: 'one of a list of values', preLabel: '[ in ]' },+ { value: '=', label: 'equals', preLabel: '[ = ]', abbrev: 'eq' },+ { value: '<>', label: 'not equal', preLabel: '[ <> ]', abbrev: 'neq' },+ { value: '>', label: 'greater than', preLabel: '[ > ]', abbrev: 'gt' },+ { value: '<', label: 'less than', preLabel: '[ < ]', abbrev: 'lt' },+ { value: '>=', label: 'greater than or equal', preLabel: '[ >= ]', abbrev: 'gte' },+ { value: '<=', label: 'less than or equal', preLabel: '[ <= ]', abbrev: 'lte' },+ { value: '~~', label: 'like operator', preLabel: '[ ~~ ]', abbrev: 'like' },+ { value: '~~*', label: 'ilike operator', preLabel: '[ ~~* ]', abbrev: 'ilike' },+ { value: 'in', label: 'one of a list of values', preLabel: '[ in ]', abbrev: 'in' },{value: 'is',label: 'checking for (null,not null,true,false)',preLabel: '[ is ]',+ abbrev: 'is',},-];+]diff --git a/studio/components/grid/components/header/sort/SortPopover.tsx b/studio/components/grid/components/header/sort/SortPopover.tsxindex d2d09548afe..58697047dbe 100644--- a/studio/components/grid/components/header/sort/SortPopover.tsx+++ b/studio/components/grid/components/header/sort/SortPopover.tsx@@ -21,7 +21,6 @@ const SortPopover: FC = () => {<IconList strokeWidth={1.5} /></div>}- // style={{ padding: '4px 8px' }}>{btnText}</Button>diff --git a/studio/components/grid/store/reducers/filter.ts b/studio/components/grid/store/reducers/filter.tsindex c9f051326b3..4897b2063bf 100644--- a/studio/components/grid/store/reducers/filter.ts+++ b/studio/components/grid/store/reducers/filter.ts@@ -35,6 +35,10 @@ type FILTER_ACTIONTYPE =const FilterReducer = (state: FilterInitialState, action: FILTER_ACTIONTYPE) => {switch (action.type) {case 'INIT_TABLE': {+ console.log('Filter Reducer INIT_TABLE', {+ savedState: action.payload.savedState,+ filters: getInitialFilters(action.payload.table, action.payload.savedState),+ })return {...state,filters: getInitialFilters(action.payload.table, action.payload.savedState),diff --git a/studio/components/grid/store/reducers/sort.ts b/studio/components/grid/store/reducers/sort.tsindex dd7abce1cfe..fcbafbaf326 100644--- a/studio/components/grid/store/reducers/sort.ts+++ b/studio/components/grid/store/reducers/sort.ts@@ -1,67 +1,62 @@-import update from 'immutability-helper';-import { Sort } from '../../types';-import { getInitialSorts } from '../../utils';-import { INIT_ACTIONTYPE } from './base';+import update from 'immutability-helper'+import { Sort } from '../../types'+import { getInitialSorts } from '../../utils'+import { INIT_ACTIONTYPE } from './base'export interface SortInitialState {- sorts: Sort[];+ sorts: Sort[]}-export const sortInitialState: SortInitialState = { sorts: [] };+export const sortInitialState: SortInitialState = { sorts: [] }type SORT_ACTIONTYPE =| INIT_ACTIONTYPE- | {- type: 'SET_SORTS';- payload: Sort[];- }| { type: 'ADD_SORT'; payload: Sort }| { type: 'REMOVE_SORT'; payload: { column: string } }| {- type: 'UPDATE_SORT';- payload: Sort;+ type: 'UPDATE_SORT'+ payload: Sort}| {- type: 'MOVE_SORT';- payload: { fromIndex: number; toIndex: number };- };+ type: 'MOVE_SORT'+ payload: { fromIndex: number; toIndex: number }+ }const SortReducer = (state: SortInitialState, action: SORT_ACTIONTYPE) => {switch (action.type) {case 'INIT_TABLE': {+ console.log(+ 'Sort Reducer INIT_TABLE',+ getInitialSorts(action.payload.table, action.payload.savedState)+ )return {...state,sorts: getInitialSorts(action.payload.table, action.payload.savedState),- };+ }}- case 'SET_SORTS':- return {- ...state,- sorts: action.payload,- };case 'ADD_SORT':return {...state,sorts: update(state.sorts, { $push: [action.payload] }),refreshPageFlag: Date.now(),- };+ }case 'REMOVE_SORT':return {...state,sorts: state.sorts.filter((x) => x.column !== action.payload.column),refreshPageFlag: Date.now(),- };+ }case 'UPDATE_SORT':return {...state,sorts: state.sorts.map((x) => {- if (x.column == action.payload.column) return action.payload;- return x;+ if (x.column == action.payload.column) return action.payload+ return x}),refreshPageFlag: Date.now(),- };+ }case 'MOVE_SORT': {- const moveItem = state.sorts[action.payload.fromIndex];+ const moveItem = state.sorts[action.payload.fromIndex]return {...state,sorts: update(state.sorts, {@@ -71,11 +66,11 @@ const SortReducer = (state: SortInitialState, action: SORT_ACTIONTYPE) => {],}),refreshPageFlag: Date.now(),- };+ }}default:- return state;+ return state}-};+}-export default SortReducer;+export default SortReducerdiff --git a/studio/components/grid/utils/row.ts b/studio/components/grid/utils/row.tsindex b0c45f8f270..69029edba02 100644--- a/studio/components/grid/utils/row.ts+++ b/studio/components/grid/utils/row.ts@@ -17,6 +17,10 @@ export async function fetchCount(state: InitialStateType, dispatch: (value: unknexport async function fetchPage(state: InitialStateType, dispatch: (value: unknown) => void) {if (!state.rowService) returndispatch({ type: 'SET_IS_LOADING', payload: { isLoading: true } })+ console.log('Fetch page', {+ filters: state.filters,+ sorts: state.sorts,+ })const { data, error } = await state.rowService.fetchPage(state.page,state.rowsPerPage,diff --git a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsxindex 085a3fbe76d..42f6631f723 100644--- a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx+++ b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx@@ -10,7 +10,6 @@ import NotFoundState from './NotFoundState'import GridHeaderActions from './GridHeaderActions'import SidePanelEditor from './SidePanelEditor'import { SchemaView } from 'components/layouts/TableEditorLayout/TableEditorLayout.types'-import { SidePanel } from '@supabase/ui'interface Props {/** Theme for the editor */@@ -102,6 +101,7 @@ const TableGridEditor: FC<Props> = ({// For some reason, selectedTable here is stale after adding a table// temporary workaround is to list grab the selected table againconst tables: PostgresTable[] = meta.tables.list()+ // @ts-ignoreconst table = tables.find((table) => table.id === Number(tableId))const column = find(table!.columns, { name }) as PostgresColumnif (column) {@@ -139,7 +139,10 @@ const TableGridEditor: FC<Props> = ({schema={selectedTable.schema}table={gridTable}headerActions={- !isViewSelected && selectedTable.schema === 'public' && <GridHeaderActions table={selectedTable as PostgresTable} />+ !isViewSelected &&+ selectedTable.schema === 'public' && (+ <GridHeaderActions table={selectedTable as PostgresTable} />+ )}onAddColumn={onAddColumn}onEditColumn={onSelectEditColumn}diff --git a/studio/hooks/ui/useUrlState.ts b/studio/hooks/ui/useUrlState.tsindex 3d22de107e2..0cdfb9858af 100644--- a/studio/hooks/ui/useUrlState.ts+++ b/studio/hooks/ui/useUrlState.ts@@ -21,7 +21,6 @@ export function useUrlState({const params: UrlStateParams = Object.fromEntries(Object.entries(router.query).map(([key, value]) => {if (arrayKeysSet.has(key)) {- console.log(value)return Array.isArray(value) ? [key, value] : [key, [value]]}@@ -50,5 +49,5 @@ export function useUrlState({[router, params, replace])- return [params, setParams]+ return [params, setParams] as const}