Databases
Databases can have a display name. Open a database in the dashboard and choose Rename to set or change it. Names are account metadata; the database UUID, provider identity, data, and site connection stay stable. Existing unnamed databases appear as Untitled database with their UUID underneath. Names do not have to be unique.
To rename through the API, send POST /v0/databases/:databaseId with
{ "name": "Customer records" }. Names are trimmed, non-empty, and at most
120 characters. Account admins and members can rename databases they own.
SQL databases are private account-owned resources with stable IDs. Create an unattached database through the CLI or REST API for structured data, queries, migration receipts, and exports without creating a site. Ownership cannot be changed.
Each site can still have one database through the existing site convenience API.
Functions and Cron Jobs access that site database through ctx.db; existing
MCP and browser-agent tools continue to use site targets. The CLI also supports
stable database IDs; see CLI databases. Unattached
databases have no runtime access and creating one does not update workers.
If your state naturally belongs in a text, JSON, or JSONL file and writes are infrequent, use Data files instead.
Dashboard
Open Databases in the dashboard and
select the owning account. Each resource keeps a stable /databases/:databaseId
page showing storage, attachment metadata, recovery actions and migration leases.
The site’s Database tab links to that same resource, and the resource links back
to its attached site. Display names identify resources, with stable UUIDs available
in database details. Rename edits the name in place.
Choose New database to open the creation dialog, optionally enter a name, and create unattached storage. The browser saves an account-scoped creation key before sending the request. Retry original creation uses that same key across reloads and network failures. A stale retry whose saved key changed in another tab is rejected before dispatch. A successful replay returns the original resource in its current attachment state. Deleted or changed-target requests require an explicit new operation; retries never reattach or silently replace the original resource. Keep browser storage when recovering a pending creation. Without the original key, standalone recovery remains deferred.
Account members can query SQL, inspect exact migration receipts and apply a reviewed numbered SQL file. Only admins can inspect or create exports. Use Check export to reconcile an existing processing export; the page also polls retained processing records automatically. Reconciliation does not start a new export. Signed download links expire. Export errors should be inspected before explicitly starting another export.
SQL can mutate data. The dashboard does not automatically repeat SQL, migration, export creation or deletion submissions. When a response is lost or an outcome is unknown, a saved browser record blocks another submission until you inspect the outcome and explicitly acknowledge it. Refresh metadata, inspect receipts and exports, or use a separate read-only query through the CLI/API to verify. An executed result with omitted rows does not mean the mutation should be repeated. Leaving a view or switching accounts aborts its waiting mutation transport and retains the uncertain operation record. Aborting does not undo server execution; inspect the originating resource before acknowledging that record. Web Locks serialize submissions, creation-key replacement and outcome acknowledgement across panels and tabs on the same browser origin. Browsers without Web Locks cannot submit these operations. The durable record is local to that browser; it cannot coordinate other clients.
Attachment changes are enabled in production after the runtime cutover and
legacy worker audit. The dashboard reads the actual server capability; if a
deployment disables changes, it reports DATABASE_ATTACHMENTS_DISABLED.
Explicit attach/detach uses a same-account active site and the server
enforces one database per site and one site per database. Unattached ownership
grants no ctx.db access. Detach preserves identities, data, exports and receipts.
Attached databases cannot be deleted from either dashboard surface, and site deletion requires detach. For unattached deletion, request an expiring challenge, then type its exact confirmation code. Deletion permanently removes the data. A lost deletion response requires inspecting the stable resource before another explicit attempt; it is never automatically replayed.
Independent REST lifecycle
Use an authenticated account member or an API key for the same account:
POST /v0/databases
Idempotency-Key: <unique-operation-key>
Content-Type: application/json
{"accountId": "<account-id>"}
The Idempotency-Key header is required: use 1–255 printable ASCII characters
without spaces, such as a UUID. Keys are scoped to the account. Repeat the same
POST with the same key and body to return the ready database or resume incomplete
creation. A different key creates a different resource. Only accountId is
accepted in the creation body; additional fields are rejected.
The response includes database.id, immutable appAccountId, siteId: null,
status, and timestamps. Provider IDs, provider names, and internal errors are
not exposed. If creation fails, error.details.databaseId identifies the
persisted resource. Repeat creation with the original key to recover it.
Mappings are retained after deletion: reusing a deleted resource’s key returns
DATABASE_CREATION_DELETED. Use a new key to intentionally create another
resource. Keys have no automatic expiration in this slice. Concurrent requests
may return DATABASE_OPERATION_BUSY; repeat the request with the same key.
If provider lookup cannot yet resolve a possibly dispatched create,
DATABASE_CREATE_OUTCOME_UNKNOWN retains the resource and blocks another create
or final deletion. Repeat creation with the same key; after deletion has begun, request
a fresh challenge and retry deletion. An empty lookup is not proof that a timed-out
create never committed.
GET /v0/databases?accountId=<account-id>&limit=25&offset=0
GET /v0/databases/:databaseId
POST /v0/databases/:databaseId/query
GET /v0/databases/:databaseId/migrations
GET /v0/databases/:databaseId/migrations/:migrationName
POST /v0/databases/:databaseId/migrations
POST /v0/databases/:databaseId/migrations/apply
GET /v0/databases/:databaseId/exports
POST /v0/databases/:databaseId/exports
POST /v0/databases/:databaseId/exports/:exportId/reconcile
POST /v0/databases/:databaseId/deletion_challenges
DELETE /v0/databases/:databaseId
Queries accept sql and optional params. Single migration apply accepts
name, sql, and confirm: true; bulk apply accepts an ordered migrations
array of {name, sql} plus confirm: true. Both reuse the receipt integrity
checks and execution leases described below. A query whose outcome is unknown
returns outcomeUnknown: true and must be verified before another write.
All mutations, including SELECT queries and export polling, require a WRITE
API key. Account members can manage databases; exports require account admin
access for browser or CLI session authentication. Manual account API keys use
their account permissions. List and retrieve require READ. The same account
checks apply even when an ID is known or a database is attached to an archived
site. Unauthenticated callers have no access.
An export creation returns an export resource. List exports and POST its
reconcile endpoint until status: COMPLETE provides an expiring download URL.
Deletion requires the confirmationCode from a fresh deletion challenge,
passed as the DELETE JSON body. It remains blocked by an active migration lease.
Both account and legacy site deletion routes reject attached resources with
DATABASE_ATTACHED. Detach first, then request a fresh challenge through the
account resource route. Site deletion cannot delete an account-owned database;
an attached database prevents physical site deletion until explicitly detached.
Attach and detach
POST /v0/databases/:databaseId/attach and
POST /v0/databases/:databaseId/detach require a WRITE API key and JSON
{ "siteId": "<site UUID>" }. The database and site must belong to the same
account. Attachment requires an active site and a ready database. Each site has
at most one database, and each database has at most one site. Repeating the same
attachment or completed detach is safe. Detach also works on archived sites.
Attach and detach update the durable site relationship in PostgreSQL. They do
not upload workers, change provider bindings, or promote deployments. Each
ctx.db call goes through an authenticated internal API that checks the active
site/runtime and resolves its current same-account database attachment.
Detach denies new database requests; requests admitted before detach may finish.
Attaching another database changes which resource subsequent calls resolve.
The response retains bindingStatus for compatibility: successful creation,
attach, and detach return READY. ATTACHING may appear during provisioning or
on migrated incomplete records; retry creation or attach to complete that
metadata transition. DETACHING is retained for legacy recovery; retry detach.
No provider reconciliation is required for either attachment operation.
An attached database left DELETING by an older failed deletion must detach
before retrying delete. Database IDs, provider identity, data, migration receipts,
and exports are preserved.
DATABASE_ATTACHED, SITE_DATABASE_EXISTS, and DATABASE_ATTACHMENT_MISMATCH
explain incompatible reservations. Cross-account sites are unavailable to the
caller. DATABASE_OPERATION_BUSY means a database lifecycle operation is active
or lifecycle capacity is busy; retry after it completes or capacity becomes
available. Runtime deployments do not participate in attachment locks.
Creation retries still require the same Idempotency-Key. Existing site-targeted routes remain convenience routes; database deletion now requires detach. These operations are REST-only; CLI and agent tools retain their existing contract.
Create a database
The account route POST /v0/databases accepts accountId and an optional name
(trimmed, 1–120 characters). The dashboard’s New database dialog offers this
name before creation. A creation retry returns the original resource and does
not change its name; use Rename to update the name afterward.
The site REST route POST /v0/sites/:siteId/databases provisions an
account-owned database and reserves its attachment to the site. Supply an
Idempotency-Key to identify the creation. The stored site determines the owner;
clients cannot choose another account. A new key requires an empty database slot.
Creation uses the same durable mapping, provider outcome protection, and recovery
as POST /v0/databases. Retry with the same key after an unknown provider outcome,
initialization failure, or an incomplete provisioning attempt.
Reusing a key for another site or the independent creation route returns
DATABASE_CREATION_REQUEST_MISMATCH.
Replaying a successful creation returns its original database in its current
attachment state. It never reattaches a detached or moved database, and it never
creates a replacement after deletion (DATABASE_CREATION_DELETED). Use a new key
to intentionally create another resource after detach.
For compatibility, omitting the header uses one permanent creation key per site. These callers can create the first database and retry it safely. After detach, a headerless retry returns the original detached database; after deletion it returns the tombstone error. Headerless callers can adopt an existing legacy site database with no creation mapping, preserving its identity, but cannot replace a resource or adopt one already created under a different key. Use an explicit key for subsequent creations, or list/retrieve an existing database.
Database commands require an explicit --site or --subdomain target:
interfold db create --site <site-id>
Creation is idempotent. Running it again safely resumes provisioning updates. It does not apply application migrations.
Query a database directly
Use a write-authorized API key to forward SQL and optional parameter values to the site database without deploying a Function:
interfold db query --site <site-id> 'SELECT id, name FROM users WHERE active = ?' --params '[true]'
The equivalent REST endpoint is:
POST /v0/sites/:siteId/databases/:databaseId/query
Content-Type: application/json
{
"sql": "UPDATE users SET active = ? WHERE id = ?",
"params": [false, 42]
}
This is a generic D1-compatible query surface: it can read or change database
data and schema. Successful queries return the D1-style success, errors,
messages, and result envelope. It requires WRITE permission even for
SELECT statements. Use placeholders for values. Known SQL mistakes return
DATABASE_QUERY_INVALID with guidance to correct the query, including failures
reported inside a provider HTTP 200 response. Raw provider error text is not
returned. Verify saved state before retrying writes after any failure; transport
failures can have an unknown outcome. Batch and raw-query variants are not part
of this first surface.
The browser-agent and MCP query tools use the same capability. Browser-agent queries always require user approval because they can change data.
Cloud migration history
Interfold’s migration ledger lives in the site database. Agents can inspect it and apply one new migration without access to a local project or every earlier SQL file:
GET /v0/sites/:siteId/databases/:databaseId/migrations
GET /v0/sites/:siteId/databases/:databaseId/migrations/:migrationName
POST /v0/sites/:siteId/databases/:databaseId/migrations
The apply body contains name, sql, and confirm: true. One D1 transaction
writes the name, SHA-256 checksum, exact SQL, and applied time together with the
schema change. A successful receipt is immutable. A confirmed failure creates
no migration resource, so corrected SQL may be retried under a name that has
never successfully applied.
_interfold_migrations is the authoritative successful migration resource. A
receipt proves that the stored SQL committed with the receipt; it does not
assert application-level correctness, represent unmanaged SQL changes, or
detect arbitrary schema drift. Legacy receipts created before SQL storage was
added remain visible with sourceAvailable: false; Interfold does not invent
their source.
When a request times out, Interfold leaves the short execution lease in place and checks for the receipt on retry. A missing receipt immediately after a timeout is not treated as proof of rollback. Receipt-first execution and the unique migration name prevent the same migration SQL from running twice when a later retry reaches D1.
CLI migration files
Run migration commands from the project. Interfold always uses the project-root
migrations/ directory and searches upward when a command runs in a nested
folder.
migrations/
0001_create_users.sql
0002_add_user_email.sql
interfold db migrations create create_users
interfold db migrations list --site <site-id>
interfold db migrations apply --site <site-id> --confirm
list reports successful cloud migration receipts. apply reads the complete
ordered migration prefix from the project migration directory, validates it
against provider history, and applies pending files. Applied files are
immutable: if a schema must change, add a new forward migration.
Interfold records names and SHA-256 checksums in _interfold_migrations.
The Function and Cron Job runtime reserves that exact table, but the generic
network query endpoint deliberately passes it through like any other D1 table.
Avoid changing the ledger directly: migration validation and recovery rely on
its contents. The CLI complete-prefix validation runs as part of apply; it is
not a separate public operation or a requirement of the cloud migration
resource.
Export a database
The Database page in the dashboard can create a full SQL export. Interfold keeps a history of export records so a long-running export remains visible after leaving and returning to the page. Only one export can be in progress for a database.
API-key clients can use the equivalent resource endpoints:
POST /v0/sites/:siteId/databases/:databaseId/exports
GET /v0/sites/:siteId/databases/:databaseId/exports
POST /v0/sites/:siteId/databases/:databaseId/exports/:exportId/reconcile
When a create or reconcile response is PROCESSING, keep calling reconcile
with the export ID until the status is COMPLETE or ERROR. The dashboard
does this automatically for processing records; the CLI does not run a poller
yet. Completed records remain in history after their temporary download URL
expires.
Runtime interface
const rows = await ctx.db.query('SELECT id, name FROM users WHERE active = ?', [
true,
])
const user = await ctx.db.first('SELECT * FROM users WHERE id = ?', [1])
const result = await ctx.db.execute('INSERT INTO users (name) VALUES (?)', [
'Ada',
])
execute() returns an Interfold-owned result:
{
changes: number
lastInsertRowId: number | null
}
batch() returns one result per statement with rows, changes, and
lastInsertRowId. Provider metadata is never part of the ctx.db runtime
contract; successful direct Query API responses preserve the D1 response
envelope and metadata. Query failures use Interfold’s safe error response.
Database access uses a credential scoped to the site and runtime; tenant workers receive no direct D1 binding. Calls preserve the existing method signatures and result shapes. Archived sites, deleted/inactive functions, paused crons, and sites with no ready attached database cannot use this internal API. Database requests add an API round trip and share the provider REST API limits. Existing workers must be redeployed once to adopt this client before attachment changes are enabled.
Use SQL placeholders for values. A batch is atomic; separate ctx.db calls are
not one transaction. Runtime failures expose a stable DATABASE_* code without
provider diagnostics.
Permanently delete a database
Detach the database using the REST endpoint first. Then request
POST /v0/databases/:databaseId/deletion_challenges and supply the returned
confirmationCode as the JSON body of DELETE /v0/databases/:databaseId.
The code expires after ten minutes; migration leases block deletion. Export first if needed; deletion cannot be undone. Existing CLI
site deletion commands now return DATABASE_ATTACHED while attached.