Files
windmill/frontend/src/lib/components/workspaceSettings/AddDataTableWizard.svelte
T
0fdf17d339 feat: data table cards and a managed-first add wizard (#11419)
* fix(datatables): refuse a save that drops a data table's roles through an undeclared rename

A data table's roles follow its entry only through a declared rename. A
settings sync sends the whole map and never declares one, so renaming a
data table under roles there read as a delete and a new entry on the same
database: the new entry carried no roles, and every caller connected as
admin. Such a save is now refused, naming both entries.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* fix(datatables): no entry without roles may newly reach a database under roles

The previous guard only caught a new name replacing an entry under roles.
A whole-map save could also repoint an existing entry without roles at
that database, or another workspace could point one there, and every
caller of that entry would connect as admin. The rule is now stated on
the saved entries: one that carries no roles and newly points at an
instance database any entry under roles uses, in this workspace or
another, is refused. A declared rename carries its roles and passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* feat(datatables): move data table role catalog and resolution to the enterprise edition

Roles are an Enterprise Edition feature. The catalog, the Postgres logins,
CONNECT convergence, tenant evaluation and the role half of connection
resolution move to windmill-ee-private. Every public function keeps its path
and signature and forwards through datatable_roles_oss, which re-exports the
enterprise implementation or, without it, refuses.

Without the enterprise edition a data table under roles, or a caller naming a
role, is refused a connection rather than resolved as admin, and the reach and
admin-access checks refuse one under roles. A data table not under roles
resolves as before in every edition, and an instance database keeps the
CONNECT grants it was created with. The catalog lock, the stream lock, the
tenant cascades and the permissions stripping stay in OSS: they only restrict.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* feat(datatables): move the data table permissions endpoints to the enterprise edition

The permissions read, save and usable-roles handlers move to
windmill-ee-private; the routes stay registered and, without the enterprise
edition, answer that data table roles are an Enterprise Edition feature.
ensure_governs_datatable and ensure_reaches_datatable keep their paths: the
first refuses, the second passes a data table not under roles.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* feat(datatables): move the data table role catalog endpoints to the enterprise edition

The superadmin list, create, update and delete handlers move to
windmill-ee-private. The routes stay registered and, without the enterprise
edition, refuse after authentication.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* test(datatables): run the roles tests on the enterprise edition, refusals without it

Each test that exercises roles runs with private and enterprise. Two tests run
without them: every roles route answers the Enterprise refusal, and a data
table saved under roles, or a named role, is refused a connection while one
not under roles resolves as before.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* feat(datatables): gate the roles UI mount sites on an enterprise license

Both mount sites are still commented out; the gate travels with them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* test(datatables): run the tenant matcher test on the enterprise edition

The matcher it covers is enterprise code now, so without the enterprise
edition the test hit the stub and failed the default windmill-common run. It
runs with private and enterprise, and a counterpart without them asserts that
no tenant list covers anyone, the wildcard and a workspace admin included.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* chore: update ee-repo-ref to a1873dbb67f2302b85ff5362f8387b48eccdb607

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

Previous ee-repo-ref: 5c853e2c20eca6b748415fc0d6862a6ebfb5fec4

New ee-repo-ref: a1873dbb67f2302b85ff5362f8387b48eccdb607

Automated by sync-ee-ref workflow.

* fix(datatables): refuse roles while a same-workspace alias reaches the database

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

* feat(datatables): add an ACL editor for data table roles

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

* feat(datatables): data table roles in the DB manager and raw apps

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

* fix: never add a role to the reference of a data table whose name contains '?'

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

* fix: read the roles of a data table whose name contains '?'

The generated client leaves a '?' in a path param unencoded, so the lookup
404'd and the raw-app picker blocked Start on such a data table.

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

* fix: take every pooled connection before the ACL apply locks

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: refresh grant options only after the ACL apply validates its plan

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix(datatables): refuse a reference naming both a legacy data table and a role

When a workspace stores both `sales` and a legacy `sales?role=analytics`, the
reference resolved to the legacy entry without a role, so browsing `sales` as
`analytics` reached another data table.

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

* fix: declare the default role in migrations written for a data table whose name contains '?'

Such a data table connects as its default role without naming it, so the
migrations the manager wrote for it declared no role and ran as admin.

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

* fix(datatables): let CE migrations connect as an explicitly named admin

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

* fix: add only missing grant options before an ACL apply, never default privileges

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix(datatables): serialize roles going on with aliases saved from other workspaces

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

* docs(datatables): note that legacy names with ? cannot be migrated

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

* fix: run one data table ACL apply at a time per server before it connects

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* feat(datatables): set up an external instance cluster for data tables

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

* fix(datatables): send external cluster passwords as SCRAM verifiers

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

* fix(datatables): scope external cluster credential readers to the crate

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

* [ee] feat(datatables): external_instance data tables on the external cluster

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

* fix: hold the ACL connection to the database that was authorized

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix(datatables): compare the external cluster settings under a row lock before storing setup

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

* fix(datatables): only drop external databases Windmill marked, and check use under the lock

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

* fix: build the ACL connection from the authorized data table entry

Resolving the settings again could land on a resource with the same
database name on another server, which the later entry checks never see.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: check ACL read reach against the entry it connects from

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* feat(datatables): put a data table's connection under Postgres roles

A data table backed by the instance database resolved to exactly one Postgres connection,
`custom_instance_user`, for everyone who could reach it at all. There was no way to say
this job reads, that one writes, this one never sees the salaries table.

A data table role is now a real Postgres login on the cluster, defined once for the
instance by a superadmin and named exactly as they named it. A script that declares
`-- role analytics` connects as `analytics`, and Postgres decides what it may touch —
grants are ordinary SQL. Windmill answers only "may this caller ask for this role", from
the tenant lists on the data table entry: `u/alice`, `g/analysts`, `f/finance` or `*`.
A data table with no `permissions` block behaves exactly as before.

Everything that opens a connection on someone's behalf goes through one chokepoint,
`get_datatable_resource_from_db`, which takes the identity explicitly and fails closed when
there is none. The role logs in as itself — never `SET ROLE`, which a script could
`RESET ROLE` its way out of.

A fork's data table entry becomes a pointer at the workspace that governs it rather than a
copy of it. The settings clone used to hand a fork a byte-identical entry naming the
parent's database, which a fork admin could edit to grant themselves `admin` there; a
pointer has nothing local to edit, and its tenants are evaluated as a member of the
governing workspace, by email. `permissions` is stripped from the workspace export and
ignored on import: tenants name principals of one workspace, and a settings push is not
where an access decision should be made.

Operations that see the whole database whatever the roles grant stay with the governing
workspace's admins: editing the roles, a migration that declares none, and opening a
replication stream for a Postgres trigger or capture.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): gate the paths that reach a whole database as admin

Auditing what still resolved through the unchecked resolver turned up three that act for a
caller and hand back the admin connection: `resolve_pg_source_checked` (behind schema
export, the full-schema read, database creation, import and the forked-database drop), the
connection test, and the schema snapshot a fork clone takes of its parent. On a data table
under roles each let any workspace member — or a fork admin who is nobody in the governing
workspace — read or copy the whole database whatever its roles grant.

All three now require admin reach on the governing workspace. A dump taken under a
restricted role would be a silently truncated copy rather than an error, so refusing is the
only right answer for the copy paths.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): confine roles to the instance database, and stop a fork reaching the parent's bookkeeping

A data table role is a login on Windmill's own Postgres. Nothing stopped a workspace admin
putting a *resource-backed* data table under roles, at which point the executor dialled the
host that resource names — one the admin chose — with the role's real cluster password, and
`CONNECT` is granted to every registered instance database. Both ends now refuse: the
permissions endpoint rejects the save, and the chokepoint refuses to substitute credentials
on a non-instance entry rather than trusting the record it read.

Two more places reached the governing database without answering to it. The initial-migration
generator returned a `pg_dump` of the whole schema to any member. And the migration
rename/delete cascade followed a fork's pointer into the parent, so a fork admin renaming or
removing their own local entry relabelled or wiped the parent's `_wm_migrations` — after
which the parent re-runs every migration from zero. The remote half is now skipped when the
entry resolves into another workspace, which is also just correct: a fork renaming what it
calls a data table changes nothing about the data table.

Also: revoking a tenant now bounces the replication streams of every workspace holding an
entry that resolves here, not only the governing one, so a fork's trigger stops rather than
living on inside its open connection; the instance role catalog and the governing workspace's
tenant lists are no longer returned to someone who cannot edit them; and the tenant rename
dedup collapses non-adjacent duplicates, per role rather than once any role changed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): fail loudly where a role or a pointer can be left half-recorded

Three ways the feature could end up in a state nobody could see or undo.

Creating a role writes the cluster first and the catalog second, but the catalog write was an
`UPDATE` that matched nothing when the instance Postgres settings row was absent — leaving a
live login with a password nobody recorded: invisible to the catalog, un-recreatable because
the name is taken, and un-deletable because there is no entry to delete. It now errors, so
the operation is retryable once the row is restored.

Deleting a workspace only nulls the fork lineage; the data table entries pointing at it are
left resolving to nothing. Sweeping them is not an option — turning a pointer back into a copy
would hand each fork the database outright — so the delete now names the data tables it
stranded, and resolving one says which workspace is missing rather than reporting a data table
this workspace never had.

`InstanceDatatableRole` derived `Debug` while holding a Postgres password; it is now
hand-written so `{:?}` on the catalog cannot put a live credential in a log line.

Adds the two branches the reviews found unpinned: a caller who is not a member of the
governing workspace at all, and `NoIdentity` — the compatibility path for an agent worker that
predates this and sends no job id.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): unbreak two operator messages and two comments that described other code

The two strings this branch added for states an operator hits once — the catalog write that
matched nothing, and the delete that stranded a pointer — were collapsed from their multi-line
form with the indentation left in, so both rendered with a fourteen-space gap mid-sentence.

`list_datatables` claimed to report a chain it cannot follow and then dropped it; it does drop
it, and the comment now says why that is the right place to stay quiet. The non-superadmin
check in `edit_datatable_config` was introduced as also covering references, which it does not
and need not: `reference` is overwritten from the stored entry for every caller before the
check runs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): serialize role catalog mutations, and state each helper's authorization contract

The catalog is one JSON document, so create, rename, enable and delete are all
read-modify-write. Two concurrent creates read the same snapshot, both succeed in the
cluster, and the second write drops the first — leaving a live Postgres login with a password
nobody recorded, which is the exact state the delete path exists to prevent. Every mutation
now runs in one transaction holding an advisory lock across the read, the cluster DDL and the
write, so a lost update cannot happen and a failure rolls the whole thing back. The DDL
helpers take that transaction rather than the pool, which is what makes the lock cover them.

Their statements moved off `sqlx::raw_sql`: the simple protocol is only needed for genuinely
multi-statement SQL, and its future is not `Send`, which an axum handler holding the
transaction requires. Each of these is one statement anyway.

The new cross-crate surface now says what callers must do. `read_role_catalog` returns
plaintext credentials; `create`/`rename`/`set_login`/`drop_instance_role` and
`converge_connect_grants` mutate cluster-wide state; `read_datatable_entry` reads a workspace's
raw config. All of them are superadmin-gated by their current handlers, but nothing said so at
the definition, which is where the next caller looks.

Also: the roles table reloads after a failed login toggle instead of leaving it claiming a flip
that did not land; the rename affordance is the design-system `Button`, not a raw one; and
`resolve_datatable_pg_as_caller` drops a `role` parameter no caller ever filled — browsing
resolves as the data table's default until the database manager grows a picker.

Why role passwords stay a plain `String` while the instance user's password beside them is a
`StringOrSecretRef`, asked three times across reviews: that one is a secret ref because an
operator supplies it and may want it from their own backend, while these are minted here and
never entered by anyone, so there is nothing for a ref to point at. Encrypting generated
secrets at rest is a separate change that would take the replication password with it. Now
said at the field.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): give the role catalog its own row, out of reach of the config machinery

Putting it inside `custom_instance_pg_databases` was the wrong call, and it cost two ways.
The catalog serializes a generated Postgres password per role, and that row is the
operator-facing instance config, so the passwords reached `get_instance_config` and its YAML
editor — a live cluster credential in a response body, a UI field and any log of either.
Worse in the other direction: `to_settings_map` strips the catalog, so a full-row upsert of
that key writes the row back without it and the catalog is gone, while the cluster keeps every
login it described.

`custom_instance_replication_pwd` is the precedent and says exactly why — a generated secret,
written only by the server, never operator-authored, hidden so the config machinery cannot
read, rewrite or drop it. The catalog is the same thing, so it now has the same shape:
`datatable_roles`, in `HIDDEN_SETTINGS`, `PROTECTED_SETTINGS` and the agent-worker denylist.
No redaction to keep in step with three code paths, and no way for a neighbouring write to
take it out.

Two races on the same shared documents. `edit_datatable_config` read the stored data tables
outside its transaction and then wrote the whole `datatable` document, so a permissions save
committing in between was silently rolled back; it now reads under `FOR UPDATE`. And
`set_datatable_permissions` validated role ids against the catalog before opening its
transaction, so a deletion in between let it write a deleted role back — including as the
default, which every later job then fails on; it now holds the catalog lock and the settings
row across validation and write.

Completes the authorization contracts the previous commit claimed but did not finish:
`read_datatable_entry` (which it named and missed), `resolve_governing_datatable`, whose whole
job is to answer for a workspace the caller may not belong to, and
`converge_connect_grants_with`, which had not inherited its wrapper's.

Also the generic Python SDK reference: `_format_py_params` learned the bare `*` last time, but
`extract_py_functions` is a second formatter and still rendered `datatable(name, role)`, so
code written from that page passed a keyword-only argument positionally.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): make the concurrency test pin the handlers, and the contracts describe what is enforced

The concurrency test reimplemented the read-modify-write inline, so deleting the lock from all
three handlers left it green — it pinned Postgres, not the code it was written for. It now
drives `create_datatable_role` twice concurrently and asserts the catalog kept both names.
Checked the way the last one should have been: removing the lock from the handler makes it
fail with "wmtest_a_… is a live cluster login the catalog forgot".

The contracts added last commit were stricter than this PR's own callers, which is worse than
none — the next reader sees a rule already broken and learns to ignore it.
`read_role_catalog` said superadmin-only while two of its four callers are open to any
workspace member, and `converge_connect_grants` said superadmin while
`set_datatable_permissions` reaches it as a workspace admin. Both were fine on substance: the
rule that actually holds is about the credential never reaching a response, log, audit record
or export, not about who may call. They now say that. `read_datatable_entry` gets the same
treatment rather than the one the earlier message claimed for it: it is the primitive every
resolution goes through, so it is deliberately open, and what must not escape is `permissions`
— it names the governing workspace's users, groups and folders.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): close the last ways a role or a pointer can be left pointing at nothing

The raw settings readers hand back whatever is in the row, so moving the catalog into its own
`global_settings` key protected the config machinery and left `GET /settings/global/datatable_roles`
and the settings listing returning every live password. Both now filter that one key. The
neighbouring `custom_instance_replication_pwd` has the same shape and is not touched here: it
predates this and widening the fix to it is a decision about an operator workflow, not a
consequence of this change.

Three ways a save could leave something resolving to nothing:

