Files
windmill/frontend/src/lib/components/DatatableSchemaDiff.svelte
T
Diego Imbert e47aedac0a feat: add SQL migrations for data tables (#9693)
* feat: add datatable_migrations table

* feat: add route to run datatable migrations

* feat: sync datatable migrations as .up.sql/.down.sql files

* feat: add datatable migrate up/down commands and post-push run prompt

* feat: add datatable migrate new command to scaffold migrations

* feat: add datatable migrations management UI

* feat: prompt to create migration on DDL in datatable SQL editors

* feat: support running a single specific datatable migration

* feat: view migration content, run single migration, fix stacked modal

* feat: per-row revert button with out-of-order warning

* fix: avoid migrations list flicker on refresh after an action

* feat: generate initial datatable migration via pg_dump

* fix: surface datatable migration API error details in toasts

* fix: revert created migration if create-and-run fails to run

* fix: include postgres error detail in migration run/rollback failures

* feat: sync datatable migrations as files via the workspace export

* refactor: move datatable migrations to migrations/datatable/ path

* fix: drop redundant datatable_migration label in sync output

* fix: exclude datatable migration sql files from script metadata generation

* feat: run datatable migrations as user-permissioned labeled jobs

* feat: reject invalid datatable migrations on sync push

* feat: datatable migrate up/down default to all datatables, --datatable to target one

* fix: surface postgres error detail when datatable migrations fail to run

* chore: regenerate CLI docs for datatable migrate commands

* feat: default new datatable migration to a BEGIN/END transaction template

* fix: validate datatable migration name and datatable at the API boundary

* fix: ensure detected DDL ends with semicolon when wrapped in transaction

* fix: re-prompt instead of stripping DDL when new-migration modal is cancelled

* feat: refresh datatable schema after running a migration from the SQL REPL

* feat: record db manager DDL on data tables as migrations

* feat: make datatable migrations opt-in per data table

* fix: make migration view editor read-only so its code can scroll

* fix: don't re-prompt DDL guard when creating a migration without running

* feat: generate down migrations for db manager DDL (postgres)

* fix: correct down migration for db manager alters (no double-wrap, serial)

* feat: explain migrations purpose with a tooltip in the migrations modal

* compare paeg

* feat: add datatable_migration kind to workspace diff pipeline

* chore: point ee-repo-ref at datatable_migration git-sync companion

* fix: harden datatable migration version allocation and initial-migration bookkeeping, add tests

* feat: deploy and run datatable migrations on workspace merge

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Refactor + handle datatable setting delete/rename

* refactor: move datatable migration rename/delete cascade into module

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(windmill-utils-internal): bump to 1.7.1 for datatable migration deploy provider methods

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(db-manager): add Migrations button to top bar, make Refresh icon-only

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* BEGIN/END placeholder in down migration

* feat: autofocus migration name input and flag it red when empty

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(datatable-migrations): allow non-admins to create/run/revert migrations, gate only opt in/out

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* border nits

* refresh db manager schema on migrations

* BEGIN/END scaffold in CLI

* feat(cli): push local datatable migrations before running on migrate up

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: flag invalid migration name with red border, not just empty

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor: drop random slug from auto-generated migration names

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: offer revert-and-delete when deleting an installed migration

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: record fork merge as a migration when target datatable opts in

* nit

* clone migrations on fork

* windmill-utils-internal

* fix(datatable-migrations): serialize run/rollback with a per-db advisory lock

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(db-manager): fail closed when migrations-status check errors on DDL apply

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: fix generate_initial migration ordering comment to match code

* chore(datatable-migrations): remove unused update_datatable_migrations endpoint

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: run DDL migration guard on the script editor Test button

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* split

* ee-repo-ref

* chore(frontend): sync package-lock with package.json (@emnapi deps)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(datatable-migrations): never resolve instance credentials into migration job args

datatable_database_arg eagerly resolved instance data-table credentials
(including the shared instance-wide Postgres password) and passed them as the
migration job's plaintext `database` arg, landing in v2_job.args. Since the
run route has no admin gate, a non-admin could run a migration and read
args.database to recover the password, granting cross-workspace psql access to
all instance data-table DBs.

Pass a `datatable://<name>` reference for both resource-backed and instance
data tables instead; the pg executor already resolves it to real credentials
server-side at run time, so nothing sensitive is ever stored in the job args.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* nit

* fix: handle dollar-quoting and comments when splitting SQL statements

* feat: deploy datatable migrations on merge with explicit opt-in error

* fix(frontend): sync package-lock with npm 11 peer-dep resolution

npm ci failed with 'Missing: @emnapi/core@1.11.2 / @emnapi/runtime@1.11.2 from
lock file'. @napi-rs/wasm-runtime declares @emnapi/core|runtime ^1.7.1 as
peerDependencies while @rolldown/binding-wasm32-wasi pins them to exactly
1.10.0. Newer npm (bundled with node 24 in CI) installs the peer deps at the
highest match (1.11.2) alongside rolldown's nested 1.10.0, so the ideal tree
needs both versions; the committed lock only had 1.10.0.

Regenerate the lock with npm 11.18 so it carries both 1.11.2 (top-level, for
the peer deps) and 1.10.0 (nested, for rolldown's pin). Verified npm ci passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* nit npm publish

* fix: fail closed on migrations-status error in fork schema merge

* nit CI emnapi/core version

* prevent initial_datatable_migration if migrations already exist

* fix(datatable-migrations): validate persisted data table names as path segments

edit_datatable_config only validated rename segments, not the actual
settings.datatables keys, so a data table could be saved directly under a name
like '..' or one containing '/'. Since new tables default to
migrations_enabled = true, generate_initial_datatable_migration would then
insert a migration row and the sync export would build
migrations/datatable/<name>/... paths from that name, producing malformed or
directory-escaping export paths.

Validate every persisted data table name in edit_datatable_config (alongside
the existing rename checks) and add validate_datatable_path_segment to
generate_initial_datatable_migration for defense in depth.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: scope datatable _wm_migrations by data table and cascade renames/deletes

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(system_prompts): resolve nested local command groups in CLI docs generator

The CLI docs generator anchored on the first `new Command()` in a file and
never resolved locally-defined command groups passed as
`.command("name", localCmd)`. For datatable this flattened the nested
`migrate` group: it emitted `datatable new/up/down` plus a bare
`datatable migrate`, and mislabeled the datatable command with the migrate
group's description. jobs was broken the same way (its description was pull's,
and pull/push rendered empty).

Anchor block extraction on the `export default`ed command, recurse into
locally-defined `const x = new Command()` groups mounted as subcommands, and
render nested sub-subcommands. Regenerated docs now show
`datatable migrate new/up/down` and `jobs pull/push` with their real
options.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor: drop unreleased _wm_migrations legacy-upgrade handling

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: return datatable migration SQL from getItemValue for the diff drawer

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(frontend): use windmill-utils-internal 1.8.2 for migration diff drawer

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* nit

* nit

* fix: handle datatable migration renames on push and dedupe timestamps

* fix: reject rewriting an already-applied datatable migration on upsert

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(frontend): add missing @emnapi/core and @emnapi/runtime lockfile entries

Resolves npm ci EUSAGE failure: the optional cpu:wasm32 @rolldown/binding-wasm32-wasi
declares deps on @emnapi/core@1.11.2 and @emnapi/runtime@1.11.2 that had no resolved
lockfile entries.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(cli): datatable migrate up/down default to main datatable, not all

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: fail closed when applied status unreadable on datatable migration rewrite

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: surface full error detail in Database Manager DDL/query errors

* "See migration" button in the toast

* feat: add Enter shortcut to Create-a-migration in the DDL guard

* fix(frontend): warn before running a newly-created datatable migration out of order

The row-level Run action warns when earlier migrations are still pending, but
the create-and-run paths ran a just-created migration with `only` directly,
applying it ahead of older pending migrations without that confirmation.

Reuse the same "Run migration out of order" confirmation across all
create-and-run paths via a shared helper (datatableMigrationUtils):
- NewDataTableMigrationModal "Create and run" (and the DDL guard path)
- DatatableSchemaDiff fork→parent merge
- dbOps schema ops (DB manager create/alter/drop) — the pure factory throws a
  MigrationRunCancelled sentinel on decline, which DBTableEditor treats as a
  silent cancel

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: keep renamed datatable migrations visible in compare view

* fix: record per-migration deployment on datatable migrations disable

* fix(cli): run deployed datatable migrations after workspace merge

The merge command upserted datatable_migration definitions into the target
workspace and reported the item as successfully deployed, but never ran the
migrations. For forked datatables backed by separate databases, this left the
target schema unchanged until someone manually ran `wmill datatable migrate up`,
while the CLI reported a successful merge.

Collect the datatable migrations deployed (not deleted) into the target and,
after the deploy loop, offer to run them via the existing offerToRunNewMigrations
helper — the same post-deploy run prompt the push/sync path uses (interactive
only; `--yes`/non-TTY skip the mutating run, matching push behavior). Export
parseDatatableMigrationDeployPath so the merge path can parse the deployed items.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(backend): serialize datatable migration edits/deletes with the run lock

A migration run snapshots a migration's code_up from datatable_migrations and
only records its version in the data table's _wm_migrations after the job
succeeds. upsert_datatable_migration checked _wm_migrations before allowing an
edit but took no lock, so a concurrent edit could read "not applied yet",
rewrite code_up/code_down, and then the in-flight run would record the version
for the old SQL — leaving _wm_migrations pointing at SQL that was never applied
(migrate up then skips it; rollback runs a down that doesn't match).

Serialize definition rewrites and deletes with the same per-database advisory
lock the run/rollback paths use:
- Factor the connect+advisory-lock into lock_datatable_migration_runs and the
  applied-versions read into read_applied_versions_on_client.
- run_datatable_migrations now snapshots the definitions AFTER taking the lock,
  so code_up can't change between snapshot and version-record.
- upsert (when changing an existing def) and delete take the lock across the
  applied-check and the write; delete now rejects deleting an already-applied
  migration (would orphan its _wm_migrations record), symmetric with upsert.
  Both fail closed if the data table database is unreachable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(frontend): stack the out-of-order migration confirm above the DB editor preview

Creating a table on a migrations-enabled data table opened the DB table editor's
"Confirm running the following" preview modal, whose confirm triggers applyDdl,
which then asks for out-of-order confirmation. Both are ConfirmationModals with a
hardcoded z-[9999]; the out-of-order one lives in DBManagerContent (mounted before
the editor), so it rendered behind the still-open preview modal.

Add an optional zIndexClass prop to ConfirmationModal (default z-[9999],
backward-compatible) and give the DB-manager out-of-order confirm z-[10000] so it
stacks on top.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: update ee-repo-ref to 27672e37df5d9dfde94f19963d5ffcdf8dd5448c

This commit updates the EE repository reference after PR #623 was merged in windmill-ee-private.

Previous ee-repo-ref: 6c287041cd7edd4a77a4bc07ad0e156cec32cce4

New ee-repo-ref: 27672e37df5d9dfde94f19963d5ffcdf8dd5448c

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
2026-07-07 08:25:16 +00:00

662 lines
23 KiB
Svelte

<script module lang="ts">
import type {
TableEditorValues,
TableEditorValuesColumn,
TableEditorForeignKey
} from '$lib/components/apps/components/display/dbtable/tableEditor'
import {
diffTableEditorValues,
type AlterTableValues,
makeAlterTableQueries
} from '$lib/components/apps/components/display/dbtable/queries/alterTable'
import { renderForeignKey } from '$lib/components/apps/components/display/dbtable/queries/dbQueriesUtils'
import type { GetDatatableFullSchemaResponse } from '$lib/gen'
export type DatabaseSchema = Record<string, Record<string, TableEditorValues>>
export function apiSchemaToEditorSchema(
apiSchema: GetDatatableFullSchemaResponse
): DatabaseSchema {
const result: DatabaseSchema = {}
for (const [schemaName, tables] of Object.entries(apiSchema)) {
result[schemaName] = {}
for (const [tableName, table] of Object.entries(tables as Record<string, any>)) {
if (!table || typeof table !== 'object') continue
result[schemaName][tableName] = {
name: table.name ?? tableName,
columns: (table.columns ?? []).map(
(c: any): TableEditorValuesColumn => ({
name: c.name,
datatype: c.datatype,
primaryKey: c.primary_key ?? c.primaryKey,
defaultValue: c.default_value ?? c.defaultValue,
nullable: c.nullable
})
),
foreignKeys: (table.foreign_keys ?? table.foreignKeys ?? []).map(
(fk: any): TableEditorForeignKey => ({
targetTable: fk.target_table ?? fk.targetTable,
columns: (fk.columns ?? []).map((col: any) => ({
sourceColumn: col.source_column ?? col.sourceColumn,
targetColumn: col.target_column ?? col.targetColumn
})),
onDelete: (fk.on_delete ?? fk.onDelete ?? 'NO ACTION') as
| 'CASCADE'
| 'SET NULL'
| 'NO ACTION',
onUpdate: (fk.on_update ?? fk.onUpdate ?? 'NO ACTION') as
| 'CASCADE'
| 'SET NULL'
| 'NO ACTION',
fk_constraint_name: fk.fk_constraint_name
})
),
pk_constraint_name: table.pk_constraint_name
}
}
}
return result
}
export type TableDiff = {
schemaName: string
tableName: string
kind: 'added' | 'removed' | 'modified'
operations?: AlterTableValues
}
export type DatatableDiff = {
datatableName: string
aheadChanges: TableDiff[]
behindChanges: TableDiff[]
originalSchema: DatabaseSchema
parentSchema: DatabaseSchema
forkSchema: DatabaseSchema
}
export function diffDatabaseSchemas(
original: DatabaseSchema,
current: DatabaseSchema
): TableDiff[] {
const diffs: TableDiff[] = []
const allSchemas = new Set([...Object.keys(original), ...Object.keys(current)])
for (const schemaName of allSchemas) {
const origTables = original[schemaName] ?? {}
const currTables = current[schemaName] ?? {}
const allTables = new Set([...Object.keys(origTables), ...Object.keys(currTables)])
for (const tableName of allTables) {
const origTable = origTables[tableName]
const currTable = currTables[tableName]
if (!origTable && currTable) {
diffs.push({ schemaName, tableName, kind: 'added' })
} else if (origTable && !currTable) {
diffs.push({ schemaName, tableName, kind: 'removed' })
} else if (origTable && currTable) {
const currWithInitial: TableEditorValues = {
...currTable,
columns: currTable.columns.map((col) => ({
...col,
initialName: col.name,
defaultValue: col.defaultValue ? `{${col.defaultValue}}` : undefined
}))
}
const origTableTransformed: TableEditorValues = {
...origTable,
columns: origTable.columns.map((col) => ({
...col,
defaultValue: col.defaultValue ? `{${col.defaultValue}}` : undefined
}))
}
const diff = diffTableEditorValues(origTableTransformed, currWithInitial)
if (diff.operations.length > 0) {
diffs.push({ schemaName, tableName, kind: 'modified', operations: diff })
}
}
}
}
return diffs
}
export function computeDatatableDiff(
datatableName: string,
originalSchema: DatabaseSchema,
parentSchema: DatabaseSchema,
forkSchema: DatabaseSchema
): DatatableDiff {
return {
datatableName,
behindChanges: diffDatabaseSchemas(originalSchema, parentSchema),
aheadChanges: diffDatabaseSchemas(originalSchema, forkSchema),
originalSchema,
parentSchema,
forkSchema
}
}
/** Detect PostgreSQL auto-increment columns and return the serial type + cleaned props.
* e.g. bigint + nextval('seq'::regclass) → BIGSERIAL (no DEFAULT needed) */
function resolveColumnType(c: TableEditorValuesColumn): {
datatype: string
defaultValue: string | undefined
} {
const dv = c.defaultValue ?? ''
if (/^{?nextval\(/.test(dv)) {
const dt = c.datatype?.toLowerCase() ?? ''
if (dt === 'bigint') return { datatype: 'BIGSERIAL', defaultValue: undefined }
if (dt === 'integer' || dt === 'int') return { datatype: 'SERIAL', defaultValue: undefined }
if (dt === 'smallint') return { datatype: 'SMALLSERIAL', defaultValue: undefined }
}
return { datatype: c.datatype, defaultValue: c.defaultValue }
}
export function generateMigrationSql(change: TableDiff, sourceSchema: DatabaseSchema): string {
if (change.kind === 'modified' && change.operations) {
const queries = makeAlterTableQueries(change.operations, 'postgresql', change.schemaName)
if (queries.length === 0) return ''
return 'BEGIN;\n' + queries.join('\n') + '\nCOMMIT;'
}
if (change.kind === 'added') {
const table = sourceSchema[change.schemaName]?.[change.tableName]
if (!table) return ''
const colDefs = table.columns
.map((c) => {
const { datatype, defaultValue } = resolveColumnType(c)
let def = `"${c.name}" ${datatype}`
if (c.nullable === false) def += ' NOT NULL'
if (defaultValue) def += ` DEFAULT ${defaultValue}`
return def
})
.join(',\n ')
const pkCols = table.columns.filter((c) => c.primaryKey).map((c) => `"${c.name}"`)
const pkLine = pkCols.length > 0 ? `,\n PRIMARY KEY (${pkCols.join(', ')})` : ''
const qualifiedName = `"${change.schemaName}"."${change.tableName}"`
let sql = `BEGIN;\nCREATE TABLE ${qualifiedName} (\n ${colDefs}${pkLine}\n);`
for (const fk of table.foreignKeys ?? []) {
const fkSql = renderForeignKey(fk, {
useSchema: true,
dbType: 'postgresql',
tableName: change.tableName
})
sql += `\nALTER TABLE ${qualifiedName} ADD ${fkSql};`
}
sql += '\nCOMMIT;'
return sql
}
if (change.kind === 'removed') {
return `BEGIN;\nDROP TABLE IF EXISTS "${change.schemaName}"."${change.tableName}";\nCOMMIT;`
}
return ''
}
</script>
<script lang="ts">
import { WorkspaceService } from '$lib/gen'
import { Loader2, ChevronDown, ChevronRight, Plus, Minus, Pencil, Eye } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import Drawer from '$lib/components/common/drawer/Drawer.svelte'
import SimpleEditor from '$lib/components/SimpleEditor.svelte'
import { sendUserToast } from '$lib/toast'
import { userWorkspaces } from '$lib/stores'
import { runScriptAndPollResult } from '$lib/components/jobs/utils'
import YAML from 'yaml'
import DrawerContent from './common/drawer/DrawerContent.svelte'
import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte'
import { createAsyncConfirmationModal } from './common/confirmationModal/asyncConfirmationModal.svelte'
import Portal from '$lib/components/Portal.svelte'
import {
pendingMigrations,
outOfOrderRunMessage
} from './workspaceSettings/datatableMigrationUtils'
import Alert from './common/alert/Alert.svelte'
import ResizeTransitionWrapper from './common/ResizeTransitionWrapper.svelte'
interface Props {
currentWorkspaceId: string
parentWorkspaceId: string
}
let { currentWorkspaceId, parentWorkspaceId }: Props = $props()
let loading = $state(true)
let error: string | undefined = $state(undefined)
let diffs: DatatableDiff[] = $state([])
// Number of forked datatables this schema-diff section applies to: those that
// have NOT opted in to the migrations feature. When a datatable enables
// migrations, its changes flow through the normal item diff instead, so it is
// excluded here and the whole section hides once none remain.
let applicableCount = $state(0)
let expandedDatatables: Set<string> = $state(new Set())
// Drawer state
let drawerOpen = $state(false)
let drawerChange: TableDiff | undefined = $state(undefined)
let drawerDiff: DatatableDiff | undefined = $state(undefined)
let drawerDirection: 'ahead' | 'behind' | undefined = $state(undefined)
let migrationSql = $state('')
let migrationRunning = $state(false)
let confirmDeployOpen = $state(false)
const outOfOrderModal = createAsyncConfirmationModal()
async function loadDiffs() {
loading = true
error = undefined
diffs = []
try {
const forkSettings = await WorkspaceService.getPublicSettings({
workspace: currentWorkspaceId
})
const datatables = forkSettings.datatable?.datatables ?? {}
const forkedEntries = Object.entries(datatables).filter(
([_, dt]) => dt.forked_from != null && dt.migrations_enabled !== true
)
applicableCount = forkedEntries.length
if (forkedEntries.length === 0) {
loading = false
return
}
const results: DatatableDiff[] = []
for (const [dtName, dt] of forkedEntries) {
try {
const originalSchema = apiSchemaToEditorSchema((dt.forked_from as any)?.schema ?? {})
const [parentSchemaRaw, forkSchemaRaw] = await Promise.all([
WorkspaceService.getDatatableFullSchema({
workspace: parentWorkspaceId,
requestBody: { source: `datatable://${dtName}` }
}),
WorkspaceService.getDatatableFullSchema({
workspace: currentWorkspaceId,
requestBody: { source: `datatable://${dtName}` }
})
])
const parentSchema = apiSchemaToEditorSchema(parentSchemaRaw)
const forkSchema = apiSchemaToEditorSchema(forkSchemaRaw)
const diff = computeDatatableDiff(dtName, originalSchema, parentSchema, forkSchema)
if (diff.aheadChanges.length > 0 || diff.behindChanges.length > 0) {
results.push(diff)
}
} catch (e: any) {
console.error(`Failed to diff datatable ${dtName}:`, e)
}
}
diffs = results
} catch (e: any) {
error = e?.body ?? e?.message ?? String(e)
} finally {
loading = false
}
}
$effect(() => {
void [currentWorkspaceId, parentWorkspaceId]
loadDiffs()
})
function toggleExpanded(name: string) {
const next = new Set(expandedDatatables)
if (next.has(name)) next.delete(name)
else next.add(name)
expandedDatatables = next
}
function operationSummary(d: TableDiff): string {
if (d.kind === 'added') return 'New table'
if (d.kind === 'removed') return 'Deleted table'
const ops = d.operations?.operations ?? []
const parts: string[] = []
const adds = ops.filter((o) => o.kind === 'addColumn').length
const drops = ops.filter((o) => o.kind === 'dropColumn').length
const alters = ops.filter((o) => o.kind === 'alterColumn').length
const renames = ops.filter((o) => o.kind === 'renameTable').length
const fkAdds = ops.filter((o) => o.kind === 'addForeignKey').length
const fkDrops = ops.filter((o) => o.kind === 'dropForeignKey').length
const pkChanges = ops.filter(
(o) => o.kind === 'addPrimaryKey' || o.kind === 'dropPrimaryKey'
).length
if (adds) parts.push(`+${adds} col`)
if (drops) parts.push(`-${drops} col`)
if (alters) parts.push(`~${alters} col`)
if (renames) parts.push('renamed')
if (fkAdds) parts.push(`+${fkAdds} FK`)
if (fkDrops) parts.push(`-${fkDrops} FK`)
if (pkChanges) parts.push('PK changed')
return parts.join(', ') || 'Modified'
}
function openReview(change: TableDiff, diff: DatatableDiff, direction: 'ahead' | 'behind') {
drawerChange = change
drawerDiff = diff
drawerDirection = direction
// ahead = fork changed → migration runs on parent to deploy
// behind = parent changed → migration runs on fork to update
const sourceSchema = direction === 'ahead' ? diff.forkSchema : diff.parentSchema
migrationSql =
'-- Migration is auto-generated on a best-effort basis. You can adjust it here \n\n' +
generateMigrationSql(change, sourceSchema)
drawerOpen = true
}
function getDiffYaml(): { original: string; modified: string } {
if (!drawerChange || !drawerDiff || !drawerDirection) return { original: '', modified: '' }
const { schemaName, tableName } = drawerChange
const origTable = drawerDiff.originalSchema[schemaName]?.[tableName]
// ahead = fork changed → show original vs fork
// behind = parent changed → show original vs parent
const changedSchema =
drawerDirection === 'ahead' ? drawerDiff.forkSchema : drawerDiff.parentSchema
const changedTable = changedSchema[schemaName]?.[tableName]
return {
original: origTable ? YAML.stringify(origTable) : '# table does not exist',
modified: changedTable ? YAML.stringify(changedTable) : '# table does not exist'
}
}
async function runMigration() {
if (!drawerDiff || !drawerChange || !drawerDirection) return
migrationRunning = true
// ahead → run on parent; behind → run on fork
const targetWorkspace = drawerDirection === 'ahead' ? parentWorkspaceId : currentWorkspaceId
const dtName = drawerDiff.datatableName
try {
// If the target data table opted in to migrations, record this merge as a
// tracked migration (named after the fork) and run it, instead of applying
// raw SQL that would bypass the target's migration history.
// Don't swallow a status-check failure by defaulting to raw apply: that
// would apply the DDL untracked (schema drift) — exactly what this feature
// prevents. Let the error propagate (fail closed, handled by the outer
// catch); only fall back to raw apply when the API explicitly returns
// enabled === false.
const status = await WorkspaceService.getDatatableMigrationsStatus({
workspace: targetWorkspace,
datatableName: dtName
})
if (status.enabled) {
// The merge migration gets the highest timestamp, so any still-pending
// migration on the target is earlier: running only the merge applies it
// out of order. Warn like the row-level Run action does.
const pending = pendingMigrations(status.migrations)
if (pending.length > 0) {
const confirmed = await outOfOrderModal.ask({
title: 'Run migration out of order',
confirmationText: 'Run anyway',
children: outOfOrderRunMessage(pending.length)
})
if (!confirmed) {
migrationRunning = false
return
}
}
const forkName =
$userWorkspaces.find((w) => w.id === currentWorkspaceId)?.name || currentWorkspaceId
const migName = `merge_${forkName}`.replace(/[^a-zA-Z0-9_-]+/g, '_')
const created = await WorkspaceService.createDatatableMigration({
workspace: targetWorkspace,
datatableName: dtName,
requestBody: { name: migName, code_up: migrationSql }
})
try {
await WorkspaceService.runDatatableMigrations({
workspace: targetWorkspace,
datatableName: dtName,
only: created.timestamp
})
} catch (runErr: any) {
// Undo the insertion so the user can fix and retry from a clean state.
await WorkspaceService.deleteDatatableMigration({
workspace: targetWorkspace,
datatableName: dtName,
timestamp: created.timestamp
}).catch(() => {})
throw runErr
}
} else {
await runScriptAndPollResult({
workspace: targetWorkspace,
requestBody: {
args: { database: `datatable://${dtName}` },
language: 'postgresql',
content: migrationSql
}
})
}
} catch (e: any) {
sendUserToast(e?.body ?? e?.message ?? String(e), true)
migrationRunning = false
return
}
// Update forked_from.schema for the migrated table
try {
const sourceSchema =
drawerDirection === 'ahead' ? drawerDiff.forkSchema : drawerDiff.parentSchema
const { schemaName, tableName } = drawerChange
const newTableDef = sourceSchema[schemaName]?.[tableName]
const forkSettings = await WorkspaceService.getPublicSettings({
workspace: currentWorkspaceId
})
const datatableConfig = forkSettings.datatable ?? { datatables: {} }
const dtConfig = datatableConfig.datatables[dtName]
if (dtConfig?.forked_from) {
const forkedFrom = dtConfig.forked_from as any
if (!forkedFrom.schema) forkedFrom.schema = {}
if (!forkedFrom.schema[schemaName]) forkedFrom.schema[schemaName] = {}
if (newTableDef) {
forkedFrom.schema[schemaName][tableName] = newTableDef
} else {
delete forkedFrom.schema[schemaName][tableName]
}
await WorkspaceService.editDataTableConfig({
workspace: currentWorkspaceId,
requestBody: { settings: datatableConfig }
})
}
} catch (e: any) {
console.error('Failed to update forked_from schema:', e)
}
migrationRunning = false
drawerOpen = false
sendUserToast('Migration applied successfully')
await loadDiffs()
}
</script>
{#if applicableCount > 0}
<div class="bg-surface-tertiary p-4 rounded-md border">
<h3 class="text-sm font-semibold">Datatable schema changes</h3>
{#if loading}
<div class="flex items-center gap-2 text-xs text-tertiary py-2">
<Loader2 class="w-4 h-4 animate-spin" /> Loading datatable diffs...
</div>
{:else if error}
<div class="text-xs text-red-500 py-2">Failed to load datatable diffs: {error}</div>
{:else if diffs.length > 0}
<div class="flex flex-col gap-2 mt-3 mb-1">
{#each diffs as diff}
<ResizeTransitionWrapper class="border rounded-md" innerClass="w-full" vertical>
<button
class="w-full flex items-center justify-between px-3 py-2 hover:bg-surface-hover"
onclick={() => toggleExpanded(diff.datatableName)}
>
<span class="text-xs font-medium">{diff.datatableName}</span>
<div class="flex items-center gap-2 text-2xs text-tertiary">
{#if diff.aheadChanges.length > 0}
<span class="text-blue-500">{diff.aheadChanges.length} ahead</span>
{/if}
{#if diff.behindChanges.length > 0}
<span class="text-orange-500">{diff.behindChanges.length} behind</span>
{/if}
{#if expandedDatatables.has(diff.datatableName)}
<ChevronDown class="w-3 h-3" />
{:else}
<ChevronRight class="w-3 h-3" />
{/if}
</div>
</button>
{#if expandedDatatables.has(diff.datatableName)}
<div class="border-t divide-y">
{#if diff.aheadChanges.length > 0}
<div class="px-3 py-1.5">
<div class="text-2xs font-semibold text-blue-500 mb-1">Fork changes (ahead)</div
>
{#each diff.aheadChanges as change}
<div class="flex items-center gap-2 text-xs py-0.5">
{#if change.kind === 'added'}
<Plus class="w-3 h-3 text-green-500 shrink-0" />
{:else if change.kind === 'removed'}
<Minus class="w-3 h-3 text-red-500 shrink-0" />
{:else}
<Pencil class="w-3 h-3 text-yellow-500 shrink-0" />
{/if}
<span class="text-tertiary">{change.schemaName}.</span>
<span class="font-medium">{change.tableName}</span>
<span class="text-tertiary text-2xs grow">{operationSummary(change)}</span>
<Button
size="xs"
variant="subtle"
startIcon={{ icon: Eye }}
onclick={() => openReview(change, diff, 'ahead')}
>
Review
</Button>
</div>
{/each}
</div>
{/if}
{#if diff.behindChanges.length > 0}
<div class="px-3 py-1.5">
<div class="text-2xs font-semibold text-orange-500 mb-1">
Parent changes (behind)
</div>
{#each diff.behindChanges as change}
<div class="flex items-center gap-2 text-xs py-0.5">
{#if change.kind === 'added'}
<Plus class="w-3 h-3 text-green-500 shrink-0" />
{:else if change.kind === 'removed'}
<Minus class="w-3 h-3 text-red-500 shrink-0" />
{:else}
<Pencil class="w-3 h-3 text-yellow-500 shrink-0" />
{/if}
<span class="text-tertiary">{change.schemaName}.</span>
<span class="font-medium">{change.tableName}</span>
<span class="text-tertiary text-2xs grow">{operationSummary(change)}</span>
<Button
size="xs"
variant="subtle"
startIcon={{ icon: Eye }}
onclick={() => openReview(change, diff, 'behind')}
>
Review
</Button>
</div>
{/each}
</div>
{/if}
</div>
{/if}
</ResizeTransitionWrapper>
{/each}
</div>
{:else}
<span class="text-xs text-secondary"> No changes detected </span>
{/if}
</div>
{/if}
<Drawer bind:open={drawerOpen} size="900px">
{#if drawerChange && drawerDiff && drawerDirection}
{@const yaml = getDiffYaml()}
<DrawerContent
on:close={() => (drawerOpen = false)}
title="{drawerChange.schemaName}.{drawerChange.tableName} ({drawerDirection === 'ahead'
? 'Fork → Parent'
: 'Parent → Fork'})"
>
{#snippet actions()}
<Button
variant="accent"
loading={migrationRunning}
onclick={() => {
if (drawerDirection === 'ahead') {
confirmDeployOpen = true
} else {
runMigration()
}
}}
>
Run migration
</Button>
{/snippet}
<div class="flex flex-col h-full">
<Alert title="Changes to {drawerChange.tableName}" type="info">
{#if drawerDirection == 'ahead'}
You have made these changes in {currentWorkspaceId} that are not yet deployed in {parentWorkspaceId}.
{:else if drawerDirection == 'behind'}
These changes were made in {parentWorkspaceId} but the current workspace is not up to date.
{/if}
</Alert>
<!-- Diff section -->
<div style="height: 45%;">
<div class="py-1.5 text-2xs font-semibold text-secondary">
Schema diff (parent ↔ fork)
</div>
<div class="h-[calc(100%-28px)] border rounded-md overflow-clip">
{#await import('$lib/components/DiffEditor.svelte')}
<div class="flex items-center justify-center h-full">
<Loader2 class="w-5 h-5 animate-spin" />
</div>
{:then Module}
<Module.default
open={true}
automaticLayout
className="h-full"
defaultLang="yaml"
defaultOriginal={yaml.original}
defaultModified={yaml.modified}
readOnly
/>
{/await}
</div>
</div>
<!-- SQL migration section -->
<div class="flex flex-col grow overflow-hidden mt-4">
<div class="py-1.5 text-2xs font-semibold text-secondary"> SQL migration </div>
<div class="grow overflow-clip rounded-md border">
<SimpleEditor class="h-full" lang="sql" bind:code={migrationSql} />
</div>
</div>
</div>
</DrawerContent>
{/if}
</Drawer>
<ConfirmationModal
open={confirmDeployOpen}
title="Deploy to parent workspace"
confirmationText="Run migration"
onConfirmed={async () => {
confirmDeployOpen = false
await runMigration()
}}
onCanceled={() => {
confirmDeployOpen = false
}}
>
<p class="text-sm">
This will run the following SQL on workspace <b>{parentWorkspaceId}</b>:
</p>
<pre
class="mt-2 p-3 bg-surface-secondary rounded text-xs font-mono whitespace-pre-wrap max-h-60 overflow-auto"
>{migrationSql}</pre
>
</ConfirmationModal>
<Portal>
<ConfirmationModal {...outOfOrderModal.props} />
</Portal>