mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-09-08 16:03:27 +00:00
* export_datatable_schema * Propose to fork the datatable on ws fork * dump datatable * Dockerfile * Fix import_datatable_dump * datatable schema fork works! * Option to copy both schema and data * Datatable fork behavior * nit ui * use psql instead * remove fork_datatable route * feat: add fork_pg_database and export_pg_schema routes with DB Manager UI Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: pluralize "schema" to "schemas" in DB Manager export/import UI Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: add import mode select (schema only vs schema + data) to DB Manager import Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Select schema or schema+data when important database * fix: prepend $res: prefix to resource paths in DB Manager import/export Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: dynamic import button label based on selected mode Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * nits * feat: add warning alert when schema+data import mode is selected Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * nit hide on cloud hosted * refactor: remove fork_behavior from datatable settings Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: split CreateWorkspace into layout wrapper and CreateWorkspaceInner Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: instantiate CreateWorkspaceInner in globalForkModal Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * nit icons * Data table fork UI * feat: pass per-datatable fork behaviors from UI to backend during workspace fork Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix fork overwriting all datatables * UI nits * custom instance db refactor * custom instance db wizard btn for all in dropdown * nit * Delete custom instance database button * Disable forking for resource datatables * Big import buttons when db empty * Revert "Disable forking for resource datatables" This reverts commit9561cc8fd4. * feat: add non_diffable flag to resource table Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add resource-type datatable fork with CREATE DATABASE Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: tag forked datatables with nonDiffable and forkedFrom Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: diff datatable and ducklake settings individually on workspace merge Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: skip non_diffable resources and datatables in workspace diff Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: default datatable fork behavior to keep_original Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: make grant permissions non-fatal in instance datatable fork Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: make datatable and ducklake diffs visible in workspace comparison Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: remove datatable fork logic from workspace fork route Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: correct ahead/behind logic for datatable and ducklake diffs Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Revert "fix: correct ahead/behind logic for datatable and ducklake diffs" This reverts commit6b50884dc6. * revert: remove datatable and ducklake settings diffing logic Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add datatable clone UI with step-by-step confirmation modal Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: extract datatable fork UI into ForkDatatableSection component Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nit * fix: run datatable cloning before workspace fork creation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nit disable fork admins * nit fix switching workspace prematurely * fix: use source workspace for forkPgDatabase calls during fork Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: update forked workspace datatable settings after fork creation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add forked_from field to DataTable and set it for instance forks Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nit onFinish * fix: add forked_from to DataTableSettings OpenAPI schema Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: track datatable table DDL changes in workspace_diff Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Revert "feat: track datatable table DDL changes in workspace_diff" This reverts commit7526dd68b9. * feat: add get_datatable_full_schema endpoint and snapshot schema on fork Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix duplicate migration key * fix: set forked_from on datatable config for both instance and resource types Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nits * feat: drop forked databases on workspace deletion with confirmation UI Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: extract drop_forked_datatable_databases from delete_workspace Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: cast pg char columns to text in FK schema query Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: show dbname instead of resource type in fork deletion modal Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * ui nit * refactor: extract drop_custom_instance_database into windmill-common Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add datatable schema diff section to merge UI Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * UI * feat: add review drawer with YAML diff and SQL migration runner Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: use Monaco DiffEditor for YAML diff in review drawer Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nit * Revert "refactor: use Monaco DiffEditor for YAML diff in review drawer" This reverts commita86008ba4c. * Revert "feat: add review drawer with YAML diff and SQL migration runner" This reverts commit0a0deb5ddb. * feat: add review drawer with DiffEditor and SQL migration runner Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * ui nits * fix: show diff between forked_from schema and changed side Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: re-fetch target live schema after migration for correct baseline Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * revert * nit auto next * feat: add confirmation modal before deploying migration to parent Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: handle missing columns/foreignKeys in schema conversion Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nits * refactor: use temp file on disk for pg_dump instead of in-memory string Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Don't replace postgres dbname * fix: add validation to drop_custom_instance_database and use source db for CREATE/DROP Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: type DataTable.forked_from as DataTableForkedFrom struct Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: simplify fork_pg_database to take source + target_dbname Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * dead code * feat: enforce schema_and_data admin-only and extract create_custom_instance_database Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: rename fork_pg_database to import_pg_database with source/target/override params Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nit * refactor: remove original_dbname/original_resource from forked_from, resolve from parent Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nit * fix: resolve forked dbname from fork workspace when dropping resource databases Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nits * fix: always clean up global_settings even if database doesn't exist Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: check datatable resource_type from config instead of URL prefix Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: wrap PG default value expressions in braces to prevent CAST quoting Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Revert "fix: wrap PG default value expressions in braces to prevent CAST quoting" This reverts commit77f5a2c4e8. * refactor: reuse columnDefToTableEditorValuesColumn for default value handling Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: store raw API schema in forked_from to avoid double transformation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Revert "fix: store raw API schema in forked_from to avoid double transformation" This reverts commite326197a20. * Revert "refactor: reuse columnDefToTableEditorValuesColumn for default value handling" This reverts commitbd8f071d9f. * fix: validate dbname with strict regex to prevent SQL injection Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix default value * always validate dbname * refactor: move get_datatable_full_schema structs and logic to query_builders.rs Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: split import_pg_database into create_pg_database + import_pg_database Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: extract drop_forked_datatable_databases into its own route Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: require admin when using $res: resource paths in import_pg_database Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: use UserDB for $res: resource access and restrict dbname creation - resolve_pg_source_checked uses UserDB (row-level security) for $res: paths - transform_json_unchecked is now pub(crate) to prevent misuse - Non-superadmins can only create databases with wm_fork_ prefix - datatable:// remains accessible to everyone Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: refuse to drop forked databases unless name starts with wm_fork_ Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: remove resolve_pg_source, use resolve_pg_source_checked everywhere Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix permissions * sqlx prepare * compilation nits * sqlx prepare * sqlx prepare * wrong route syntax * fix: allow workspace owner to edit datatable config for fork setup Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Revert "fix: allow workspace owner to edit datatable config for fork setup" This reverts commitab683e637b. * refactor: move datatable fork setup into create_workspace_fork backend Instead of updating datatable settings from the frontend after fork creation (which required admin/owner access), pass forked_datatables info to create_workspace_fork and handle it atomically in the same transaction. Removes applyPostForkDatatableUpdates from frontend. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: snapshot schema in backend during fork instead of frontend The schema snapshot is now taken by the backend in apply_forked_datatable via snapshot_datatable_schema, which connects to the parent workspace's datatable and runs pg_get_full_schema. This removes the need for the frontend to call getDatatableFullSchema and pass the schema through. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: use get_resource_value_interpolated_internal for $res: to resolve $var: references Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nit * sqlx prepare * fix: add permission check to drop_forked_datatable_databases, validate dbnames, restrict temp file perms - drop_forked_datatable_databases: same permission as delete_workspace (fork owner or super admin) - validate_dbname on target_dbname_override and ForkedDatatableInfo.new_dbname - Enforce wm_fork_ prefix on forked datatable new_dbname - DumpFile: set /tmp/windmill/ to 0700 and create files with 0600 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * nit CLI * Rename to ws_specific * sqlx prepare * nit always validate dbname * fix: include foreign keys in CREATE TABLE migration for added tables Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: detect nextval defaults and use SERIAL/BIGSERIAL types in CREATE TABLE Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update frontend/src/lib/components/DBManagerDrawer.svelte Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * Update backend/windmill-common/src/lib.rs Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * Update backend/windmill-common/src/lib.rs Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * fix: sort foreign keys by constraint name for deterministic schema output Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * sqlx prepare * rename migration to update timestamp --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
583 lines
20 KiB
Svelte
583 lines
20 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 { 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 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([])
|
|
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)
|
|
|
|
async function loadDiffs() {
|
|
loading = true
|
|
error = undefined
|
|
diffs = []
|
|
try {
|
|
const forkSettings = await WorkspaceService.getSettings({
|
|
workspace: currentWorkspaceId
|
|
})
|
|
const datatables = forkSettings.datatable?.datatables ?? {}
|
|
const forkedEntries = Object.entries(datatables).filter(([_, dt]) => dt.forked_from != null)
|
|
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 {
|
|
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.getSettings({
|
|
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>
|
|
|
|
<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}
|
|
|
|
<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>
|