A permissioned data table could be moved to a PostgreSQL resource. The block was carried across
as a server-owned field, the runtime refuses roles on a resource-backed table, so the save
succeeded and every job afterwards failed. Refused instead — turning roles off first is one step,
and it keeps discarding an access decision something somebody chose.

Renaming a governing data table left every fork pointing at the old name: the data table
disappears from their pickers and their jobs stop, with nothing in the renaming workspace to
suggest why. The rename now follows into the pointers in the same transaction.

Deleting one cannot be followed the same way, so it is reported instead — the response names what
it stranded, the way deleting a workspace does, and the fork's own error already says which
workspace is gone.

Also: `ensure_instance_db_grant_options_unchecked` claimed superadmin while the permissions
handler reaches it as a workspace admin (the same class fixed last commit, one instance missed);
the role entry kept an `instance_config_schema` derive it no longer needs; `write_role_catalog`
was the one writer of that table not stamping `updated_at`; and the concurrency test dropped its
roles only on success — a failing run is exactly the one that creates them without recording them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* refactor(datatables): put the role catalog in its own table, not in global_settings

Five findings across three rounds were all the same choice. A set of live Postgres credentials
was living in `global_settings`, which has generic read, list, write, config-export and CLI
round-trip paths that know nothing about what they carry: the passwords reached the instance
config and its YAML editor, a full-row upsert of a neighbouring key erased the catalog,
`GET /settings/global/{key}` and the settings listing returned them raw, and this round the
redaction that fixed the last two turned `wmill instance push` into something that wipes every
password — a fix breaking the assumption the previous fix made. `POST /settings/global/datatable_roles`
could also empty it outside the lock.

The approved plan offered a table or `global_settings`, so this is the other option it already
allowed rather than a new design. `datatable_role` is a table: no generic settings path can read
it, list it, export it, write it or round-trip it, so none of the five needs a guard. The
redaction, the hidden/protected/agent-denylist entries and the JSON document all go with it.

One row per role also removes the read-modify-write the concurrency work was about: two
concurrent creates are two inserts, and the unique index on `name` is what settles a collision.
The advisory lock stays for the one window rows do not cover — `CREATE ROLE` is invisible to
another transaction until commit, so without it both creates pass their `pg_roles` check.

Also from this round: rename mappings are checked against the configuration they claim to
describe, since fork pointers are rewritten from them — a caller could otherwise submit
`main -> missing` against an unchanged config and repoint every fork of `main` at a name nothing
has, and `A -> B` plus `B -> C` moved what pointed at `A` all the way to `C`. And the warning
naming forks a delete stranded reached the response but not the screen: both the data table
settings save and the workspace delete now show it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): validate a rename against the save it describes, and re-check under the locks

Three from the round, all about deciding on state that could already have moved.

A permission save resolved the data table and checked it was instance-backed before taking any
lock, then wrote under one. A config save committing in between could move the table onto a
PostgreSQL resource — recreating exactly what the transition guard refuses — or rename it, in
which case the write targeted a key that no longer existed and reported success having changed
nothing. It now re-resolves and re-checks on the locked state.

Rename validation checked that the source existed before and the target existed after, which
still accepts `main -> decoy` against a save that keeps both: every fork of `main` then follows
onto a different data table, silently, because it keeps resolving. The rule is now the actual
old-to-new key transition — a source may only survive if another rename took its name, and a
target may only pre-exist if another rename freed it. That also stops two sources sharing one
target, and it admits a swap, which the previous guard refused: `datatables` is keyed by name, so
a swap cannot be done one save at a time, and refusing it was a regression against main. The
pointer cascade now runs in two passes through a temporary name, the way the migration cascade
one layer down already handles the same shape, so `A -> B` with `B -> C` moves each pointer once
from what it named before the save.

The tenant mutators say what they are for: they write an access decision for any workspace named,
with an arbitrary mutation, and exist for the transaction that frees or renames a principal.
Editing a decision on purpose belongs in the permissions endpoint.

Carried in the same change: the stranded-fork list is a field rather than a phrase to grep out of
a success string; the pointer cascade matches with `EXISTS` instead of a `LIKE` over the whole
document, so a workspace whose pointers name something else is not rewritten to a byte-identical
value under an exclusive lock; and `InstanceDatatableRole` drops the serde derives left over from
the JSON document, one of which would emit `pwd`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): cascade on the leave route that is used, gate migrations before the admin connection, and drop a role atomically

The tenant cascade on leaving went onto `/users/leave`. The UI and the generated client call
`/workspaces/leave` — a different handler in a different crate with the same name — which
deleted the membership and left `u/<username>` in the tenant lists. Leaving and rejoining
therefore restored the access the leave was supposed to end, and a later account taking the
username would have inherited it. The regression test drives the route the client actually
calls; without the fix it fails with "leaving kept the tenant".

The migration endpoints authorized too late. `run_datatable_migrations` opened the data table's
admin connection, created `_wm_migrations` and read it before reaching the per-migration role
check — so with nothing pending, nothing was checked at all. Rollback returned before its check
when nothing was applied, and the status endpoint had none. All three now ask, before any
connection is opened, whether the caller can reach the data table as any role at all; which role
a given migration runs as is still decided per migration, and by the executor after that.

Deleting a role committed the cluster drop and the catalog row, then swept the tenant lists in
separate transactions. A sweep failing part-way left workspaces naming a role nothing can connect
as, while the retry answered `NotFound` because the catalog entry was already gone. The sweep now
runs in the same transaction, so the drop, the row and every tenant list commit together.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): refuse to copy a data table that is under roles

pg_dump carries no roles and the import runs with --no-privileges, so a copied
data table arrives owned by the admin connection with no GRANT for any role.
The settings clone brings `permissions` across, so the fork's tenants pass
Windmill's check, connect as the role they were given, and are denied by
Postgres on everything: an entry that reads as configured and answers nothing.

Refuse the copy — in the import endpoint before any data moves, and in the fork
path the CLI takes. Replaying the source's owners and ACLs into the clone is
what lifts this, and is a change of its own. Dropping `permissions` from the
copy instead would be the unsafe half, since the copy holds the parent's rows.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): refuse the clone's database too, not only its data

A clone is two endpoints: `create_pg_database` then `import_pg_database`. Only
the second refused a data table under roles, so a fork asking to clone one
created and registered an empty `wm_fork_…` instance database and then failed —
and nothing collects it, since `drop_forked_datatable_databases` only drops
entries carrying `forked_from` and no entry names this one.

Refuse in both, so the clone stops before a database exists.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* nit worker error msg

* fix pg_dump stuck on version 17 on nix

* fix(datatables): refuse a malformed role annotation instead of ignoring it

`-- Role operator`, `-- role operator;` and `-- role operator -- why` all failed
the annotation parser's exact-match rule, so the query fell through to the data
table's default role and ran, silently, under a login the author did not choose.
Naming a role exists precisely to not do that.

A leading comment whose first word is `role` is now an annotation attempt: the
keyword matches case-insensitively, one trailing `;` is tolerated, and anything
else is an error naming the line. Only callers that already know the target is a
`datatable://` reference ever run this, so ordinary SQL keeps its comments.

Also bumps the dev shell's postgres client to 18 — it trailed the server the dev
database runs, which takes out every data table export, clone and fork-with-data.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): refuse a malformed role query string instead of ignoring it

`?Role=analytics`, `?role=` and `?x=1&role=…` all fell through the reference
parser's exact-match rule, so the connection resolved to the data table's default
role and ran under a login the caller never asked for — the URI half of the same
trap as a malformed `-- role` annotation.

The key now matches case-insensitively, and anything else in the query string is
an error naming it; `role` is the only parameter a reference takes. Callers that
only need the entry keep a lenient `datatable_ref_name`, since they never act on
the role. The DuckDB `ATTACH` parser propagates it rather than attaching under
the default.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ti5HyeTikPMYyW8YSdiHR

* fix(datatables): carry the role annotation into the row_to_json retry

The retry rebuilds its SQL from `pruneComments(code)`, so the leading comment
block never reached the second attempt — and with it the `-- role <name>` line
that decides which login the query runs as. The retry connected as the data
table's default role instead, so a query the first attempt was denied could
succeed on the second, reported as "recovered with the row_to_json fix".

Carry the leading comment block over. The retry itself is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* chore(datatables): don't mount the roles UI until the ACL editor lands

Enforcement ships first. The permissions drawer is what turns roles on, and the
catalog section is what creates them — both are only useful once there is a way
to grant a role the privileges it needs, which arrives with the ACL editor. Left
mounted they would offer a feature whose other half does not exist.

The two components are complete and reviewed; only their call sites here are
commented out, with a note pointing the follow-up PRs at them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* fix(datatables): honour `-- role: x`, and fix the DuckDB attach test

Two review findings, both real.

`attach_datatable_parses_name_and_role` never compiled: `parse_attach_datatable`
returns `Result<Option<_>>` now and one call site kept a single `unwrap`. Its
`?Role=analytics` case also asserted a refusal, contradicting the parser in the
same commit, which matches the key case-insensitively. Replaced with the cases
that are genuinely malformed, and a positive one for the cased key.

`-- role: analytics` fell through to the default role — the silent fallback the
strict parser exists to remove, for the spelling most likely to be typed. The
keyword now accepts an optional colon, attached or spaced, while a word that
merely starts with it (`rolebased`) is still not an attempt.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* fix(datatables): clone a fork's pointer instead of failing after the copy

Forking a fork with cloning left an orphan database. The preflight resolves the
pointer and sees the governing entry, so both endpoints ran and filled the new
database; `apply_forked_datatable` then refused the inherited pointer and rolled
the fork back, stranding a registered `wm_fork_*` that no entry names and whose
name blocks the retry.

Refusing earlier would have been the smaller change, but forking a fork and
cloning worked before pointers existed, so it would trade an orphan for a
regression. Resolve what the pointer names and write the terminal entry the
clone needs: the whole `database` object rather than a patch of its
`resource_path`, since a pointer has none, and `reference` removed with it.

Also accepts `-- role=x` and `-- Role = x`, two more spellings that fell through
to the default role.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* fix(datatables): refuse to roll back the catalog while roles exist

The down migration dropped the table and left every role behind: live Postgres
logins whose passwords only that table carried, so after a revert Windmill could
neither use, disable nor delete them, and re-applying could not recreate them
because the names were taken. Cleaning up here is not possible either — dropping
a role means reassigning what it owns in every instance database, and a
migration runs in one — so it now refuses while the catalog is non-empty and
says to delete the roles through instance settings, which does the cluster work.

Also enforces the instance-only invariant the resolved-pointer clone relies on
rather than only asserting it in a comment.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* refactor(datatables): settle clonability in one place, before anything is created

A clone is three stages a workspace apart — `create_pg_database`, then
`import_pg_database`, then `apply_forked_datatable` inside the fork transaction.
Only the third can roll back, and `CREATE DATABASE` is not transactional, so any
refusal that lives there strands a registered `wm_fork_*` that no entry names
and whose name blocks the retry.

That orphan has now been fixed three times, most recently reintroduced by a
guard added one commit ago. Patching each new refusal into the first endpoint is
not the fix; having two places that can refuse is. `ensure_datatable_is_clonable`
now answers every reason a copy can be refused and returns what it resolved, and
the stage that writes the entry only does the work.

Also takes an ACCESS EXCLUSIVE lock before the rollback guard counts, so a role
created concurrently cannot slip between the check and the drop.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* fix(datatables): let a retried clone reclaim its own leftover database

A clone creates its target database one request before it copies into it, and
the fork that would name it is written a request after that. Any failure in
between — a pg_dump error, a bad restore, a dropped connection, the source's
roles changing mid-flow — left a registered `wm_fork_*` that no entry names,
and every retry then failed on its name. This predates data table roles.

`create_pg_database` now reclaims such a leftover before creating: only a
`wm_fork_*` database Windmill registered as a data table database and that no
data table or ducklake entry names, in any workspace, archived ones included.
The drop never terminates connections, so a clone still copying into it makes
the reclaim fail instead of being cut off. It is limited to callers who
administer the source — reaching it is not enough, since on a data table
without roles every member reaches it — and anyone else gets the refusal an
existing database always got.

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

* Revert "fix(datatables): let a retried clone reclaim its own leftover database"

This reverts commit 7dd3275a10.

The reclaim tied the caller to the source they administer, but not to the
database it dropped. Between another workspace's import and its final fork
request, that workspace's target is full, registered, unnamed and has no open
connection, so an admin of any instance data table could name it and have it
dropped and recreated empty. The victim's fork would then commit pointing at
the empty copy. Safe reclaim needs durable clone ownership and serialization
with the request that names the database; until then the leftover stays, as it
did before this PR.

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

* docs(datatables): record the stale clone database as a known limitation

A clone is three requests and `CREATE DATABASE` is not transactional, so a
failure after the first leaves a registered `wm_fork_*` behind, as it did
before data table roles. Accepted for this PR: it is harmless to data and goes
away once the clone is a single server-side operation.

The comment also records why the obvious fix is wrong: reclaiming the leftover
on retry, without durable clone ownership, can drop another workspace's fully
copied database between its import and its final fork request.

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

* fix(datatables): bounce the streams reading a data table when it is deleted

Deleting a governing data table, or the workspace that holds it, only collected
the fork pointers it stranded, for the warning. A Postgres trigger or capture
already streaming through one of those pointers kept the replication connection
it opened while the pointer still resolved, so it went on dispatching the
governing database's rows after the fork lost access — until its connection
happened to restart. The governing workspace's own streams on a deleted entry
did the same.

Both deletion paths now bounce the affected listeners inside their own
transaction, through the helper a permission change already uses, so a
listener that reconnects re-resolves the entry and finds it gone. The helper is
split so a caller can pass the (workspace, local name) pairs it already holds.

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

* fix(datatables): keep the fork schema baseline, and bounce streams on every removal

Three fixes from review.

`edit_datatable_config` took `forked_from` wholesale from the stored entry, so
the fork schema diff's save of an advanced baseline was silently discarded and
an applied change was offered again. Whether an entry carries a clone stamp is
still carried from the store, since that is what marks its database droppable,
but the baseline inside it is now taken from the request.

The stranded-pointer warning and the stream bounce ran over the optional
`deleted_datatables` hint, which the settings-sync CLI never sends, so removing
a governing data table through `wmill` bounced nothing. Removals are now derived
from the stored configuration against the saved one.

`delete_workspace` read the pointers to bounce before its transaction, so a fork
committing a pointer during the deletion was missed. The read now happens inside
the transaction, after the workspace row is deleted: a fork's insert key-share
locks that row through its parent foreign key, so it is either seen or fails on
the missing parent.

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

* refactor(datatables): keep Postgres triggers and data table roles apart

A replication stream reads every row of every table whatever the data table's
roles grant, and its listener checks access only when it connects. Rather than
chase every way access can change and bounce the streams each one affects, a
data table now carries one or the other:

- a Postgres trigger or capture cannot be created on, or connect to, a data
  table under roles;
- roles cannot be turned on while an enabled trigger or a live capture reads
  the data table, its own or a fork's through its pointer. The refusal names
  each one to disable.

This removes the stream bounces on roles edits and on data table and workspace
deletion, and the trigger gate that admitted admins. The fork schema baseline
fix from the same review round is kept.

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

* fix(datatables): refuse a Postgres trigger on a data table under roles when it is saved

Creating or editing a trigger that points at a data table under roles was
accepted, and its listener then retried the refused connection every 30
seconds forever. The save is now refused, and a trigger that reaches such a
data table anyway (re-enabled, or cloned into a fork) is disabled by its
listener with the reason, as a missing replication slot is.

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

