Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor(databases): share the editor through a host API (#7709)

Wolf Mermelstein3c4404f18bb6
diff --git a/.agents/skills/database-core/SKILL.md b/.agents/skills/database-core/SKILL.md
index 25599b59be..6fee319198 100644
--- a/.agents/skills/database-core/SKILL.md
+++ b/.agents/skills/database-core/SKILL.md
@@ -1,6 +1,6 @@
---
name: database-core
-description: Use when building a feature on reusable database storage or UI, such as CRM, or deciding whether it needs a Macro database entity. Covers storage and UI entry points, ownership, authorization, and the _entities naming convention.
+description: Use when building a feature on reusable database storage or UI, such as CRM, or deciding whether it needs a Macro database entity. Covers shared storage, a host-independent database UI and API contract, ownership, authorization, and the _entities naming convention.
---
# Database core
@@ -35,14 +35,91 @@ identity and lifecycle and references any reusable resource it uses. The naming
convention starts with databases; existing unrelated entity tables keep their names.
Rust type names stay singular.
-## Reuse the records UI
+## Build one database UI for multiple hosts
-Use [DatabaseRecordsView](../../../apps/web/src/features/block-database/views/database-records-view.tsx)
-with a host-provided `DatabaseRowsSource`, query/layout state, and action callbacks.
-It needs no Macro database entity, saved-view metadata, or block context. Omit
-schema actions when a feature allows record editing with a fixed schema.
-The Macro app's `DatabaseGrid` supplies its API, Soup, and saved-view adapters;
-other domains supply their own authorized reads, writes, and change notifications.
+The Macro database app, CRM pipelines, and other consumers are hosts of the same
+editor. A host supplies an authorized API and its capabilities; it should not
+reimplement database editing, pagination, option creation, or refresh behavior.
+Follow the [frontend architecture](../../../docs/FRONTEND_FEATURE_ARCHITECTURE.md).
+
+### Target ownership
+
+Use `apps/web/src/features/database/` for reusable database behavior and UI. Keep `features/block-database/` as the Macro app composition and
+`features/crm/` as the CRM composition. Move code with its dependencies and migrate
+its callers; a directory rename alone does not establish the boundary.
+
+- `core/` owns editor models, operations, errors, and capability vocabulary.
+- `queries/` adapts injected transport into schema, row and view sources, and owns
+ pagination, cache updates, conflict handling, and refresh after mutations.
+- `primitives/` owns shared editing, selection, draft, and layout behavior.
+- `components/` and `views/` render the grid, board, record panel, column controls,
+ filters, sorting, and view controls using supplied sources and actions.
+- Host entry points wire identity, permissions, concrete clients, navigation,
+ sharing, entity pickers, and presence. Shared components do not import these
+ entry points, app singletons, Soup, or legacy block context.
+
+### API contract and shared controller
+
+Define a feature-owned, typed contract for reading schema, reading rows for a
+query (including pagination and table versions), and applying an operation batch.
+Preserve the existing `DatabaseOp` / `OpBatch` semantics instead of defining a
+CRM-specific mutation language. Keep generated HTTP DTOs and route choices in
+transport adapters; shared rendering consumes feature models.
+
+Build the rows source and schema/view actions once from this contract. A Macro
+adapter can call the database routes and a pipeline adapter can call CRM routes;
+neither should duplicate cell-to-op conversion, option-label handling, batch
+submission, or committed-write refresh semantics. Keep transport errors distinct
+from a refresh failure after a successful commit so the UI does not retry a
+committed insert.
+
+Reads must implement the requested filtering, sorting, cursor, and version
+semantics. Do not silently replace a server query with sorting one loaded page.
+SQL reads are an optional adapter capability, not a requirement for every host.
+Query keys must distinguish host/resource identities and query state.
+
+### Capabilities and extension points
+
+Expose supported actions as cohesive capabilities: row editing, schema editing,
+stored views, board positioning, relations, history/undo, and presence. UI controls
+appear only when the corresponding capability is available and permitted.
+A missing capability is absent, never a callback that pretends to save successfully.
+Keep column protections and requiredness in shared schema metadata and enforcement;
+frontend capabilities guide the UI but do not replace server authorization.
+
+Use slots for host-specific presentation such as entity pickers, record links,
+and surrounding toolbars. Standard column controls and database interactions
+belong to the shared editor; hosts should not need to assemble them individually.
+Keep local view preferences explicitly separate from persisted shared views.
+Change notifications may be supplied through events or polling; the shared query
+adapter owns invalidation behavior, while the host owns the subscription lifecycle.
+
+### Current extraction points
+
+Start from [DatabaseRecordsView](../../../apps/web/src/features/database/views/database-records-view.tsx)
+and [DatabaseRowsSource](../../../apps/web/src/features/database/context/table-source.ts).
+`DatabaseProvider` creates the shared controller from `DatabaseApi` and scoped
+capabilities. `DatabaseRecords` wires the standard schema controls once. Read the
+[API contract](../../../apps/web/src/features/database/core/api.ts) and
+[provider](../../../apps/web/src/features/database/context/database.tsx) when adding
+a host. `DatabaseGrid` composes the Macro app with its SQL cache and inference
+source; ordinary API hosts use the provider's paginated source. Keep host-specific
+optimizations behind the same data-source contract. CRM can adopt this boundary
+without importing the Macro app adapter.
+
+Verify the same editor against a small fake API without app providers, then test
+the Macro and CRM adapters against the same behavioral contract. Cover a failed
+batch, a successful write followed by failed refresh, version conflicts, and
+unsupported capabilities. Exercise changed interactions in both hosts in a browser.
+
+## Keep API authorization and tools at the host boundary
+
+A host may accept the common operation types while restricting their scope (for
+example, CRM allows edits only to its pipeline table). Validate that scope and
+resource access in the host's domain service before calling the database engine.
+UI and AI adapters should call that same authorized host service. An API endpoint
+or a shared database engine does not automatically make a host available to AI;
+wire host discovery/read/write tools explicitly without bypassing its permissions.
Read the [storage boundary](../../../crates/databases/README.md#storage-and-app-entities)
and [domain ports](../../../crates/databases/src/domain/ports.rs) before wiring a
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index 1bfa8d5b65..f6eff059a4 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -85,7 +85,7 @@ import { useAppSquishHandlers } from './useAppSquishHandlers';
const StarterDatabase = lazy(async () => {
const module = await import(
- '@app/features/block-database/views/starter-database'
+ '../../features/block-database/views/starter-database'
);
return { default: module.StarterDatabase };
});
diff --git a/apps/web/src/features/block-database/browser-test/api.browser.e2e.ts b/apps/web/src/features/block-database/browser-test/api.browser.e2e.ts
new file mode 100644
index 0000000000..23b1901cbf
--- /dev/null
+++ b/apps/web/src/features/block-database/browser-test/api.browser.e2e.ts
@@ -0,0 +1,40 @@
+import { expect, test } from '@playwright/test';
+
+test('an API-only host pages rows, writes cells and creates columns through the shared controller', async ({
+ page,
+}) => {
+ await page.routeWebSocket('**', (socket) => socket.close());
+ await page.route('https://**', (route) => route.abort());
+ await page.route('**/__macro_dev/**', (route) => route.abort());
+ await page.goto('/src/features/block-database/browser-test/api.html');
+ await expect(page.getByRole('grid', { name: 'API records' })).toBeVisible();
+ await expect(
+ page.getByRole('button', { name: /^Name: Second\./ })
+ ).toBeVisible();
+ await page.getByRole('button', { name: /^Name: First\./ }).dblclick();
+ const input = page.getByRole('textbox', { name: 'Edit Name' });
+ await input.fill('Changed through API');
+ await input.press('Tab');
+ await expect(page.getByLabel('API writes')).toHaveText('1');
+ await page.getByRole('button', { name: 'Add column', exact: true }).click();
+ await expect(page.getByLabel('API writes')).toHaveText('2');
+ await expect(
+ page.getByRole('columnheader', { name: 'Unnamed', exact: true })
+ ).toBeVisible();
+ await page.keyboard.press('Escape');
+ await page.getByRole('button', { name: 'Toggle editing' }).click();
+ await expect(
+ page.getByRole('button', { name: 'Add column', exact: true })
+ ).toHaveCount(0);
+ await page.getByRole('button', { name: 'Toggle editing' }).click();
+ await page.getByRole('button', { name: 'Show board' }).click();
+ await expect(
+ page.getByText('Changed through API', { exact: true }).first()
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', { name: 'Move Changed through API', exact: true })
+ ).toHaveCount(0);
+ await expect(
+ page.getByRole('button', { name: 'Drag Changed through API', exact: true })
+ ).toHaveCount(0);
+});
diff --git a/apps/web/src/features/block-database/browser-test/api.html b/apps/web/src/features/block-database/browser-test/api.html
new file mode 100644
index 0000000000..b59907bc00
--- /dev/null
+++ b/apps/web/src/features/block-database/browser-test/api.html
@@ -0,0 +1 @@
+<!doctype html><html><head><meta charset="utf-8" /><title>Database API host</title></head><body><div id="root"></div><script type="module" src="./api.tsx"></script></body></html>
diff --git a/apps/web/src/features/block-database/browser-test/api.tsx b/apps/web/src/features/block-database/browser-test/api.tsx
new file mode 100644
index 0000000000..50925bf54a
--- /dev/null
+++ b/apps/web/src/features/block-database/browser-test/api.tsx
@@ -0,0 +1,206 @@
+import '@app/index.css';
+import type { OpResult } from '@core/database-sql/generated/types';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { errAsync, okAsync } from 'neverthrow';
+import { createSignal } from 'solid-js';
+import { render } from 'solid-js/web';
+import { DatabaseProvider } from '../../database/context/database';
+import type { DatabaseApi, DatabaseTableSchema } from '../../database/core/api';
+import type { DatabaseRow } from '../../database/core/table';
+import type { DatabaseViewState } from '../../database/core/view-state';
+import { DatabaseRecords } from '../../database/views/database-records';
+
+const tableId = '00000000-0000-0000-0000-000000000001';
+const nameId = '00000000-0000-0000-0000-000000000002';
+const statusId = '00000000-0000-0000-0000-000000000003';
+const optionId = '00000000-0000-0000-0000-000000000004';
+
+function ApiFixture() {
+ const [editable, setEditable] = createSignal(true);
+ const [writes, setWrites] = createSignal(0);
+ const [view, setView] = createSignal<DatabaseViewState>({
+ query: { filter: null },
+ layout: { kind: 'table', columns: [] },
+ });
+ let table: DatabaseTableSchema = {
+ id: tableId,
+ databaseId: tableId,
+ name: 'API records',
+ version: 1,
+ columns: [
+ {
+ id: nameId,
+ name: 'Name',
+ dataType: 'STRING',
+ isMultiSelect: false,
+ writable: true,
+ options: [],
+ },
+ {
+ id: statusId,
+ name: 'Status',
+ dataType: 'SELECT_STRING',
+ isMultiSelect: false,
+ writable: true,
+ options: [{ id: optionId, label: 'Open', color: null }],
+ },
+ ],
+ };
+ let rows: DatabaseRow[] = ['First', 'Second'].map((name, index) => ({
+ rowId: `00000000-0000-0000-0000-00000000001${index}`,
+ cells: { [nameId]: name, [statusId]: 'Open' },
+ }));
+ const api: DatabaseApi = {
+ key: ['standalone-api-fixture'],
+ readTable: () => okAsync(table),
+ readRows: ({ cursor, rowIds }) => {
+ const selected = rowIds
+ ? rows.filter((row) => rowIds.includes(row.rowId))
+ : rows;
+ const offset = Number(cursor ?? 0);
+ return okAsync({
+ rows: selected.slice(offset, offset + 1),
+ nextCursor:
+ offset + 1 < selected.length ? String(offset + 1) : undefined,
+ tableVersion: table.version,
+ });
+ },
+ applyOps: ({ ops }) => {
+ const results: OpResult[] = [];
+ const version = table.version + 1;
+ for (const op of ops) {
+ if (
+ op.kind === 'column' &&
+ op.change.kind === 'create' &&
+ op.change.definition.source === 'new'
+ ) {
+ table = {
+ ...table,
+ version,
+ columns: [
+ ...table.columns,
+ {
+ id: op.column,
+ name: op.change.definition.name,
+ dataType: 'STRING',
+ writable: true,
+ isMultiSelect: false,
+ options: [],
+ },
+ ],
+ };
+ results.push({
+ kind: 'column',
+ table: tableId,
+ column: op.column,
+ tableVersion: version,
+ change: { kind: 'created' },
+ });
+ } else if (op.kind === 'column' && op.change.kind === 'rename') {
+ const name = op.change.name;
+ table = {
+ ...table,
+ version,
+ columns: table.columns.map((column) =>
+ column.id === op.column ? { ...column, name } : column
+ ),
+ };
+ results.push({
+ kind: 'column',
+ table: tableId,
+ column: op.column,
+ tableVersion: version,
+ change: { kind: 'renamed' },
+ });
+ } else if (
+ op.kind === 'rows' &&
+ op.change.kind === 'update' &&
+ op.change.changes.kind === 'per_row'
+ ) {
+ for (const change of op.change.changes.rows)
+ rows = rows.map((row) =>
+ row.rowId === change.row
+ ? {
+ ...row,
+ cells: {
+ ...row.cells,
+ ...Object.fromEntries(
+ change.cells.map((cell) => [
+ cell.column,
+ cell.value.type === 'text' ? cell.value.value : null,
+ ])
+ ),
+ },
+ }
+ : row
+ );
+ table = { ...table, version };
+ results.push({
+ kind: 'rows',
+ table: tableId,
+ tableVersion: version,
+ change: {
+ kind: 'updated',
+ affected: op.change.changes.rows.length,
+ },
+ });
+ } else
+ return errAsync({
+ code: 'INVALID_OP',
+ refusal: null,
+ message: 'Unsupported fixture operation',
+ });
+ }
+ setWrites((count) => count + 1);
+ return okAsync({ results });
+ },
+ };
+ return (
+ <QueryClientProvider
+ client={
+ new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ }
+ >
+ <main class="flex h-screen flex-col bg-panel text-ink">
+ <div class="flex gap-4 p-4">
+ <button onClick={() => setEditable((value) => !value)}>
+ Toggle editing
+ </button>
+ <button
+ onClick={() =>
+ setView({
+ query: { filter: null },
+ layout: {
+ kind: 'board',
+ groupBy: statusId,
+ title: nameId,
+ lanes: [],
+ cardFields: [],
+ hideEmptyLanes: false,
+ },
+ })
+ }
+ >
+ Show board
+ </button>
+ <output aria-label="API writes">{writes()}</output>
+ </div>
+ <DatabaseProvider
+ api={api}
+ tableId={tableId}
+ view={view()}
+ capabilities={{ editRows: editable(), editColumns: editable() }}
+ >
+ <DatabaseRecords
+ view={view()}
+ stored={false}
+ onViewChange={(change) =>
+ setView((view) => ({ ...view, ...change }))
+ }
+ />
+ </DatabaseProvider>
+ </main>
+ </QueryClientProvider>
+ );
+}
+render(ApiFixture, document.getElementById('root')!);
diff --git a/apps/web/src/features/block-database/browser-test/records.tsx b/apps/web/src/features/block-database/browser-test/records.tsx
index 1ba88b43ef..9a0486951c 100644
--- a/apps/web/src/features/block-database/browser-test/records.tsx
+++ b/apps/web/src/features/block-database/browser-test/records.tsx
@@ -5,10 +5,10 @@ import { render } from 'solid-js/web';
import type {
DatabaseRowsSnapshot,
DatabaseRowsSource,
-} from '../context/table-source';
-import type { DatabaseViewColumn } from '../core/database-view';
-import { optimisticRows } from '../core/table';
-import { DatabaseRecordsView } from '../views/database-records-view';
+} from '../../database/context/table-source';
+import type { DatabaseViewColumn } from '../../database/core/database-view';
+import { optimisticRows } from '../../database/core/table';
+import { DatabaseRecordsView } from '../../database/views/database-records-view';
// A host owns the records and writes. No database entity, saved view, or app provider.
function RecordsFixture() {
diff --git a/apps/web/src/features/block-database/browser-test/table.tsx b/apps/web/src/features/block-database/browser-test/table.tsx
index ca632b06f3..5d89f1a217 100644
--- a/apps/web/src/features/block-database/browser-test/table.tsx
+++ b/apps/web/src/features/block-database/browser-test/table.tsx
@@ -2,12 +2,12 @@ import '@app/index.css';
import type { SortKey } from '@core/database-sql/generated/types';
import { createSignal } from 'solid-js';
import { render } from 'solid-js/web';
-import { GridCell } from '../component/GridCell';
-import type { DatabaseViewColumn } from '../core/database-view';
-import { moveBeside } from '../core/move-beside';
-import type { DatabaseRow } from '../core/table';
-import { withSort } from '../core/view-query';
-import { DatabaseTableView } from '../views/database-table-view';
+import { GridCell } from '../../database/components/grid-cell';
+import type { DatabaseViewColumn } from '../../database/core/database-view';
+import { moveBeside } from '../../database/core/move-beside';
+import type { DatabaseRow } from '../../database/core/table';
+import { withSort } from '../../database/core/view-query';
+import { DatabaseTableView } from '../../database/views/database-table-view';
// Real grid and editors; records and saved layout are local to this browser fixture.
function TableFixture() {
diff --git a/apps/web/src/features/block-database/component/AddColumnMenu.tsx b/apps/web/src/features/block-database/component/AddColumnMenu.tsx
index bdf3fe29b7..0a5167ebb6 100644
--- a/apps/web/src/features/block-database/component/AddColumnMenu.tsx
+++ b/apps/web/src/features/block-database/component/AddColumnMenu.tsx
@@ -2,8 +2,8 @@ import PlusIcon from '@phosphor/plus.svg';
import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';
import { Button } from '@ui/components/Button';
import { createSignal, Show } from 'solid-js';
-import { columnSchemaMessage } from '../core/column-schema';
-import { defaultDatabaseColumnName } from '../core/property-creation';
+import { columnSchemaMessage } from '../../database/core/column-schema';
+import { defaultDatabaseColumnName } from '../../database/core/property-creation';
import { createDatabaseColumn } from '../queries/columns';
/**
diff --git a/apps/web/src/features/block-database/component/Block.tsx b/apps/web/src/features/block-database/component/Block.tsx
index 460aae9853..925043fc8f 100644
--- a/apps/web/src/features/block-database/component/Block.tsx
+++ b/apps/web/src/features/block-database/component/Block.tsx
@@ -44,18 +44,21 @@ import {
Suspense,
} from 'solid-js';
import { match } from 'ts-pattern';
-import { DatabaseSearch } from '../components/database-search';
-import type { ShownLayout } from '../components/database-toolbar';
-import { DatabaseToolbar } from '../components/database-toolbar';
-import type { NewFormChoice, NewView } from '../components/new-view-dialog';
+import { DatabaseSearch } from '../../database/components/database-search';
+import type { ShownLayout } from '../../database/components/database-toolbar';
+import { DatabaseToolbar } from '../../database/components/database-toolbar';
+import type {
+ NewFormChoice,
+ NewView,
+} from '../../database/components/new-view-dialog';
+import type { DatabaseRelatedDestination } from '../../database/core/database-relations';
+import type { ViewChange } from '../../database/core/view-state';
+import { allRecordsView, boardLayout } from '../../database/core/views';
+import { databaseOpMessage } from '../../database/core/write-failure';
+import { createDatabaseSearch } from '../../database/primitives/database-search';
+import { createDatabaseUndo } from '../../database/primitives/undo-controller';
+import { createViewCreation } from '../../database/primitives/view-creation';
import { databaseChat } from '../core/chat-context';
-import type { DatabaseRelatedDestination } from '../core/database-relations';
-import type { ViewChange } from '../core/view-state';
-import { allRecordsView, boardLayout } from '../core/views';
-import { databaseOpMessage } from '../core/write-failure';
-import { createDatabaseSearch } from '../primitives/database-search';
-import { createDatabaseUndo } from '../primitives/undo-controller';
-import { createViewCreation } from '../primitives/view-creation';
import { createDatabaseViewSelection } from '../primitives/view-selection';
import { searchDatabase } from '../queries/database-search';
import { toViewColumn } from '../queries/table-rows';
diff --git a/apps/web/src/features/block-database/component/DatabaseGrid.tsx b/apps/web/src/features/block-database/component/DatabaseGrid.tsx
index 3074e77fbf..c01b83b242 100644
--- a/apps/web/src/features/block-database/component/DatabaseGrid.tsx
+++ b/apps/web/src/features/block-database/component/DatabaseGrid.tsx
@@ -13,7 +13,7 @@ import {
} from '@queries/storage/databases-sync';
import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';
import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
-import { ResultAsync } from 'neverthrow';
+import { useQueryClient } from '@tanstack/solid-query';
import {
createMemo,
createSignal,
@@ -23,36 +23,42 @@ import {
Show,
Suspense,
} from 'solid-js';
-import { DatabaseRelationCell } from '../components/database-relation-cell';
-import type { DatabaseCellFocus } from '../components/database-table';
-import { ColumnUsageContext } from '../context/column-usage';
+import { DatabaseRelationCell } from '../../database/components/database-relation-cell';
+import type { DatabaseCellFocus } from '../../database/components/database-table';
+import type {
+ DatabaseMentionPickerProps,
+ DatabaseTextEditorProps,
+} from '../../database/components/grid-cell';
+import { ColumnUsageContext } from '../../database/context/column-usage';
+import { DatabaseProvider } from '../../database/context/database';
import {
type OptionEditing,
OptionEditingContext,
-} from '../context/option-editing';
-import type { DatabaseRelationSource } from '../context/relation-source';
-import type { DatabaseRowsSource } from '../context/table-source';
-import type { DatabaseEntityType } from '../core/column-inference';
-import { mergeDatabaseColumnOrder } from '../core/column-order';
-import { convertedColumnName } from '../core/column-schema';
-import type { DatabaseRelatedDestination } from '../core/database-relations';
-import type { ViewChange } from '../core/view-state';
+} from '../../database/context/option-editing';
+import type { DatabaseRelationSource } from '../../database/context/relation-source';
+import type { DatabaseRowsSource } from '../../database/context/table-source';
+import type { DatabaseEntityType } from '../../database/core/column-inference';
+import { convertedColumnName } from '../../database/core/column-schema';
+import type { DatabaseRelatedDestination } from '../../database/core/database-relations';
+import type { ViewChange } from '../../database/core/view-state';
+import type { BoardPositionsState } from '../../database/primitives/board-layout';
+import type { BoardPositions } from '../../database/views/database-board-view';
+import { DatabaseRecords } from '../../database/views/database-records';
+import type { DatabaseRecordsActions } from '../../database/views/database-records-view';
import {
DatabaseMentionPicker,
DatabaseMentionValue,
DatabaseTextEditor,
DatabaseTextValue,
} from '../database-mentions';
-import type { BoardPositionsState } from '../primitives/board-layout';
import { createColumnCasts } from '../queries/column-casts';
-import { opColumnKind } from '../queries/column-schema';
import {
addDatabaseColumnOptions,
convertDatabaseColumn,
} from '../queries/columns';
import { createDatabaseRelations } from '../queries/database-relations';
import { useRelatedDatabaseSync } from '../queries/database-relations-sync';
-import { patchTable } from '../queries/detail-cache';
+import { createMacroDatabaseApi, editorTable } from '../queries/editor-api';
import { useFormsAskingColumns } from '../queries/forms-usage';
import { deleteDatabaseOption, updateDatabaseOption } from '../queries/options';
import { tableChangesOf } from '../queries/table-changes';
@@ -63,16 +69,6 @@ import {
setCardPositions,
useCardPositions,
} from '../queries/views';
-import type { BoardPositions } from '../views/database-board-view';
-import {
- type DatabaseRecordsActions,
- DatabaseRecordsView,
-} from '../views/database-records-view';
-import { AddColumnMenu, createDefaultColumn } from './AddColumnMenu';
-import type {
- DatabaseMentionPickerProps,
- DatabaseTextEditorProps,
-} from './GridCell';
export type DatabaseGridProps = {
databaseId: string;
@@ -156,6 +152,7 @@ function RelatedDatabaseSync(props: {
}
function TableAdapter(props: DatabaseGridProps & { tableId: string }) {
+ const queryClient = useQueryClient();
// Keep the final schema for this table available to already-queued writes
// after its tab is closed; a new selected table must never redirect them.
let ownedTable = props.table;
@@ -305,183 +302,58 @@ function TableAdapter(props: DatabaseGridProps & { tableId: string }) {
<OptionEditingContext.Provider
value={props.canEdit ? optionEditing : undefined}
>
- <DatabaseRecordsView
- name={table().table.name}
- source={source}
- canEdit={props.canEdit}
+ <DatabaseProvider
+ api={createMacroDatabaseApi(databaseId, queryClient)}
+ tableId={props.tableId}
view={props.view}
- stored={props.stored}
- preparingView={props.preparingView}
- onViewChange={props.onViewChange}
- onClearConstraints={props.onClearConstraints}
- boardPositions={boardPositions}
- onCellFocus={setFocusedCell}
- remoteUsers={remoteUsers()}
- renderTextEditor={renderTextEditor}
- renderTextValue={renderTextValue}
- renderMentionPicker={renderMentionPicker}
- renderMentionValue={renderMentionValue}
- renderRelationCell={(cell) => (
- <DatabaseRelationCell
- {...cell}
- source={relations(cell.column.relation.tableId)}
- onOpen={(rowId) =>
- props.onOpenRelated?.({ ...cell.column.relation, rowId })
- }
- />
- )}
- relationTables={relationTables()}
- columnCasts={columnCasts}
- onChangeColumnType={(columnId, change) =>
- // Checked against the version the menu's dry run read, so a
- // change made since is not converted blind.
- applyDatabaseOps(
- databaseId,
- [
- {
- kind: 'column',
- table: props.tableId,
- column: columnId,
- change: {
- kind: 'change_type',
- to: opColumnKind(databaseId, change.to),
- },
- },
- ],
- {
- [props.tableId]:
- change.baseVersion ?? table().table.version,
- }
- ).map(() => undefined)
- }
- onConvertColumn={(columnId, conversion) =>
- convertDatabaseColumn({
- databaseId,
- tableId: props.tableId,
- columnId,
- to: conversion.to,
- name: convertedColumnName(
- conversion.columnName,
- conversion.label,
- table().columns.map((column) => toViewColumn(column).name)
- ),
- })
- }
- onDeleteColumn={(columnId) => {
- const tableId = props.tableId;
- const version = table().table.version;
- return ResultAsync.fromSafePromise(
- patchTable(databaseId, tableId, (entry) => ({
- ...entry,
- columns: entry.columns.filter(
- ({ column }) => column.id !== columnId
- ),
- }))
- )
- .andThen((rollback) =>
- applyDatabaseOps(
- databaseId,
- [
- {
- kind: 'column',
- table: tableId,
- column: columnId,
- change: { kind: 'delete' },
- },
- ],
- { [tableId]: version }
- ).mapErr((error) => {
- rollback();
- return error;
- })
- )
- .map(() => undefined);
+ capabilities={{
+ editRows: props.canEdit,
+ editColumns: props.canEdit,
}}
- onReorderColumns={(columnIds) => {
- const tableId = props.tableId;
- const version = table().table.version;
- const order = mergeDatabaseColumnOrder(
- table().columns.map(({ column }) => column.id),
- columnIds
- );
- const rank = new Map(order.map((id, i) => [id, i]));
- return ResultAsync.fromSafePromise(
- patchTable(databaseId, tableId, (entry) => ({
- ...entry,
- columns: entry.columns.toSorted(
- (a, b) =>
- (rank.get(a.column.id) ?? Infinity) -
- (rank.get(b.column.id) ?? Infinity)
+ data={{ table: () => editorTable(table()), rows: source }}
+ inferNewColumns
+ >
+ <DatabaseRecords
+ view={props.view}
+ stored={props.stored}
+ preparingView={props.preparingView}
+ onViewChange={props.onViewChange}
+ onClearConstraints={props.onClearConstraints}
+ boardPositions={boardPositions}
+ onCellFocus={setFocusedCell}
+ remoteUsers={remoteUsers()}
+ renderTextEditor={renderTextEditor}
+ renderTextValue={renderTextValue}
+ renderMentionPicker={renderMentionPicker}
+ renderMentionValue={renderMentionValue}
+ renderRelationCell={(cell) => (
+ <DatabaseRelationCell
+ {...cell}
+ source={relations(cell.column.relation.tableId)}
+ onOpen={(rowId) =>
+ props.onOpenRelated?.({ ...cell.column.relation, rowId })
+ }
+ />
+ )}
+ relationTables={relationTables()}
+ columnCasts={columnCasts}
+ onConvertColumn={(columnId, conversion) =>
+ convertDatabaseColumn({
+ databaseId,
+ tableId: props.tableId,
+ columnId,
+ to: conversion.to,
+ name: convertedColumnName(
+ conversion.columnName,
+ conversion.label,
+ table().columns.map((column) => toViewColumn(column).name)
),
- }))
- )
- .andThen((rollback) =>
- applyDatabaseOps(
- databaseId,
- [
- {
- kind: 'table',
- table: tableId,
- change: { kind: 'reorder_columns', order },
- },
- ],
- { [tableId]: version }
- ).mapErr((error) => {
- rollback();
- return error;
- })
- )
- .map(() => undefined);
- }}
- onRenameColumn={(columnId, name, previousName) => {
- const tableId = props.tableId;
- return ResultAsync.fromSafePromise(
- patchTable(databaseId, tableId, (entry) => ({
- ...entry,
- columns: entry.columns.map((column) =>
- column.column.id === columnId
- ? {
- ...column,
- column: { ...column.column, display_name: name },
- }
- : column
- ),
- }))
- )
- .andThen((rollback) =>
- applyDatabaseOps(databaseId, [
- {
- kind: 'column',
- table: tableId,
- column: columnId,
- change: { kind: 'rename', name, previousName },
- },
- ]).mapErr((error) => {
- rollback();
- return error;
- })
- )
- .map(() => undefined);
- }}
- actionsRef={props.actionsRef}
- renderToolbar={props.renderToolbar}
- createColumn={() =>
- createDefaultColumn({
- databaseId,
- tableId: props.tableId,
- columns: table().columns,
- })
- }
- addColumn={(label, onCreated) => (
- <AddColumnMenu
- databaseId={databaseId}
- tableId={props.tableId}
- columns={table().columns}
- label={label}
- onCreated={onCreated}
- />
- )}
- />
+ })
+ }
+ actionsRef={props.actionsRef}
+ renderToolbar={props.renderToolbar}
+ />
+ </DatabaseProvider>
</OptionEditingContext.Provider>
</ColumnUsageContext.Provider>
</StaticMarkdownContext>
diff --git a/apps/web/src/features/block-database/component/TableTabs.tsx b/apps/web/src/features/block-database/component/TableTabs.tsx
index 5d124b7003..43574f99e8 100644
--- a/apps/web/src/features/block-database/component/TableTabs.tsx
+++ b/apps/web/src/features/block-database/component/TableTabs.tsx
@@ -2,9 +2,12 @@ import { toast } from '@core/component/Toast/Toast';
import { applyDatabaseOps } from '@queries/storage/databases';
import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
import { ResultAsync } from 'neverthrow';
-import { TableNavigation } from '../components/table-navigation';
-import { tableDeleteMessage, tableOrderMessage } from '../core/column-schema';
-import { tableDeleteConsequence } from '../core/forms-usage';
+import { TableNavigation } from '../../database/components/table-navigation';
+import {
+ tableDeleteMessage,
+ tableOrderMessage,
+} from '../../database/core/column-schema';
+import { tableDeleteConsequence } from '../../database/core/forms-usage';
import { createTableWithName } from '../queries/create-table';
import { patchDetail, patchTable } from '../queries/detail-cache';
import { useFormsOverTables } from '../queries/forms-usage';
diff --git a/apps/web/src/features/block-database/component/TopBar.tsx b/apps/web/src/features/block-database/component/TopBar.tsx
index efa346439c..23cb2b3004 100644
--- a/apps/web/src/features/block-database/component/TopBar.tsx
+++ b/apps/web/src/features/block-database/component/TopBar.tsx
@@ -22,11 +22,11 @@ import { getEntityGraphqlClient } from '@service-storage/graphql-soup';
import { Button } from '@ui';
import type { ResultAsync } from 'neverthrow';
import { lazy, Show, Suspense } from 'solid-js';
-import { DatabaseTitle } from '../components/database-title';
+import { DatabaseTitle } from '../../database/components/database-title';
import {
type DatabaseEntityFailure,
databaseEntityMessage,
-} from '../core/write-failure';
+} from '../../database/core/write-failure';
import { renameDatabase } from '../queries/rename-database';
import { DatabasePageActions } from '../views/database-page-actions';
import { TableTabs } from './TableTabs';
diff --git a/apps/web/src/features/block-database/core/native-mentions.ts b/apps/web/src/features/block-database/core/native-mentions.ts
index f9617cd684..eeb37ce3e6 100644
--- a/apps/web/src/features/block-database/core/native-mentions.ts
+++ b/apps/web/src/features/block-database/core/native-mentions.ts
@@ -2,7 +2,10 @@ import type { MentionBucketId } from '@core/component/LexicalMarkdown/component/
import type { MentionItem } from '@core/component/LexicalMarkdown/utils/mentionsUtils';
import type { EntityBucket } from '@core/context/quickAccess';
import { match } from 'ts-pattern';
-import type { DatabaseEntityType, DatabaseMention } from './column-inference';
+import type {
+ DatabaseEntityType,
+ DatabaseMention,
+} from '../../database/core/column-inference';
const ENTITY_TYPE_OF_BUCKET: Partial<Record<EntityBucket, DatabaseEntityType>> =
{
diff --git a/apps/web/src/features/block-database/database-mentions.test.tsx b/apps/web/src/features/block-database/database-mentions.test.tsx
index 019b5c49e7..d4e9a1be2b 100644
--- a/apps/web/src/features/block-database/database-mentions.test.tsx
+++ b/apps/web/src/features/block-database/database-mentions.test.tsx
@@ -8,7 +8,7 @@ import {
Show,
} from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { DatabaseMentionPickerProps } from './component/GridCell';
+import type { DatabaseMentionPickerProps } from '../database/components/grid-cell';
import {
databaseMentionFromItem,
databaseMentionScope,
diff --git a/apps/web/src/features/block-database/database-mentions.tsx b/apps/web/src/features/block-database/database-mentions.tsx
index 695133f8a9..d2fcb094cf 100644
--- a/apps/web/src/features/block-database/database-mentions.tsx
+++ b/apps/web/src/features/block-database/database-mentions.tsx
@@ -13,15 +13,15 @@ import { encodeCellMention } from '@macro-inc/spreadsheet/cell-mentions';
import { usePropertyEntityDisplay } from '@property/hooks/usePropertyEntityDisplay';
import { ErrorBoundary, Show, Suspense } from 'solid-js';
import { match } from 'ts-pattern';
-import type {
- DatabaseMentionPickerProps,
- DatabaseTextEditorProps,
-} from './component/GridCell';
import {
DatabaseMentionLabel,
DatabaseMentionPlaceholder,
-} from './components/database-mention-label';
-import type { DatabaseEntityType } from './core/column-inference';
+} from '../database/components/database-mention-label';
+import type {
+ DatabaseMentionPickerProps,
+ DatabaseTextEditorProps,
+} from '../database/components/grid-cell';
+import type { DatabaseEntityType } from '../database/core/column-inference';
import {
databaseMentionFromItem,
databaseMentionScope,
diff --git a/apps/web/src/features/block-database/primitives/view-selection.ts b/apps/web/src/features/block-database/primitives/view-selection.ts
index a6fb8dd6e9..2a4714e7c2 100644
--- a/apps/web/src/features/block-database/primitives/view-selection.ts
+++ b/apps/web/src/features/block-database/primitives/view-selection.ts
@@ -4,7 +4,7 @@ import { type Accessor, createMemo, createSignal, type Setter } from 'solid-js';
import {
type DatabaseViewSelection,
readViewSelection,
-} from '../core/view-selection';
+} from '../../database/core/view-selection';
export function createDatabaseViewSelection(
userId: Accessor<string | undefined>,
diff --git a/apps/web/src/features/block-database/queries/column-casts.test.tsx b/apps/web/src/features/block-database/queries/column-casts.test.tsx
index 64cb42d92f..53c74fb902 100644
--- a/apps/web/src/features/block-database/queries/column-casts.test.tsx
+++ b/apps/web/src/features/block-database/queries/column-casts.test.tsx
@@ -4,7 +4,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
import { ok } from 'neverthrow';
import { createSignal } from 'solid-js';
import { afterEach, expect, it, vi } from 'vitest';
-import type { DatabaseColumnCasts } from '../core/column-schema';
+import type { DatabaseColumnCasts } from '../../database/core/column-schema';
import { createColumnCasts } from './column-casts';
const transport = vi.hoisted(() => ({
diff --git a/apps/web/src/features/block-database/queries/column-casts.ts b/apps/web/src/features/block-database/queries/column-casts.ts
index 4eea64f5f6..2edab59a7c 100644
--- a/apps/web/src/features/block-database/queries/column-casts.ts
+++ b/apps/web/src/features/block-database/queries/column-casts.ts
@@ -8,7 +8,7 @@ import type {
DatabaseColumnCast,
DatabaseColumnCasts,
DatabaseColumnCastsSource,
-} from '../core/column-schema';
+} from '../../database/core/column-schema';
import { databaseColumnKeys } from './keys';
/** The type menu's dry runs for one table, fetched when a menu opens. */
diff --git a/apps/web/src/features/block-database/queries/column-schema.ts b/apps/web/src/features/block-database/queries/column-schema.ts
index debb8c8836..e6e7662bf2 100644
--- a/apps/web/src/features/block-database/queries/column-schema.ts
+++ b/apps/web/src/features/block-database/queries/column-schema.ts
@@ -1,5 +1,5 @@
import type { OpColumnKind } from '@core/database-sql/generated/types';
-import type { DatabaseColumnKind } from '../core/column-schema';
+import type { DatabaseColumnKind } from '../../database/core/column-schema';
/** The op's spelling of a kind; a relation's rows live in this database. */
export function opColumnKind(
diff --git a/apps/web/src/features/block-database/queries/columns.ts b/apps/web/src/features/block-database/queries/columns.ts
index 01a7b2da40..f43a48c397 100644
--- a/apps/web/src/features/block-database/queries/columns.ts
+++ b/apps/web/src/features/block-database/queries/columns.ts
@@ -9,7 +9,7 @@ import { v7 as uuidv7 } from 'uuid';
import type {
DatabaseColumnKind,
DatabaseSchemaChange,
-} from '../core/column-schema';
+} from '../../database/core/column-schema';
import { opColumnKind } from './column-schema';
/**
diff --git a/apps/web/src/features/block-database/queries/create-table.ts b/apps/web/src/features/block-database/queries/create-table.ts
index 59224bdb32..9daf5b94e3 100644
--- a/apps/web/src/features/block-database/queries/create-table.ts
+++ b/apps/web/src/features/block-database/queries/create-table.ts
@@ -6,8 +6,8 @@ import {
import { databasesKeys } from '@queries/storage/keys';
import { okAsync, ResultAsync } from 'neverthrow';
import { v7 as uuidv7 } from 'uuid';
-import type { DatabaseSchemaChange } from '../core/column-schema';
-import type { TableCreationResult } from '../core/table-creation';
+import type { DatabaseSchemaChange } from '../../database/core/column-schema';
+import type { TableCreationResult } from '../../database/core/table-creation';
/**
* Create a table with its Name column, which infers its type like any new
diff --git a/apps/web/src/features/block-database/queries/database-relations.test.tsx b/apps/web/src/features/block-database/queries/database-relations.test.tsx
index da745e040b..542af33b89 100644
--- a/apps/web/src/features/block-database/queries/database-relations.test.tsx
+++ b/apps/web/src/features/block-database/queries/database-relations.test.tsx
@@ -9,7 +9,7 @@ import { createClient, type Exchange } from '@urql/core';
import { okAsync } from 'neverthrow';
import { afterEach, expect, it, vi } from 'vitest';
import { empty, fromValue, mergeMap, pipe } from 'wonka';
-import type { DatabaseRelationSource } from '../context/relation-source';
+import type { DatabaseRelationSource } from '../../database/context/relation-source';
import { createDatabaseRelations } from './database-relations';
const transport = vi.hoisted(() => ({ get: vi.fn() }));
diff --git a/apps/web/src/features/block-database/queries/database-relations.ts b/apps/web/src/features/block-database/queries/database-relations.ts
index 9c16969ae8..1ac13d2b79 100644
--- a/apps/web/src/features/block-database/queries/database-relations.ts
+++ b/apps/web/src/features/block-database/queries/database-relations.ts
@@ -15,12 +15,12 @@ import { type Accessor, createMemo, mapArray } from 'solid-js';
import type {
DatabaseRelationFailure,
DatabaseRelationSource,
-} from '../context/relation-source';
+} from '../../database/context/relation-source';
import {
type DatabaseRelatedRow,
sameRelatedRows,
-} from '../core/database-relations';
-import { titleColumn } from '../core/table';
+} from '../../database/core/database-relations';
+import { titleColumn } from '../../database/core/table';
import { tableRowsStatement } from '../sql';
import { toViewColumn } from './table-rows';
diff --git a/apps/web/src/features/block-database/queries/database-search.ts b/apps/web/src/features/block-database/queries/database-search.ts
index bffd5fd0d0..4988fdf9ee 100644
--- a/apps/web/src/features/block-database/queries/database-search.ts
+++ b/apps/web/src/features/block-database/queries/database-search.ts
@@ -13,10 +13,10 @@ import { match } from 'ts-pattern';
import {
type DatabaseSearchGroup,
databaseSearchGroups,
-} from '../core/database-search';
-import { gridRows } from '../core/grid-cells';
-import { searchFilter } from '../core/view-query';
-import { allRecordsView } from '../core/views';
+} from '../../database/core/database-search';
+import { gridRows } from '../../database/core/grid-cells';
+import { searchFilter } from '../../database/core/view-query';
+import { allRecordsView } from '../../database/core/views';
import { toViewColumn } from './table-rows';
/**
diff --git a/apps/web/src/features/block-database/queries/detail-cache.ts b/apps/web/src/features/block-database/queries/detail-cache.ts
index 9a8b144c94..2fea2f681c 100644
--- a/apps/web/src/features/block-database/queries/detail-cache.ts
+++ b/apps/web/src/features/block-database/queries/detail-cache.ts
@@ -10,7 +10,7 @@ import type { OpResult } from '@service-storage/generated/schemas/opResult';
import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
import type { QueryClient } from '@tanstack/solid-query';
import { errAsync, okAsync, type ResultAsync } from 'neverthrow';
-import type { DatabaseOpFailure } from '../core/write-failure';
+import type { DatabaseOpFailure } from '../../database/core/write-failure';
/**
* Change the cached detail in place; nothing happens before it is first read.
diff --git a/apps/web/src/features/block-database/queries/editor-api.ts b/apps/web/src/features/block-database/queries/editor-api.ts
new file mode 100644
index 0000000000..c963ff547d
--- /dev/null
+++ b/apps/web/src/features/block-database/queries/editor-api.ts
@@ -0,0 +1,90 @@
+import { databaseSqlSchema } from '@core/database-sql/catalog';
+import { readDatabaseSql } from '@queries/database-sql/create-database-sql-query';
+import {
+ applyDatabaseOps,
+ databaseDetailQueryOptions,
+} from '@queries/storage/databases';
+import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
+import type { QueryClient } from '@tanstack/solid-query';
+import { err, errAsync, ok, ResultAsync } from 'neverthrow';
+import type {
+ DatabaseApi,
+ DatabaseRowPage,
+ DatabaseTableSchema,
+} from '../../database/core/api';
+import { gridRows } from '../../database/core/grid-cells';
+import { allRecordsView } from '../../database/core/views';
+import type { DatabaseReadFailure } from '../../database/core/write-failure';
+import { rowsByIdStatement } from '../sql';
+import { toViewColumn } from './table-rows';
+
+export function editorTable(table: TableDetail): DatabaseTableSchema {
+ return {
+ id: table.table.id,
+ databaseId: table.table.database_id,
+ name: table.table.name,
+ version: table.table.version,
+ columns: table.columns.map(toViewColumn),
+ };
+}
+
+/** The Macro app's implementation of the same API an embedded host supplies. */
+export function createMacroDatabaseApi(
+ databaseId: string,
+ client: QueryClient
+): DatabaseApi {
+ const detail = () =>
+ ResultAsync.fromPromise(
+ client.fetchQuery(databaseDetailQueryOptions(databaseId)),
+ (): DatabaseReadFailure => ({
+ kind: 'fetch',
+ message: 'Could not load the database schema.',
+ })
+ );
+ return {
+ key: ['macro-database', databaseId],
+ readTable: (id) =>
+ detail().andThen((detail) => {
+ const table = detail.tables.find((table) => table.table.id === id);
+ return table
+ ? ok(editorTable(table))
+ : err({ kind: 'table-unavailable' as const });
+ }),
+ readRows: (request) =>
+ detail().andThen(
+ (detail): ResultAsync<DatabaseRowPage, DatabaseReadFailure> => {
+ const table = detail.tables.find(
+ (table) => table.table.id === request.tableId
+ );
+ if (!table) return errAsync({ kind: 'table-unavailable' });
+ return readDatabaseSql({
+ schema: databaseSqlSchema([{ ...detail, tables: [table] }]),
+ scope: databaseId,
+ ...(request.rowIds
+ ? { sql: rowsByIdStatement(table.sql_name, request.rowIds) }
+ : {
+ view: {
+ ...allRecordsView(table.table),
+ query: request.query,
+ },
+ }),
+ }).andThen(({ catalog, outcome }) =>
+ outcome.truncated
+ ? err({
+ kind: 'fetch' as const,
+ message:
+ 'This query exceeds the row limit. Narrow the filter.',
+ })
+ : ok({
+ rows: gridRows(outcome, catalog, table.columns),
+ tableVersion: table.table.version,
+ })
+ );
+ }
+ ),
+ applyOps: ({ ops, baseVersions }) =>
+ applyDatabaseOps(databaseId, ops, baseVersions).map((results) => ({
+ results,
+ })),
+ };
+}
diff --git a/apps/web/src/features/block-database/queries/forms-usage.test.tsx b/apps/web/src/features/block-database/queries/forms-usage.test.tsx
index 64eaf55ec8..3bc6bf7526 100644
--- a/apps/web/src/features/block-database/queries/forms-usage.test.tsx
+++ b/apps/web/src/features/block-database/queries/forms-usage.test.tsx
@@ -3,7 +3,7 @@ import { render, waitFor } from '@solidjs/testing-library';
import { QueryClientProvider } from '@tanstack/solid-query';
import { okAsync } from 'neverthrow';
import { expect, it, vi } from 'vitest';
-import { tableDeleteConsequence } from '../core/forms-usage';
+import { tableDeleteConsequence } from '../../database/core/forms-usage';
import { useFormsOverTables } from './forms-usage';
// The storage client's imports reach the realtime connection.
diff --git a/apps/web/src/features/block-database/queries/forms-usage.ts b/apps/web/src/features/block-database/queries/forms-usage.ts
index b61c2314c9..61e5c3473d 100644
--- a/apps/web/src/features/block-database/queries/forms-usage.ts
+++ b/apps/web/src/features/block-database/queries/forms-usage.ts
@@ -6,8 +6,8 @@ import {
import type { FilterGroup } from '@service-storage/generated/schemas/filterGroup';
import { useQueries } from '@tanstack/solid-query';
import { type Accessor, createSignal } from 'solid-js';
-import type { ColumnUsage } from '../context/column-usage';
-import type { FormsUsage } from '../core/forms-usage';
+import type { ColumnUsage } from '../../database/context/column-usage';
+import type { FormsUsage } from '../../database/core/forms-usage';
type ListRead = ReturnType<typeof useFormsForDatabaseQuery>;
diff --git a/apps/web/src/features/block-database/queries/options.ts b/apps/web/src/features/block-database/queries/options.ts
index 522464d0d1..d8e745c0a0 100644
--- a/apps/web/src/features/block-database/queries/options.ts
+++ b/apps/web/src/features/block-database/queries/options.ts
@@ -5,9 +5,9 @@ import { databasesKeys } from '@queries/storage/keys';
import type { DatabaseDetail } from '@service-storage/generated/schemas/databaseDetail';
import type { PropertyOption } from '@service-storage/generated/schemas/propertyOption';
import { err, errAsync, ok, type Result, ResultAsync } from 'neverthrow';
-import type { OptionChange } from '../context/option-editing';
-import { inferDatabaseNumber } from '../core/column-inference';
-import type { DatabaseOpFailure } from '../core/write-failure';
+import type { OptionChange } from '../../database/context/option-editing';
+import { inferDatabaseNumber } from '../../database/core/column-inference';
+import type { DatabaseOpFailure } from '../../database/core/write-failure';
import { applyOp, patchDetail } from './detail-cache';
type OptionTarget = {
diff --git a/apps/web/src/features/block-database/queries/rename-database.ts b/apps/web/src/features/block-database/queries/rename-database.ts
index 434daf9928..f5bb165c6b 100644
--- a/apps/web/src/features/block-database/queries/rename-database.ts
+++ b/apps/web/src/features/block-database/queries/rename-database.ts
@@ -14,7 +14,7 @@ import {
import type { CombinedError } from '@urql/core';
import { err, errAsync, ok, type Result, ResultAsync } from 'neverthrow';
import { match } from 'ts-pattern';
-import type { DatabaseEntityFailure } from '../core/write-failure';
+import type { DatabaseEntityFailure } from '../../database/core/write-failure';
/** The slice of the GraphQL client a database rename sends through. */
export type RenameDatabaseClient = {
diff --git a/apps/web/src/features/block-database/queries/reorder-tables.ts b/apps/web/src/features/block-database/queries/reorder-tables.ts
index d1bc66f674..de9bd5df30 100644
--- a/apps/web/src/features/block-database/queries/reorder-tables.ts
+++ b/apps/web/src/features/block-database/queries/reorder-tables.ts
@@ -6,8 +6,8 @@ import {
import { databasesKeys } from '@queries/storage/keys';
import type { DatabaseDetail } from '@service-storage/generated/schemas/databaseDetail';
import { ResultAsync } from 'neverthrow';
-import type { DatabaseSchemaChange } from '../core/column-schema';
-import { createKeyedSerializer } from '../core/keyed-serializer';
+import type { DatabaseSchemaChange } from '../../database/core/column-schema';
+import { createKeyedSerializer } from '../../database/core/keyed-serializer';
function withTableOrder(
detail: DatabaseDetail,
diff --git a/apps/web/src/features/block-database/queries/starter-database.ts b/apps/web/src/features/block-database/queries/starter-database.ts
index 605b9ed3ce..c53b792426 100644
--- a/apps/web/src/features/block-database/queries/starter-database.ts
+++ b/apps/web/src/features/block-database/queries/starter-database.ts
@@ -7,7 +7,7 @@ import { useDatabasesQuery } from '@queries/storage/databases';
import { databasesKeys } from '@queries/storage/keys';
import { storageServiceClient } from '@service-storage/client';
import { useQuery, useQueryClient } from '@tanstack/solid-query';
-import type { DatabaseViewSelection } from '../core/view-selection';
+import type { DatabaseViewSelection } from '../../database/core/view-selection';
/** Mounted inside authenticated app chrome. Provisioning never suspends the app. */
export function useStarterDatabase() {
diff --git a/apps/web/src/features/block-database/queries/table-changes.ts b/apps/web/src/features/block-database/queries/table-changes.ts
index 589552afb7..eb67427e4f 100644
--- a/apps/web/src/features/block-database/queries/table-changes.ts
+++ b/apps/web/src/features/block-database/queries/table-changes.ts
@@ -3,7 +3,7 @@ import { storageServiceClient } from '@service-storage/client';
import type { TableChanges } from '@service-storage/generated/schemas/tableChanges';
import { getGraphqlSoupCacheHost } from '@service-storage/graphql-soup';
import { errAsync, okAsync, ResultAsync } from 'neverthrow';
-import { keyHintChunks, refreshPlan } from '../core/refresh-plan';
+import { keyHintChunks, refreshPlan } from '../../database/core/refresh-plan';
/** What an incremental refresh needs of the journal and the row cache. */
export type TableChangesCapabilities = {
diff --git a/apps/web/src/features/block-database/queries/table-rows.test.tsx b/apps/web/src/features/block-database/queries/table-rows.test.tsx
index dd58391a3c..c8a43f00c9 100644
--- a/apps/web/src/features/block-database/queries/table-rows.test.tsx
+++ b/apps/web/src/features/block-database/queries/table-rows.test.tsx
@@ -29,11 +29,11 @@ import { err, errAsync, ok, okAsync, ResultAsync } from 'neverthrow';
import { type Accessor, createSignal, onCleanup } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { empty, fromValue, mergeMap, pipe } from 'wonka';
-import type { DatabaseRowsSource } from '../context/table-source';
-import type { DatabaseRowMutation } from '../core/table';
-import { allRecordsView } from '../core/views';
-import { createDraftRows } from '../primitives/draft-rows';
-import { createTableController } from '../primitives/table-controller';
+import type { DatabaseRowsSource } from '../../database/context/table-source';
+import type { DatabaseRowMutation } from '../../database/core/table';
+import { allRecordsView } from '../../database/core/views';
+import { createDraftRows } from '../../database/primitives/draft-rows';
+import { createTableController } from '../../database/primitives/table-controller';
import { createDatabaseColumn } from './columns';
function renameDatabaseColumn(params: {
diff --git a/apps/web/src/features/block-database/queries/table-rows.ts b/apps/web/src/features/block-database/queries/table-rows.ts
index 66f66e194f..22add2e708 100644
--- a/apps/web/src/features/block-database/queries/table-rows.ts
+++ b/apps/web/src/features/block-database/queries/table-rows.ts
@@ -35,28 +35,29 @@ import {
ResultAsync,
} from 'neverthrow';
import { type Accessor, createMemo, createSignal, untrack } from 'solid-js';
-import { match, P } from 'ts-pattern';
-import { v7 as uuidv7 } from 'uuid';
import type {
DatabaseRowsSource,
DatabaseWriteResult,
-} from '../context/table-source';
-import { missingOptionLabels, mutationOp } from '../core/cell-ops';
+} from '../../database/context/table-source';
import {
type DatabaseColumnType,
inferDatabaseNumber,
-} from '../core/column-inference';
+} from '../../database/core/column-inference';
import type {
DatabaseCellValue,
DatabaseViewColumn,
-} from '../core/database-view';
-import { gridRows } from '../core/grid-cells';
-import type { DatabaseRow, DatabaseRowMutation } from '../core/table';
+} from '../../database/core/database-view';
+import { gridRows } from '../../database/core/grid-cells';
+import { writeDatabaseRow } from '../../database/core/row-write';
+import type {
+ DatabaseRow,
+ DatabaseRowMutation,
+} from '../../database/core/table';
import type {
DatabaseCellFailure,
DatabaseReadFailure,
DatabaseWriteFailure,
-} from '../core/write-failure';
+} from '../../database/core/write-failure';
import { rowsByIdStatement } from '../sql';
import { patchTableColumn } from './detail-cache';
import {
@@ -104,23 +105,6 @@ function isStaleSchema(
);
}
-/** The service answered and refused: the write certainly did not land. */
-function isDefiniteRefusal(error: DatabaseOpsError): boolean {
- return match(error.code)
- .with(
- P.union(
- 'INVALID_OP',
- 'UNAUTHORIZED',
- 'FORBIDDEN',
- 'NOT_FOUND',
- 'CONFLICT',
- 'GONE'
- ),
- () => true
- )
- .otherwise(() => false);
-}
-
const TABLE_UNAVAILABLE = { kind: 'table-unavailable' } as const;
/** A missing or deleted database means the table is gone; anything else is a failed read. */
@@ -427,15 +411,6 @@ export function createDatabaseRowsSource(props: {
return column?.writable ? ok(column) : err({ kind: 'read-only-column' });
}
- function optionLabelsOf(table: TableDetail, columnId: string): string[] {
- const column = table.columns.find(
- (column) => column.column.id === columnId
- );
- return (column?.definition.property_options ?? []).map((option) =>
- String(option.value.value)
- );
- }
-
/** The base a new column's type is settled against, past the settlements this writer made from it. */
function latestInferenceBase(
inferenceBaseVersion: number | undefined
@@ -610,35 +585,19 @@ export function createDatabaseRowsSource(props: {
// Read the refreshed cache directly; Solid props may notify after fetchQuery resolves.
const table = currentTable();
if (!table) return err(TABLE_UNAVAILABLE);
- const op = mutationOp(tableId, prepared.value, (columnId) =>
- columnForWrite(table, columnId)
+ const written = await writeDatabaseRow(
+ {
+ tableId,
+ columns: table.columns.map(toViewColumn),
+ applyOps: ({ ops }) =>
+ props.applyOps(ops).map((results) => ({ results })),
+ },
+ prepared.value,
+ createOptions
);
- if (op.isErr()) return err(op.error);
- // A label the column lacks becomes an option in the same batch, ahead of the write.
- const newOptions: DatabaseOp[] = createOptions
- ? missingOptionLabels(op.value, (columnId) =>
- optionLabelsOf(table, columnId)
- ).map(({ column, labels }) => ({
- kind: 'column',
- table: tableId,
- column,
- change: {
- kind: 'add_options',
- options: labels.map((label) => ({ id: uuidv7(), label })),
- },
- }))
- : [];
- const applied = await props.applyOps([...newOptions, op.value]);
- if (applied.isErr())
- return err(
- mutation.kind === 'create' && !isDefiniteRefusal(applied.error)
- ? { kind: 'outcome-unknown' }
- : { kind: 'ops', error: applied.error }
- );
- const written = applied.value.at(-1);
- if (written?.kind !== 'rows') return err({ kind: 'unexpected-result' });
- writtenVersion = Math.max(writtenVersion, written.tableVersion);
- props.applyVersions({ [tableId]: written.tableVersion });
+ if (written.isErr()) return written;
+ writtenVersion = Math.max(writtenVersion, written.value.version);
+ props.applyVersions({ [tableId]: written.value.version });
// New options live in the schema; read it again in the background
// so they show as options without suspending the grid.
if (createOptions)
@@ -646,13 +605,7 @@ export function createDatabaseRowsSource(props: {
queryKey: detailKey,
exact: true,
});
- return ok({
- insertedRowIds: match(written.change)
- .with({ kind: 'inserted' }, ({ rows }) => rows)
- .with({ kind: 'updated' }, { kind: 'deleted' }, () => [])
- .exhaustive(),
- version: written.tableVersion,
- });
+ return written;
}
async function write(
diff --git a/apps/web/src/features/block-database/queries/transfer.ts b/apps/web/src/features/block-database/queries/transfer.ts
index ce52111cd8..d435de2111 100644
--- a/apps/web/src/features/block-database/queries/transfer.ts
+++ b/apps/web/src/features/block-database/queries/transfer.ts
@@ -10,14 +10,14 @@ import type { ImportTable } from '@service-storage/generated/schemas/importTable
import type { Table } from '@service-storage/generated/schemas/table';
import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
import { err, ok, type ResultAsync } from 'neverthrow';
-import { encodeDatabaseCsv } from '../core/csv';
-import { relatedRowIds } from '../core/database-relations';
+import { encodeDatabaseCsv } from '../../database/core/csv';
+import { relatedRowIds } from '../../database/core/database-relations';
import type {
DatabaseCellValue,
DatabaseViewColumn,
-} from '../core/database-view';
-import { gridRows } from '../core/grid-cells';
-import { formatCellValue } from '../core/table';
+} from '../../database/core/database-view';
+import { gridRows } from '../../database/core/grid-cells';
+import { formatCellValue } from '../../database/core/table';
import { tableRowsStatement } from '../sql';
import { toViewColumn } from './table-rows';
diff --git a/apps/web/src/features/block-database/queries/trash-database.ts b/apps/web/src/features/block-database/queries/trash-database.ts
index 976ff2b80c..696cfd2bdd 100644
--- a/apps/web/src/features/block-database/queries/trash-database.ts
+++ b/apps/web/src/features/block-database/queries/trash-database.ts
@@ -9,7 +9,7 @@ import {
import type { CombinedError } from '@urql/core';
import { err, ok, type Result, ResultAsync } from 'neverthrow';
import { match } from 'ts-pattern';
-import type { DatabaseEntityFailure } from '../core/write-failure';
+import type { DatabaseEntityFailure } from '../../database/core/write-failure';
/** The slice of the GraphQL client a database trash sends through. */
export type TrashDatabaseClient = {
diff --git a/apps/web/src/features/block-database/queries/view-creation.ts b/apps/web/src/features/block-database/queries/view-creation.ts
index 784d478cff..536fc9888a 100644
--- a/apps/web/src/features/block-database/queries/view-creation.ts
+++ b/apps/web/src/features/block-database/queries/view-creation.ts
@@ -3,10 +3,10 @@ import { databaseDetailQueryOptions } from '@queries/storage/databases';
import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';
import { okAsync, ResultAsync } from 'neverthrow';
import { v7 as uuidv7 } from 'uuid';
-import type { DatabaseViewColumn } from '../core/database-view';
-import type { NewView, ViewCreation } from '../core/view-creation';
-import { boardLayout } from '../core/views';
-import type { DatabaseOpFailure } from '../core/write-failure';
+import type { DatabaseViewColumn } from '../../database/core/database-view';
+import type { NewView, ViewCreation } from '../../database/core/view-creation';
+import { boardLayout } from '../../database/core/views';
+import type { DatabaseOpFailure } from '../../database/core/write-failure';
import { createBoardWithStatusColumn, createDatabaseView } from './views';
/** Mint the whole intent once. A retry checks for a committed view before writing again. */
diff --git a/apps/web/src/features/block-database/queries/views.ts b/apps/web/src/features/block-database/queries/views.ts
index de4860d3ea..e5dfeb17ab 100644
--- a/apps/web/src/features/block-database/queries/views.ts
+++ b/apps/web/src/features/block-database/queries/views.ts
@@ -1,4 +1,4 @@
-import type { CardMoved, ViewChange } from '../core/view-state';
+import type { CardMoved, ViewChange } from '../../database/core/view-state';
/** A table's typed views and a board's card places, written as ops and shown in the cached detail ahead of the answer. */
import type { DatabaseOp } from '@core/database-sql/generated/types';
@@ -21,11 +21,11 @@ import {
boardWithStatusColumn,
type MintedStatusColumn,
newBoardWithStatusColumn,
-} from '../core/board-grouping';
-import type { CardMove } from '../core/board-moves';
-import type { DatabaseViewColumn } from '../core/database-view';
-import { createKeyedSerializer } from '../core/keyed-serializer';
-import type { DatabaseOpFailure } from '../core/write-failure';
+} from '../../database/core/board-grouping';
+import type { CardMove } from '../../database/core/board-moves';
+import type { DatabaseViewColumn } from '../../database/core/database-view';
+import { createKeyedSerializer } from '../../database/core/keyed-serializer';
+import type { DatabaseOpFailure } from '../../database/core/write-failure';
import { applyOp, isResult, patchViews } from './detail-cache';
import { databaseViewKeys } from './keys';
diff --git a/apps/web/src/features/block-database/views/database-page-actions.test.tsx b/apps/web/src/features/block-database/views/database-page-actions.test.tsx
index 2113914993..2992321368 100644
--- a/apps/web/src/features/block-database/views/database-page-actions.test.tsx
+++ b/apps/web/src/features/block-database/views/database-page-actions.test.tsx
@@ -1,4 +1,3 @@
-import { toast } from '@core/component/Toast/Toast';
import type { DatabaseDetail } from '@service-storage/generated/schemas/databaseDetail';
import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
import {
@@ -11,15 +10,16 @@ import {
} from '@solidjs/testing-library';
import { errAsync, okAsync, type ResultAsync } from 'neverthrow';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { DatabaseTitle } from '../components/database-title';
-import type { DatabaseEntityFailure } from '../core/write-failure';
+import { toast } from '../../../lib/core/component/Toast/Toast';
+import { DatabaseTitle } from '../../database/components/database-title';
+import type { DatabaseEntityFailure } from '../../database/core/write-failure';
import { DatabasePageActions } from './database-page-actions';
const mocks = vi.hoisted(() => ({
download: vi.fn(),
csv: vi.fn(),
}));
-vi.mock('@core/component/Toast/Toast', () => ({
+vi.mock('../../../lib/core/component/Toast/Toast', () => ({
toast: { failure: vi.fn(), success: vi.fn() },
}));
vi.mock('@filesystem/download', () => ({ downloadFile: mocks.download }));
diff --git a/apps/web/src/features/block-database/views/database-page-actions.tsx b/apps/web/src/features/block-database/views/database-page-actions.tsx
index 0a6e1b816d..77224ea6cf 100644
--- a/apps/web/src/features/block-database/views/database-page-actions.tsx
+++ b/apps/web/src/features/block-database/views/database-page-actions.tsx
@@ -1,4 +1,3 @@
-import { toast } from '@core/component/Toast/Toast';
import { downloadFile } from '@filesystem/download';
import CaretRightIcon from '@phosphor/caret-right.svg';
import DotsThreeIcon from '@phosphor/dots-three.svg';
@@ -13,19 +12,20 @@ import { DeleteDialog } from '@ui/components/DeleteDialog';
import { Dropdown } from '@ui/components/Dropdown';
import { errAsync, ResultAsync } from 'neverthrow';
import { createSignal, Show } from 'solid-js';
-import { CsvImportDialog } from '../components/csv-import-dialog';
+import { toast } from '../../../lib/core/component/Toast/Toast';
+import { CsvImportDialog } from '../../database/components/csv-import-dialog';
import {
type DatabaseCsv,
type DatabaseCsvFailure,
databaseCsvMessage,
MAX_CSV_BYTES,
parseDatabaseCsv,
-} from '../core/csv';
-import { isDatabaseNameTaken } from '../core/property-creation';
+} from '../../database/core/csv';
+import { isDatabaseNameTaken } from '../../database/core/property-creation';
import {
type DatabaseEntityFailure,
databaseEntityMessage,
-} from '../core/write-failure';
+} from '../../database/core/write-failure';
import {
exportDatabaseTableCsv,
importDatabaseTable,
diff --git a/apps/web/src/features/block-form/form-condition-editor.tsx b/apps/web/src/features/block-form/form-condition-editor.tsx
index 5128cc199c..c4aae573ed 100644
--- a/apps/web/src/features/block-form/form-condition-editor.tsx
+++ b/apps/web/src/features/block-form/form-condition-editor.tsx
@@ -2,9 +2,10 @@
* App adapter: a gate's rules, edited with the database grid's own filter
* editor over the questions before the gate (RFC 02 §3).
*/
-import { FilterPanel } from '@block-database/components/database-view-filters';
-import type { DatabaseViewColumn } from '@block-database/core/database-view';
+
import { match } from 'ts-pattern';
+import { FilterPanel } from '../database/components/database-view-filters';
+import type { DatabaseViewColumn } from '../database/core/database-view';
import type { ConditionEditorProps } from './context/form-context';
import type { FormColumn } from './core/form-model';
diff --git a/apps/web/src/features/block-form/form-context-production.tsx b/apps/web/src/features/block-form/form-context-production.tsx
index aece9997e6..06a0758049 100644
--- a/apps/web/src/features/block-form/form-context-production.tsx
+++ b/apps/web/src/features/block-form/form-context-production.tsx
@@ -6,7 +6,6 @@
*/
import { createPublicBookingSource } from '@app/features/scheduling/queries/public';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import type { DatabaseRelatedDestination } from '@block-database/core/database-relations';
import { DatabaseMentionValue } from '@block-database/database-mentions';
import { exportDatabaseTableCsv } from '@block-database/queries/transfer';
import { toast } from '@core/component/Toast/Toast';
@@ -22,6 +21,7 @@ import { getEntityGraphqlClient } from '@service-storage/graphql-soup';
import { useNavigate } from '@solidjs/router';
import { confirmDialog } from '@ui';
import { errAsync, ResultAsync } from 'neverthrow';
+import type { DatabaseRelatedDestination } from '../database/core/database-relations';
import type { FormContext, FormWriteFailure } from './context/form-context';
import { FormConditionEditor } from './form-condition-editor';
import { FormEditors } from './form-editors';
diff --git a/apps/web/src/features/block-form/form-responses-grid.tsx b/apps/web/src/features/block-form/form-responses-grid.tsx
index 6b99086b5b..d409311313 100644
--- a/apps/web/src/features/block-form/form-responses-grid.tsx
+++ b/apps/web/src/features/block-form/form-responses-grid.tsx
@@ -5,12 +5,12 @@
* access rule, so the grid edits as it does on the database page.
*/
import { DatabaseGrid } from '@block-database/component/DatabaseGrid';
-import type { DatabaseRelatedDestination } from '@block-database/core/database-relations';
-import { allRecordsView } from '@block-database/core/views';
import { useDatabaseDetailQuery } from '@queries/storage/databases';
import { useDatabaseTableChangedSync } from '@queries/storage/databases-sync';
import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';
import { createSignal, Show } from 'solid-js';
+import type { DatabaseRelatedDestination } from '../database/core/database-relations';
+import { allRecordsView } from '../database/core/views';
export function FormResponsesGrid(props: {
databaseId: string;
diff --git a/apps/web/src/features/block-form/queries/column-writes.ts b/apps/web/src/features/block-form/queries/column-writes.ts
index 4bdd619954..e40736c2ec 100644
--- a/apps/web/src/features/block-form/queries/column-writes.ts
+++ b/apps/web/src/features/block-form/queries/column-writes.ts
@@ -3,10 +3,6 @@
* `POST /databases/{id}/ops`. The forms service never proxies schema edits.
*/
-import {
- columnSchemaMessage,
- type DatabaseColumnKind,
-} from '@block-database/core/column-schema';
import { convertDatabaseColumn } from '@block-database/queries/columns';
import type {
DatabaseOp,
@@ -15,6 +11,10 @@ import type {
import { applyDatabaseOps } from '@queries/storage/databases';
import type { DatabaseOpsError } from '@service-storage/databases';
import type { ResultAsync } from 'neverthrow';
+import {
+ columnSchemaMessage,
+ type DatabaseColumnKind,
+} from '../../database/core/column-schema';
import type {
FormColumnWrites,
FormWriteFailure,
diff --git a/apps/web/src/features/database-query/components/answer-value.tsx b/apps/web/src/features/database-query/components/answer-value.tsx
index 957ad8206b..32248095ed 100644
--- a/apps/web/src/features/database-query/components/answer-value.tsx
+++ b/apps/web/src/features/database-query/components/answer-value.tsx
@@ -1,5 +1,5 @@
-import { OptionPill } from '@app/features/block-database/components/select-pill';
import { For, Match, Switch } from 'solid-js';
+import { OptionPill } from '../../database/components/select-pill';
import type { AnswerRenderers } from '../context/answer-display';
import {
type ReferenceNames,
diff --git a/apps/web/src/features/database-query/context/answer-display.tsx b/apps/web/src/features/database-query/context/answer-display.tsx
index 228c12bea1..f9d0db623e 100644
--- a/apps/web/src/features/database-query/context/answer-display.tsx
+++ b/apps/web/src/features/database-query/context/answer-display.tsx
@@ -1,5 +1,5 @@
-import type { DatabaseEntityType } from '@app/features/block-database/core/column-inference';
import { type Accessor, createContext, type JSX, useContext } from 'solid-js';
+import type { DatabaseEntityType } from '../../database/core/column-inference';
import type { ReferenceNames } from '../core/answer-cell';
import type { QueryAnswer } from '../core/query';
diff --git a/apps/web/src/features/database-query/core/answer-cell.ts b/apps/web/src/features/database-query/core/answer-cell.ts
index 5aa83803fb..c1dfc339f1 100644
--- a/apps/web/src/features/database-query/core/answer-cell.ts
+++ b/apps/web/src/features/database-query/core/answer-cell.ts
@@ -1,10 +1,10 @@
-import type { DatabaseEntityType } from '@app/features/block-database/core/column-inference';
import type { AnswerColumn, AnswerOption } from '@core/database-sql/answer';
import type { Cell, EntityKind } from '@core/database-sql/generated/types';
import { formatTime } from '@core/util/date';
import { markdownToPlainText } from '@macro-inc/lexical-core/utils/parsers';
import { formatDate } from '@property/utils/formatting';
import { match } from 'ts-pattern';
+import type { DatabaseEntityType } from '../../database/core/column-inference';
import { formatQueryValue } from './query';
/** What one result value shows, drawn with the database grid's own pieces. */
diff --git a/apps/web/src/features/database-query/tests/plain-answer-display.tsx b/apps/web/src/features/database-query/tests/plain-answer-display.tsx
index fc0f31a3da..f439202407 100644
--- a/apps/web/src/features/database-query/tests/plain-answer-display.tsx
+++ b/apps/web/src/features/database-query/tests/plain-answer-display.tsx
@@ -1,6 +1,6 @@
-import { DatabaseMentionPlaceholder } from '@app/features/block-database/components/database-mention-label';
import { markdownToPlainText } from '@macro-inc/lexical-core/utils/parsers';
import type { JSX } from 'solid-js';
+import { DatabaseMentionPlaceholder } from '../../database/components/database-mention-label';
import {
type AnswerDisplay,
AnswerDisplayProvider,
diff --git a/apps/web/src/features/database/README.md b/apps/web/src/features/database/README.md
new file mode 100644
index 0000000000..b811e161c7
--- /dev/null
+++ b/apps/web/src/features/database/README.md
@@ -0,0 +1,75 @@
+# Shared database editor
+
+`DatabaseProvider` owns one editor controller. A host supplies `DatabaseApi` with a
+stable cache key, schema reads, paginated row reads, and atomic operation batches.
+`DatabaseRecords` supplies the standard column controls, grid, board and record
+panel. The host supplies presentation slots and navigation when needed.
+
+```tsx
+const [view, setView] = createSignal<DatabaseViewState>({
+ query: { filter: null },
+ layout: { kind: 'table', columns: [] },
+});
+
+<DatabaseProvider
+ api={api}
+ tableId={tableId}
+ view={view()}
+ capabilities={{ editRows: canEdit, editColumns: canEditSchema }}
+>
+ <DatabaseRecords
+ view={view()}
+ stored={false}
+ onViewChange={(change) => setView((view) => ({ ...view, ...change }))}
+ renderMentionPicker={HostMentionPicker}
+ />
+</DatabaseProvider>
+```
+
+Mount under the application's `QueryClientProvider`, or supply one for a standalone
+surface. Remount the database provider when its API identity or table changes;
+views and permission changes are reactive within that lifetime. `useDatabase()`
+exposes the controller to other controls inside this editor. Small presentation
+components remain usable with props and without this context.
+
+## API semantics
+
+- `readTable` returns normalized editor columns, with names, types, options and
+ protections. Hosts convert their transport DTOs at the adapter boundary.
+- `readRows` applies the requested filter and sort before pagination. Every page
+ carries its table version. The shared source restarts inconsistent reads rather
+ than combining pages from different versions. `rowIds` reads retained records
+ outside the active filter, so an open record remains available.
+- `applyOps` uses the existing `DatabaseOp` protocol and optional `baseVersions`.
+ It must commit the batch atomically. The shared row writer adds missing options
+ in the same batch and distinguishes a refused insert from an unknown outcome.
+- A successful commit remains successful if a subsequent refresh fails. The
+ queries own refresh errors; retrying the mutation could duplicate an insert.
+
+The API does not require SQL reads, a Macro database entity, Soup, app block
+context, or a particular URL layout. `DatabaseApi.key` must identify the host and
+resource within the query cache. Authentication and resource authorization belong
+to the host's API/service; UI capabilities only determine which controls appear.
+
+## Host capabilities
+
+`editRows` and `editColumns` enable their respective controls. Optional record-view
+props supply persisted board positions, conversion previews, relationships,
+presence, and stored-view changes. Omit an unsupported action. A board can render
+without a position writer; it cannot offer card moves that pretend to persist.
+View preferences in the example are local; hosts that save views pass their own
+view state and authorized persistence callback. Shared filter, sort, toolbar and
+view components are in `components/`.
+
+The Macro app's `DatabaseGrid` supplies an optimized `DatabaseDataSource` to the
+same provider, preserving SQL caching, incremental updates and first-value type
+inference. Normal API hosts use the provider's built-in paginated source. Both
+paths share row-op construction and the schema controller. The app keeps its
+sharing, navigation, Forms integration and concrete network clients in
+`features/block-database/`.
+
+The API-only browser fixture is in
+`../block-database/browser-test/api.tsx`. It exercises pagination, row edits,
+column creation, permission changes and board rendering without app providers
+beyond the query client. CRM wiring belongs in the CRM feature after it rebases
+on this extraction.
diff --git a/apps/web/src/features/database/components/add-column-button.tsx b/apps/web/src/features/database/components/add-column-button.tsx
new file mode 100644
index 0000000000..6ada7e4437
--- /dev/null
+++ b/apps/web/src/features/database/components/add-column-button.tsx
@@ -0,0 +1,50 @@
+import PlusIcon from '@phosphor/plus.svg';
+import { Button } from '@ui/components/Button';
+import { createSignal, Show } from 'solid-js';
+import {
+ columnSchemaMessage,
+ type DatabaseSchemaChange,
+} from '../core/column-schema';
+
+/** Shared add-column control; the host owns schema persistence. */
+export function AddColumnButton(props: {
+ create(): DatabaseSchemaChange<string>;
+ label?: string;
+ onCreated?: (columnId: string) => boolean;
+}) {
+ const [pending, setPending] = createSignal(false);
+ const [error, setError] = createSignal('');
+ async function add() {
+ if (pending()) return;
+ setPending(true);
+ setError('');
+ const created = await props.create();
+ setPending(false);
+ created.match(
+ (id) => props.onCreated?.(id),
+ (error) => setError(columnSchemaMessage(error))
+ );
+ }
+ return (
+ <div class="relative">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={pending()}
+ aria-label={props.label ?? 'Add column'}
+ onClick={() => void add()}
+ >
+ <PlusIcon class="size-3.5" />
+ {props.label ?? 'Add column'}
+ </Button>
+ <Show when={error()}>
+ <span
+ role="alert"
+ class="absolute top-full right-0 z-2 w-52 rounded-md border border-edge-muted bg-panel p-2 text-xs text-failure-ink shadow-md"
+ >
+ {error()}
+ </span>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-database/components/board-card-title-picker.test.tsx b/apps/web/src/features/database/components/board-card-title-picker.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/board-card-title-picker.test.tsx
rename to apps/web/src/features/database/components/board-card-title-picker.test.tsx
diff --git a/apps/web/src/features/block-database/components/board-card-title-picker.tsx b/apps/web/src/features/database/components/board-card-title-picker.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/board-card-title-picker.tsx
rename to apps/web/src/features/database/components/board-card-title-picker.tsx
diff --git a/apps/web/src/features/block-database/components/board-menu.test.tsx b/apps/web/src/features/database/components/board-menu.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/board-menu.test.tsx
rename to apps/web/src/features/database/components/board-menu.test.tsx
diff --git a/apps/web/src/features/block-database/components/board-menu.tsx b/apps/web/src/features/database/components/board-menu.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/board-menu.tsx
rename to apps/web/src/features/database/components/board-menu.tsx
diff --git a/apps/web/src/features/block-database/components/cell-focus.ts b/apps/web/src/features/database/components/cell-focus.ts
similarity index 100%
rename from apps/web/src/features/block-database/components/cell-focus.ts
rename to apps/web/src/features/database/components/cell-focus.ts
diff --git a/apps/web/src/features/block-database/components/column-type-menu.test.tsx b/apps/web/src/features/database/components/column-type-menu.test.tsx
similarity index 98%
rename from apps/web/src/features/block-database/components/column-type-menu.test.tsx
rename to apps/web/src/features/database/components/column-type-menu.test.tsx
index ff55d6a526..9b2eb89480 100644
--- a/apps/web/src/features/block-database/components/column-type-menu.test.tsx
+++ b/apps/web/src/features/database/components/column-type-menu.test.tsx
@@ -16,7 +16,7 @@ import type {
import type { DatabaseViewColumn } from '../core/database-view';
import { DatabaseColumnHeader } from './database-column-header';
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('../../../lib/core/mobile/isMobile', () => ({ isMobile: () => false }));
const column: DatabaseViewColumn = {
id: 'price',
diff --git a/apps/web/src/features/block-database/components/column-type-menu.tsx b/apps/web/src/features/database/components/column-type-menu.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/column-type-menu.tsx
rename to apps/web/src/features/database/components/column-type-menu.tsx
diff --git a/apps/web/src/features/block-database/components/create-table-dialog.tsx b/apps/web/src/features/database/components/create-table-dialog.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/create-table-dialog.tsx
rename to apps/web/src/features/database/components/create-table-dialog.tsx
diff --git a/apps/web/src/features/block-database/components/csv-import-dialog.test.tsx b/apps/web/src/features/database/components/csv-import-dialog.test.tsx
similarity index 97%
rename from apps/web/src/features/block-database/components/csv-import-dialog.test.tsx
rename to apps/web/src/features/database/components/csv-import-dialog.test.tsx
index da5d9b8764..bddc030cb1 100644
--- a/apps/web/src/features/block-database/components/csv-import-dialog.test.tsx
+++ b/apps/web/src/features/database/components/csv-import-dialog.test.tsx
@@ -10,7 +10,7 @@ import { createSignal, Show } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CsvImportDialog } from './csv-import-dialog';
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('../../../lib/core/mobile/isMobile', () => ({ isMobile: () => false }));
afterEach(cleanup);
const data = { columns: ['Customer', 'Postal code'], rows: [['Ada', '00123']] };
diff --git a/apps/web/src/features/block-database/components/csv-import-dialog.tsx b/apps/web/src/features/database/components/csv-import-dialog.tsx
similarity index 98%
rename from apps/web/src/features/block-database/components/csv-import-dialog.tsx
rename to apps/web/src/features/database/components/csv-import-dialog.tsx
index cc708e5328..faafd31179 100644
--- a/apps/web/src/features/block-database/components/csv-import-dialog.tsx
+++ b/apps/web/src/features/database/components/csv-import-dialog.tsx
@@ -1,4 +1,3 @@
-import type { ResultError } from '@core/util/result';
import type { DatabaseSchemaErrorCode } from '@service-storage/databases';
import type { ImportTable } from '@service-storage/generated/schemas/importTable';
import { Button } from '@ui/components/Button';
@@ -8,6 +7,7 @@ import { Panel } from '@ui/components/Panel';
import type { ResultAsync } from 'neverthrow';
import { createSignal, For, Show } from 'solid-js';
import { v7 as uuidv7 } from 'uuid';
+import type { ResultError } from '../../../lib/core/util/result';
import { csvImportMessage, type DatabaseCsv } from '../core/csv';
export function CsvImportDialog(props: {
diff --git a/apps/web/src/features/block-database/components/database-board.drag.test.tsx b/apps/web/src/features/database/components/database-board.drag.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-board.drag.test.tsx
rename to apps/web/src/features/database/components/database-board.drag.test.tsx
diff --git a/apps/web/src/features/block-database/components/database-board.test.tsx b/apps/web/src/features/database/components/database-board.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-board.test.tsx
rename to apps/web/src/features/database/components/database-board.test.tsx
index ebb9a4a058..77208aeac7 100644
--- a/apps/web/src/features/block-database/components/database-board.test.tsx
+++ b/apps/web/src/features/database/components/database-board.test.tsx
@@ -1,4 +1,3 @@
-import type { LaneKey } from '@core/database-sql/generated/types';
import type { DatabaseOpsError } from '@service-storage/databases';
import {
cleanup,
@@ -11,6 +10,7 @@ import {
import { err, ok, okAsync, type Result } from 'neverthrow';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { LaneKey } from '../../../lib/core/database-sql/generated/types';
import { OptionEditingContext } from '../context/option-editing';
import type { DatabaseViewColumn } from '../core/database-view';
import type { DatabaseRow } from '../core/table';
diff --git a/apps/web/src/features/block-database/components/database-board.tsx b/apps/web/src/features/database/components/database-board.tsx
similarity index 98%
rename from apps/web/src/features/block-database/components/database-board.tsx
rename to apps/web/src/features/database/components/database-board.tsx
index da30981b30..f0e8bc3513 100644
--- a/apps/web/src/features/block-database/components/database-board.tsx
+++ b/apps/web/src/features/database/components/database-board.tsx
@@ -1,5 +1,3 @@
-import type { Board, LaneKey } from '@core/database-sql/generated/types';
-import { isEditableInput } from '@core/util/isEditableInput';
import OpenIcon from '@phosphor/arrow-square-out.svg';
import CaretDownIcon from '@phosphor/caret-down.svg';
import CheckIcon from '@phosphor/check.svg';
@@ -28,6 +26,11 @@ import {
KanbanHandle,
KanbanLane,
} from '../../../components/kanban/kanban';
+import type {
+ Board,
+ LaneKey,
+} from '../../../lib/core/database-sql/generated/types';
+import { isEditableInput } from '../../../lib/core/util/isEditableInput';
import { useOptionEditing } from '../context/option-editing';
import {
type DatabaseEntityType,
@@ -84,7 +87,7 @@ type DatabaseBoardProps = {
createComplete?: (intentId: string) => boolean;
onOpen: (rowId: string) => void;
/** A card dropped into `lane` in front of `next`, or last there without one. */
- onMove: (rowId: string, lane: LaneKey, next?: string) => void;
+ onMove?: (rowId: string, lane: LaneKey, next?: string) => void;
/** The lanes, every one, in their new order. */
onLaneOrderChange?: (order: LaneKey[]) => void;
onHideLane?: (lane: LaneKey) => void;
@@ -152,7 +155,8 @@ export function DatabaseBoard(props: DatabaseBoardProps) {
const newButtons = new Map<string, HTMLElement>();
const titleField = () => cardTitleColumn(props.layout, props.columns);
const canSetTitle = () => isWritableText(titleField());
- const canMove = () => props.canEdit && props.groupColumn.writable;
+ const canMove = () =>
+ props.canEdit && props.groupColumn.writable && !!props.onMove;
const isSaving = (draft: CardDraft) =>
draft.saving || Boolean(props.createPending?.(draft.id));
const laneDrafts = (lane: string) =>
@@ -222,7 +226,7 @@ export function DatabaseBoard(props: DatabaseBoardProps) {
function move(rowId: string, lane: BoardGroup, next?: string) {
const row = props.rows.find((row) => row.rowId === rowId);
if (!row || !canMove()) return;
- props.onMove(rowId, lane.lane, next);
+ props.onMove?.(rowId, lane.lane, next);
setAnnouncement(`${cellTitle(row, titleField())} moved to ${lane.label}.`);
}
function reorder(from: string, to: string, edge?: 'before' | 'after') {
@@ -283,7 +287,7 @@ export function DatabaseBoard(props: DatabaseBoardProps) {
drafts={laneDrafts(group().key)}
canSetTitle={canSetTitle()}
titlePlaceholder={titleField()?.name ?? 'Record title'}
- acceptsRecords={props.canEdit && props.groupColumn.writable}
+ acceptsRecords={canMove()}
canMove={canMove()}
isSaving={isSaving}
onStartDraft={() => startDraft(group().key)}
diff --git a/apps/web/src/features/block-database/components/database-column-header.test.tsx b/apps/web/src/features/database/components/database-column-header.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-column-header.test.tsx
rename to apps/web/src/features/database/components/database-column-header.test.tsx
index 8c335c5ef7..4532270ee3 100644
--- a/apps/web/src/features/block-database/components/database-column-header.test.tsx
+++ b/apps/web/src/features/database/components/database-column-header.test.tsx
@@ -13,7 +13,7 @@ import { OptionEditingContext } from '../context/option-editing';
import type { DatabaseViewColumn } from '../core/database-view';
import { DatabaseColumnHeader } from './database-column-header';
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('../../../lib/core/mobile/isMobile', () => ({ isMobile: () => false }));
const column: DatabaseViewColumn = {
id: 'name',
name: 'Name',
diff --git a/apps/web/src/features/block-database/components/database-column-header.tsx b/apps/web/src/features/database/components/database-column-header.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-column-header.tsx
rename to apps/web/src/features/database/components/database-column-header.tsx
index 2dd7491a1e..ab68bc3bcb 100644
--- a/apps/web/src/features/block-database/components/database-column-header.tsx
+++ b/apps/web/src/features/database/components/database-column-header.tsx
@@ -1,8 +1,3 @@
-import {
- ContextMenuContent,
- MenuItem,
- MenuSeparator,
-} from '@core/component/ContextMenu';
import { ContextMenu } from '@kobalte/core/context-menu';
import { Popover } from '@kobalte/core/popover';
import ArrowDownIcon from '@phosphor/arrow-down.svg';
@@ -23,6 +18,11 @@ import { Dropdown } from '@ui/components/Dropdown';
import type { JSX } from 'solid-js';
import { createSignal, createUniqueId, For, onCleanup, Show } from 'solid-js';
import { match } from 'ts-pattern';
+import {
+ ContextMenuContent,
+ MenuItem,
+ MenuSeparator,
+} from '../../../lib/core/component/ContextMenu';
import { useColumnUsage } from '../context/column-usage';
import { useOptionEditing } from '../context/option-editing';
import {
diff --git a/apps/web/src/features/block-database/components/database-load-state.tsx b/apps/web/src/features/database/components/database-load-state.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-load-state.tsx
rename to apps/web/src/features/database/components/database-load-state.tsx
diff --git a/apps/web/src/features/block-database/components/database-mention-label.tsx b/apps/web/src/features/database/components/database-mention-label.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-mention-label.tsx
rename to apps/web/src/features/database/components/database-mention-label.tsx
diff --git a/apps/web/src/features/block-database/components/database-relation-cell.test.tsx b/apps/web/src/features/database/components/database-relation-cell.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-relation-cell.test.tsx
rename to apps/web/src/features/database/components/database-relation-cell.test.tsx
diff --git a/apps/web/src/features/block-database/components/database-relation-cell.tsx b/apps/web/src/features/database/components/database-relation-cell.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-relation-cell.tsx
rename to apps/web/src/features/database/components/database-relation-cell.tsx
diff --git a/apps/web/src/features/block-database/components/database-search.test.tsx b/apps/web/src/features/database/components/database-search.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-search.test.tsx
rename to apps/web/src/features/database/components/database-search.test.tsx
diff --git a/apps/web/src/features/block-database/components/database-search.tsx b/apps/web/src/features/database/components/database-search.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-search.tsx
rename to apps/web/src/features/database/components/database-search.tsx
diff --git a/apps/web/src/features/block-database/components/database-table-notices.tsx b/apps/web/src/features/database/components/database-table-notices.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-table-notices.tsx
rename to apps/web/src/features/database/components/database-table-notices.tsx
diff --git a/apps/web/src/features/block-database/components/database-table.test.tsx b/apps/web/src/features/database/components/database-table.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-table.test.tsx
rename to apps/web/src/features/database/components/database-table.test.tsx
index f049b1806f..e64ecb3cb9 100644
--- a/apps/web/src/features/block-database/components/database-table.test.tsx
+++ b/apps/web/src/features/database/components/database-table.test.tsx
@@ -10,18 +10,18 @@ import userEvent from '@testing-library/user-event';
import { okAsync } from 'neverthrow';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { GridCell } from '../component/GridCell';
import type { DatabaseViewColumn } from '../core/database-view';
import type { DatabaseRow } from '../core/table';
import { DatabaseTableView as DatabaseTable } from '../views/database-table-view';
import type { DatabaseTableControls } from './database-table';
+import { GridCell } from './grid-cell';
// JSDOM has no intersection observer to drive the date selector's focus.
vi.mock('@property/utils/focus', () => ({
useSearchInputFocus: (input: () => HTMLElement | undefined) =>
setTimeout(() => input()?.focus(), 100),
}));
-vi.mock('@core/user', () => ({
+vi.mock('../../../lib/core/user/index', () => ({
tryMacroId: (id: string) => (id.startsWith('macro|') ? id : undefined),
macroIdToEmail: (id: string) => id.slice(6),
getDisplayNameParts: (id: string | undefined) =>
diff --git a/apps/web/src/features/block-database/components/database-table.tsx b/apps/web/src/features/database/components/database-table.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-table.tsx
rename to apps/web/src/features/database/components/database-table.tsx
index 3ac1f19568..951031d993 100644
--- a/apps/web/src/features/block-database/components/database-table.tsx
+++ b/apps/web/src/features/database/components/database-table.tsx
@@ -1,14 +1,3 @@
-import {
- ContextMenuContent,
- MenuItem,
- MenuSeparator,
-} from '@core/component/ContextMenu';
-import {
- getDisplayNameParts,
- getInitials,
- macroIdToEmail,
- tryMacroId,
-} from '@core/user';
import { ContextMenu } from '@kobalte/core/context-menu';
import ArrowSquareOutIcon from '@phosphor/arrow-square-out.svg';
import CopyIcon from '@phosphor/copy.svg';
@@ -33,6 +22,17 @@ import { createHorizontalReorder } from '../../../components/drag-drop/create-ho
import { createReorderItem } from '../../../components/drag-drop/create-reorder';
import { DragSessionSensors } from '../../../components/drag-drop/drag-session-sensors';
import { InsertionLine } from '../../../components/drag-drop/insertion-line';
+import {
+ ContextMenuContent,
+ MenuItem,
+ MenuSeparator,
+} from '../../../lib/core/component/ContextMenu';
+import {
+ getDisplayNameParts,
+ getInitials,
+ macroIdToEmail,
+ tryMacroId,
+} from '../../../lib/core/user/index';
import type {
DatabaseColumnCastsSource,
DatabaseColumnConversion,
diff --git a/apps/web/src/features/block-database/components/database-title.test.tsx b/apps/web/src/features/database/components/database-title.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/database-title.test.tsx
rename to apps/web/src/features/database/components/database-title.test.tsx
diff --git a/apps/web/src/features/block-database/components/database-title.tsx b/apps/web/src/features/database/components/database-title.tsx
similarity index 94%
rename from apps/web/src/features/block-database/components/database-title.tsx
rename to apps/web/src/features/database/components/database-title.tsx
index 798924aba5..999282337b 100644
--- a/apps/web/src/features/block-database/components/database-title.tsx
+++ b/apps/web/src/features/database/components/database-title.tsx
@@ -1,5 +1,5 @@
-import { InlineTitleEditor } from '@core/component/InlineTitleEditor';
import { onCleanup, onMount, Show } from 'solid-js';
+import { InlineTitleEditor } from '../../../lib/core/component/InlineTitleEditor';
/** The split header's database name, edited in place by editors. */
export function DatabaseTitle(props: {
diff --git a/apps/web/src/features/block-database/components/database-toolbar.test.tsx b/apps/web/src/features/database/components/database-toolbar.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-toolbar.test.tsx
rename to apps/web/src/features/database/components/database-toolbar.test.tsx
index 2880b85373..fdadec63ff 100644
--- a/apps/web/src/features/block-database/components/database-toolbar.test.tsx
+++ b/apps/web/src/features/database/components/database-toolbar.test.tsx
@@ -12,7 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ViewChange } from '../core/view-state';
import { DatabaseToolbar } from './database-toolbar';
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('../../../lib/core/mobile/isMobile', () => ({ isMobile: () => false }));
let menuStyles: HTMLStyleElement;
beforeEach(() => {
diff --git a/apps/web/src/features/block-database/components/database-toolbar.tsx b/apps/web/src/features/database/components/database-toolbar.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-toolbar.tsx
rename to apps/web/src/features/database/components/database-toolbar.tsx
index b860efea87..50109511b2 100644
--- a/apps/web/src/features/block-database/components/database-toolbar.tsx
+++ b/apps/web/src/features/database/components/database-toolbar.tsx
@@ -1,8 +1,3 @@
-import {
- ContextMenuContent,
- MenuItem,
- SubTrigger,
-} from '@core/component/ContextMenu';
import { ContextMenu } from '@kobalte/core/context-menu';
import FunnelIcon from '@phosphor/funnel.svg';
import KanbanIcon from '@phosphor/kanban.svg';
@@ -23,6 +18,11 @@ import { DeleteDialog } from '@ui/components/DeleteDialog';
import { Tooltip } from '@ui/components/Tooltip';
import type { ResultAsync } from 'neverthrow';
import { createSignal, For, type JSX, Show } from 'solid-js';
+import {
+ ContextMenuContent,
+ MenuItem,
+ SubTrigger,
+} from '../../../lib/core/component/ContextMenu';
import type { BoardGrouping } from '../core/board-grouping';
import type { DatabaseViewColumn } from '../core/database-view';
import type { ViewChange } from '../core/view-state';
diff --git a/apps/web/src/features/block-database/components/database-view-filters.test.tsx b/apps/web/src/features/database/components/database-view-filters.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-view-filters.test.tsx
rename to apps/web/src/features/database/components/database-view-filters.test.tsx
index 6fccf92f6e..68cb0d94fc 100644
--- a/apps/web/src/features/block-database/components/database-view-filters.test.tsx
+++ b/apps/web/src/features/database/components/database-view-filters.test.tsx
@@ -9,7 +9,7 @@ import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FilterPanel, filterConditionCount } from './database-view-filters';
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('../../../lib/core/mobile/isMobile', () => ({ isMobile: () => false }));
beforeEach(() => {
vi.stubGlobal('scrollTo', vi.fn());
diff --git a/apps/web/src/features/block-database/components/database-view-filters.tsx b/apps/web/src/features/database/components/database-view-filters.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/database-view-filters.tsx
rename to apps/web/src/features/database/components/database-view-filters.tsx
index 6c43da9231..7c855a13ea 100644
--- a/apps/web/src/features/block-database/components/database-view-filters.tsx
+++ b/apps/web/src/features/database/components/database-view-filters.tsx
@@ -1,9 +1,3 @@
-import type {
- Conjunction,
- FilterGroup,
- FilterNode,
- FilterTest,
-} from '@core/database-sql/generated/types';
import PlusIcon from '@phosphor/plus.svg';
import XIcon from '@phosphor/x.svg';
import { Button } from '@ui/components/Button';
@@ -17,6 +11,12 @@ import {
Show,
Switch,
} from 'solid-js';
+import type {
+ Conjunction,
+ FilterGroup,
+ FilterNode,
+ FilterTest,
+} from '../../../lib/core/database-sql/generated/types';
import type { DatabaseViewColumn } from '../core/database-view';
import {
addCondition,
diff --git a/apps/web/src/features/block-database/component/GridCell.test.tsx b/apps/web/src/features/database/components/grid-cell.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/component/GridCell.test.tsx
rename to apps/web/src/features/database/components/grid-cell.test.tsx
index 6a6c4c3fa2..2bd6828515 100644
--- a/apps/web/src/features/block-database/component/GridCell.test.tsx
+++ b/apps/web/src/features/database/components/grid-cell.test.tsx
@@ -18,7 +18,7 @@ import {
type DatabaseMentionPickerProps,
type DatabaseTextEditorProps,
GridCell,
-} from './GridCell';
+} from './grid-cell';
// JSDOM has no intersection observer to drive the date selector's focus.
vi.mock('@property/utils/focus', () => ({
diff --git a/apps/web/src/features/block-database/component/GridCell.tsx b/apps/web/src/features/database/components/grid-cell.tsx
similarity index 98%
rename from apps/web/src/features/block-database/component/GridCell.tsx
rename to apps/web/src/features/database/components/grid-cell.tsx
index 0553cc451c..a46cda153b 100644
--- a/apps/web/src/features/block-database/component/GridCell.tsx
+++ b/apps/web/src/features/database/components/grid-cell.tsx
@@ -1,8 +1,3 @@
-import type { CellTextEditorProps } from '@app/components/cell-text-editor/types';
-import {
- startUiOperation,
- type UiOperation,
-} from '@app/observability/ui-operation';
import { Popover } from '@kobalte/core/popover';
import CaretDownIcon from '@phosphor/caret-down.svg';
import { PropertyDateSelector } from '@property/editors/selectors/PropertyDateSelector';
@@ -19,14 +14,11 @@ import {
Switch,
} from 'solid-js';
import { match } from 'ts-pattern';
-import { focusAdjacent } from '../components/cell-focus';
-
-import { OptionPicker } from '../components/option-picker';
+import type { CellTextEditorProps } from '../../../components/cell-text-editor/types';
import {
- createPopupCellKeys,
- isComposingKey,
-} from '../components/popup-cell-keys';
-import { SelectPill } from '../components/select-pill';
+ startUiOperation,
+ type UiOperation,
+} from '../../../observability/ui-operation';
import { useOptionEditing } from '../context/option-editing';
import { fromCellDate, toCellDate } from '../core/cell-date';
import {
@@ -45,6 +37,10 @@ import type {
GridCellEditorOptions,
} from '../core/grid-cell-editor';
import { canEditCell, formatCellValue } from '../core/table';
+import { focusAdjacent } from './cell-focus';
+import { OptionPicker } from './option-picker';
+import { createPopupCellKeys, isComposingKey } from './popup-cell-keys';
+import { SelectPill } from './select-pill';
export type DatabaseMentionPickerProps = {
anchor?: HTMLElement;
diff --git a/apps/web/src/features/block-database/components/inline-rename.test.ts b/apps/web/src/features/database/components/inline-rename.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/components/inline-rename.test.ts
rename to apps/web/src/features/database/components/inline-rename.test.ts
diff --git a/apps/web/src/features/block-database/components/inline-rename.ts b/apps/web/src/features/database/components/inline-rename.ts
similarity index 100%
rename from apps/web/src/features/block-database/components/inline-rename.ts
rename to apps/web/src/features/database/components/inline-rename.ts
diff --git a/apps/web/src/features/block-database/components/new-view-dialog.test.tsx b/apps/web/src/features/database/components/new-view-dialog.test.tsx
similarity index 98%
rename from apps/web/src/features/block-database/components/new-view-dialog.test.tsx
rename to apps/web/src/features/database/components/new-view-dialog.test.tsx
index 5e6ca838c5..3ab2d36024 100644
--- a/apps/web/src/features/block-database/components/new-view-dialog.test.tsx
+++ b/apps/web/src/features/database/components/new-view-dialog.test.tsx
@@ -11,7 +11,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import type { DatabaseViewColumn } from '../core/database-view';
import { NewViewDialog } from './new-view-dialog';
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('../../../lib/core/mobile/isMobile', () => ({ isMobile: () => false }));
afterEach(cleanup);
diff --git a/apps/web/src/features/block-database/components/new-view-dialog.tsx b/apps/web/src/features/database/components/new-view-dialog.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/new-view-dialog.tsx
rename to apps/web/src/features/database/components/new-view-dialog.tsx
diff --git a/apps/web/src/features/block-database/components/option-editor.test.tsx b/apps/web/src/features/database/components/option-editor.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/option-editor.test.tsx
rename to apps/web/src/features/database/components/option-editor.test.tsx
diff --git a/apps/web/src/features/block-database/components/option-editor.tsx b/apps/web/src/features/database/components/option-editor.tsx
similarity index 98%
rename from apps/web/src/features/block-database/components/option-editor.tsx
rename to apps/web/src/features/database/components/option-editor.tsx
index 251bef0df9..938d1bebd0 100644
--- a/apps/web/src/features/block-database/components/option-editor.tsx
+++ b/apps/web/src/features/database/components/option-editor.tsx
@@ -1,4 +1,3 @@
-import { toast } from '@core/component/Toast/Toast';
import { Popover } from '@kobalte/core/popover';
import DotsIcon from '@phosphor/dots-three.svg';
import TrashIcon from '@phosphor/trash.svg';
@@ -6,6 +5,7 @@ import { ColorSwatches } from '@property/tags/components/color-swatches';
import { Button } from '@ui/components/Button';
import type { ResultAsync } from 'neverthrow';
import { createSignal, Show } from 'solid-js';
+import { toast } from '../../../lib/core/component/Toast/Toast';
import type { OptionEditing } from '../context/option-editing';
import { inferDatabaseNumber } from '../core/column-inference';
import type { DatabaseOption, DatabaseViewColumn } from '../core/database-view';
diff --git a/apps/web/src/features/block-database/components/option-picker.test.tsx b/apps/web/src/features/database/components/option-picker.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/option-picker.test.tsx
rename to apps/web/src/features/database/components/option-picker.test.tsx
diff --git a/apps/web/src/features/block-database/components/option-picker.tsx b/apps/web/src/features/database/components/option-picker.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/option-picker.tsx
rename to apps/web/src/features/database/components/option-picker.tsx
diff --git a/apps/web/src/features/block-database/components/popup-cell-keys.test.ts b/apps/web/src/features/database/components/popup-cell-keys.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/components/popup-cell-keys.test.ts
rename to apps/web/src/features/database/components/popup-cell-keys.test.ts
diff --git a/apps/web/src/features/block-database/components/popup-cell-keys.ts b/apps/web/src/features/database/components/popup-cell-keys.ts
similarity index 100%
rename from apps/web/src/features/block-database/components/popup-cell-keys.ts
rename to apps/web/src/features/database/components/popup-cell-keys.ts
diff --git a/apps/web/src/features/block-database/components/property-icon.tsx b/apps/web/src/features/database/components/property-icon.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/property-icon.tsx
rename to apps/web/src/features/database/components/property-icon.tsx
diff --git a/apps/web/src/features/block-database/components/record-panel.tsx b/apps/web/src/features/database/components/record-panel.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/record-panel.tsx
rename to apps/web/src/features/database/components/record-panel.tsx
diff --git a/apps/web/src/features/block-database/components/select-pill.test.tsx b/apps/web/src/features/database/components/select-pill.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/select-pill.test.tsx
rename to apps/web/src/features/database/components/select-pill.test.tsx
diff --git a/apps/web/src/features/block-database/components/select-pill.tsx b/apps/web/src/features/database/components/select-pill.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/select-pill.tsx
rename to apps/web/src/features/database/components/select-pill.tsx
diff --git a/apps/web/src/features/block-database/components/sort-panel.test.tsx b/apps/web/src/features/database/components/sort-panel.test.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/sort-panel.test.tsx
rename to apps/web/src/features/database/components/sort-panel.test.tsx
diff --git a/apps/web/src/features/block-database/components/sort-panel.tsx b/apps/web/src/features/database/components/sort-panel.tsx
similarity index 98%
rename from apps/web/src/features/block-database/components/sort-panel.tsx
rename to apps/web/src/features/database/components/sort-panel.tsx
index ec13d83c0c..9cbfb210f9 100644
--- a/apps/web/src/features/block-database/components/sort-panel.tsx
+++ b/apps/web/src/features/database/components/sort-panel.tsx
@@ -1,4 +1,3 @@
-import type { SortKey } from '@core/database-sql/generated/types';
import GripIcon from '@phosphor/dots-six-vertical.svg';
import PlusIcon from '@phosphor/plus.svg';
import XIcon from '@phosphor/x.svg';
@@ -12,6 +11,7 @@ import { createReorderItem } from '../../../components/drag-drop/create-reorder'
import { createVerticalReorder } from '../../../components/drag-drop/create-vertical-reorder';
import { DragSessionSensors } from '../../../components/drag-drop/drag-session-sensors';
import { VerticalInsertionLine } from '../../../components/drag-drop/insertion-line';
+import type { SortKey } from '../../../lib/core/database-sql/generated/types';
import type { DatabaseViewColumn } from '../core/database-view';
import { withSort, withSortMoved } from '../core/view-query';
import type { ViewChange } from '../core/view-state';
diff --git a/apps/web/src/features/block-database/components/table-navigation.test.tsx b/apps/web/src/features/database/components/table-navigation.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/table-navigation.test.tsx
rename to apps/web/src/features/database/components/table-navigation.test.tsx
index d3bc0e1d58..ca9e4cc0e5 100644
--- a/apps/web/src/features/block-database/components/table-navigation.test.tsx
+++ b/apps/web/src/features/database/components/table-navigation.test.tsx
@@ -12,7 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { CreateTable, TableCreationResult } from '../core/table-creation';
import { TableNavigation } from './table-navigation';
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('../../../lib/core/mobile/isMobile', () => ({ isMobile: () => false }));
class ResizeObserverMock implements ResizeObserver {
static instances: ResizeObserverMock[] = [];
readonly targets = new Set<Element>();
diff --git a/apps/web/src/features/block-database/components/table-navigation.tsx b/apps/web/src/features/database/components/table-navigation.tsx
similarity index 99%
rename from apps/web/src/features/block-database/components/table-navigation.tsx
rename to apps/web/src/features/database/components/table-navigation.tsx
index 3f75d8baff..60bd86d7c5 100644
--- a/apps/web/src/features/block-database/components/table-navigation.tsx
+++ b/apps/web/src/features/database/components/table-navigation.tsx
@@ -1,8 +1,3 @@
-import {
- ContextMenuContent,
- MenuItem,
- MenuSeparator,
-} from '@core/component/ContextMenu';
import { ContextMenu } from '@kobalte/core/context-menu';
import { Tabs } from '@kobalte/core/tabs';
import ArrowLeftIcon from '@phosphor/arrow-left.svg';
@@ -28,6 +23,11 @@ import { createHorizontalReorder } from '../../../components/drag-drop/create-ho
import { createReorderItem } from '../../../components/drag-drop/create-reorder';
import { DragSessionSensors } from '../../../components/drag-drop/drag-session-sensors';
import { InsertionLine } from '../../../components/drag-drop/insertion-line';
+import {
+ ContextMenuContent,
+ MenuItem,
+ MenuSeparator,
+} from '../../../lib/core/component/ContextMenu';
import {
type DatabaseSchemaChange,
tableRenameMessage,
diff --git a/apps/web/src/features/block-database/components/view-control-popover.tsx b/apps/web/src/features/database/components/view-control-popover.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/view-control-popover.tsx
rename to apps/web/src/features/database/components/view-control-popover.tsx
diff --git a/apps/web/src/features/block-database/components/view-select.tsx b/apps/web/src/features/database/components/view-select.tsx
similarity index 100%
rename from apps/web/src/features/block-database/components/view-select.tsx
rename to apps/web/src/features/database/components/view-select.tsx
diff --git a/apps/web/src/features/block-database/context/column-usage.ts b/apps/web/src/features/database/context/column-usage.ts
similarity index 100%
rename from apps/web/src/features/block-database/context/column-usage.ts
rename to apps/web/src/features/database/context/column-usage.ts
diff --git a/apps/web/src/features/database/context/database.tsx b/apps/web/src/features/database/context/database.tsx
new file mode 100644
index 0000000000..e28947a433
--- /dev/null
+++ b/apps/web/src/features/database/context/database.tsx
@@ -0,0 +1,55 @@
+import { useQueryClient } from '@tanstack/solid-query';
+import { createContext, type JSX, useContext } from 'solid-js';
+import type { DatabaseApi, DatabaseCapabilities } from '../core/api';
+import type { DatabaseViewState } from '../core/view-state';
+import {
+ createDatabaseController,
+ type DatabaseController,
+} from '../primitives/database-controller';
+import {
+ createDatabaseApiSource,
+ type DatabaseDataSource,
+} from '../queries/api-source';
+
+const DatabaseContext = createContext<DatabaseController>();
+
+/** One editor owns one controller lifetime. Remount it when the resource changes. */
+export function DatabaseProvider(props: {
+ api: DatabaseApi;
+ tableId: string;
+ capabilities: DatabaseCapabilities;
+ view: DatabaseViewState;
+ /** An optimized source may supply SQL caching or inference behind the same editor contract. */
+ data?: DatabaseDataSource;
+ inferNewColumns?: boolean;
+ children: JSX.Element;
+}) {
+ const client = useQueryClient();
+ const data =
+ props.data ??
+ createDatabaseApiSource({
+ api: props.api,
+ tableId: props.tableId,
+ view: () => props.view,
+ client,
+ });
+ const controller = createDatabaseController({
+ api: props.api,
+ tableId: props.tableId,
+ data,
+ capabilities: () => props.capabilities,
+ inferNewColumns: props.inferNewColumns,
+ });
+ return (
+ <DatabaseContext.Provider value={controller}>
+ {props.children}
+ </DatabaseContext.Provider>
+ );
+}
+
+export function useDatabase(): DatabaseController {
+ const database = useContext(DatabaseContext);
+ if (!database)
+ throw new Error('Database components require a DatabaseProvider.');
+ return database;
+}
diff --git a/apps/web/src/features/block-database/context/option-editing.ts b/apps/web/src/features/database/context/option-editing.ts
similarity index 100%
rename from apps/web/src/features/block-database/context/option-editing.ts
rename to apps/web/src/features/database/context/option-editing.ts
diff --git a/apps/web/src/features/block-database/context/relation-source.ts b/apps/web/src/features/database/context/relation-source.ts
similarity index 87%
rename from apps/web/src/features/block-database/context/relation-source.ts
rename to apps/web/src/features/database/context/relation-source.ts
index a422bbbef5..43ae8a100b 100644
--- a/apps/web/src/features/block-database/context/relation-source.ts
+++ b/apps/web/src/features/database/context/relation-source.ts
@@ -1,6 +1,6 @@
-import type { DatabaseSqlFailure } from '@core/database-sql/driver';
import type { ResultAsync } from 'neverthrow';
import type { Accessor } from 'solid-js';
+import type { DatabaseSqlFailure } from '../../../lib/core/database-sql/driver';
import type { DatabaseRelatedRow } from '../core/database-relations';
/** The related table's schema could not be read, or its rows could not. */
diff --git a/apps/web/src/features/block-database/context/table-source.ts b/apps/web/src/features/database/context/table-source.ts
similarity index 96%
rename from apps/web/src/features/block-database/context/table-source.ts
rename to apps/web/src/features/database/context/table-source.ts
index 415c1025ea..f4a771c179 100644
--- a/apps/web/src/features/block-database/context/table-source.ts
+++ b/apps/web/src/features/database/context/table-source.ts
@@ -1,11 +1,11 @@
+import type { DatabaseOpsError } from '@service-storage/databases';
+import type { ResultAsync } from 'neverthrow';
+import type { Accessor } from 'solid-js';
import type {
Catalog,
DatabaseView,
Outcome,
-} from '@core/database-sql/generated/types';
-import type { DatabaseOpsError } from '@service-storage/databases';
-import type { ResultAsync } from 'neverthrow';
-import type { Accessor } from 'solid-js';
+} from '../../../lib/core/database-sql/generated/types';
import type { DatabaseViewColumn } from '../core/database-view';
import type { DatabaseRow, DatabaseRowMutation } from '../core/table';
import type {
@@ -30,7 +30,7 @@ export type DatabaseRowsSource = {
columns: Accessor<DatabaseViewColumn[]>;
snapshot: Accessor<DatabaseRowsSnapshot | undefined>;
/** The view's last read as the engine answered it. */
- read: Accessor<
+ read?: Accessor<
{ outcome: Outcome; catalog: Catalog; view: DatabaseView } | undefined
>;
loading: Accessor<boolean>;
diff --git a/apps/web/src/features/database/core/api.ts b/apps/web/src/features/database/core/api.ts
new file mode 100644
index 0000000000..a3855c5446
--- /dev/null
+++ b/apps/web/src/features/database/core/api.ts
@@ -0,0 +1,58 @@
+import type {
+ DatabaseOp,
+ OpResult,
+ ViewQuery,
+} from '@core/database-sql/generated/types';
+import type { DatabaseOpsError } from '@service-storage/databases';
+import type { ResultAsync } from 'neverthrow';
+import type { DatabaseViewColumn } from './database-view';
+import type { DatabaseRow } from './table';
+import type { DatabaseReadFailure } from './write-failure';
+
+/** Schema consumed by the editor, independent of property storage and app entities. */
+export type DatabaseTableSchema = {
+ id: string;
+ databaseId: string;
+ name: string;
+ version: number;
+ columns: DatabaseViewColumn[];
+};
+
+/** The existing database operation protocol, shared by every host. */
+export type DatabaseOpBatch = {
+ ops: DatabaseOp[];
+ baseVersions?: Record<string, number>;
+};
+export type DatabaseAppliedOps = { results: OpResult[] };
+export type DatabaseRowRequest = {
+ tableId: string;
+ query: ViewQuery;
+ cursor?: string;
+ /** Read retained records even when they no longer match the current query. */
+ rowIds?: string[];
+};
+export type DatabaseRowPage = {
+ rows: DatabaseRow[];
+ nextCursor?: string;
+ tableVersion: number;
+};
+
+/** Transport boundary. Adapters own routes, authentication and DTO conversion. */
+export type DatabaseApi = {
+ key: readonly string[];
+ readTable(
+ tableId: string
+ ): ResultAsync<DatabaseTableSchema, DatabaseReadFailure>;
+ readRows(
+ request: DatabaseRowRequest
+ ): ResultAsync<DatabaseRowPage, DatabaseReadFailure>;
+ applyOps(
+ batch: DatabaseOpBatch
+ ): ResultAsync<DatabaseAppliedOps, DatabaseOpsError>;
+};
+
+/** UI permissions are advisory; the host service authorizes every operation. */
+export type DatabaseCapabilities = {
+ editRows: boolean;
+ editColumns: boolean;
+};
diff --git a/apps/web/src/features/block-database/core/board-grouping.test.ts b/apps/web/src/features/database/core/board-grouping.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/board-grouping.test.ts
rename to apps/web/src/features/database/core/board-grouping.test.ts
diff --git a/apps/web/src/features/block-database/core/board-grouping.ts b/apps/web/src/features/database/core/board-grouping.ts
similarity index 97%
rename from apps/web/src/features/block-database/core/board-grouping.ts
rename to apps/web/src/features/database/core/board-grouping.ts
index ad4691c26b..8a4c526e5d 100644
--- a/apps/web/src/features/block-database/core/board-grouping.ts
+++ b/apps/web/src/features/database/core/board-grouping.ts
@@ -2,9 +2,10 @@
* What a new board groups by, and the Status column a table with nothing a
* board can group by is offered: created in the same batch as the board.
*/
-import type { DatabaseOp } from '@core/database-sql/generated/types';
+
import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';
import type { ViewQuery } from '@service-storage/generated/schemas/viewQuery';
+import type { DatabaseOp } from '../../../lib/core/database-sql/generated/types';
import type { DatabaseViewColumn } from './database-view';
import { isDatabaseNameTaken } from './property-creation';
import { boardLayout } from './views';
diff --git a/apps/web/src/features/database/core/board-input.ts b/apps/web/src/features/database/core/board-input.ts
new file mode 100644
index 0000000000..38cce54487
--- /dev/null
+++ b/apps/web/src/features/database/core/board-input.ts
@@ -0,0 +1,129 @@
+import type {
+ Catalog,
+ Cell,
+ ColumnKind,
+ DatabaseView,
+ Outcome,
+} from '@core/database-sql/generated/types';
+import { match } from 'ts-pattern';
+import type { DatabaseTableSchema } from './api';
+import { cellValue } from './cell-ops';
+import type { DatabaseViewColumn } from './database-view';
+import type { DatabaseRow } from './table';
+import type { DatabaseViewState } from './view-state';
+
+function kind(column: DatabaseViewColumn): ColumnKind {
+ if (column.relation)
+ return { kind: 'entity', multi: true, target: 'DATABASE_ROW' };
+ return match(column.dataType)
+ .returnType<ColumnKind>()
+ .with('STRING', () => ({ kind: 'text' }))
+ .with('NUMBER', () => ({ kind: 'number' }))
+ .with('BOOLEAN', () => ({ kind: 'boolean' }))
+ .with('DATE', () => ({ kind: 'date' }))
+ .with('LINK', () => ({ kind: 'link' }))
+ .with('SELECT_STRING', 'SELECT_NUMBER', 'TAG', () => ({
+ kind: 'select',
+ multi: column.isMultiSelect,
+ options: column.options,
+ }))
+ .with('ENTITY', () =>
+ column.specificEntityType
+ ? {
+ kind: 'entity',
+ multi: column.isMultiSelect,
+ target: column.specificEntityType,
+ }
+ : { kind: 'text' }
+ )
+ .exhaustive();
+}
+
+function cell(column: DatabaseViewColumn, row: DatabaseRow): Cell | null {
+ const value = cellValue(column, row.cells[column.id] ?? null);
+ if (value.isErr()) return null;
+ return match(value.value)
+ .returnType<Cell | null>()
+ .with({ type: 'clear' }, () => null)
+ .with(
+ { type: 'text' },
+ { type: 'number' },
+ { type: 'date' },
+ (cell) => cell
+ )
+ .with({ type: 'boolean' }, ({ value }) => ({ type: 'bool', value }))
+ .with({ type: 'link' }, ({ value }) => ({
+ type: 'text',
+ value: value[0] ?? '',
+ }))
+ .with({ type: 'entities' }, ({ value }) => ({
+ type: 'entities',
+ value: value.map((ref) => ref.entityId),
+ }))
+ .with({ type: 'rows' }, ({ value }) => ({ type: 'entities', value }))
+ .with({ type: 'options' }, ({ value }) => ({
+ type: 'options',
+ value: value.flatMap((ref) => {
+ const id =
+ 'id' in ref
+ ? ref.id
+ : column.options.find((option) => option.label === ref.label)?.id;
+ return id ? [id] : [];
+ }),
+ }))
+ .exhaustive();
+}
+
+/** Adapt normalized API rows to the existing board layout engine; no SQL query is needed. */
+export function boardInput(
+ table: DatabaseTableSchema,
+ rows: DatabaseRow[],
+ state: DatabaseViewState
+): {
+ catalog: Catalog;
+ outcome: Outcome;
+ view: DatabaseView;
+} {
+ const columns = table.columns.map((column) => ({
+ id: column.id,
+ placement: column.id,
+ name: column.name,
+ kind: kind(column),
+ }));
+ return {
+ catalog: {
+ tables: [
+ {
+ id: table.id,
+ databaseId: table.databaseId,
+ database: '',
+ name: table.name,
+ columns,
+ },
+ ],
+ },
+ outcome: {
+ columns: columns.map((column) => ({
+ name: column.name,
+ column: column.id,
+ kind: column.kind.kind === 'link' ? 'text' : column.kind.kind,
+ })),
+ rows: rows.map((row) => table.columns.map((column) => cell(column, row))),
+ rowIds: rows.map((row) => row.rowId),
+ readTables: [table.id],
+ truncated: false,
+ insertedRowIds: [],
+ changesApplied: 0,
+ },
+ view: {
+ id: table.id,
+ databaseId: table.databaseId,
+ tableId: table.id,
+ name: '',
+ position: '80',
+ createdAt: new Date(0).toISOString(),
+ updatedAt: new Date(0).toISOString(),
+ ...state,
+ },
+ };
+}
diff --git a/apps/web/src/features/block-database/core/board-moves.test.ts b/apps/web/src/features/database/core/board-moves.test.ts
similarity index 99%
rename from apps/web/src/features/block-database/core/board-moves.test.ts
rename to apps/web/src/features/database/core/board-moves.test.ts
index 4f661d66d7..be74eca91b 100644
--- a/apps/web/src/features/block-database/core/board-moves.test.ts
+++ b/apps/web/src/features/database/core/board-moves.test.ts
@@ -1,6 +1,6 @@
-import type { Board } from '@core/database-sql/generated/types';
import { err, ok } from 'neverthrow';
import { describe, expect, it } from 'vitest';
+import type { Board } from '../../../lib/core/database-sql/generated/types';
import {
cardMove,
laneCards,
diff --git a/apps/web/src/features/block-database/core/board-moves.ts b/apps/web/src/features/database/core/board-moves.ts
similarity index 98%
rename from apps/web/src/features/block-database/core/board-moves.ts
rename to apps/web/src/features/database/core/board-moves.ts
index 0a40682923..47b25b415a 100644
--- a/apps/web/src/features/block-database/core/board-moves.ts
+++ b/apps/web/src/features/database/core/board-moves.ts
@@ -2,9 +2,13 @@
* A dragged card as the `move_card` op names it and as it shows before the
* answer; placement mirrors `models_databases::views::lanes::place_card`.
*/
-import type { Board, LaneKey } from '@core/database-sql/generated/types';
+
import type { CardPosition } from '@service-storage/generated/schemas/cardPosition';
import { err, ok, Result } from 'neverthrow';
+import type {
+ Board,
+ LaneKey,
+} from '../../../lib/core/database-sql/generated/types';
import { sameLane } from './views';
/** A card's move: `before` is the card it lands right after, `after` the one right before it. */
diff --git a/apps/web/src/features/block-database/core/cell-date.test.ts b/apps/web/src/features/database/core/cell-date.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/cell-date.test.ts
rename to apps/web/src/features/database/core/cell-date.test.ts
diff --git a/apps/web/src/features/block-database/core/cell-date.ts b/apps/web/src/features/database/core/cell-date.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/cell-date.ts
rename to apps/web/src/features/database/core/cell-date.ts
diff --git a/apps/web/src/features/block-database/core/cell-ops.test.ts b/apps/web/src/features/database/core/cell-ops.test.ts
similarity index 81%
rename from apps/web/src/features/block-database/core/cell-ops.test.ts
rename to apps/web/src/features/database/core/cell-ops.test.ts
index 7caad98c85..ed4c2031bb 100644
--- a/apps/web/src/features/block-database/core/cell-ops.test.ts
+++ b/apps/web/src/features/database/core/cell-ops.test.ts
@@ -1,47 +1,28 @@
-import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';
import { err, ok } from 'neverthrow';
import { describe, expect, it } from 'vitest';
import { cellValue, missingOptionLabels, mutationOp } from './cell-ops';
+import type { DatabaseViewColumn } from './database-view';
import { UNAVAILABLE_OPTION } from './grid-cells';
function column(
- dataType: ColumnDetail['definition']['definition']['data_type'],
+ dataType: DatabaseViewColumn['dataType'],
options: {
multi?: boolean;
entityType?: 'USER' | 'DOCUMENT';
relation?: boolean;
} = {}
-): ColumnDetail {
+): DatabaseViewColumn {
return {
- shared_outside_database: false,
- column: {
- id: 'column',
- table_id: 'table',
- property_definition_id: 'definition',
- position: 'a',
- config: options.relation
- ? { kind: 'link', database_id: 'db', table_id: 'related' }
- : null,
- display_name: null,
- infer_type: false,
- },
- sql_name: '"Column"',
+ id: 'column',
+ name: 'Column',
+ dataType,
+ isMultiSelect: options.multi ?? false,
+ specificEntityType: options.entityType ?? null,
+ options: [],
writable: true,
- definition: {
- definition: {
- id: 'definition',
- owner: { scope: 'database', database_id: 'db' },
- display_name: 'Column',
- data_type: dataType,
- is_multi_select: options.multi ?? false,
- specific_entity_type: options.entityType ?? null,
- created_at: '',
- updated_at: '',
- is_system: false,
- is_metadata: false,
- },
- property_options: [],
- },
+ ...(options.relation
+ ? { relation: { databaseId: 'db', tableId: 'related' } }
+ : {}),
};
}
@@ -153,34 +134,9 @@ describe('grid values as cell values', () => {
describe('grid values a column cannot take', () => {
it('refuses references to rows outside a relation column', () => {
- const rows: ColumnDetail = {
- shared_outside_database: false,
- column: {
- id: 'column',
- table_id: 'table',
- property_definition_id: 'definition',
- position: 'a',
- config: null,
- display_name: null,
- infer_type: false,
- },
- sql_name: '"Parties"',
- writable: true,
- definition: {
- definition: {
- id: 'definition',
- owner: { scope: 'database', database_id: 'db' },
- display_name: 'Parties',
- data_type: 'ENTITY',
- is_multi_select: false,
- specific_entity_type: 'DATABASE_ROW',
- created_at: '',
- updated_at: '',
- is_system: false,
- is_metadata: false,
- },
- property_options: [],
- },
+ const rows: DatabaseViewColumn = {
+ ...column('ENTITY'),
+ specificEntityType: 'DATABASE_ROW',
};
expect(cellValue(rows, 'row-1')).toEqual(
diff --git a/apps/web/src/features/block-database/core/cell-ops.ts b/apps/web/src/features/database/core/cell-ops.ts
similarity index 90%
rename from apps/web/src/features/block-database/core/cell-ops.ts
rename to apps/web/src/features/database/core/cell-ops.ts
index b69923d1dd..911e78b861 100644
--- a/apps/web/src/features/block-database/core/cell-ops.ts
+++ b/apps/web/src/features/database/core/cell-ops.ts
@@ -3,17 +3,16 @@
* own values (option labels, JSON-array strings for multi-valued cells).
*/
+import { err, ok, Result } from 'neverthrow';
+import { match } from 'ts-pattern';
import type {
CellValue,
CellWrite,
DatabaseOp,
OpEntityKind,
-} from '@core/database-sql/generated/types';
-import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';
-import { err, ok, Result } from 'neverthrow';
-import { match } from 'ts-pattern';
+} from '../../../lib/core/database-sql/generated/types';
import { inferDatabaseNumber } from './column-inference';
-import type { DatabaseCellValue } from './database-view';
+import type { DatabaseCellValue, DatabaseViewColumn } from './database-view';
import { UNAVAILABLE_OPTION } from './grid-cells';
import type { DatabaseRowMutation } from './table';
import type { DatabaseCellFailure } from './write-failure';
@@ -45,10 +44,10 @@ function listedValues(
/** The kind of entity an entity column's references point at. */
function referenceKind(
- column: ColumnDetail
+ column: DatabaseViewColumn
): Result<OpEntityKind, DatabaseCellFailure> {
- const target = column.definition.definition.specific_entity_type;
- if (target === null) return err({ kind: 'untyped-entity' });
+ const target = column.specificEntityType;
+ if (target == null) return err({ kind: 'untyped-entity' });
if (target === 'DATABASE_ROW') return err({ kind: 'relation-as-entity' });
return ok(target);
}
@@ -72,20 +71,20 @@ function instant(value: string): string {
* any cell but a text one, which keeps the empty text.
*/
export function cellValue(
- column: ColumnDetail,
+ column: DatabaseViewColumn,
value: DatabaseCellValue
): Result<CellValue, DatabaseCellFailure> {
- const definition = column.definition.definition;
- if (column.column.config?.kind === 'link')
+ const definition = column;
+ if (column.relation)
return listedValues(value).map(
(rows): CellValue =>
rows.length ? { type: 'rows', value: [...new Set(rows)] } : CLEAR
);
- if (definition.is_multi_select)
+ if (definition.isMultiSelect)
return listedValues(value).andThen(
(values): Result<CellValue, DatabaseCellFailure> => {
if (!values.length) return ok(CLEAR);
- return definition.data_type === 'ENTITY'
+ return definition.dataType === 'ENTITY'
? referenceKind(column).map((entityType) => ({
type: 'entities',
value: values.map((entityId) => ({ entityType, entityId })),
@@ -94,8 +93,8 @@ export function cellValue(
}
);
if (value === null) return ok(CLEAR);
- if (value === '' && definition.data_type !== 'STRING') return ok(CLEAR);
- return match(definition.data_type)
+ if (value === '' && definition.dataType !== 'STRING') return ok(CLEAR);
+ return match(definition.dataType)
.returnType<Result<CellValue, DatabaseCellFailure>>()
.with('STRING', () => ok({ type: 'text', value: String(value) }))
.with('NUMBER', () => {
@@ -135,7 +134,9 @@ export function cellValue(
export function mutationOp(
tableId: string,
mutation: DatabaseRowMutation,
- columnFor: (columnId: string) => Result<ColumnDetail, DatabaseCellFailure>
+ columnFor: (
+ columnId: string
+ ) => Result<DatabaseViewColumn, DatabaseCellFailure>
): Result<DatabaseOp, DatabaseCellFailure> {
const cell = (columnId: string, value: DatabaseCellValue) =>
columnFor(columnId)
diff --git a/apps/web/src/features/block-database/core/column-inference.test.ts b/apps/web/src/features/database/core/column-inference.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/column-inference.test.ts
rename to apps/web/src/features/database/core/column-inference.test.ts
diff --git a/apps/web/src/features/block-database/core/column-inference.ts b/apps/web/src/features/database/core/column-inference.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/column-inference.ts
rename to apps/web/src/features/database/core/column-inference.ts
diff --git a/apps/web/src/features/block-database/core/column-order.test.ts b/apps/web/src/features/database/core/column-order.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/column-order.test.ts
rename to apps/web/src/features/database/core/column-order.test.ts
diff --git a/apps/web/src/features/block-database/core/column-order.ts b/apps/web/src/features/database/core/column-order.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/column-order.ts
rename to apps/web/src/features/database/core/column-order.ts
diff --git a/apps/web/src/features/block-database/core/column-schema.test.ts b/apps/web/src/features/database/core/column-schema.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/column-schema.test.ts
rename to apps/web/src/features/database/core/column-schema.test.ts
diff --git a/apps/web/src/features/block-database/core/column-schema.ts b/apps/web/src/features/database/core/column-schema.ts
similarity index 98%
rename from apps/web/src/features/block-database/core/column-schema.ts
rename to apps/web/src/features/database/core/column-schema.ts
index ec2d773288..67ced04d67 100644
--- a/apps/web/src/features/block-database/core/column-schema.ts
+++ b/apps/web/src/features/database/core/column-schema.ts
@@ -1,9 +1,9 @@
-import type { OpColumnKind } from '@core/database-sql/generated/types';
import type { DatabaseOpsError } from '@service-storage/databases';
import type { DataType } from '@service-storage/generated/schemas/dataType';
import type { ResultAsync } from 'neverthrow';
import type { Accessor } from 'solid-js';
import { match, P } from 'ts-pattern';
+import type { OpColumnKind } from '../../../lib/core/database-sql/generated/types';
import type { DatabaseEntityType } from './column-inference';
/** The refusal's own words, when the service refused the batch. */
diff --git a/apps/web/src/features/block-database/core/csv.test.ts b/apps/web/src/features/database/core/csv.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/csv.test.ts
rename to apps/web/src/features/database/core/csv.test.ts
diff --git a/apps/web/src/features/block-database/core/csv.ts b/apps/web/src/features/database/core/csv.ts
similarity index 98%
rename from apps/web/src/features/block-database/core/csv.ts
rename to apps/web/src/features/database/core/csv.ts
index 2e7c6f48b5..3683d6f9f1 100644
--- a/apps/web/src/features/block-database/core/csv.ts
+++ b/apps/web/src/features/database/core/csv.ts
@@ -1,8 +1,8 @@
-import type { ResultError } from '@core/util/result';
import type { DatabaseSchemaErrorCode } from '@service-storage/databases';
import { err, ok, type Result } from 'neverthrow';
import Papa from 'papaparse';
import { match } from 'ts-pattern';
+import type { ResultError } from '../../../lib/core/util/result';
export type DatabaseCsv = {
columns: string[];
diff --git a/apps/web/src/features/block-database/core/database-relations.test.ts b/apps/web/src/features/database/core/database-relations.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/database-relations.test.ts
rename to apps/web/src/features/database/core/database-relations.test.ts
diff --git a/apps/web/src/features/block-database/core/database-relations.ts b/apps/web/src/features/database/core/database-relations.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/database-relations.ts
rename to apps/web/src/features/database/core/database-relations.ts
diff --git a/apps/web/src/features/block-database/core/database-search.test.ts b/apps/web/src/features/database/core/database-search.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/database-search.test.ts
rename to apps/web/src/features/database/core/database-search.test.ts
diff --git a/apps/web/src/features/block-database/core/database-search.ts b/apps/web/src/features/database/core/database-search.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/database-search.ts
rename to apps/web/src/features/database/core/database-search.ts
diff --git a/apps/web/src/features/block-database/core/database-view.ts b/apps/web/src/features/database/core/database-view.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/database-view.ts
rename to apps/web/src/features/database/core/database-view.ts
diff --git a/apps/web/src/features/block-database/core/forms-usage.test.ts b/apps/web/src/features/database/core/forms-usage.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/forms-usage.test.ts
rename to apps/web/src/features/database/core/forms-usage.test.ts
diff --git a/apps/web/src/features/block-database/core/forms-usage.ts b/apps/web/src/features/database/core/forms-usage.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/forms-usage.ts
rename to apps/web/src/features/database/core/forms-usage.ts
diff --git a/apps/web/src/features/block-database/core/grid-cell-editor.ts b/apps/web/src/features/database/core/grid-cell-editor.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/grid-cell-editor.ts
rename to apps/web/src/features/database/core/grid-cell-editor.ts
diff --git a/apps/web/src/features/block-database/core/grid-cells.test.ts b/apps/web/src/features/database/core/grid-cells.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/grid-cells.test.ts
rename to apps/web/src/features/database/core/grid-cells.test.ts
diff --git a/apps/web/src/features/block-database/core/grid-cells.ts b/apps/web/src/features/database/core/grid-cells.ts
similarity index 98%
rename from apps/web/src/features/block-database/core/grid-cells.ts
rename to apps/web/src/features/database/core/grid-cells.ts
index 864184895f..4cf4bfebf9 100644
--- a/apps/web/src/features/block-database/core/grid-cells.ts
+++ b/apps/web/src/features/database/core/grid-cells.ts
@@ -3,14 +3,14 @@
* checkbox as 0 or 1, and a JSON array for a multi-valued cell.
*/
+import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';
+import { match } from 'ts-pattern';
import type {
Catalog,
Cell,
ColumnKind,
Outcome,
-} from '@core/database-sql/generated/types';
-import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';
-import { match } from 'ts-pattern';
+} from '../../../lib/core/database-sql/generated/types';
import type { DatabaseCellValue } from './database-view';
import type { DatabaseRow } from './table';
diff --git a/apps/web/src/features/block-database/core/keyed-serializer.test.ts b/apps/web/src/features/database/core/keyed-serializer.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/keyed-serializer.test.ts
rename to apps/web/src/features/database/core/keyed-serializer.test.ts
diff --git a/apps/web/src/features/block-database/core/keyed-serializer.ts b/apps/web/src/features/database/core/keyed-serializer.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/keyed-serializer.ts
rename to apps/web/src/features/database/core/keyed-serializer.ts
diff --git a/apps/web/src/features/block-database/core/move-beside.test.ts b/apps/web/src/features/database/core/move-beside.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/move-beside.test.ts
rename to apps/web/src/features/database/core/move-beside.test.ts
diff --git a/apps/web/src/features/block-database/core/move-beside.ts b/apps/web/src/features/database/core/move-beside.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/move-beside.ts
rename to apps/web/src/features/database/core/move-beside.ts
diff --git a/apps/web/src/features/block-database/core/property-creation.ts b/apps/web/src/features/database/core/property-creation.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/property-creation.ts
rename to apps/web/src/features/database/core/property-creation.ts
diff --git a/apps/web/src/features/block-database/core/refresh-plan.test.ts b/apps/web/src/features/database/core/refresh-plan.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/refresh-plan.test.ts
rename to apps/web/src/features/database/core/refresh-plan.test.ts
diff --git a/apps/web/src/features/block-database/core/refresh-plan.ts b/apps/web/src/features/database/core/refresh-plan.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/refresh-plan.ts
rename to apps/web/src/features/database/core/refresh-plan.ts
diff --git a/apps/web/src/features/database/core/row-write.ts b/apps/web/src/features/database/core/row-write.ts
new file mode 100644
index 0000000000..4c83a385b1
--- /dev/null
+++ b/apps/web/src/features/database/core/row-write.ts
@@ -0,0 +1,75 @@
+import type { DatabaseOp } from '@core/database-sql/generated/types';
+import { err, ok, ResultAsync } from 'neverthrow';
+import { v7 as uuidv7 } from 'uuid';
+import type { DatabaseApi } from './api';
+import { missingOptionLabels, mutationOp } from './cell-ops';
+import type { DatabaseViewColumn } from './database-view';
+import type { DatabaseRowMutation } from './table';
+import type { DatabaseWriteFailure } from './write-failure';
+
+/** One row mutation and any new select options are committed together. */
+export function writeDatabaseRow(
+ args: {
+ tableId: string;
+ columns: readonly DatabaseViewColumn[];
+ applyOps: DatabaseApi['applyOps'];
+ },
+ mutation: DatabaseRowMutation,
+ createOptions: boolean
+): ResultAsync<
+ {
+ insertedRowIds: string[];
+ version: number;
+ },
+ DatabaseWriteFailure
+> {
+ const op = mutationOp(args.tableId, mutation, (id) => {
+ const column = args.columns.find((column) => column.id === id);
+ return column?.writable
+ ? ok(column)
+ : err({ kind: 'read-only-column' as const });
+ });
+ if (op.isErr()) return new ResultAsync(Promise.resolve(err(op.error)));
+ const options: DatabaseOp[] = createOptions
+ ? missingOptionLabels(
+ op.value,
+ (id) =>
+ args.columns
+ .find((column) => column.id === id)
+ ?.options.map((option) => option.label) ?? []
+ ).map(({ column, labels }) => ({
+ kind: 'column',
+ table: args.tableId,
+ column,
+ change: {
+ kind: 'add_options',
+ options: labels.map((label) => ({ id: uuidv7(), label })),
+ },
+ }))
+ : [];
+ return args
+ .applyOps({ ops: [...options, op.value] })
+ .mapErr((error): DatabaseWriteFailure => {
+ const refused = [
+ 'INVALID_OP',
+ 'UNAUTHORIZED',
+ 'FORBIDDEN',
+ 'NOT_FOUND',
+ 'CONFLICT',
+ 'GONE',
+ ].includes(error.code);
+ return mutation.kind === 'create' && !refused
+ ? { kind: 'outcome-unknown' }
+ : { kind: 'ops', error };
+ })
+ .andThen((applied) => {
+ const result = applied.results.at(-1);
+ return result?.kind === 'rows'
+ ? ok({
+ insertedRowIds:
+ result.change.kind === 'inserted' ? result.change.rows : [],
+ version: result.tableVersion,
+ })
+ : err({ kind: 'unexpected-result' as const });
+ });
+}
diff --git a/apps/web/src/features/block-database/core/table-creation.ts b/apps/web/src/features/database/core/table-creation.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/table-creation.ts
rename to apps/web/src/features/database/core/table-creation.ts
diff --git a/apps/web/src/features/block-database/core/table.test.ts b/apps/web/src/features/database/core/table.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/table.test.ts
rename to apps/web/src/features/database/core/table.test.ts
diff --git a/apps/web/src/features/block-database/core/table.ts b/apps/web/src/features/database/core/table.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/table.ts
rename to apps/web/src/features/database/core/table.ts
diff --git a/apps/web/src/features/block-database/core/undo-stack.test.ts b/apps/web/src/features/database/core/undo-stack.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/undo-stack.test.ts
rename to apps/web/src/features/database/core/undo-stack.test.ts
diff --git a/apps/web/src/features/block-database/core/undo-stack.ts b/apps/web/src/features/database/core/undo-stack.ts
similarity index 98%
rename from apps/web/src/features/block-database/core/undo-stack.ts
rename to apps/web/src/features/database/core/undo-stack.ts
index e326c23423..7839c0828c 100644
--- a/apps/web/src/features/block-database/core/undo-stack.ts
+++ b/apps/web/src/features/database/core/undo-stack.ts
@@ -1,8 +1,8 @@
-import type { DatabaseOp } from '@core/database-sql/generated/types';
import type { SkippedCell } from '@service-storage/generated/schemas/skippedCell';
import type { UndoOutcome } from '@service-storage/generated/schemas/undoOutcome';
import type { UndoRefusal } from '@service-storage/generated/schemas/undoRefusal';
import { match } from 'ts-pattern';
+import type { DatabaseOp } from '../../../lib/core/database-sql/generated/types';
/** One batch the viewer committed: the journal's change for each table it wrote. */
export type DatabaseUndoEntry = {
diff --git a/apps/web/src/features/block-database/core/view-creation.ts b/apps/web/src/features/database/core/view-creation.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/view-creation.ts
rename to apps/web/src/features/database/core/view-creation.ts
diff --git a/apps/web/src/features/block-database/core/view-query.test.ts b/apps/web/src/features/database/core/view-query.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/view-query.test.ts
rename to apps/web/src/features/database/core/view-query.test.ts
diff --git a/apps/web/src/features/block-database/core/view-query.ts b/apps/web/src/features/database/core/view-query.ts
similarity index 99%
rename from apps/web/src/features/block-database/core/view-query.ts
rename to apps/web/src/features/database/core/view-query.ts
index ea00688efb..5ffa95ba3c 100644
--- a/apps/web/src/features/block-database/core/view-query.ts
+++ b/apps/web/src/features/database/core/view-query.ts
@@ -2,6 +2,8 @@
* Editing a view's typed filter tree and sort keys. A node is addressed by its
* path of indexes from the root group; `[]` is the root.
*/
+
+import { match } from 'ts-pattern';
import type {
Conjunction,
DateOperator,
@@ -16,8 +18,7 @@ import type {
SortKey,
TextOperator,
ValueKind,
-} from '@core/database-sql/generated/types';
-import { match } from 'ts-pattern';
+} from '../../../lib/core/database-sql/generated/types';
import type { DatabaseViewColumn } from './database-view';
import { moveBeside } from './move-beside';
diff --git a/apps/web/src/features/block-database/core/view-selection.test.ts b/apps/web/src/features/database/core/view-selection.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/view-selection.test.ts
rename to apps/web/src/features/database/core/view-selection.test.ts
diff --git a/apps/web/src/features/block-database/core/view-selection.ts b/apps/web/src/features/database/core/view-selection.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/view-selection.ts
rename to apps/web/src/features/database/core/view-selection.ts
diff --git a/apps/web/src/features/block-database/core/view-state.ts b/apps/web/src/features/database/core/view-state.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/view-state.ts
rename to apps/web/src/features/database/core/view-state.ts
diff --git a/apps/web/src/features/block-database/core/views.test.ts b/apps/web/src/features/database/core/views.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/views.test.ts
rename to apps/web/src/features/database/core/views.test.ts
diff --git a/apps/web/src/features/block-database/core/views.ts b/apps/web/src/features/database/core/views.ts
similarity index 98%
rename from apps/web/src/features/block-database/core/views.ts
rename to apps/web/src/features/database/core/views.ts
index 3c9794f281..9e70a5f51a 100644
--- a/apps/web/src/features/block-database/core/views.ts
+++ b/apps/web/src/features/database/core/views.ts
@@ -1,10 +1,14 @@
/** A table's typed views as the grid and board draw them, and the layouts new views start with. */
-import type { FilterNode, LaneKey } from '@core/database-sql/generated/types';
+
import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';
import type { ViewColumn } from '@service-storage/generated/schemas/viewColumn';
import type { ViewLayout } from '@service-storage/generated/schemas/viewLayout';
import { err, ok, type Result } from 'neverthrow';
import { match } from 'ts-pattern';
+import type {
+ FilterNode,
+ LaneKey,
+} from '../../../lib/core/database-sql/generated/types';
import { type DatabaseViewColumn, isBoardGroupColumn } from './database-view';
import { moveBeside } from './move-beside';
import { titleColumn } from './table';
diff --git a/apps/web/src/features/block-database/core/write-failure.test.ts b/apps/web/src/features/database/core/write-failure.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/core/write-failure.test.ts
rename to apps/web/src/features/database/core/write-failure.test.ts
diff --git a/apps/web/src/features/block-database/core/write-failure.ts b/apps/web/src/features/database/core/write-failure.ts
similarity index 98%
rename from apps/web/src/features/block-database/core/write-failure.ts
rename to apps/web/src/features/database/core/write-failure.ts
index 760aa2ee73..dedcdec9d4 100644
--- a/apps/web/src/features/block-database/core/write-failure.ts
+++ b/apps/web/src/features/database/core/write-failure.ts
@@ -1,11 +1,11 @@
-import type { DatabaseSqlFailure } from '@core/database-sql/driver';
-import type { ResultError } from '@core/util/result';
import type {
DatabaseOpsError,
DatabaseSchemaErrorCode,
} from '@service-storage/databases';
import type { GraphqlEntityMutationErrorCode } from '@service-storage/graphql/generated/graphql';
import { match } from 'ts-pattern';
+import type { DatabaseSqlFailure } from '../../../lib/core/database-sql/driver';
+import type { ResultError } from '../../../lib/core/util/result';
/** A grid value the column it is written to cannot take. */
export type DatabaseCellFailure =
diff --git a/apps/web/src/features/block-database/primitives/board-layout.ts b/apps/web/src/features/database/primitives/board-layout.ts
similarity index 95%
rename from apps/web/src/features/block-database/primitives/board-layout.ts
rename to apps/web/src/features/database/primitives/board-layout.ts
index fcc35cd9b7..d3303657e8 100644
--- a/apps/web/src/features/block-database/primitives/board-layout.ts
+++ b/apps/web/src/features/database/primitives/board-layout.ts
@@ -1,12 +1,12 @@
-import {
- type DatabaseSqlFailure,
- engineFailure,
-} from '@core/database-sql/driver';
-import { loadDatabaseSqlWasm } from '@core/database-sql/wasm-module';
import type { CardPosition } from '@service-storage/generated/schemas/cardPosition';
import { ResultAsync } from 'neverthrow';
import { createSignal } from 'solid-js';
import { match, P } from 'ts-pattern';
+import {
+ type DatabaseSqlFailure,
+ engineFailure,
+} from '../../../lib/core/database-sql/driver';
+import { loadDatabaseSqlWasm } from '../../../lib/core/database-sql/wasm-module';
export type BoardEngine = Awaited<ReturnType<typeof loadDatabaseSqlWasm>>;
diff --git a/apps/web/src/features/block-database/primitives/cell-selection.ts b/apps/web/src/features/database/primitives/cell-selection.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/cell-selection.ts
rename to apps/web/src/features/database/primitives/cell-selection.ts
diff --git a/apps/web/src/features/block-database/primitives/column-layout.ts b/apps/web/src/features/database/primitives/column-layout.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/column-layout.ts
rename to apps/web/src/features/database/primitives/column-layout.ts
diff --git a/apps/web/src/features/database/primitives/database-controller.test.ts b/apps/web/src/features/database/primitives/database-controller.test.ts
new file mode 100644
index 0000000000..2113d90008
--- /dev/null
+++ b/apps/web/src/features/database/primitives/database-controller.test.ts
@@ -0,0 +1,88 @@
+import { errAsync, okAsync } from 'neverthrow';
+import { describe, expect, it, vi } from 'vitest';
+import type { DatabaseRowsSource } from '../context/table-source';
+import type { DatabaseApi, DatabaseCapabilities } from '../core/api';
+import { createDatabaseController } from './database-controller';
+
+function fixture(
+ capabilities: DatabaseCapabilities = { editRows: true, editColumns: true }
+) {
+ const rows: DatabaseRowsSource = {
+ columns: () => [],
+ snapshot: () => ({ rows: [], retained: [], version: 7 }),
+ loading: () => false,
+ refreshing: () => false,
+ error: () => undefined,
+ refresh: () => okAsync(undefined),
+ retain: () => {},
+ addOption: () => okAsync(undefined),
+ write: () => okAsync({ insertedRowIds: [], version: 7 }),
+ };
+ const applyOps = vi.fn<DatabaseApi['applyOps']>(() =>
+ okAsync({ results: [] })
+ );
+ const api: DatabaseApi = {
+ key: ['test'],
+ readTable: () => errAsync({ kind: 'table-unavailable' }),
+ readRows: () => okAsync({ rows: [], tableVersion: 1 }),
+ applyOps,
+ };
+ const refresh = vi.fn(() =>
+ errAsync({ kind: 'fetch' as const, message: 'offline' })
+ );
+ const controller = createDatabaseController({
+ api,
+ tableId: 'table',
+ capabilities: () => capabilities,
+ data: {
+ rows: { ...rows, refresh },
+ table: () => ({
+ id: 'table',
+ databaseId: 'db',
+ name: 'Table',
+ columns: [],
+ version: 7,
+ }),
+ },
+ });
+ return { controller, applyOps, refresh, capabilities };
+}
+
+describe('shared database controller', () => {
+ it('keeps a committed column creation successful when refreshing fails', async () => {
+ const { controller, applyOps, refresh } = fixture();
+ const result = await controller.schemaEditing()!.createDefaultColumn();
+ expect(result.isOk()).toBe(true);
+ expect(applyOps).toHaveBeenCalledTimes(1);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ });
+ it('preserves a version refusal without retrying the mutation', async () => {
+ const { controller, applyOps, refresh } = fixture();
+ applyOps.mockReturnValueOnce(
+ errAsync({ code: 'CONFLICT', refusal: null, message: 'Changed' })
+ );
+ expect((await controller.schemaEditing()!.remove('column')).isErr()).toBe(
+ true
+ );
+ expect(applyOps).toHaveBeenCalledWith({
+ ops: [
+ {
+ kind: 'column',
+ table: 'table',
+ column: 'column',
+ change: { kind: 'delete' },
+ },
+ ],
+ baseVersions: { table: 7 },
+ });
+ expect(refresh).not.toHaveBeenCalled();
+ });
+ it('hides unsupported schema actions and rechecks revoked capabilities', async () => {
+ const { controller, applyOps, capabilities } = fixture();
+ const savedAction = controller.schemaEditing()!.remove;
+ capabilities.editColumns = false;
+ expect(controller.schemaEditing()).toBeUndefined();
+ expect((await savedAction('column')).isErr()).toBe(true);
+ expect(applyOps).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/database/primitives/database-controller.ts b/apps/web/src/features/database/primitives/database-controller.ts
new file mode 100644
index 0000000000..bc716eb5ed
--- /dev/null
+++ b/apps/web/src/features/database/primitives/database-controller.ts
@@ -0,0 +1,128 @@
+import type { DatabaseOp } from '@core/database-sql/generated/types';
+import { errAsync, ok } from 'neverthrow';
+import type { Accessor } from 'solid-js';
+import { v7 as uuidv7 } from 'uuid';
+import type { OptionEditing } from '../context/option-editing';
+import type { DatabaseApi, DatabaseCapabilities } from '../core/api';
+import { mergeDatabaseColumnOrder } from '../core/column-order';
+import type { DatabaseColumnTypeChange } from '../core/column-schema';
+import { defaultDatabaseColumnName } from '../core/property-creation';
+import type { DatabaseDataSource } from '../queries/api-source';
+
+/** Shared schema actions. The API owns persistence; the source owns refresh. */
+export function createDatabaseController(args: {
+ api: DatabaseApi;
+ data: DatabaseDataSource;
+ tableId: string;
+ capabilities: Accessor<DatabaseCapabilities>;
+ inferNewColumns?: boolean;
+}) {
+ const { api, data, tableId } = args;
+ const apply = (ops: DatabaseOp[], baseVersion?: number) =>
+ api
+ .applyOps({
+ ops,
+ ...(baseVersion === undefined
+ ? {}
+ : { baseVersions: { [tableId]: baseVersion } }),
+ })
+ .andThen((applied) =>
+ data.rows
+ .refresh('after-write')
+ .orElse(() => ok(undefined))
+ .map(() => applied)
+ );
+ const schemaApply: typeof apply = (ops, version) =>
+ args.capabilities().editColumns
+ ? apply(ops, version)
+ : errAsync({
+ code: 'FORBIDDEN',
+ refusal: null,
+ message: 'You cannot edit columns.',
+ });
+ const change = (
+ column: string,
+ change: Extract<DatabaseOp, { kind: 'column' }>['change'],
+ version?: number
+ ) =>
+ schemaApply(
+ [{ kind: 'column', table: tableId, column, change }],
+ version
+ ).map(() => undefined);
+ const schemaEditing = {
+ createDefaultColumn: () => {
+ const column = uuidv7();
+ return change(column, {
+ kind: 'create',
+ definition: {
+ source: 'new',
+ name: defaultDatabaseColumnName(
+ data.rows.columns().map((column) => column.name)
+ ),
+ type: { type: 'text' },
+ inferType: args.inferNewColumns ?? false,
+ },
+ }).map(() => column);
+ },
+ rename: (column: string, name: string, previousName: string) =>
+ change(column, { kind: 'rename', name, previousName }),
+ remove: (column: string) =>
+ change(column, { kind: 'delete' }, data.table()?.version),
+ reorder: (columns: string[]) =>
+ schemaApply(
+ [
+ {
+ kind: 'table',
+ table: tableId,
+ change: {
+ kind: 'reorder_columns',
+ order: mergeDatabaseColumnOrder(
+ data.rows.columns().map((column) => column.id),
+ columns
+ ),
+ },
+ },
+ ],
+ data.table()?.version
+ ).map(() => undefined),
+ changeType: (column: string, request: DatabaseColumnTypeChange) => {
+ const table = data.table();
+ if (!table)
+ return errAsync({
+ code: 'NOT_FOUND' as const,
+ refusal: null,
+ message: 'This table is unavailable.',
+ });
+ const to =
+ request.to.type === 'relation'
+ ? { ...request.to, database: table.databaseId }
+ : request.to;
+ return change(
+ column,
+ { kind: 'change_type', to },
+ request.baseVersion ?? table.version
+ );
+ },
+ };
+ const optionEditing: OptionEditing = {
+ update: (column, option, request) =>
+ change(column, { kind: 'update_option', option, ...request }).mapErr(
+ (error) => ({ kind: 'ops', error })
+ ),
+ remove: (column, option) =>
+ change(column, { kind: 'delete_option', option }).mapErr((error) => ({
+ kind: 'ops',
+ error,
+ })),
+ };
+ return {
+ data,
+ optionEditing: () =>
+ args.capabilities().editColumns ? optionEditing : undefined,
+ capabilities: args.capabilities,
+ apply,
+ schemaEditing: () =>
+ args.capabilities().editColumns ? schemaEditing : undefined,
+ };
+}
+export type DatabaseController = ReturnType<typeof createDatabaseController>;
diff --git a/apps/web/src/features/block-database/primitives/database-search.ts b/apps/web/src/features/database/primitives/database-search.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/database-search.ts
rename to apps/web/src/features/database/primitives/database-search.ts
diff --git a/apps/web/src/features/block-database/primitives/draft-rows.test.ts b/apps/web/src/features/database/primitives/draft-rows.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/draft-rows.test.ts
rename to apps/web/src/features/database/primitives/draft-rows.test.ts
diff --git a/apps/web/src/features/block-database/primitives/draft-rows.ts b/apps/web/src/features/database/primitives/draft-rows.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/draft-rows.ts
rename to apps/web/src/features/database/primitives/draft-rows.ts
diff --git a/apps/web/src/features/block-database/primitives/held-grid-rows.test.ts b/apps/web/src/features/database/primitives/held-grid-rows.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/held-grid-rows.test.ts
rename to apps/web/src/features/database/primitives/held-grid-rows.test.ts
diff --git a/apps/web/src/features/block-database/primitives/held-grid-rows.ts b/apps/web/src/features/database/primitives/held-grid-rows.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/held-grid-rows.ts
rename to apps/web/src/features/database/primitives/held-grid-rows.ts
diff --git a/apps/web/src/features/block-database/primitives/record-actions.ts b/apps/web/src/features/database/primitives/record-actions.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/record-actions.ts
rename to apps/web/src/features/database/primitives/record-actions.ts
diff --git a/apps/web/src/features/block-database/primitives/table-controller.test.ts b/apps/web/src/features/database/primitives/table-controller.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/table-controller.test.ts
rename to apps/web/src/features/database/primitives/table-controller.test.ts
diff --git a/apps/web/src/features/block-database/primitives/table-controller.ts b/apps/web/src/features/database/primitives/table-controller.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/table-controller.ts
rename to apps/web/src/features/database/primitives/table-controller.ts
diff --git a/apps/web/src/features/block-database/primitives/table-model.test.ts b/apps/web/src/features/database/primitives/table-model.test.ts
similarity index 98%
rename from apps/web/src/features/block-database/primitives/table-model.test.ts
rename to apps/web/src/features/database/primitives/table-model.test.ts
index e95d4231ff..3181678662 100644
--- a/apps/web/src/features/block-database/primitives/table-model.test.ts
+++ b/apps/web/src/features/database/primitives/table-model.test.ts
@@ -1,6 +1,6 @@
-import type { SortKey } from '@core/database-sql/generated/types';
import { createRoot, createSignal } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
+import type { SortKey } from '../../../lib/core/database-sql/generated/types';
import type { DatabaseViewColumn } from '../core/database-view';
import type { DatabaseRow } from '../core/table';
import { createDatabaseTableModel } from './table-model';
diff --git a/apps/web/src/features/block-database/primitives/table-model.ts b/apps/web/src/features/database/primitives/table-model.ts
similarity index 98%
rename from apps/web/src/features/block-database/primitives/table-model.ts
rename to apps/web/src/features/database/primitives/table-model.ts
index dc67530d6b..76f0df1e4e 100644
--- a/apps/web/src/features/block-database/primitives/table-model.ts
+++ b/apps/web/src/features/database/primitives/table-model.ts
@@ -1,4 +1,3 @@
-import type { SortKey } from '@core/database-sql/generated/types';
import {
type ColumnDef,
columnOrderingFeature,
@@ -11,6 +10,7 @@ import {
tableFeatures,
} from '@tanstack/solid-table';
import { createMemo, createSignal } from 'solid-js';
+import type { SortKey } from '../../../lib/core/database-sql/generated/types';
import type { DatabaseViewColumn } from '../core/database-view';
import type { DatabaseRow } from '../core/table';
diff --git a/apps/web/src/features/block-database/primitives/undo-controller.test.ts b/apps/web/src/features/database/primitives/undo-controller.test.ts
similarity index 96%
rename from apps/web/src/features/block-database/primitives/undo-controller.test.ts
rename to apps/web/src/features/database/primitives/undo-controller.test.ts
index f9543ff0e7..84796cccac 100644
--- a/apps/web/src/features/block-database/primitives/undo-controller.test.ts
+++ b/apps/web/src/features/database/primitives/undo-controller.test.ts
@@ -1,8 +1,8 @@
-import type { DatabaseOp } from '@core/database-sql/generated/types';
import type { UndoOutcome } from '@service-storage/generated/schemas/undoOutcome';
import { okAsync } from 'neverthrow';
import { createRoot } from 'solid-js';
import { describe, expect, it } from 'vitest';
+import type { DatabaseOp } from '../../../lib/core/database-sql/generated/types';
import { createDatabaseUndo } from './undo-controller';
describe('the database undo controller', () => {
diff --git a/apps/web/src/features/block-database/primitives/undo-controller.ts b/apps/web/src/features/database/primitives/undo-controller.ts
similarity index 97%
rename from apps/web/src/features/block-database/primitives/undo-controller.ts
rename to apps/web/src/features/database/primitives/undo-controller.ts
index 50210de206..6de369d9e5 100644
--- a/apps/web/src/features/block-database/primitives/undo-controller.ts
+++ b/apps/web/src/features/database/primitives/undo-controller.ts
@@ -1,7 +1,7 @@
-import type { DatabaseOp } from '@core/database-sql/generated/types';
import type { UndoOutcome } from '@service-storage/generated/schemas/undoOutcome';
import type { ResultAsync } from 'neverthrow';
import { createSignal } from 'solid-js';
+import type { DatabaseOp } from '../../../lib/core/database-sql/generated/types';
import {
begin,
type CombinedUndo,
diff --git a/apps/web/src/features/block-database/primitives/view-creation.test.ts b/apps/web/src/features/database/primitives/view-creation.test.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/view-creation.test.ts
rename to apps/web/src/features/database/primitives/view-creation.test.ts
diff --git a/apps/web/src/features/block-database/primitives/view-creation.ts b/apps/web/src/features/database/primitives/view-creation.ts
similarity index 100%
rename from apps/web/src/features/block-database/primitives/view-creation.ts
rename to apps/web/src/features/database/primitives/view-creation.ts
diff --git a/apps/web/src/features/database/queries/api-source.test.ts b/apps/web/src/features/database/queries/api-source.test.ts
new file mode 100644
index 0000000000..465876959e
--- /dev/null
+++ b/apps/web/src/features/database/queries/api-source.test.ts
@@ -0,0 +1,78 @@
+import { errAsync, okAsync } from 'neverthrow';
+import { describe, expect, it, vi } from 'vitest';
+import type { DatabaseApi } from '../core/api';
+import { readDatabasePages } from './api-source';
+
+const request = { tableId: 'table', query: { filter: null } };
+function api(readRows: DatabaseApi['readRows']): DatabaseApi {
+ return {
+ key: ['test'],
+ readRows,
+ readTable: () => errAsync({ kind: 'table-unavailable' }),
+ applyOps: () => okAsync({ results: [] }),
+ };
+}
+
+describe('API row pagination', () => {
+ it('restarts the complete read when versions differ, preserving the query', async () => {
+ const read = vi
+ .fn<DatabaseApi['readRows']>()
+ .mockReturnValueOnce(
+ okAsync({
+ rows: [{ rowId: 'old', cells: {} }],
+ tableVersion: 1,
+ nextCursor: 'next',
+ })
+ )
+ .mockReturnValueOnce(okAsync({ rows: [], tableVersion: 2 }))
+ .mockReturnValueOnce(
+ okAsync({
+ rows: [{ rowId: 'new', cells: {} }],
+ tableVersion: 2,
+ nextCursor: 'next',
+ })
+ )
+ .mockReturnValueOnce(
+ okAsync({ rows: [{ rowId: 'last', cells: {} }], tableVersion: 2 })
+ );
+ const result = await readDatabasePages(api(read), request);
+ expect(result._unsafeUnwrap()).toEqual({
+ rows: [
+ { rowId: 'new', cells: {} },
+ { rowId: 'last', cells: {} },
+ ],
+ version: 2,
+ });
+ expect(read.mock.calls.map(([args]) => args.cursor)).toEqual([
+ undefined,
+ 'next',
+ undefined,
+ 'next',
+ ]);
+ expect(
+ read.mock.calls.every(([args]) => args.query === request.query)
+ ).toBe(true);
+ });
+ it('refuses a repeated cursor instead of looping forever', async () => {
+ const read = vi.fn<DatabaseApi['readRows']>(() =>
+ okAsync({ rows: [], tableVersion: 1, nextCursor: 'same' })
+ );
+ expect((await readDatabasePages(api(read), request)).isErr()).toBe(true);
+ expect(read).toHaveBeenCalledTimes(2);
+ });
+ it('preserves retained-row requests across pages and returns read failures', async () => {
+ const read = vi.fn<DatabaseApi['readRows']>(() =>
+ errAsync({ kind: 'fetch', message: 'offline' })
+ );
+ expect(
+ (
+ await readDatabasePages(api(read), { ...request, rowIds: ['held'] })
+ ).isErr()
+ ).toBe(true);
+ expect(read).toHaveBeenCalledWith({
+ ...request,
+ rowIds: ['held'],
+ cursor: undefined,
+ });
+ });
+});
diff --git a/apps/web/src/features/database/queries/api-source.ts b/apps/web/src/features/database/queries/api-source.ts
new file mode 100644
index 0000000000..b36db1b86b
--- /dev/null
+++ b/apps/web/src/features/database/queries/api-source.ts
@@ -0,0 +1,173 @@
+import { queryReadyGate } from '@queries/gate';
+import { type QueryClient, useQuery } from '@tanstack/solid-query';
+import { err, ok, ResultAsync } from 'neverthrow';
+import { type Accessor, createSignal } from 'solid-js';
+import { v7 as uuidv7 } from 'uuid';
+import type { DatabaseRowsSource } from '../context/table-source';
+import type {
+ DatabaseApi,
+ DatabaseRowRequest,
+ DatabaseTableSchema,
+} from '../core/api';
+import { boardInput } from '../core/board-input';
+import { writeDatabaseRow } from '../core/row-write';
+import type { DatabaseRow } from '../core/table';
+import type { DatabaseViewState } from '../core/view-state';
+import type { DatabaseReadFailure } from '../core/write-failure';
+
+export type DatabaseDataSource = {
+ table: Accessor<DatabaseTableSchema | undefined>;
+ rows: DatabaseRowsSource;
+};
+
+/** Pages must belong to one version; never show a mixture from concurrent edits. */
+export async function readDatabasePages(
+ api: DatabaseApi,
+ request: DatabaseRowRequest
+) {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const rows: DatabaseRow[] = [];
+ const seen = new Set<string>();
+ let cursor: string | undefined;
+ let version: number | undefined;
+ do {
+ const page = await api.readRows({ ...request, cursor });
+ if (page.isErr()) return page;
+ if (version !== undefined && page.value.tableVersion !== version) break;
+ version = page.value.tableVersion;
+ rows.push(...page.value.rows);
+ cursor = page.value.nextCursor;
+ if (!cursor) return ok({ rows, version });
+ if (seen.has(cursor))
+ return err<never, DatabaseReadFailure>({
+ kind: 'fetch',
+ message: 'The API returned a repeated cursor.',
+ });
+ seen.add(cursor);
+ } while (cursor);
+ }
+ return err<never, DatabaseReadFailure>({
+ kind: 'fetch',
+ message: 'The table changed while loading. Refresh and try again.',
+ });
+}
+
+/** Default data adapter for a paginated, database-shaped API. */
+export function createDatabaseApiSource(args: {
+ api: DatabaseApi;
+ tableId: string;
+ view: Accessor<DatabaseViewState>;
+ client: QueryClient;
+}): DatabaseDataSource {
+ const { api, tableId, client } = args;
+ const key = [...api.key, 'database-editor', tableId];
+ const [retained, setRetained] = createSignal<Accessor<readonly string[]>>(
+ () => []
+ );
+ const table = useQuery(
+ () => ({
+ queryKey: [...key, 'schema'],
+ queryFn: async () => {
+ const result = await api.readTable(tableId);
+ if (result.isErr()) throw result.error;
+ return result.value;
+ },
+ }),
+ () => client
+ );
+ const rows = useQuery(
+ () => ({
+ queryKey: [...key, 'rows', args.view().query],
+ queryFn: async () => {
+ const result = await readDatabasePages(api, {
+ tableId,
+ query: args.view().query,
+ });
+ if (result.isErr()) throw result.error;
+ return result.value;
+ },
+ }),
+ () => client
+ );
+ const held = useQuery(
+ () => ({
+ queryKey: [...key, 'retained', [...retained()()].sort()],
+ enabled: retained()().length > 0,
+ queryFn: async () => {
+ const result = await readDatabasePages(api, {
+ tableId,
+ query: { filter: null },
+ rowIds: [...retained()()],
+ });
+ if (result.isErr()) throw result.error;
+ return result.value;
+ },
+ }),
+ () => client
+ );
+ const schema = () => (queryReadyGate(table) ? table.data : undefined);
+ const refresh = () =>
+ ResultAsync.fromPromise(
+ client.invalidateQueries({ queryKey: key }, { throwOnError: true }),
+ (): DatabaseReadFailure => ({
+ kind: 'fetch',
+ message: 'Could not refresh this table.',
+ })
+ );
+ return {
+ table: schema,
+ rows: {
+ columns: () => schema()?.columns ?? [],
+ read: () => {
+ const table = schema();
+ return table && queryReadyGate(rows)
+ ? boardInput(table, rows.data.rows, args.view())
+ : undefined;
+ },
+ snapshot: () =>
+ queryReadyGate(rows)
+ ? {
+ rows: rows.data.rows,
+ version: rows.data.version,
+ retained: queryReadyGate(held) ? held.data.rows : [],
+ }
+ : undefined,
+ loading: () => table.isPending || rows.isPending,
+ refreshing: () => table.isRefetching || rows.isRefetching,
+ error: () =>
+ table.isError ||
+ rows.isError ||
+ (retained()().length > 0 && held.isError)
+ ? { kind: 'fetch', message: 'Could not read this table.' }
+ : undefined,
+ refresh,
+ retain: (ids) => setRetained(() => ids),
+ write: (mutation, _base, createOptions) =>
+ writeDatabaseRow(
+ {
+ tableId,
+ columns: schema()?.columns ?? [],
+ applyOps: (batch) => api.applyOps(batch),
+ },
+ mutation,
+ createOptions
+ ),
+ addOption: (column, label) =>
+ api
+ .applyOps({
+ ops: [
+ {
+ kind: 'column',
+ table: tableId,
+ column,
+ change: {
+ kind: 'add_options',
+ options: [{ id: uuidv7(), label }],
+ },
+ },
+ ],
+ })
+ .andThen(() => refresh().orElse(() => ok(undefined))),
+ },
+ };
+}
diff --git a/apps/web/src/features/block-database/tests/fake-rows-source.ts b/apps/web/src/features/database/tests/fake-rows-source.ts
similarity index 100%
rename from apps/web/src/features/block-database/tests/fake-rows-source.ts
rename to apps/web/src/features/database/tests/fake-rows-source.ts
diff --git a/apps/web/src/features/block-database/views/database-board-view.test.tsx b/apps/web/src/features/database/views/database-board-view.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/views/database-board-view.test.tsx
rename to apps/web/src/features/database/views/database-board-view.test.tsx
index 21b09b6988..837b7e219b 100644
--- a/apps/web/src/features/block-database/views/database-board-view.test.tsx
+++ b/apps/web/src/features/database/views/database-board-view.test.tsx
@@ -1,8 +1,3 @@
-import type {
- Board,
- Catalog,
- Outcome,
-} from '@core/database-sql/generated/types';
import type { CardPosition } from '@service-storage/generated/schemas/cardPosition';
import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';
import {
@@ -16,6 +11,11 @@ import {
import { errAsync, ok, okAsync, ResultAsync } from 'neverthrow';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type {
+ Board,
+ Catalog,
+ Outcome,
+} from '../../../lib/core/database-sql/generated/types';
import type { CardMoved } from '../core/view-state';
import type { DatabaseOpFailure } from '../core/write-failure';
import type { BoardPositionsState } from '../primitives/board-layout';
@@ -41,10 +41,10 @@ const loadEngine = vi.hoisted(() =>
}))
);
-vi.mock('@core/database-sql/wasm-module', () => ({
+vi.mock('../../../lib/core/database-sql/wasm-module', () => ({
loadDatabaseSqlWasm: loadEngine,
}));
-vi.mock('@core/component/Toast/Toast', () => ({
+vi.mock('../../../lib/core/component/Toast/Toast', () => ({
toast: { failure: toastFailure },
}));
diff --git a/apps/web/src/features/block-database/views/database-board-view.tsx b/apps/web/src/features/database/views/database-board-view.tsx
similarity index 94%
rename from apps/web/src/features/block-database/views/database-board-view.tsx
rename to apps/web/src/features/database/views/database-board-view.tsx
index 4e604b7b7a..9788082793 100644
--- a/apps/web/src/features/block-database/views/database-board-view.tsx
+++ b/apps/web/src/features/database/views/database-board-view.tsx
@@ -1,6 +1,3 @@
-import { toast } from '@core/component/Toast/Toast';
-import { engineFailure } from '@core/database-sql/driver';
-import type { LaneKey } from '@core/database-sql/generated/types';
import type { DatabaseOpsError } from '@service-storage/databases';
import type { CardPosition } from '@service-storage/generated/schemas/cardPosition';
import type { ViewLayout } from '@service-storage/generated/schemas/viewLayout';
@@ -16,6 +13,9 @@ import {
Show,
Switch,
} from 'solid-js';
+import { toast } from '../../../lib/core/component/Toast/Toast';
+import { engineFailure } from '../../../lib/core/database-sql/driver';
+import type { LaneKey } from '../../../lib/core/database-sql/generated/types';
import { BoardMenu } from '../components/board-menu';
import {
DatabaseBoard,
@@ -65,8 +65,10 @@ type BoardLayout = Extract<ViewLayout, { kind: 'board' }>;
/** Where a board's card places come from, and how a move is written. */
export type BoardPositions = {
state: Accessor<BoardPositionsState>;
- setPositions: (change: (positions: CardPosition[]) => CardPosition[]) => void;
- move: (move: CardMove) => ResultAsync<CardMoved, DatabaseOpFailure>;
+ setPositions?: (
+ change: (positions: CardPosition[]) => CardPosition[]
+ ) => void;
+ move?: (move: CardMove) => ResultAsync<CardMoved, DatabaseOpFailure>;
};
type DatabaseBoardViewProps = {
@@ -191,7 +193,7 @@ function GroupedBoard(
/** The board as the engine lays it out, sorted as the view says or, with `unsorted`, by hand. */
const layOut = (unsorted: boolean) => {
const ready = state();
- const read = props.source.read();
+ const read = props.source.read?.();
if (ready.kind !== 'ready' || !read) return undefined;
const query = unsorted ? { ...read.view.query, sort: [] } : read.view.query;
return Result.fromThrowable(ready.engine.board, engineFailure)(
@@ -226,6 +228,8 @@ function GroupedBoard(
);
}
function write(move: CardMove) {
+ const persist = props.positions.move;
+ if (!persist) return;
const ready = state();
const shown = board();
// A move the shown lane has no place for writes no early places; the server's answer settles them.
@@ -238,14 +242,13 @@ function GroupedBoard(
)
: undefined;
if (placed?.isOk())
- props.positions.setPositions((current) =>
+ props.positions.setPositions?.((current) =>
withPositions(current, placed.value)
);
setMoves((current) => [...current, { move }]);
- void props.positions
- .move(move)
+ void persist(move)
.map(({ positions, tableVersion }) => {
- props.positions.setPositions((current) =>
+ props.positions.setPositions?.((current) =>
withPositions(current, positions)
);
taken(move, tableVersion);
@@ -340,7 +343,7 @@ function GroupedBoard(
createPending={props.createPending}
createComplete={props.createComplete}
onOpen={props.onOpen}
- onMove={drop}
+ onMove={props.positions.move ? drop : undefined}
onLaneOrderChange={
props.onViewChange
? (order) => changeLayout(withLaneOrder(props.layout, order))
diff --git a/apps/web/src/features/block-database/views/database-records-view.test.tsx b/apps/web/src/features/database/views/database-records-view.test.tsx
similarity index 99%
rename from apps/web/src/features/block-database/views/database-records-view.test.tsx
rename to apps/web/src/features/database/views/database-records-view.test.tsx
index c39da61215..67a81eba97 100644
--- a/apps/web/src/features/block-database/views/database-records-view.test.tsx
+++ b/apps/web/src/features/database/views/database-records-view.test.tsx
@@ -1,8 +1,3 @@
-import type {
- Board,
- Catalog,
- Outcome,
-} from '@core/database-sql/generated/types';
import type { DatabaseOpsError } from '@service-storage/databases';
import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';
import {
@@ -24,6 +19,11 @@ import {
} from 'neverthrow';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type {
+ Board,
+ Catalog,
+ Outcome,
+} from '../../../lib/core/database-sql/generated/types';
import type { DatabaseWriteResult } from '../context/table-source';
import type { DatabaseViewColumn } from '../core/database-view';
import type { ViewChange } from '../core/view-state';
@@ -40,7 +40,7 @@ import {
vi.mock('@property/editors/selectors/PropertyDateSelector', () => ({
PropertyDateSelector: () => null,
}));
-vi.mock('@core/database-sql/wasm-module', () => ({
+vi.mock('../../../lib/core/database-sql/wasm-module', () => ({
// Stands in for the engine's board: the layout's listed lanes, each holding
// the answered rows whose group cell names its option.
loadDatabaseSqlWasm: () =>
diff --git a/apps/web/src/features/block-database/views/database-records-view.tsx b/apps/web/src/features/database/views/database-records-view.tsx
similarity index 98%
rename from apps/web/src/features/block-database/views/database-records-view.tsx
rename to apps/web/src/features/database/views/database-records-view.tsx
index df5da22b41..df97017b9d 100644
--- a/apps/web/src/features/block-database/views/database-records-view.tsx
+++ b/apps/web/src/features/database/views/database-records-view.tsx
@@ -10,7 +10,6 @@ import {
Switch,
untrack,
} from 'solid-js';
-import { GridCell, type GridCellProps } from '../component/GridCell';
import type { DatabaseBoardControls } from '../components/database-board';
import {
DatabaseLoadFailure,
@@ -29,6 +28,7 @@ import {
SchemaErrorNotice,
} from '../components/database-table-notices';
import { filterConditionCount } from '../components/database-view-filters';
+import { GridCell, type GridCellProps } from '../components/grid-cell';
import { RecordPanel } from '../components/record-panel';
import type { DatabaseRowsSource } from '../context/table-source';
import type { DatabaseColumnType } from '../core/column-inference';
@@ -102,7 +102,7 @@ export type DatabaseRecordsViewProps = {
/** Clear the view's filter. */
onClearConstraints?: () => void;
/** A board's card places. */
- boardPositions: BoardPositions;
+ boardPositions?: BoardPositions;
renderTextEditor?: GridCellProps['renderTextEditor'];
renderTextValue?: GridCellProps['renderTextValue'];
renderMentionPicker?: GridCellProps['renderMentionPicker'];
@@ -452,7 +452,11 @@ export function DatabaseRecordsView(props: DatabaseRecordsViewProps) {
source={props.source}
rows={rows()}
columns={columns()}
- positions={props.boardPositions}
+ positions={
+ props.boardPositions ?? {
+ state: () => ({ kind: 'ready', positions: [] }),
+ }
+ }
canEdit={props.canEdit}
onViewChange={
!props.stored || props.canEdit ? props.onViewChange : undefined
diff --git a/apps/web/src/features/database/views/database-records.tsx b/apps/web/src/features/database/views/database-records.tsx
new file mode 100644
index 0000000000..0dfa793e22
--- /dev/null
+++ b/apps/web/src/features/database/views/database-records.tsx
@@ -0,0 +1,62 @@
+import { Show } from 'solid-js';
+import { AddColumnButton } from '../components/add-column-button';
+import { useDatabase } from '../context/database';
+import {
+ OptionEditingContext,
+ useOptionEditing,
+} from '../context/option-editing';
+import {
+ DatabaseRecordsView,
+ type DatabaseRecordsViewProps,
+} from './database-records-view';
+
+type HostProps = Omit<
+ DatabaseRecordsViewProps,
+ | 'name'
+ | 'source'
+ | 'canEdit'
+ | 'onChangeColumnType'
+ | 'onDeleteColumn'
+ | 'onReorderColumns'
+ | 'onRenameColumn'
+ | 'createColumn'
+ | 'addColumn'
+>;
+
+/** The complete records editor, wired once to the surrounding database controller. */
+export function DatabaseRecords(props: HostProps) {
+ const database = useDatabase();
+ const hostOptions = useOptionEditing();
+ return (
+ <OptionEditingContext.Provider
+ value={hostOptions ?? database.optionEditing()}
+ >
+ <DatabaseRecordsView
+ {...props}
+ name={database.data.table()?.name ?? ''}
+ source={database.data.rows}
+ canEdit={database.capabilities().editRows}
+ onChangeColumnType={database.schemaEditing()?.changeType}
+ onDeleteColumn={database.schemaEditing()?.remove}
+ onReorderColumns={database.schemaEditing()?.reorder}
+ onRenameColumn={database.schemaEditing()?.rename}
+ createColumn={database.schemaEditing()?.createDefaultColumn}
+ addColumn={
+ database.schemaEditing()
+ ? (label, onCreated) => (
+ <Show when={database.schemaEditing()}>
+ {(schema) => (
+ <AddColumnButton
+ create={schema().createDefaultColumn}
+ label={label}
+ onCreated={onCreated}
+ />
+ )}
+ </Show>
+ )
+ : undefined
+ }
+ />
+ </OptionEditingContext.Provider>
+ );
+}
diff --git a/apps/web/src/features/block-database/views/database-table-view.tsx b/apps/web/src/features/database/views/database-table-view.tsx
similarity index 100%
rename from apps/web/src/features/block-database/views/database-table-view.tsx
rename to apps/web/src/features/database/views/database-table-view.tsx
diff --git a/docs/AGENT_GUIDE/databases.md b/docs/AGENT_GUIDE/databases.md
index 2d5129b521..cd49bd7c6c 100644
--- a/docs/AGENT_GUIDE/databases.md
+++ b/docs/AGENT_GUIDE/databases.md
@@ -488,3 +488,16 @@ Schema edits update their UI optimistically and finish after the write commits;
they do not wait for the background catalog refresh. A refused edit rolls back
its optimistic state when no newer cache update has replaced it, then refreshes.
A slow or failed refresh is not a reason to resend a successful mutation.
+
+### Embedded database editors
+
+The shared editor also runs under a host's `DatabaseProvider`, using schema reads,
+row queries and operation batches from that host's API. Verify cell edits and
+column edits on the host surface, not only in the Macro database block. A host
+without schema-edit permission offers no add, rename, delete or type-change
+actions. Board card dragging requires a supplied position writer; a board without
+one is still readable and must not report a successful move.
+
+For local UI regression coverage, the database browser fixtures include an API
+host with no Macro database entity. Its reads are paginated and its edits pass
+through the same controller used by the database block.