* fix(datatables): disable a data table role before deleting it

Deleting a role reassigns and drops what it owns in each registered
database on its own connection, and each of those passes commits as it
goes. A database failing part-way left the role enabled in the catalog and
able to log in, but already stripped in the databases reached before it.
The role is now disabled in its own commit first, so a failed delete
leaves a disabled role to retry.

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

* fix(datatables): serialize roles going on with a stream starting

Turning roles on looked for enabled triggers and live captures once,
without a lock anything starting a stream also took. A trigger enabled in
that window could have its listener connect before roles committed, and a
healthy listener never checks again. Both transitions now serialize on one
advisory lock: roles going on hold it exclusive while they look, and
trigger create, edit and enable, and capture setup and ping hold it shared
while they commit. Either the look sees the stream, or the listener
connects after roles are committed and refuses.

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

* fix(datatables): wait out live listeners, and resolve stored names containing `?`

Turning roles on counted a trigger as gone once disabled, and a capture
once its client stopped pinging, but the listener keeps its replication
connection until its next heartbeat notices. A trigger or capture whose
listener pinged in the last 15 seconds, the window a server holds a
listener for, now still counts as streaming.

Data table names could contain `?` before they were restricted, and such
entries are still stored. Splitting `?role=` off a reference misread them:
`a?b` became `a` with an unknown parameter, and the clone checks looked at
a different entry than the one copied. An entry stored under the whole
reference is now looked up first, in the Postgres executor, DuckDB ATTACH
and the clone checks. Agent workers cannot read the workspace and keep
the strict parse, which refuses such a name rather than misreading it.

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

* fix(datatables): warn when a settings sync strands fork pointers

A settings save reported the fork pointers left resolving to nothing only
for the names in `deleted_datatables`, which `wmill sync push` never sends.
The save now works out what it removed from the locked entries, and the
CLI prints the stranded pointers it returns.

Also correct the replication helper's contract: no role or admin check
makes a replication connection safe, so a data table under roles is
refused outright rather than gated as an admin operation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* fix(datatables): refuse a save that drops a data table's roles through an undeclared rename

A data table's roles follow its entry only through a declared rename. A
settings sync sends the whole map and never declares one, so renaming a
data table under roles there read as a delete and a new entry on the same
database: the new entry carried no roles, and every caller connected as
admin. Such a save is now refused, naming both entries.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* fix(datatables): no entry without roles may newly reach a database under roles

The previous guard only caught a new name replacing an entry under roles.
A whole-map save could also repoint an existing entry without roles at
that database, or another workspace could point one there, and every
caller of that entry would connect as admin. The rule is now stated on
the saved entries: one that carries no roles and newly points at an
instance database any entry under roles uses, in this workspace or
another, is refused. A declared rename carries its roles and passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* feat(datatables): move data table role catalog and resolution to the enterprise edition

Roles are an Enterprise Edition feature. The catalog, the Postgres logins,
CONNECT convergence, tenant evaluation and the role half of connection
resolution move to windmill-ee-private. Every public function keeps its path
and signature and forwards through datatable_roles_oss, which re-exports the
enterprise implementation or, without it, refuses.

Without the enterprise edition a data table under roles, or a caller naming a
role, is refused a connection rather than resolved as admin, and the reach and
admin-access checks refuse one under roles. A data table not under roles
resolves as before in every edition, and an instance database keeps the
CONNECT grants it was created with. The catalog lock, the stream lock, the
tenant cascades and the permissions stripping stay in OSS: they only restrict.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* feat(datatables): move the data table permissions endpoints to the enterprise edition

The permissions read, save and usable-roles handlers move to
windmill-ee-private; the routes stay registered and, without the enterprise
edition, answer that data table roles are an Enterprise Edition feature.
ensure_governs_datatable and ensure_reaches_datatable keep their paths: the
first refuses, the second passes a data table not under roles.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* feat(datatables): move the data table role catalog endpoints to the enterprise edition

The superadmin list, create, update and delete handlers move to
windmill-ee-private. The routes stay registered and, without the enterprise
edition, refuse after authentication.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* test(datatables): run the roles tests on the enterprise edition, refusals without it

Each test that exercises roles runs with private and enterprise. Two tests run
without them: every roles route answers the Enterprise refusal, and a data
table saved under roles, or a named role, is refused a connection while one
not under roles resolves as before.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* feat(datatables): gate the roles UI mount sites on an enterprise license

Both mount sites are still commented out; the gate travels with them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* test(datatables): run the tenant matcher test on the enterprise edition

The matcher it covers is enterprise code now, so without the enterprise
edition the test hit the stub and failed the default windmill-common run. It
runs with private and enterprise, and a counterpart without them asserts that
no tenant list covers anyone, the wildcard and a workspace admin included.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjfMkJyKzodxkobqGZ6Lqb

* chore: update ee-repo-ref to a1873dbb67f2302b85ff5362f8387b48eccdb607

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

Previous ee-repo-ref: 5c853e2c20eca6b748415fc0d6862a6ebfb5fec4

New ee-repo-ref: a1873dbb67f2302b85ff5362f8387b48eccdb607

Automated by sync-ee-ref workflow.

* fix(datatables): refuse roles while a same-workspace alias reaches the database

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

* fix(datatables): let CE migrations connect as an explicitly named admin

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

* fix(datatables): serialize roles going on with aliases saved from other workspaces

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

* docs(datatables): note that legacy names with ? cannot be migrated

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

* feat(datatables): add an ACL editor for data table roles

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

* fix: take every pooled connection before the ACL apply locks

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: refresh grant options only after the ACL apply validates its plan

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: add only missing grant options before an ACL apply, never default privileges

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: run one data table ACL apply at a time per server before it connects

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: hold the ACL connection to the database that was authorized

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: build the ACL connection from the authorized data table entry

Resolving the settings again could land on a resource with the same
database name on another server, which the later entry checks never see.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: check ACL read reach against the entry it connects from

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* feat(datatables): Ducklake catalogs on the external instance cluster

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

* fix(datatables): never grant CREATEROLE to custom_instance_user on the external cluster

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

* docs(datatables): state the authorization contract of external database usage lookups

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

* fix(datatables): drop a DuckDB data table secret once its ATTACH has used it

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

* perf(datatables): resolve a workspace's data tables per pointer hop, not per entry

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

* fix(datatables): hold the parent's settings while a fork points at its data tables

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

* fix(datatables): refuse repointing the external cluster while it is in use, and keep verify-ca working for pg_dump

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

* fix(datatables): protect external databases pending fork cleanup, and describe Ducklake usage in the API

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

* feat(datatables): per-cluster data table role catalogs, with roles on the external instance cluster

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

* fix(datatables): write the external cluster setting under the lifecycle lock, and check fork targets are registered

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

* fix(datatables): register external fork catalogs under the lifecycle lock, and keep certificate verification in DuckDB attaches

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

* fix(datatables): keep certificate verification when DuckDB attaches an external data table

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

* fix(datatables): keep certificate verification when DuckDB attaches an external data table

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

* fix(datatables): refuse fork cleanup of an external database another workspace uses

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

* fix(datatables): refuse rolling back while external data tables are under roles, and type external_instance in the CLI

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

* fix(datatables): stop counting storage-only fork cleanup rows as uses of an external database

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

* fix(datatables): bind fork database copies to their workspace, and count every use before dropping one

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

* fix(datatables): authenticate instance database setup before writing its status, and keep a fork reservation across it

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

* fix(datatables): create external databases only on a cluster setup succeeded on, and document the registry reader

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

* fix(datatables): keep only the most recently used DuckDB root certificate files

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

* fix(datatables): migrate fork reservations on workspace rename, and lock the parent's data tables for the whole fork

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

* fix(datatables): take the fork data table lock once, before the external cluster's

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

* docs(datatables): describe the external instance cluster and how to run one locally

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

* fix(datatables): keep fork reservations private, drop a cleaned-up entry with its database, and serialize cleanup with settings saves

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

* fix(datatables): hold the fork lock across a fork import, and carry the reservation inside the setup write

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

* fix(datatables): check the external cluster setting on its own transaction, and gate the registry probe

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

* feat(datatables): add an ACL editor for data table roles

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

* fix: take every pooled connection before the ACL apply locks

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: refresh grant options only after the ACL apply validates its plan

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: add only missing grant options before an ACL apply, never default privileges

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: run one data table ACL apply at a time per server before it connects

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: hold the ACL connection to the database that was authorized

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: build the ACL connection from the authorized data table entry

Resolving the settings again could land on a resource with the same
database name on another server, which the later entry checks never see.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* fix: check ACL read reach against the entry it connects from

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BRoYE5ZeAVvrDYdfhDAYXb

* chore: update ee-repo-ref to 7e338e4dabf91689bfd7fb0333c6534040b17b59

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

Previous ee-repo-ref: 0edd40979cf36bfba59323f3f6a0811ae1369cf5

New ee-repo-ref: 7e338e4dabf91689bfd7fb0333c6534040b17b59

Automated by sync-ee-ref workflow.

* fix(datatables): keep DuckDB root certificate files in the job directory

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

* chore: drop the unused json import from the settings crate

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

* fix(datatables): drop the serde_json::json import left unused by the fork setup write

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

* fix(datatables): accept external_instance data tables in the settings form type

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

* fix(datatables): serialize fork database reservations, cleanup, setup and Ducklake saves on the database

- A fork copy is created and registered under its workspace's fork lock, and refused once the
  workspace is archived; a rename re-migrates reservations under that lock after archiving.
- Ducklake saves lock every instance database they newly name, as data table saves do.
- Instance database setup holds the database's lock until its entry is written.
- Fork import also holds the database's lock across the restore.
- Cleanup re-reads the entry under its locks before dropping anything.
- Non-superadmins no longer see fork copies reserved for workspaces they are not in.

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

* fix(datatables): state the authorization contract of the external cluster status and write check

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

* fix(datatables): lock the fork copy at finalization, and order cleanup's registry write after its settings row

- Fork finalization holds the copy's database lock from its availability check to the commit.
- Cleanup removes the registry entry in its own transaction, in a task of its own, instead of on a
  second connection; a rename migrates reservations after its settings rewrites, so both take the
  settings rows before the registry.

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

* fix(datatables): hold the fork lock across a rename's settings copy

Fork cleanup of the old id could otherwise drop a copy the renamed workspace goes on using. Also
states the authorization contract of the instance database drop helpers.

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

* fix(datatables): refuse moving the external cluster to another host or port while it holds databases

Every settings writer goes through the same check as removal: the login, TLS and maintenance
database may still change, the cluster may not.

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

* feat(datatables): clone a data table under roles with its owners and grants (#11120)

Claude-Session: https://claude.ai/code/session_01UbrtwiYNfayrmqouBJHwGV

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: open the raw app data table drawer when the workspace has none

Selecting the first data table of an empty list passed undefined to the name
check, which threw instead of opening the drawer on no data table.

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

* fix(datatables): offer cloning a data table under roles where its grants can be replayed

The server clones such a data table and replays the source's owners and grants,
which only the Enterprise Edition does, so the fork wizard hid both clone
options everywhere instead of on a build that cannot replay them.

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

* docs: name the placeholder the empty raw app data drawer renders

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

* fix(datatables): replace a job directory file at the DuckDB root certificate path instead of trusting it

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

* test: pin the enterprise refusal the role pickers read as 'not under roles'

The server's sentence and the frontend's copy of it were coupled by nothing,
so rewording either one turned every role picker on a community build into a
failed lookup.

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

* fix(datatables): type Ducklake catalogs on the external instance cluster in the settings form

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

* fix(datatables): read a roles answer only for the workspace it was asked in

A fork and its parent each have their own roles on a data table of the same
name, so an answer stamped with the name alone settled the role from the
workspace the editor was acting on before.

Also derive the AI table creation flag from the data replaced into the editor:
data naming no data table left the flag on from before.

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

* fix(datatables): keep an instance database a settings save is waiting to name

Cleanup for a database whose setup failed took the lock first, read no user,
and dropped it while a save blocked on that same lock was about to commit a
reference to it.

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

* fix(datatables): check the workspace stamp in the default database selector too

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

* fix(datatables): read what a save racing instance-database cleanup committed

A transaction blocked on the lock may still roll back, so keeping the database
for it stranded one whose name then blocks every retry: it is let through and
its outcome read instead. The waiter query also matches this database's locks
only, since pg_locks spans the cluster.

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

* fix(datatables): tell a waiting request apart from the workspaces using a database

Both callers render what cleanup returns as the workspaces that keep the
database, so a waiting request's pid read as one of them. Each now words that
case itself, and the give-up comment names where the kept name actually goes.

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

* fix(datatables): take the cleanup lock on a connection the pool cannot reclaim

A session lock outlives the future holding it, so a cancellation between
taking it and releasing it handed a locked session back to the pool, where
every later settings save waits on it. Detached, the connection closes when it
is dropped and the server releases the lock with the session.

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

* fix(datatables): close the cleanup connection on drop instead of detaching it

Detaching released the pool permit while the session stayed alive, so
concurrent cleanups waiting on their locks could open as many connections as
they liked. Closing on drop covers the same cancellation and keeps them
counted.

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

* chore: update ee-repo-ref to 179d2454a063ee818a9387a1eafdd354a217a16c

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

Previous ee-repo-ref: c2e43f5b5ff753d339b70e232fd17b6ffecb054d

New ee-repo-ref: 179d2454a063ee818a9387a1eafdd354a217a16c

Automated by sync-ee-ref workflow.

* chore: update ee-repo-ref to fd5b8af748f2c985b13e18d9ea30894f3bd7e9a3

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

Previous ee-repo-ref: 3145e422d61d580f0a82804f075285c112879da0

New ee-repo-ref: fd5b8af748f2c985b13e18d9ea30894f3bd7e9a3

Automated by sync-ee-ref workflow.

* fix(datatables): classify a fork import's target from the resolution that built its connection

A second read could see the entry flipped to a resource and skip the reservation check while the
connection already built still reached the instance cluster.

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

* fix(datatables): run external database lifecycle on the caller's transaction, one lock order for fork cleanup

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

* fix(datatables): check a fork copy's reservation on the locked transaction's connection

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

* fix(datatables): make and drop fork copies of external data tables on the external cluster

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

* fix(datatables): refuse a fork whose external copy something already names

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

* fix(datatables): check an external fork copy's uses before removing its entry, so child fork pointers still count

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

* fix(datatables): migrate external cluster fork reservations on workspace rename

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

* feat(datatables): configure the external instance cluster and pick its databases from the UI

Instance settings gets an External Postgres tab: the cluster's connection, the setup run
with its report, and the databases Windmill created there. Data table and Ducklake settings
offer the external_instance kind, with a picker over those databases.

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

* fix(datatables): keep the external cluster form out of the instance settings the page bulk-saves

The form seeded its key into the settings store after the page snapshotted them, so merely
opening the tab made the page send a setting the validator refuses, failing an admin's
unrelated save. The form is local state now, and only the setup writes the key.

The database picker also treats a superadmin-only listing as authoritative: a workspace
admin, who cannot list, no longer sees a saved database as missing.

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

* fix(tests): app paths are validated, so a guest app cannot be renamed to one with a space

Path validation on apps landed after this test, which still expected a space to be accepted
and created its fixture on a ':' path. The scopable-path guard it exists for is kept by
planting that path on the row, which is now the only way an app can hold one.

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

* feat(datatables): one Managed Postgres tab, and a switch for Windmill's own database

The instance settings tab covers both substrates Windmill administers: the external cluster,
which can now be disabled once nothing sits on it, and Windmill's own database, which an
operator can turn off so the cluster is the only one a workspace may newly name. A save that
names it then refuses, as the create endpoint does.

Workspace settings name them the way an admin meets them: Postgres Resource, and Managed
instance, qualified as Internal or External only while both are on offer.

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

* feat(datatables): offer the external cluster in the add-data-table wizard, and give Ducklake its room back

The wizard gets the external cluster as a fourth substrate: pick a database it already holds
or name a new one, which the run creates before writing the entry, so Try again does not trip
on a database the last attempt made.

Ducklake's maintenance column moves into the settings popover next to the extra args, which
the wider catalog select had squeezed the name box out of.

A setting a component saves itself now also moves the page's baseline, or Discard would
restore what it replaced and a later save would send that stale value back.

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

* fix(datatables): only a database this wizard run made makes its retry idempotent

A retry skipped the create whenever the name was registered, which let a run adopt a database
another superadmin had made and share their data without the warning the existing-database
branch shows. The run tracks what it created instead, and reports it so Discard can say the
database is still there. Creating one now refreshes the registry the next run's default name
and its validation read, and that default counts the external cluster's databases rather than
the instance's.

Row ownership carries the substrate: "instance" and "external_instance" can hold the same name,
and a row repointed between them while a run probes must not read as that run's own.

Also fixes the merge leftovers in the DuckDB executor's tests, which cargo check never compiles:
the new PgDatabase field and the attach helper's job directory.

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

* fix(datatables): shorten the picked managed kind, and say what an empty database list means

The closed select has room for the qualifier, not the whole name, so a picked managed kind
reads "Managed (Internal)". An external entry gets the tooltip its internal counterpart has,
and a database picker with nothing in it says to type a name rather than "No items found".

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

* fix(datatables): keep the wizard's external-database bookkeeping optional and parked

The run deps gained a required field, which every existing caller of runSetup -- the sibling
test suite included -- does not pass. It defaults to empty instead, the parked payload carries
it across a Supabase redirect as it claims to, and a resumed run counts it as something left
behind. Two regressions pin the create: made on a first attempt, skipped only for a database
this run made.

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

* fix(datatables): review an external-cluster database as one, not as a Postgres resource

The review step fell through to the resource branch for the new provider, so it announced a
connection already in the workspace for a database that does not exist yet.

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

* fix(datatables): show the server's refusal instead of an object in the toast

Saving data table settings passed the whole error to the toast, which rendered the request
and response as JSON, and the instance-database wizard replaced it with "check console".
Both surface the message the API sent, through the helper that exists for it.

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

* chore: point at the EE commit dropping the unused import

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

* fix(datatables): define a role on the cluster its data table sits on

The permissions drawer created and listed roles without naming a cluster, so a role defined
from an external data table became a login on Windmill's own, and the refresh then replaced
the correct catalog with the internal one. The drawer passes the data table's cluster to both.

The wizard also read a database it had just created as a name collision, which blocked
returning to the failed attempt and finishing under the same name.

And the merge had left the CONNECT-grant pass and its log in both the caller and the callee.

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

* feat(datatables): manage the external cluster's role catalog, and name the cluster in the copy

The roles drawer offered one catalog, so the external cluster's roles could only be reached
through a data table sitting on it — and became unreachable once the last one was gone, while
the cluster could not be unset until they were dropped. Opened from the page it now offers the
clusters the instance has; a data table's own drawer still pins its cluster, and its copy names
that cluster rather than "the instance".

A DuckDB attach also decides whether to verify certificates the way every other Postgres
connection does, so a resource carrying a root certificate is no longer downgraded to require
here alone.

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

* fix(datatables): bind the roles list to the cluster it was read for

Switching catalogs left the previous cluster's rows on screen and applied whichever response
landed last, so a slower read could seat one cluster's logins under the other's heading while
every control acted on the wrong id — invisible where a name exists on both. The switch clears
the rows, a token discards a response the selection has moved past, and the controls stay inert
while a catalog is being read.

The drop confirmation also names the cluster whose databases it reaches.

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

* feat: show data tables as cards and enable the add wizard by default

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

* feat: offer managed vs resource in the data table wizard, with external setup hints

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

* feat: move the external database hint next to the wizard's primary action

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

* feat: open managed postgres settings in place, prefilled from the picked resource

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

* feat: preview data table usage in python, duckdb and typescript in the wizard review

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

* feat: lay a data table card's fields out on one row, with manage set apart

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

* fix: hide data table grants while the data table is not under roles

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

* fix: default a new data table to the workspace name, and frame the usage preview

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

* feat: warn when disabling the internal instance while data still sits on it

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

* feat: disable the unavailable cluster in the instance roles toggle

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

* feat: make the data table manage buttons accent

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

* fix: stop resolving data tables on windmill's database once it is disabled

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

* feat: hint superadmins that typing in the add-role picker creates a role

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

* style: border the assets page cards instead of elevating them

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

* feat: confirm data table deletions on save, and show no success when a save is called off

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

* test: pin that instance data tables stop resolving once disabled

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

* fix: give the import wizard real managed availability, and lock the roles catalog when no cluster is on offer

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

* feat: mark the managed database as recommended in the data table wizard

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

* feat: skip the data table wizard's first step when a resource is the only option

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
2026-09-29 20:26:23 +02:00

2029 lines
77 KiB
Svelte

<script lang="ts">
import { parkWizard, type WizardResume } from './wizardParking'
import { untrack, type Snippet } from 'svelte'
import { Database, ArrowRight, Plus, Lightbulb, Server } from 'lucide-svelte'
import Button from '../common/button/Button.svelte'
import ToggleButtonGroup from '../common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '../common/toggleButton-v2/ToggleButton.svelte'
import Modal2 from '../common/modal/Modal2.svelte'
import Stepper from '../common/stepper/Stepper.svelte'
import Alert from '../common/alert/Alert.svelte'
import TextInput from '../text_input/TextInput.svelte'
import InputError from '../InputError.svelte'
import Password from '../Password.svelte'
import Select from '../select/Select.svelte'
import Toggle from '../Toggle.svelte'
import MeltTooltip from '../meltComponents/Tooltip.svelte'
import Path from '../Path.svelte'
import Label from '../Label.svelte'
import Section from '../Section.svelte'
import SupabaseIcon from '../icons/SupabaseIcon.svelte'
import {
FolderService,
OauthService,
ResourceService,
UserService,
type User,
VariableService,
WorkspaceService
} from '$lib/gen'
import type {
ListExternalInstancePgDatabasesResponse,
ListCustomInstanceDbsResponse
} from '$lib/gen'
import { resource, type ResourceReturn } from 'runed'
import type { ConfirmationModalHandle } from '../common/confirmationModal/asyncConfirmationModal.svelte'
import SetupChecklist, { type SetupStep } from '../wizards/SetupChecklist.svelte'
import SupabaseProjectStep from './SupabaseProjectStep.svelte'
import DataTableConnectionReport from './DataTableConnectionReport.svelte'
import DataTableUsagePreview from './DataTableUsagePreview.svelte'
import { useSupabaseOauth } from './supabaseOauth.svelte'
import { probeDatatableConnection } from './datatableProbe'
import { logDatatableWizard } from './datatableTelemetry'
import {
anythingClaimed,
claimOf,
claimsFromJSON,
claimsToJSON,
noClaims,
release,
type Claims
} from './setupClaims'
import { enterpriseLicense, superadmin, userStore, workspaceStore } from '$lib/stores'
import { isCloudHosted } from '$lib/cloud'
import { goto } from '$lib/navigation'
import { sendUserToast } from '$lib/toast'
import { apiErrorMessage, escapeHtml } from '$lib/utils'
import {
externalInstancePgPrefill,
prefillFromResourceValue,
type ExternalInstancePgPrefill
} from '../instanceSettings/externalInstancePgPrefill'
import { superadminSettingsHref } from '../sidebar/settings'
import { isCustomInstanceDbEnabled } from './utils.svelte'
import {
composePostgresConnectionString,
parsePostgresConnectionString,
connectionParamRefusal
} from '$lib/utils/postgresConnectionString'
import {
clearProbe,
datatableNameError,
hasAdvanced,
instanceDbNameError,
intentComplete,
newResourceParts,
newWizardState,
postgresResourceValue,
supabaseSummary,
planSteps,
probeValue,
resourcePathOf,
runSetup,
type CreatedProject,
type Provider,
type RunResult,
type WizardState
} from './addDataTableModel'
import {
resolveSupabaseConnection,
supabaseResourceValue,
DEFAULT_SUPABASE_REGION
} from './supabaseProvisioning'
type Props = {
opened: boolean
existingNames: string[]
/** Every data table already configured, so the review step can warn about sharing one. */
existingDataTables: { name: string; resourcePath: string | undefined }[]
/** Set when Supabase redirected the user back here mid-flow. */
resume?: WizardResume | undefined
onDone: () => void
/** The instance database pool and its confirmation host are owned by the settings page,
* which already loads them for the rows; sharing them keeps one source of truth. */
customInstanceDbs: ResourceReturn<ListCustomInstanceDbsResponse>
/** The external cluster's databases, and whether it is on offer at all. Owned by the
* settings page for the same reason as `customInstanceDbs`. */
externalInstanceDbs?: ResourceReturn<ListExternalInstancePgDatabasesResponse> | undefined
externalInstanceAvailable?: boolean
/** Whether Windmill's own database can take a new data table. Defaults to the superadmin
* check alone, for callers that do not load `instance_pg_disabled`. */
instanceAvailable?: boolean
/** Reloads what decides the two flags above, which a superadmin may have changed in the
* instance settings since the wizard last opened. */
refreshManagedInstances?: () => void
/** Whether to point a superadmin at the instance settings drawer to set up an external
* cluster. Only pages under the app layout have that drawer to open. */
offerExternalSetup?: boolean
/** A free name on the external cluster. Its registry and the workspace's entries there are
* a different set from the instance's, so the two defaults cannot be the same helper. */
defaultExternalDbName?: () => string
confirmationModal: ConfirmationModalHandle
defaultInstanceDbName: () => string
/** Name to open with, when the caller needs a table of a particular name rather
* than whatever the user picks — the import wizard configures the one a project's
* migrations target.
*
* Locked when `onFinishAlso` is also given, because that work targets this name and
* nothing carries an edit through to it: renaming `main` to `other` would create
* `other`, then run the migrations against `main`, fail, and leave a data table
* nobody asked for. Editable without one, where the name is only a name. */
initialName?: string
/** Where the dialog portals to. `#content` is the app shell's scroll container,
* which only exists inside the `(logged)` layout; a page reparented out of it
* (the hub import wizard) has to say `body` or the portal finds nothing and the
* dialog never appears. */
modalTarget?: string
/** What the caller does once the table exists, named on the final button so the
* user is told before pressing it — the import wizard runs the project's
* migrations, which is otherwise invisible until it has already happened. */
finishAlso?: string
/** The work `finishAlso` names. Run as the last checklist step, so it reports
* where the rest of the run does instead of starting after the dialog closes.
* Throwing marks that step failed; the table itself is already made either way. */
onFinishAlso?: () => Promise<void>
/** The workspace everything here is created in and checked against.
*
* Defaults to `$workspaceStore`, which is right for the settings page — it is the
* workspace being looked at. The import wizard is the exception: its page is
* reparented out of `(logged)`, so nothing re-runs the layout's workspace
* persistence, and after a reload the store still names whatever workspace the
* user came from while the plan in the URL names the destination. Left ambient,
* this would create the data table in one workspace and run the project's
* migrations in the other. */
workspace?: string
}
let {
opened = $bindable(),
existingNames,
existingDataTables,
resume,
onDone,
customInstanceDbs,
externalInstanceDbs,
externalInstanceAvailable = false,
instanceAvailable: instanceAvailableProp,
refreshManagedInstances,
offerExternalSetup = false,
defaultExternalDbName,
confirmationModal,
defaultInstanceDbName,
initialName,
modalTarget = '#content',
finishAlso,
onFinishAlso,
workspace: workspaceProp
}: Props = $props()
/**
* The caller needs this exact table, and has follow-up work bound to its name.
*
* Captured when the dialog opens rather than read live: `initialName` is the caller's
* `wizardFor`, which it clears from `onDone` — and that fires after a *failed* run too,
* while the dialog stays up offering Back. Reading it live releases the lock exactly when
* the user is most likely to edit, which is the divergence the lock exists to stop.
*/
let nameLocked = $state(false)
/** Every write and every check goes through this, never `$workspaceStore` directly. */
const targetWorkspace = $derived(workspaceProp ?? $workspaceStore ?? '')
/**
* Who the caller is *in the destination*, which is not who `$userStore` describes.
*
* `$userStore` is the membership of the workspace the app is in. Routing the API calls
* elsewhere without routing this leaves the username behind: after a reload on the import
* wizard's step 4 it names the workspace the user came from, and a resource path built
* from it lands on `u/<someone-else>` inside the destination — failing an ownership check,
* or for an admin, quietly putting database credentials in another member's namespace.
*/
let targetUser = $state<User | undefined>(undefined)
const aimedElsewhere = $derived(!!workspaceProp && workspaceProp !== $workspaceStore)
const ambientUsername = $derived($userStore?.username ?? '')
const targetUsername = $derived(aimedElsewhere ? (targetUser?.username ?? '') : ambientUsername)
/** The destination's membership could not be read, so nothing here knows who the user is. */
let membershipFailed = $state(false)
async function loadTargetUser(): Promise<void> {
const ws = workspaceProp
if (!ws || ws === $workspaceStore) {
targetUser = undefined
membershipFailed = false
return
}
try {
targetUser = await UserService.whoami({ workspace: ws })
membershipFailed = false
} catch {
// Recorded rather than swallowed: an unknown username silently becomes `admin` in
// the default path, which is the wrong namespace to write credentials into. Setup
// is blocked instead.
targetUser = undefined
membershipFailed = true
}
}
const STEPS = ['Choose a database', 'Set it up', 'Review']
let wiz: WizardState = $state(
newWizardState({ name: 'main', projectName: 'windmill-data', folder: '' })
)
let instanceAvailable = $derived(instanceAvailableProp ?? !!$isCustomInstanceDbEnabled)
let managedProvider = $derived(
wiz.provider === 'instance' || wiz.provider === 'external_instance'
)
/** A managed kind was picked that this instance does not offer, so nothing can be set up. */
let managedKindUnavailable = $derived(
(wiz.provider === 'instance' && !instanceAvailable) ||
(wiz.provider === 'external_instance' && !externalInstanceAvailable)
)
// Both substrates are set up by a superadmin, so only they are shown the managed option while
// neither is on offer yet: it leads to the explainer on how to set one up.
// Cloud has no Postgres Windmill manages, internal or external: data tables there are always a
// resource.
let managedOffered = $derived(
!isCloudHosted() && (instanceAvailable || externalInstanceAvailable || !!$superadmin)
)
let canSetUpExternal = $derived(
offerExternalSetup && !isCloudHosted() && !!$superadmin && !!$enterpriseLicense
)
function preferredManagedProvider(): Provider {
return instanceAvailable || !externalInstanceAvailable ? 'instance' : 'external_instance'
}
// Availability can change under an open wizard — a superadmin setting the cluster up in the
// tab the explainer opened — and a kind that stopped or started being the only one on offer
// is the one the toggle has to show.
$effect(() => {
if (!opened || !managedProvider || !managedKindUnavailable) return
const preferred = preferredManagedProvider()
if (preferred !== wiz.provider) untrack(() => selectProvider(preferred))
})
/** Leaves the wizard for the instance settings drawer, on the tab that sets a cluster up. */
async function openManagedPostgresSettings() {
close()
const { pathname, search } = window.location
await goto(pathname + search + superadminSettingsHref('managed_postgres'))
}
/**
* The connection on screen in the resource step, to seed the external cluster form: a
* resource that already reaches a Postgres is usually the cluster someone means to hand over.
*/
function prefillSourceLabel(): string | undefined {
if (wiz.provider !== 'resource') return undefined
if (wiz.own.creating) return newResourceParts(wiz) ? 'the connection you entered' : undefined
return wiz.own.resourcePath
}
async function prefillFromResourceStep(): Promise<ExternalInstancePgPrefill | undefined> {
if (wiz.provider !== 'resource') return undefined
if (wiz.own.creating) {
const parts = newResourceParts(wiz)
if (!parts) return undefined
return prefillFromResourceValue(
'the connection you entered',
postgresResourceValue(parts, parts.password ?? '', wiz.own.advanced)
)
}
const path = wiz.own.resourcePath
if (!path) return undefined
// Interpolated: the stored password is a `$var:` reference the setting cannot follow.
const value = await ResourceService.getResourceValueInterpolated({
workspace: targetWorkspace,
path
})
return value && typeof value === 'object'
? prefillFromResourceValue(path, value as Record<string, any>)
: undefined
}
async function explainExternalInstance() {
const useIt = externalInstanceAvailable
const source = useIt ? undefined : prefillSourceLabel()
// The explainer sits outside this dialog, so the click that answers it reads as a click
// outside and would ask to discard the run. Released a task later: that click is still
// being dispatched when `ask` resolves.
dismissing = true
const confirmed = await confirmationModal
.ask({
title: 'Let Windmill manage your external database',
type: 'info',
confirmationText: useIt ? 'Use the external cluster' : 'Open managed Postgres settings',
children: `<div class="flex flex-col gap-2 text-sm text-primary">
<p>Point Windmill at a Postgres cluster you run &mdash; RDS, Cloud SQL, Azure, self-hosted &mdash; with an admin login that has <span class="font-mono">CREATEDB</span> and <span class="font-mono">CREATEROLE</span>.</p>
<p>Windmill then creates one database per data table there, generates and rotates its credentials, and manages the data table roles jobs connect as. Nobody in the workspace handles a password, and the admin login is never handed to a job.</p>
<p>${
useIt
? 'An external cluster is already set up on this instance.'
: 'A superadmin sets it up once for the whole instance, under Instance settings &rarr; Managed Postgres. It is an Enterprise Edition feature.'
}</p>${
source
? `<p>The form opens filled in with the connection of <span class="font-mono">${escapeHtml(source)}</span>, for you to review before saving.</p>`
: ''
}
</div>`
})
.finally(() => setTimeout(() => (dismissing = false)))
if (!confirmed) return
if (useIt) {
selectProvider('external_instance')
return
}
// Closed before reading the resource, not after: the guard against the explainer's click
// is released a task later, and the read takes longer than that.
close()
try {
externalInstancePgPrefill.set(await prefillFromResourceStep())
} catch (e) {
// The settings are still worth opening; the form just starts empty.
sendUserToast(`Could not read the resource to fill the form in: ${apiErrorMessage(e)}`, true)
}
await openManagedPostgresSettings()
}
let preventClose = $state(false)
/** A dismissal dialog is up, so a second one must not stack on it. */
let dismissing = false
/** Set once Finish has been pressed; the modal shows the checklist from then on. */
let run: { steps: SetupStep[]; running: boolean; result?: Awaited<ReturnType<typeof runSetup>> } =
$state({ steps: [], running: false })
/** Why the session pooler could not be used, once something has tried to read it. */
let poolerUnavailable: string | undefined = $state(undefined)
let initialResourcePath = $state('')
let resourcePathError = $state('')
/**
* Whichever namespace refused this path. The run writes a resource *and* a secret variable
* at the one path, and both writes upsert, so anything already sitting at either would be
* overwritten. `Path` reports the resource namespace itself; the effect below covers the
* variable one, and the check in `finish()` covers both.
*/
let pathTakenError = $state('')
let variableCheck: ReturnType<typeof setTimeout> | undefined = undefined
/**
* Whether a check for `path` still answers the question on screen. Read once before the
* request and again after it: the cleanup can cancel a pending timer but not a request
* already in flight, so an answer that arrives late has to re-earn its relevance. `path`
* alone is not enough -- it is built from the review step's fields, so picking an existing
* resource stops the wizard minting one without changing it.
*/
function pathStillChecked(path: string): boolean {
return (
path === resourcePath && wiz.step === 3 && mintsResource && !!path && path !== claimedPath
)
}
$effect(() => {
const path = resourcePath
// A path this wizard already wrote is not somebody else's to protect -- the same
// exemption the hard check in `finish()` makes, or a retry would refuse its own secret
// and leave Finish permanently disabled.
if (!pathStillChecked(path)) {
pathTakenError = ''
return
}
clearTimeout(variableCheck)
variableCheck = setTimeout(async () => {
const taken = await VariableService.existsVariable({ workspace: targetWorkspace, path })
// Two checks can be in flight at once and resolve out of order. A `false` for a path
// nobody is on any more would clear the error guarding the one about to be written;
// a `true` would disable Finish over a path this run stopped caring about.
if (!pathStillChecked(path)) return
pathTakenError = taken ? 'a variable already exists at this path' : ''
}, 500)
return () => clearTimeout(variableCheck)
})
/**
* Both namespaces at once, for the check that has to be right rather than quick. While the
* user is still typing the two halves are reported separately -- `Path` does the resource
* one, the debounced effect above does the variable one -- and either debounce can still be
* in flight when Finish is pressed.
*/
async function pathConflictMessage(path: string): Promise<string | undefined> {
const workspace = targetWorkspace
// Each namespace answers to its own claim. Holding the secret says nothing about who owns
// the resource beside it, so one claim must not wave the other's check through.
const [variable, resource] = await Promise.all([
claimedPath === path ? false : VariableService.existsVariable({ workspace, path }),
claimedResourcePath === path ? false : ResourceService.existsResource({ workspace, path })
])
if (variable) return 'a variable already exists at this path'
if (resource) return 'a resource already exists at this path'
return undefined
}
/** Furthest step reached, so going back to check something does not cost the progress. */
let maxStep = $state(1)
function defaultProjectName(): string {
return `windmill-${targetWorkspace || 'workspace'}`
}
function defaultTableName(): string {
// A caller that needs a specific name wins over the usual "main, unless taken":
// the import wizard's migrations only apply to a table of the name they target.
if (initialName) return initialName
if (!existingNames.includes('main')) return 'main'
const base = targetWorkspace || 'data'
let name = base
for (let i = 2; existingNames.includes(name); i++) name = `${base}_${i}`
return name
}
// Takes the list rather than reading it, so the fetch that loads it can seed off its own
// result before the resource has settled.
function defaultFolder(list: string[] = folders): string {
// The first folder this admin can write to, so the resource lands somewhere the team
// can find and repair. A workspace with no folders falls back to the personal space.
return list.length ? `f/${list[0]}` : `u/${targetUsername || 'admin'}`
}
// A row this run wrote and could not take back out is still its own: `removeRow` reports
// `kept` when the undo cannot reach the server, and counting that name as taken refuses the
// retry on the one name the user has every right to reuse.
let nameError = $derived(
datatableNameError(
wiz.review.name,
existingNames.filter((n) => n !== claimedName)
)
)
// Every database on the instance, not just the data table ones: the name has to be free
// in PostgreSQL, and a collision with a database created for something else still fails.
let instanceNameError = $derived(
wiz.provider === 'instance' && wiz.instance.mode === 'create'
? instanceDbNameError(
wiz.instance.dbName ?? '',
// `setup_custom_instance_db` registers the name whether it succeeds or fails, so
// after a failed attempt the instance holds a database this very wizard asked
// for. Counting it as taken would refuse the retry, on the step the user cannot
// see it from.
Object.keys(customInstanceDbs.current ?? {}).filter((n) => n !== claimedInstanceDb)
)
: undefined
)
// The cluster refuses a name it already holds, whoever made it, so the registry is the list
// to check against — same shape as the instance one.
const externalDbName = () => defaultExternalDbName?.() ?? defaultInstanceDbName()
let externalNameError = $derived(
wiz.provider === 'external_instance' && wiz.external.mode === 'create'
? instanceDbNameError(
wiz.external.dbName ?? '',
// A database this run already created is not a collision: after a failed probe,
// Back returns here under the same name, and the retry reuses what it made.
Object.keys(externalInstanceDbs?.current ?? {}).filter(
(n) => !createdExternalDbs.includes(n)
)
)
: undefined
)
let connectionStringError = $derived.by(() => {
const text = wiz.own.connectionString
if (!text) return undefined
if (!parsePostgresConnectionString(text)) return 'That is not a Postgres connection string.'
return connectionParamRefusal(text)
})
let resourcePath = $derived(resourcePathOf(wiz))
/**
* Another data table on the same database. They would share one schema, so their tables are
* visible to each other and two of the same name collide. Migration bookkeeping is keyed by
* data table, so that part stays separate.
*/
let sharesDatabaseWith = $derived(
wiz.provider === 'resource' && !wiz.own.creating && wiz.own.resourcePath
? existingDataTables.find((d) => d.resourcePath === wiz.own.resourcePath)
: undefined
)
const pgResources = resource(
() => (opened && wiz.provider === 'resource' ? targetWorkspace : ''),
async (workspace) => {
if (!workspace) return undefined
const list = await ResourceService.listResource({ workspace, resourceType: 'postgresql' })
// The step opens on a choice rather than on nothing: the first resource where the
// workspace has any, the creation form where it has none. Only ever fills an empty
// selection, so it cannot overwrite what the user picked.
if (!wiz.own.creating && !wiz.own.resourcePath) {
if (list.length) wiz.own.resourcePath = list[0].path
else wiz.own.creating = true
}
return list
}
)
/** Exclusive: one list, and a card is either the selection or it is not. */
function selectResource(path: string) {
if (wiz.own.resourcePath !== path || wiz.own.creating) invalidate()
wiz.own.resourcePath = path
wiz.own.creating = false
}
function selectNewResource() {
if (!wiz.own.creating) invalidate()
wiz.own.creating = true
wiz.own.resourcePath = undefined
}
/**
* A connection string is a way of writing the fields down, so typing one fills them in as it
* is read. Unparseable text leaves the last good values alone to be corrected; `sslmode` is
* kept when the URI names none, since not mentioning it is not the same as clearing it.
*/
function absorbConnectionString(text: string) {
const parts = parsePostgresConnectionString(text)
if (parts) wiz.own.fields = { ...parts, sslmode: parts.sslmode ?? wiz.own.fields.sslmode }
}
function useFields() {
wiz.own.form = 'fields'
}
/** Composed for the box to start from; the fields stay the connection. */
function useConnectionString() {
const parts = newResourceParts(wiz)
if (parts) wiz.own.connectionString = composePostgresConnectionString(parts)
wiz.own.form = 'string'
}
const SSL_MODES = ['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']
// `accept_invalid_certs` is a tri-state, and its unset state is not a default anyone would
// guess -- name all three rather than offer a checkbox that cannot express one of them.
const CERT_VERIFICATION = [
{ value: 'default', label: 'Verify only when a root certificate is set' },
{ value: 'enforce', label: 'Always verify' },
{ value: 'accept', label: 'Accept any certificate' }
]
let certVerification = $derived(
wiz.own.advanced.accept_invalid_certs === undefined
? 'default'
: wiz.own.advanced.accept_invalid_certs
? 'accept'
: 'enforce'
)
function setField<K extends keyof typeof wiz.own.fields>(
key: K,
value: (typeof wiz.own.fields)[K]
) {
wiz.own.fields = { ...wiz.own.fields, [key]: value }
invalidate()
}
function setAdvanced<K extends keyof typeof wiz.own.advanced>(
key: K,
value: (typeof wiz.own.advanced)[K]
) {
wiz.own.advanced = { ...wiz.own.advanced, [key]: value }
invalidate()
}
// The Supabase branch goes through the instance's `supabase_wizard` OAuth client; where a
// superadmin has not configured one, the connect endpoint dead-ends, so do not offer it.
const oauthConnects = resource(
() => opened,
async (isOpen) => (isOpen ? await OauthService.listOauthConnects() : [])
)
let supabaseAvailable = $derived(
(oauthConnects.current ?? []).some((c) => c.name === 'supabase_wizard')
)
/** A resource is the only thing step 1 would offer, so it is skipped: there is no choice to
* make. Decided once Supabase's availability is known, since that is the other option. */
let onlyResource = $derived(
!managedOffered &&
!oauthConnects.loading &&
oauthConnects.current !== undefined &&
!supabaseAvailable
)
$effect(() => {
if (!opened || !onlyResource || wiz.step !== 1 || wiz.provider) return
untrack(() => {
selectProvider('resource')
enterStep(2)
})
})
const folderNames = resource(
() => (opened ? targetWorkspace : ''),
async (workspace) => {
if (!workspace) return []
const all = await FolderService.listFolderNames({ workspace })
const usable = all.filter((x) => !['app_groups', 'app_custom', 'app_themes'].includes(x))
// The list lands after `open()` has already seeded the folder, so the first open would
// otherwise always fall back to the personal space. Only re-seed what the user has not
// reached yet: the review step is where the folder becomes theirs. A resumed run has
// already chosen one -- reseeding would move its secret out from under the path claim
// it came back to finish.
if (wiz.step < 3 && !resumedPath) wiz.review.folder = defaultFolder(usable)
return usable
}
)
let folders = $derived(folderNames.current ?? [])
const SUPABASE_SIGNUP_URL = 'https://supabase.com/dashboard/sign-up'
const supaOauth = useSupabaseOauth({
// Safe to navigate this tab away: what the wizard had collected is parked first, and the
// settings page picks it back up when Supabase sends the user home.
redirectIfBlocked: true,
onPopupBlocked: () =>
parkWizard({
name: wiz.review.name,
region: wiz.supabase.region,
projectName: wiz.supabase.projectName,
resourcePath,
claims: claimsToJSON(claims),
createdProjects,
createdExternalDbs,
mode: wiz.supabase.mode,
org: wiz.supabase.org,
project: wiz.supabase.project,
connectionMode: wiz.supabase.connectionMode
})
})
/**
* The path a resumed run came back to finish, taken from whatever `reset` was given rather
* than the `resume` prop, so the two cannot disagree about which run is being restored.
*/
let resumedPath = $state<string | undefined>(undefined)
function reset(from: WizardResume | undefined) {
nameLocked = !!initialName && !!onFinishAlso
resumedPath = from?.resourcePath
// A pending confirmation that never settled leaves `dismissing` true, and `finally`
// cannot clear what never resolves — so a fresh open always starts dismissable.
dismissing = false
wiz = newWizardState({
name: from?.name || defaultTableName(),
projectName: from?.projectName || defaultProjectName(),
folder: defaultFolder()
})
wiz.supabase.region = from?.region ?? DEFAULT_SUPABASE_REGION
run = { steps: [], running: false }
maxStep = 1
// What the last run claimed belongs to the data table it created; a fresh one has to
// earn the name and the path again, or it would write over its predecessor's secret.
claims = noClaims
claimedInstanceDb = undefined
leftBehind = false
createdProjects = []
createdExternalDbs = []
nameConflictFor = undefined
lastFailure = ''
finishAlsoFailed = false
pathTakenError = ''
poolerUnavailable = undefined
if (from) {
wiz.provider = 'supabase'
// The clears above are for a fresh run. This one is the same run coming back from the
// redirect, so what it had already created is still its own to write over.
claims = claimsFromJSON(from.claims)
createdProjects = from.createdProjects ?? []
createdExternalDbs = from.createdExternalDbs ?? []
leftBehind =
anythingClaimed(claims) || createdProjects.length > 0 || createdExternalDbs.length > 0
// Which side of the toggle it was on, and the organization it was pointed at. Left to
// default, a run that died mid-create comes back asking for the password it generated.
if (from.mode) wiz.supabase.mode = from.mode
if (from.org) wiz.supabase.org = from.org
// The password is deliberately not parked -- it is a secret and sessionStorage is not
// the place for one. Carrying the project is what stops the resume landing on a
// different database with an empty password field and no sign anything moved.
if (from.project) wiz.supabase.project = from.project
if (from.connectionMode) wiz.supabase.connectionMode = from.connectionMode
const cut = from.resourcePath?.lastIndexOf('/') ?? -1
if (from.resourcePath && cut > 0) {
wiz.review.folder = from.resourcePath.slice(0, cut)
wiz.review.resourceName = from.resourcePath.slice(cut + 1)
}
enterStep(2)
}
}
/**
* Opened by the settings page. A run coming back from the Supabase redirect is handed in
* rather than read off the `resume` prop: the caller has it, and taking it as an argument is
* what keeps the restore independent of when the prop it was assigned to reaches this
* component.
*/
export async function open(parked?: WizardResume) {
// Awaited before `reset`, which seeds the resource path from `defaultFolder()` and so
// needs the destination's username. Seeding first and correcting later loses whenever
// the folder list resolves first, and never corrects at all if `whoami` fails.
await loadTargetUser()
// A superadmin may have set a cluster up in the instance settings since the last open.
refreshManagedInstances?.()
reset(parked ?? resume)
opened = true
logDatatableWizard({ step: 'opened' })
}
function selectProvider(key: Provider) {
if (key === wiz.provider) return
wiz.provider = key
logDatatableWizard({ step: 'picked', provider: key })
invalidate()
if (key === 'instance') wiz.instance.dbName ??= defaultInstanceDbName()
if (key === 'external_instance') wiz.external.dbName ??= externalDbName()
}
function suggestedResourceName(): string {
const base =
wiz.provider === 'supabase'
? wiz.supabase.mode === 'create'
? wiz.supabase.projectName
: (wiz.supabase.project?.name ?? 'supabase')
: wiz.review.name
return `${wiz.provider === 'supabase' ? 'supabase_' : 'pg_'}${base
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_|_$/g, '')}`
}
/** Moving forward through the primary action, which is what validated the step. */
function enterStep(step: 1 | 2 | 3) {
wiz.step = step
if (step > maxStep) maxStep = step
}
/**
* The stepper reaches any step already passed, in either direction -- going back to check
* something should not cost the progress. It cannot reach past `maxStep`: the primary
* action is what validates a step, and on step 2 what probes the connection.
*/
function goToStep(index: number) {
const target = index + 1
if (run.steps.length || target > maxStep || target === wiz.step) return
if (target === 1 && onlyResource) return
wiz.step = target as 1 | 2 | 3
}
/** Intent changed, so the review built from it is stale and stops being reachable. */
function invalidate() {
// Also retires any check still in flight, so its answer cannot land on the edited value.
probeToken++
clearProbe(wiz)
// Read off one attempt against one project, so it does not survive a change of inputs:
// the review step would otherwise warn about a limitation that does not apply to what
// it is describing, while claiming session pooling right above it.
poolerUnavailable = undefined
// Same for the failure carried back to the review step: it names inputs that have since
// been edited, so it would describe a run nobody can still act on.
lastFailure = ''
finishAlsoFailed = false
if (maxStep > wiz.step) maxStep = wiz.step
}
function enterReview() {
if (!wiz.review.resourceName) wiz.review.resourceName = suggestedResourceName()
// Path seeds itself from initialPath, so it has to be the suggestion as it stood when
// the step opened, not a live view of it -- a moving initialPath fights the typing.
initialResourcePath = resourcePathOf(wiz)
enterStep(3)
}
/**
* Proves the connection before anything is written. Supabase reads the pooler first: the
* value under test has to be the value that will be saved.
*/
// Fields stay editable while a check is out. Without a token the older answer lands after
// an edit and unlocks Continue for a connection nobody proved.
let probeToken = 0
async function probe() {
const token = ++probeToken
const settle = (probe: WizardState['probe']) => {
if (token === probeToken) wiz.probe = probe
}
wiz.probe = { checking: true, report: undefined, error: undefined }
try {
let value = probeValue(wiz)
if (!value && wiz.provider === 'supabase' && wiz.supabase.project) {
const connection = await resolveSupabaseConnection(
supaOauth.token!,
wiz.supabase.project,
wiz.supabase.connectionMode
)
// Retired while the pooler lookup was out: the user has changed something since,
// and writing the resolved mode back would silently undo their choice.
if (token !== probeToken) return
wiz.supabase.connectionMode = connection.mode
poolerUnavailable = connection.unavailable
value = {
...supabaseResourceValue(wiz.supabase.project, '', connection),
password: wiz.supabase.password
}
}
// An existing resource goes as a reference the worker resolves, exactly as a Postgres
// step would take it; anything unsaved goes as the value itself.
const database = value ?? (wiz.own.resourcePath ? `$res:${wiz.own.resourcePath}` : undefined)
if (!database) {
settle({ checking: false, report: undefined, error: undefined })
return
}
const report = await probeDatatableConnection(targetWorkspace, database)
settle({ checking: false, report, error: undefined })
} catch (err: any) {
settle({
checking: false,
report: undefined,
error: err?.body ?? err?.message ?? String(err)
})
}
}
/** True when step 2 has nothing to prove before Finish, so Continue is the only action. */
let probeable = $derived(
wiz.provider === 'resource' || (wiz.provider === 'supabase' && wiz.supabase.mode === 'existing')
)
let probePassed = $derived(!!wiz.probe.report?.can_create_table && !wiz.probe.error)
/**
* A run in this session left something behind -- a row, a secret, a database, a project.
* It outlives the checklist, which `backToReview` clears, because what was created does too.
*/
let leftBehind = $state(false)
/**
* Every Supabase project this session created, each guarding the path holding its only
* password. Held here rather than read off `run.result`: the checklist is cleared by every
* return to review, and the projects are not. A set, because two attempts at two paths each
* leave a password nothing later may write over.
*/
let createdProjects = $state<CreatedProject[]>([])
/** Databases this session created on the external cluster, so a retry does not create twice
* and Discard can say one was left behind. */
let createdExternalDbs = $state<string[]>([])
/** The instance database this session asked for, which is registered even when it failed. */
let claimedInstanceDb = $state<string | undefined>(undefined)
/**
* What this run created and may write over again. `writeRow` merges into whatever the
* server holds under the name, so a name free in the table on screen but taken on the
* server would repoint someone else's data table at this database.
*/
let claims = $state<Claims>(noClaims)
/** The path whose secret and resource this run holds, for the gates that ask by path. */
let claimedPath = $derived(claimOf(claims, 'secret', resourcePath)?.path)
let claimedResourcePath = $derived(claimOf(claims, 'resource', resourcePath)?.path)
let claimedName = $derived(claims.find((c) => c.kind === 'row')?.path)
/**
* The name the pre-flight refused, kept with the message so editing the name retires it.
* Storing only the message would need something to clear it, and the check that raises it
* runs where a clear cannot see the edit that follows.
*/
let nameConflictFor = $state<{ name: string; message: string } | undefined>(undefined)
let nameConflict = $derived(
nameConflictFor?.name === wiz.review.name.trim() ? nameConflictFor.message : ''
)
/** Why the last run failed, kept on the review step after the checklist is dropped. */
let lastFailure = $state('')
/**
* The appended `onFinishAlso` step failed while `runSetup` itself succeeded. Tracked apart
* from `run.result`, which stays the setup's own verdict: the data table really was
* created, so a retry must re-run only this last step. Re-running the setup would ask for
* the table name it has just taken, and be refused as a duplicate.
*/
let finishAlsoFailed = $state(false)
/**
* A refused pre-flight means nothing ran, so the checklist from a previous attempt has to
* give way -- it is the only thing rendered while it exists, and the refusal is shown on
* the review step.
*/
function backToReview() {
// The checklist is the only place a failure is reported, and this drops it -- so what it
// said has to come with us. It is the whole reason the user is on their way back: which
// project to rename to, which path not to write over.
lastFailure = run.result?.ok ? '' : (run.result?.error ?? '')
run = { steps: [], running: false }
enterStep(3)
}
/**
* Latched before the pre-flight's first await. `run.running` -- what otherwise disables the
* button -- is only set a round trip later, and on the Supabase create branch two clicks in
* that window bill two projects and leave the first one's password overwritten, which
* Supabase can never give back.
*/
let submitting = $state(false)
/**
* A failed run can always be sent back to be corrected. What a run already created is
* protected by `runSetup` refusing to mint a second Supabase password over the first one's
* variable, not by keeping the fields out of reach -- a lock here would only take away the
* rename that undoes the mistake.
*/
let canEditAfterFailure = $derived(
!!run.steps.length && !run.running && !submitting && !run.result?.ok
)
async function finish() {
if (submitting) return
submitting = true
// Held from here, not from where the run starts: the pre-flight awaits twice first, and
// a dismissal landing in that window would otherwise let the modal close under a setup
// that is about to create things.
preventClose = true
try {
await runFinish()
} finally {
submitting = false
preventClose = false
}
}
async function runFinish() {
const name = wiz.review.name.trim()
try {
if (claimedName !== name) {
const settings = await WorkspaceService.getSettings({ workspace: targetWorkspace })
if (settings.datatable?.datatables?.[name]) {
nameConflictFor = {
name,
message: `A data table called ${name} already exists in this workspace.`
}
backToReview()
return
}
nameConflictFor = undefined
}
// The debounced path check is advisory -- it can still be in flight when Finish is
// pressed -- and the writes that follow replace a secret and a resource in place. Ask
// once more here, where refusing costs nothing; what this run already holds is exempt
// per namespace inside, so Try again can repair its own half-finished attempt.
if (mintsResource) {
const conflict = await pathConflictMessage(resourcePath)
if (conflict) {
pathTakenError = conflict
backToReview()
return
}
}
} catch (err: any) {
// Everything inside the run reports through the checklist; this runs before there is
// one, so it has to speak for itself rather than fail silently.
nameConflictFor = {
name,
message: `Could not check the name: ${err?.body ?? err?.message ?? String(err)}`
}
backToReview()
return
}
run = { steps: planSteps(wiz), running: true }
lastFailure = ''
finishAlsoFailed = false
// The database is registered by the call whatever it answers, so asking for one is
// already leaving something behind.
if (wiz.provider === 'instance' && wiz.instance.mode === 'create') {
claimedInstanceDb = wiz.instance.dbName?.trim()
leftBehind = true
}
let result: RunResult | undefined = undefined
try {
result = await runSetup(wiz, {
workspace: targetWorkspace,
supabaseToken: supaOauth.token,
onInstanceDbsChanged: async () => {
await customInstanceDbs.refetch()
},
onExternalDbsChanged: async () => {
await externalInstanceDbs?.refetch()
},
onProgress: (steps) => (run.steps = steps),
onPoolerUnavailable: (reason) => (poolerUnavailable = reason),
createdProjects,
createdExternalDbs,
claims,
username: targetUsername
})
} finally {
// The caller's own finishing work, appended to the same checklist. It only runs
// on a clean setup: there is no table for it to act on otherwise.
if (result?.ok && onFinishAlso && finishAlso) {
const title = finishAlso.charAt(0).toUpperCase() + finishAlso.slice(1)
run.steps = [...run.steps, { title, status: 'running' }]
try {
await onFinishAlso()
run.steps = run.steps.map((s, i) =>
i === run.steps.length - 1 ? { ...s, status: 'done' as const } : s
)
} catch (err: any) {
const description = err?.body ?? err?.message ?? String(err)
run.steps = run.steps.map((s, i) =>
i === run.steps.length - 1 ? { ...s, status: 'failed' as const, description } : s
)
finishAlsoFailed = true
}
}
// `runSetup` catches per step, but anything escaping it would otherwise leave the
// button spinning with a page reload the only way out.
// Kept, not replaced: what an earlier attempt wrote is still out there, so a later
// one failing sooner must not hand its own objects back to the collision checks.
createdProjects = result?.createdProjects ?? createdProjects
createdExternalDbs = result?.createdExternalDbs ?? createdExternalDbs
claims = result?.claims ?? claims
// A row taken back out frees its name again, and free is somebody else's to take.
if (result?.rowRolledBack) claims = release(claims, 'row', name)
leftBehind =
anythingClaimed(claims) ||
createdProjects.length > 0 ||
createdExternalDbs.length > 0 ||
!!claimedInstanceDb
run = {
...run,
running: false,
result: result ?? {
ok: false,
error: 'The setup stopped unexpectedly.',
claims,
createdExternalDbs,
createdProjects
}
}
// The setup's own verdict, so a data table that exists counts as done even when the
// caller's appended `onFinishAlso` step failed after it.
if (wiz.provider) {
logDatatableWizard({ step: result?.ok ? 'done' : 'failed', provider: wiz.provider })
}
onDone()
}
}
/**
* Whether closing would throw away work. A failed run counts: its inputs are still editable
* and it may have left something behind. A run in flight cannot be closed at all, and one
* that made its data table has nothing left to lose — including when `onFinishAlso` failed
* afterwards, because the table is real and working and the caller owns what is left. The
* import step, the only caller that passes one, shows that failure on its own row with a
* way to run it again and will not let Finish through while it stands.
*/
function hasUnfinishedIntent(): boolean {
return wiz.provider !== undefined && !run.running && !run.result?.ok
}
/** Backdrop, Escape and the close button all arrive here. */
async function requestClose() {
// `dismissing` is its own flag rather than a second use of `preventClose`: a run started
// while the dialog was up would have its hold cleared here, and the modal would become
// closable in the middle of creating things.
if (preventClose || dismissing) return
if (!hasUnfinishedIntent()) {
close()
return
}
dismissing = true
// `finally`, because the flag is what blocks a second attempt: an `ask` that throws
// would otherwise leave the dialog permanently undismissable — the backdrop, Escape
// and the close button all return early here, so the only way out would be a reload.
try {
const confirmed = await confirmationModal.ask({
title: 'Leave without adding a data table?',
// A run that failed and was sent back to be edited leaves whatever it got through
// behind it, so promising otherwise would be a lie exactly when it matters most.
children: leftBehind
? 'The setup that already ran left what it created behind, and what you have filled in here will be lost.'
: 'Nothing has been created yet, and what you have filled in here will be lost.',
confirmationText: 'Discard'
})
// Re-read rather than trust the entry check: a run can start while the dialog is up, and
// answering Discard would otherwise tear the modal down in the middle of it.
if (confirmed && !preventClose) close()
} finally {
dismissing = false
}
}
/** Re-runs only the appended step, which is the only thing that failed. */
async function retryFinishAlso() {
if (!onFinishAlso || !finishAlso) return
const title = finishAlso.charAt(0).toUpperCase() + finishAlso.slice(1)
finishAlsoFailed = false
run = {
...run,
running: true,
steps: [...run.steps.slice(0, -1), { title, status: 'running' as const }]
}
try {
await onFinishAlso()
run.steps = run.steps.map((s, i) =>
i === run.steps.length - 1 ? { ...s, status: 'done' as const } : s
)
} catch (err: any) {
const description = err?.body ?? err?.message ?? String(err)
run.steps = run.steps.map((s, i) =>
i === run.steps.length - 1 ? { ...s, status: 'failed' as const, description } : s
)
finishAlsoFailed = true
} finally {
run = { ...run, running: false }
onDone()
}
}
function close() {
opened = false
}
// The single primary action. Its label says what it is about to do, and doing it is what
// moves the wizard on.
let primary = $derived.by(() => {
// Ahead of everything: without the destination's membership the resource path would be
// guessed, and a guess here writes database credentials into somebody else's namespace.
if (aimedElsewhere && membershipFailed)
return { label: 'Cannot read your access to this workspace', disabled: true }
if (submitting && !run.running)
return { label: 'Setting things up', disabled: true, busy: true }
if (run.steps.length) {
if (run.running) return { label: 'Setting things up', disabled: true, busy: true }
// Before the `ok` check: the setup succeeded and the step after it did not, so
// "Done" would be offered over a failed row.
if (finishAlsoFailed) return { label: 'Try again', disabled: false, act: retryFinishAlso }
if (run.result?.ok) return { label: 'Done', disabled: false, act: close }
// A run that died because the Supabase token expired would retry into the same 401
// forever; authorizing again is the only thing that can move it on.
if (wiz.provider === 'supabase' && !supaOauth.authed)
return {
label: 'Connect to Supabase',
disabled: false,
busy: supaOauth.pending,
act: () => supaOauth.connect()
}
return { label: 'Try again', disabled: false, act: finish }
}
if (wiz.step === 1) {
if (wiz.provider === 'supabase' && !supaOauth.authed)
return {
label: 'Connect to Supabase',
disabled: false,
busy: supaOauth.pending,
act: () => {
supaOauth.connect()
enterStep(2)
}
}
return {
label: 'Continue',
disabled: !wiz.provider,
act: () => enterStep(2)
}
}
if (wiz.step === 2) {
// Reachable by closing the Supabase window without consenting -- which this flow
// invites, since creating an account happens over there. Without a way back in, the
// step offers only a Test connection that can never enable.
if (wiz.provider === 'supabase' && !supaOauth.authed)
return {
label: 'Connect to Supabase',
disabled: false,
busy: supaOauth.pending,
act: () => supaOauth.connect()
}
if (wiz.probe.checking) return { label: 'Checking', disabled: true, busy: true }
if (probeable && !probePassed)
return {
label: wiz.probe.error || wiz.probe.report ? 'Try again' : 'Test connection',
disabled: !intentComplete(wiz),
act: probe
}
return {
label: 'Continue',
disabled:
managedKindUnavailable ||
!intentComplete(wiz) ||
!!instanceNameError ||
!!externalNameError,
act: enterReview
}
}
const created =
wiz.provider === 'supabase' && wiz.supabase.mode === 'create'
? 'Create project and data table'
: 'Create data table'
return {
label: finishAlso ? `${created} and ${finishAlso}` : created,
disabled:
// Guards the way back as well as the way forward: the stepper can return to step 2,
// and not every control there invalidates the review it just made stale.
managedKindUnavailable ||
!intentComplete(wiz) ||
!wiz.review.name.trim() ||
!!nameError ||
!wiz.review.resourceName.trim() ||
!!resourcePathError ||
!!pathTakenError ||
!!instanceNameError ||
!!externalNameError,
act: finish
}
})
/** The review step only mints a resource when the wizard is the one creating it. */
let mintsResource = $derived(
wiz.provider === 'supabase' || (wiz.provider === 'resource' && wiz.own.creating)
)
</script>
<Modal2
bind:isOpen={
() => opened,
(v) => {
if (!v) requestClose()
else opened = v
}
}
target={modalTarget}
formStyling
title="Add a data table"
contentClasses="flex flex-col"
fixedWidth="md"
fixedHeight="lg"
>
<div class="flex h-full flex-col gap-4">
<Stepper
tabs={STEPS}
selectedIndex={wiz.step - 1}
maxReachedIndex={run.steps.length ? -1 : maxStep - 1}
small
on:click={(e) => goToStep(e.detail.index)}
/>
<div class="flex-1 flex flex-col min-h-0">
<div class="flex-1 overflow-y-auto flex flex-col gap-3">
{#if run.steps.length}
<SetupChecklist steps={run.steps} />
{#if run.running}
<p class="text-xs text-secondary">
Setting up. This can take a few minutes &mdash; leave this open until it finishes.
</p>
{/if}
{#if run.result}
{@render poolerWarning()}
<DataTableConnectionReport
name={wiz.review.name}
report={run.result.report}
error={run.result.error}
bgClass="border-0"
/>
{/if}
{:else if wiz.step === 1}
<Alert type="info" size="xs" bgClass="border-0" title="">
A data table runs on a database of your own. It stays yours &mdash; you can take it with
you at any time.
</Alert>
<div class="flex flex-col gap-2">
{#if managedOffered}
{#snippet managedIcon()}
<Server size={18} class="text-secondary" />
{/snippet}
{@render providerCard(
managedProvider ? wiz.provider! : preferredManagedProvider(),
managedIcon,
'Windmill managed database (Recommended)',
'Windmill manages the databases and roles for you.'
)}
{/if}
{#if supabaseAvailable}
{#snippet supabaseIcon()}
<SupabaseIcon height="18px" width="18px" />
{/snippet}
{@render providerCard(
'supabase',
supabaseIcon,
'Supabase',
'Create a project, or connect one you already have. Signing in is required, and connecting an existing project needs its database password.'
)}
{/if}
{#snippet ownIcon()}
<Database size={18} class="text-secondary" />
{/snippet}
{@render providerCard(
'resource',
ownIcon,
'Use a resource',
'Select or create a Postgres resource.'
)}
</div>
{:else if wiz.step === 2}
{#if wiz.provider === 'supabase'}
{#if !supaOauth.authed}
<Alert type="info" size="xs" bgClass="border-0" title="">
{#if supaOauth.pending}
Sign in and approve Windmill in the Supabase window, then come back here.
{:else}
Windmill needs your approval on Supabase to see your databases.
{/if}
</Alert>
{:else}
<SupabaseProjectStep
bind:intent={wiz.supabase}
token={supaOauth.token!}
onIntentChange={() => invalidate()}
/>
{/if}
{:else if managedProvider}
{@render managedKindToggle()}
{#if managedKindUnavailable}
<p class="text-xs text-secondary">
{#if $superadmin}
Windmill has no Postgres it can manage databases on yet. Set up an external
cluster, or turn Windmill's own database back on, in the instance settings.
{:else}
Only a superadmin can create a database Windmill manages.
{/if}
</p>
{:else if wiz.provider === 'instance'}
{@render instanceStep()}
{:else}
{@render externalStep()}
{/if}
{:else}
{@render ownStep()}
{/if}
<DataTableConnectionReport
name={wiz.review.name}
report={wiz.probe.report}
error={wiz.probe.error}
bgClass="border-0"
/>
{:else}
<div class="flex flex-col gap-8">
{@render reviewStep()}
</div>
{/if}
</div>
<div class="flex flex-col gap-1 pt-3">
<div class="flex justify-between items-center gap-2">
<div>
{#if wiz.step > 1 && !run.steps.length && !(wiz.step === 2 && onlyResource)}
<Button
size="xs"
variant="default"
onClick={() => (wiz.step = wiz.step === 3 ? 2 : 1)}
>
Back
</Button>
{:else if canEditAfterFailure}
<!-- Try again repeats the same inputs, so it cannot help a run that failed on
one of them -- a database name already taken on the instance, a project name
Supabase refuses. Dropping the checklist puts the earlier steps back within
reach, which is the only way to edit those. -->
<Button size="xs" variant="default" onClick={backToReview}>Back</Button>
{/if}
</div>
<div class="flex items-center gap-2">
{#if wiz.step === 2 && !run.steps.length && wiz.provider === 'resource' && canSetUpExternal}
<Button
unifiedSize="md"
variant="default"
startIcon={{ icon: Lightbulb }}
onClick={explainExternalInstance}
>
Let Windmill manage your external database
</Button>
{/if}
<Button
unifiedSize="md"
variant="accent"
disabled={primary.disabled}
loading={primary.busy}
endIcon={primary.busy ? undefined : { icon: ArrowRight }}
onClick={() => primary.act?.()}
>
{primary.label}
</Button>
</div>
</div>
{#if wiz.provider === 'supabase' && !supaOauth.authed}
<p class="text-2xs text-secondary text-right">
If you do not have a Supabase account you can <a
href={SUPABASE_SIGNUP_URL}
target="_blank"
rel="noreferrer"
class="text-accent hover:underline">create one for free</a
>.
</p>
{/if}
</div>
</div>
</div>
</Modal2>
{#snippet externalHint(label: string)}
<div class="flex">
<Button
unifiedSize="sm"
variant="subtle"
startIcon={{ icon: Lightbulb }}
onClick={explainExternalInstance}
>
{label}
</Button>
</div>
{/snippet}
{#snippet managedKindToggle()}
{@const internalReason = instanceAvailable
? "A database on Windmill's own Postgres."
: !$superadmin
? "Only a superadmin can create a database on Windmill's own Postgres."
: isCloudHosted()
? "Windmill's own Postgres is not available on cloud."
: "Windmill's own Postgres is turned off for data tables in the instance settings."}
{@const externalReason = externalInstanceAvailable
? 'A database on the external Postgres cluster Windmill administers.'
: !$enterpriseLicense
? 'An external cluster is an Enterprise Edition feature.'
: !$superadmin
? 'Only a superadmin can create a database on the external cluster.'
: 'No external cluster is set up on this instance.'}
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">Postgres cluster</span>
<div class="flex items-center gap-2">
<!-- A choice only while both are on offer. With one, the toggle still shows which one the
data table lands on. Its items cannot carry the reasons: a disabled group takes no hover. -->
<MeltTooltip disablePopup={instanceAvailable && externalInstanceAvailable}>
<ToggleButtonGroup
disabled={!(instanceAvailable && externalInstanceAvailable)}
noWFull
bind:selected={
() => (managedKindUnavailable ? undefined : wiz.provider),
(v) => {
if (v === 'instance' || v === 'external_instance') selectProvider(v)
}
}
>
{#snippet children({ item })}
<ToggleButton value="instance" label="Internal" {item} small />
<ToggleButton value="external_instance" label="External" {item} small />
{/snippet}
</ToggleButtonGroup>
{#snippet text()}
<div class="flex flex-col gap-1">
<span><span class="font-semibold">Internal:</span> {internalReason}</span>
<span><span class="font-semibold">External:</span> {externalReason}</span>
</div>
{/snippet}
</MeltTooltip>
{#if !externalInstanceAvailable && canSetUpExternal}
{@render externalHint('Set up externally managed Postgres')}
{/if}
</div>
</div>
{/snippet}
{#snippet providerCard(key: Provider, icon: Snippet, title: string, subtitle: string)}
{@const selected =
wiz.provider === key ||
(managedProvider && (key === 'instance' || key === 'external_instance'))}
<button
class="text-left border rounded-md p-3 flex gap-3 items-start transition-colors {selected
? 'border-border-selected/50 bg-surface-accent-selected'
: 'border-border-light hover:bg-surface-hover'}"
onclick={() => selectProvider(key)}
>
<span class="mt-0.5 shrink-0">{@render icon()}</span>
<span class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs font-medium {selected ? 'text-accent' : 'text-emphasis'}">{title}</span>
<span class="text-xs text-secondary font-normal">{subtitle}</span>
</span>
</button>
{/snippet}
{#snippet instanceStep()}
{@const instanceDbs = Object.entries(customInstanceDbs.current ?? {})
.filter(([_, db]) => db.tag === 'datatable')
.map(([name, db]) => ({ name, db }))}
{#if instanceDbs.length}
<ToggleButtonGroup
bind:selected={
() => wiz.instance.mode,
(v) => {
wiz.instance.mode = v
wiz.instance.dbName = v === 'create' ? defaultInstanceDbName() : undefined
}
}
>
{#snippet children({ item })}
<ToggleButton value="existing" label="Use an existing one" {item} small />
<ToggleButton value="create" label="Create a new one" {item} small />
{/snippet}
</ToggleButtonGroup>
{/if}
{#if wiz.instance.mode === 'existing'}
{@const shared = (
customInstanceDbs.current?.[wiz.instance.dbName ?? '']?.used_by_workspaces ?? []
).filter((w) => w !== targetWorkspace)}
<!-- Above the list, not under it: the list scrolls, and a warning about sharing another
workspace's data is worthless if the user has to scroll to reach it. -->
{#if shared.length}
<Alert type="warning" size="xs" bgClass="border-0" title="">
This database is also used by workspace{shared.length > 1 ? 's' : ''}
<span class="font-semibold">{shared.join(', ')}</span>. Any data written here will be shared
with {shared.length > 1 ? 'them' : 'it'}.
</Alert>
{/if}
<div class="flex flex-col gap-2 overflow-y-auto flex-1 min-h-24 pr-1">
{#each instanceDbs as { name, db } (name)}
{@const selected = wiz.instance.dbName === name}
{@const others = (db.used_by_workspaces ?? []).filter((w) => w !== targetWorkspace)}
<button
class="text-left border rounded-md p-3 flex gap-3 items-start transition-colors {selected
? 'border-border-selected/50 bg-surface-accent-selected'
: 'border-border-light hover:bg-surface-hover'}"
onclick={() => (wiz.instance.dbName = name)}
>
<span class="mt-0.5 shrink-0"><Database size={18} class="text-secondary" /></span>
<span class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs font-medium {selected ? 'text-accent' : 'text-emphasis'}"
>{name}</span
>
<span class="text-xs text-secondary font-normal">
{db.success ? 'Ready' : 'Needs setup'}{others.length
? ` · shared with ${others.length} other workspace${others.length > 1 ? 's' : ''}`
: ''}
</span>
</span>
</button>
{/each}
</div>
{:else}
<div>
<span class="text-xs font-semibold text-emphasis">Database name</span>
<TextInput
bind:value={() => wiz.instance.dbName ?? '', (v) => (wiz.instance.dbName = v)}
error={!!instanceNameError}
inputProps={{ placeholder: defaultInstanceDbName() }}
/>
<InputError error={instanceNameError} />
{#if !instanceNameError}
<p class="text-2xs text-secondary mt-1">
Created in the Windmill PostgreSQL instance when you finish. Windmill manages its
credentials.
</p>
{/if}
</div>
{/if}
{/snippet}
{#snippet externalStep()}
{@const externalDbs = Object.entries(externalInstanceDbs?.current ?? {})
.filter(([_, db]) => db.tag === 'datatable')
.map(([name, db]) => ({ name, db }))}
{#if externalDbs.length}
<ToggleButtonGroup
bind:selected={
() => wiz.external.mode,
(v) => {
wiz.external.mode = v
wiz.external.dbName = v === 'create' ? externalDbName() : undefined
}
}
>
{#snippet children({ item })}
<ToggleButton value="existing" label="Use an existing one" {item} small />
<ToggleButton value="create" label="Create a new one" {item} small />
{/snippet}
</ToggleButtonGroup>
{/if}
{#if wiz.external.mode === 'existing'}
{@const shared = (
externalInstanceDbs?.current?.[wiz.external.dbName ?? '']?.used_by_workspaces ?? []
).filter((w) => w !== targetWorkspace)}
{#if shared.length}
<Alert type="warning" size="xs" bgClass="border-0" title="">
This database is also used by workspace{shared.length > 1 ? 's' : ''}
<span class="font-semibold">{shared.join(', ')}</span>. Any data written here will be shared
with {shared.length > 1 ? 'them' : 'it'}.
</Alert>
{/if}
<div class="flex flex-col gap-2 overflow-y-auto flex-1 min-h-24 pr-1">
{#each externalDbs as { name, db } (name)}
{@const selected = wiz.external.dbName === name}
{@const others = (db.used_by_workspaces ?? []).filter((w) => w !== targetWorkspace)}
<button
class="text-left border rounded-md p-3 flex gap-3 items-start transition-colors {selected
? 'border-border-selected/50 bg-surface-accent-selected'
: 'border-border-light hover:bg-surface-hover'}"
onclick={() => (wiz.external.dbName = name)}
>
<span class="mt-0.5 shrink-0"><Database size={18} class="text-secondary" /></span>
<span class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs font-medium {selected ? 'text-accent' : 'text-emphasis'}"
>{name}</span
>
<span class="text-xs text-secondary font-normal">
On the external cluster{others.length
? ` · shared with ${others.length} other workspace${others.length > 1 ? 's' : ''}`
: ''}
</span>
</span>
</button>
{/each}
</div>
{:else}
<div>
<span class="text-xs font-semibold text-emphasis">Database name</span>
<TextInput
bind:value={() => wiz.external.dbName ?? '', (v) => (wiz.external.dbName = v)}
error={!!externalNameError}
inputProps={{ placeholder: externalDbName() }}
/>
<InputError error={externalNameError} />
{#if !externalNameError}
<p class="text-2xs text-secondary mt-1">
Created on the external PostgreSQL cluster when you finish. Windmill manages its
credentials.
</p>
{/if}
</div>
{/if}
{/snippet}
{#snippet ownStep()}
{@const resources = pgResources.loading ? undefined : pgResources.current}
{#if resources === undefined}
<p class="text-xs text-secondary">Loading resources...</p>
{:else}
{#if resources.length}
<span class="text-xs font-semibold text-emphasis">Postgres resources in this workspace</span>
{:else}
<p class="text-xs text-secondary">A resource is a saved connection your scripts can use.</p>
{/if}
<div class="flex flex-col gap-2 overflow-y-auto flex-1 min-h-24 pr-1">
{#each resources as r (r.path)}
{@const selected = !wiz.own.creating && wiz.own.resourcePath === r.path}
<button
class="shrink-0 text-left border rounded-md p-3 flex gap-3 items-start transition-colors {selected
? 'border-border-selected/50 bg-surface-accent-selected'
: 'border-border-light hover:bg-surface-hover'}"
onclick={() => selectResource(r.path)}
>
<span class="mt-0.5 shrink-0"><Database size={18} class="text-secondary" /></span>
<span class="flex flex-col gap-0.5 min-w-0">
<span
class="text-xs font-medium font-mono truncate {selected
? 'text-accent'
: 'text-emphasis'}">{r.path}</span
>
{#if r.description}
<span class="text-xs text-secondary font-normal truncate">{r.description}</span>
{/if}
</span>
</button>
{/each}
<!-- shrink-0 or the flex column squeezes the cards to fit instead of letting the list
scroll, and the selected one loses its expanded form to the clip. -->
<div
class="shrink-0 border rounded-md overflow-hidden transition-colors {wiz.own.creating
? 'border-border-selected/50 bg-surface-accent-selected'
: 'border-border-light'}"
>
<button
class="w-full text-left p-3 flex gap-3 items-start {wiz.own.creating
? ''
: 'hover:bg-surface-hover'}"
onclick={selectNewResource}
>
<span class="mt-0.5 shrink-0"><Plus size={18} class="text-secondary" /></span>
<span class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs font-medium {wiz.own.creating ? 'text-accent' : 'text-emphasis'}"
>New resource</span
>
<span class="text-xs text-secondary font-normal"
>Windmill saves it as a Postgres resource</span
>
</span>
</button>
{#if wiz.own.creating}
<div class="px-3 pb-3">{@render newResourceForm()}</div>
{/if}
</div>
</div>
{/if}
{/snippet}
{#snippet newResourceForm()}
<div class="flex flex-col gap-2">
<div class="flex items-baseline justify-between gap-2">
<span class="text-xs font-semibold text-emphasis">
{wiz.own.form === 'string' ? 'Connection string' : 'Connection'}
</span>
<Button
variant="subtle"
size="xs2"
onclick={() => (wiz.own.form === 'string' ? useFields() : useConnectionString())}
>
{wiz.own.form === 'string'
? 'Enter fields individually'
: 'Paste a connection string instead'}
</Button>
</div>
{#if wiz.own.form === 'string'}
<TextInput
bind:value={
() => wiz.own.connectionString,
(v) => {
wiz.own.connectionString = v
absorbConnectionString(v)
invalidate()
}
}
error={!!connectionStringError}
inputProps={{ placeholder: 'postgres://user:password@host:5432/database' }}
/>
<InputError error={connectionStringError} />
{:else}
<div class="grid grid-cols-[2fr_1fr] gap-2">
<div>
<span class="text-2xs text-secondary">Host</span>
<TextInput
bind:value={() => wiz.own.fields.host, (v) => setField('host', v)}
inputProps={{ placeholder: 'db.example.com' }}
/>
</div>
<div>
<span class="text-2xs text-secondary">Port</span>
<TextInput
bind:value={
() => wiz.own.fields.port ?? '',
(v) => setField('port', v === '' ? undefined : Number(v))
}
inputProps={{ placeholder: '5432', type: 'number' }}
/>
</div>
<div>
<span class="text-2xs text-secondary">Database</span>
<TextInput
bind:value={() => wiz.own.fields.dbname ?? '', (v) => setField('dbname', v)}
inputProps={{ placeholder: 'postgres' }}
/>
</div>
<div>
<span class="text-2xs text-secondary">SSL mode</span>
<Select
items={SSL_MODES.map((value) => ({ value }))}
bind:value={() => wiz.own.fields.sslmode ?? '', (v) => setField('sslmode', v)}
clearable={false}
/>
</div>
<div>
<span class="text-2xs text-secondary">User</span>
<TextInput
bind:value={() => wiz.own.fields.user, (v) => setField('user', v)}
inputProps={{ placeholder: 'postgres' }}
/>
</div>
<div>
<span class="text-2xs text-secondary">Password</span>
<Password
bind:password={
() => wiz.own.fields.password ?? '', (v) => setField('password', v ?? '')
}
placeholder="••••••••"
/>
</div>
</div>
{@render advancedGroup()}
{/if}
{#if wiz.own.form === 'string' && !connectionStringError && hasAdvanced(wiz.own.advanced)}
<p class="text-2xs text-secondary">
Certificate and IAM settings from the fields view still apply &mdash; a connection string
cannot show them.
</p>
{/if}
</div>
{/snippet}
{#snippet advancedGroup()}
<div class="border-t border-border-light pt-2">
<Section label="Advanced" small collapsable>
<div class="flex flex-col gap-2">
<div>
<span class="text-2xs text-secondary">Root certificate</span>
<TextInput
underlyingInputEl="textarea"
bind:value={
() => wiz.own.advanced.root_certificate_pem,
(v) => setAdvanced('root_certificate_pem', String(v ?? ''))
}
class="min-h-16 font-mono text-2xs resize-y"
inputProps={{ placeholder: '-----BEGIN CERTIFICATE-----', rows: 3 }}
/>
<p class="text-2xs text-secondary mt-1">
The CA to check the server against. Needed for <span class="font-mono">verify-ca</span>
and <span class="font-mono">verify-full</span> when the certificate is not signed by a public
authority.
</p>
</div>
<div>
<span class="text-2xs text-secondary">Certificate verification</span>
<Select
items={CERT_VERIFICATION}
bind:value={
() => certVerification,
(v) =>
setAdvanced('accept_invalid_certs', v === 'default' ? undefined : v === 'accept')
}
clearable={false}
/>
</div>
<div>
<span class="text-2xs text-secondary">Options</span>
<TextInput
bind:value={() => wiz.own.fields.options ?? '', (v) => setField('options', v)}
inputProps={{ placeholder: 'endpoint=ep-example-123456' }}
/>
<p class="text-2xs text-secondary mt-1">
Startup options sent to the server, such as the endpoint ID a Neon pooled or private
connection needs.
</p>
</div>
<Toggle
size="xs"
checked={wiz.own.advanced.use_iam_auth}
on:change={(e) => setAdvanced('use_iam_auth', e.detail)}
options={{ right: 'Authenticate with AWS IAM' }}
/>
{#if wiz.own.advanced.use_iam_auth}
<div>
<span class="text-2xs text-secondary">Region</span>
<TextInput
bind:value={() => wiz.own.advanced.region, (v) => setAdvanced('region', v)}
inputProps={{ placeholder: 'us-east-1' }}
/>
</div>
{/if}
</div>
</Section>
</div>
{/snippet}
{#snippet poolerWarning()}
{#if poolerUnavailable}
<Alert type="warning" size="xs" title="Session pooling is not available">
<div class="flex flex-col gap-1">
<span>{poolerUnavailable}</span>
<span>
Windmill connects directly instead, which needs IPv6 from the workers, or the IPv4 add-on
on the project. Granting the Supabase OAuth app
<span class="font-mono">database_pooling_config_read</span> and connecting again restores the
pooler.
</span>
</div>
</Alert>
{/if}
{/snippet}
{#snippet reviewStep()}
{#if lastFailure}
<Alert type="error" size="xs" bgClass="border-0" title="">{lastFailure}</Alert>
{/if}
<Label label="Data table name" class="gap-1">
<p class="text-2xs text-secondary">
This is how your scripts reach the database behind it:
<span class="font-mono">datatable://{wiz.review.name.trim() || 'main'}</span>
reads and writes it, whatever it is connected to.
<span class="font-mono">main</span> is used by default when a script does not name one.
</p>
<TextInput
bind:value={wiz.review.name}
error={!!nameError || !!nameConflict}
inputProps={{ placeholder: 'main', disabled: nameLocked }}
/>
{#if nameLocked}
<p class="text-2xs text-secondary">
Fixed: the project's migrations target this name, and they run against it whatever this
table ends up called.
</p>
{/if}
<InputError error={nameError ?? (nameConflict || undefined)} />
</Label>
<Label label="Using it from a script" class="gap-1">
<DataTableUsagePreview name={wiz.review.name.trim() || 'main'} />
</Label>
{#if wiz.provider === 'supabase'}
<!-- A card carrying Supabase's own mark rather than a disabled field: this is the one
thing on the step that will not live in Windmill, and it should not read as a greyed-out
Windmill input. -->
<Label
label={wiz.supabase.mode === 'create' ? 'New Supabase project' : 'Supabase project'}
class="gap-1"
>
<p class="text-2xs text-secondary">
{#if wiz.supabase.mode === 'create'}
It does not exist yet — Windmill creates it on Supabase when you finish. The project is
yours, and you can open and manage it from the Supabase dashboard.
{:else}
A project already in your Supabase account. Windmill saves its connection and changes
nothing about the project itself.
{/if}
</p>
<div class="border border-border-light rounded-md p-3 flex gap-3 items-start">
<span class="mt-0.5 shrink-0"><SupabaseIcon height="18px" width="18px" /></span>
<span class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs font-medium text-emphasis">
{wiz.supabase.mode === 'create'
? wiz.supabase.projectName
: (wiz.supabase.project?.name ?? '')}
</span>
<span class="text-xs text-secondary">
{[
supabaseSummary(wiz).org,
supabaseSummary(wiz).region,
wiz.supabase.connectionMode === 'session' ? 'session pooler' : 'direct (IPv6)'
]
.filter(Boolean)
.join(' · ')}
</span>
</span>
</div>
</Label>
{@render poolerWarning()}
{:else if wiz.provider === 'instance'}
<Label label="Windmill database" class="gap-1">
<p class="text-2xs text-secondary">
{#if wiz.instance.mode === 'create'}
It does not exist yet — Windmill creates it on this instance's PostgreSQL server when you
finish, and manages its credentials.
{:else}
A database already on this instance's PostgreSQL server, managed by Windmill.
{/if}
</p>
<TextInput value={wiz.instance.dbName ?? ''} inputProps={{ disabled: true }} />
</Label>
{:else if wiz.provider === 'external_instance'}
<Label label="External cluster database" class="gap-1">
<p class="text-2xs text-secondary">
{#if wiz.external.mode === 'create'}
It does not exist yet — Windmill creates it on the external PostgreSQL cluster when you
finish, and manages its credentials.
{:else}
A database already on the external PostgreSQL cluster, managed by Windmill.
{/if}
</p>
<TextInput value={wiz.external.dbName ?? ''} inputProps={{ disabled: true }} />
</Label>
{:else if !wiz.own.creating}
<Label label="Postgres resource" class="gap-1">
<p class="text-2xs text-secondary">
The connection already in this workspace. The data table points at it; nothing is written to
it here.
</p>
<TextInput value={wiz.own.resourcePath ?? ''} inputProps={{ disabled: true }} />
</Label>
{/if}
{#if mintsResource}
<Label label="Resource path" class="gap-1">
<p class="text-2xs text-secondary">
The connection {wiz.provider === 'supabase' ? 'to the Supabase project ' : ''}is saved here
as a Postgres resource, with its password in a secret variable beside it.
</p>
<Path
bind:path={
() => resourcePath,
(p) => {
const cut = p.lastIndexOf('/')
wiz.review.folder = cut > 0 ? p.slice(0, cut) : p
wiz.review.resourceName = cut > 0 ? p.slice(cut + 1) : ''
}
}
bind:error={resourcePathError}
initialPath={initialResourcePath}
checkInitialPathExistence
allowedExistingPath={claimedResourcePath}
namePlaceholder="database"
kind="resource"
autofocus={false}
/>
<InputError error={pathTakenError} />
</Label>
{/if}
{#if sharesDatabaseWith}
<Alert type="warning" size="xs" bgClass="border-0" title="">
<span class="font-semibold">{sharesDatabaseWith.name}</span> already uses this database. Both data
tables would write to the same schema, so each one's tables are visible to the other and two tables
of the same name collide. Migrations are tracked per data table, so those stay separate.
</Alert>
{/if}
{#if wiz.provider === 'supabase'}
<Alert type="info" size="xs" bgClass="border-0" title="">
Your Supabase sign-in is not stored. If the database password ever changes, anyone with access
to the project can sign in and reconnect it. Deleting the data table never deletes the
Supabase project.
</Alert>
{/if}
{/snippet}