Management
The control plane. Create, inspect, update, and delete provider resources with one verb set, then bridge to the query client.
The management layer is dbSDK’s control plane. You bring a provider
credential (a Supabase personal access token, a Neon API key, or a
PlanetScale service token) and get one
stable verb set over the provider’s resources: create, list, get,
update, delete, and wait, plus discovery (organizations,
regions), connection retrieval (connection), lifecycle actions, and
resetCredential. It is the provisioning and lifecycle half of dbSDK; the
query client is the other half.
What it is not, stated plainly: there is no central dbSDK backend, no credential proxying, no automatic retry or replay of create or delete, and no silent fallback between providers. Every request goes from your process to the provider’s official API with your credential.
import { createManagement } from "dbsdk/management";
import { neonManagement } from "dbsdk/management/neon";
const management = createManagement({
adapter: neonManagement({ apiKey: process.env.NEON_API_KEY! }),
});
The verb set
| Verb | What it does |
|---|---|
create(spec) |
Creates a resource and returns a write result. |
list(kind, query?) |
Lists resources of a kind. |
get(ref) |
Fetches one resource. |
update(spec) |
Patches a resource (per-kind availability). |
delete(ref) |
Deletes a resource (per-kind availability). |
wait(target) |
Polls until a write finishes; GET requests only. |
organizations() |
Lists organizations (the create-project prerequisite on the providers). |
regions(input?) |
Lists deployable regions; Supabase requires organizationId. |
connection(ref, input?) |
Returns provider connection details; passwords redacted unless reveal: true. |
action(ref, action, options?) |
Runs a declared lifecycle action (pause, restart, resume, reset, restore, start, suspend). |
resetCredential(ref, options?) |
Rotates a credential; the new password appears only in secrets. |
Every call is checked against the adapter’s declared capabilities before
dispatch: an unsupported kind, verb, or pagination argument fails with a
ManagementError of code CAPABILITY and nothing is sent. Scope rules are
enforced the same way: a Neon database must carry both projectId and
branchId, because that is how Neon actually addresses databases.
Create, wait, connect, query
The full path on Neon, with the real option names:
import { createDatabase } from "dbsdk";
import { createManagement } from "dbsdk/management";
import { neon } from "dbsdk/neon";
import { neonManagement } from "dbsdk/management/neon";
const management = createManagement({
adapter: neonManagement({ apiKey: process.env.NEON_API_KEY! }),
});
// 1. Create the project. The write may involve several provider
// operations; the result carries them all.
const result = await management.create({
kind: "project",
name: "my-app",
});
// 2. Wait until every operation finished. wait() issues GET requests
// only and never resubmits the create.
const project = await management.wait(result, { timeoutMs: 120_000 });
// 3. Credentials: Neon's create responses carry connection URIs and role
// passwords (shown once by Neon). dbSDK surfaces them only in
// result.secrets and redacts them from every raw payload and error.
const secret = result.secrets.find((s) => s.label === "connectionString");
// 4. An official connection URI on demand. By default the URI comes back
// with the password segment redacted; `reveal: true` is the explicit
// opt-in that returns the credential-bearing URI for connecting.
// The default database is `neondb` and its default role is
// `neondb_owner` — the ones a fresh project actually has.
const uri = await management.raw.connectionUri({
projectId: project.id,
databaseName: "neondb",
roleName: "neondb_owner",
reveal: true,
});
// 5. Bridge to the query client. The management credential and the SQL
// connection string are different credentials; the URI from step 3 or
// 4 is the one the query adapter needs.
const db = createDatabase({
adapter: neon({ connectionString: uri, transport: "http" }),
});
type NeonConnectionUriInput = {
projectId: string;
branchId?: string; // omit for the project's default branch
databaseName: string; // required by the official endpoint
roleName: string; // required by the official endpoint
pooled?: boolean; // true returns the PgBouncer `-pooler` URI
reveal?: boolean; // explicit opt-in to receive the real password
};
Steps 1 to 4 run against the real Neon API with a real key; nothing here
hides a host or invents an endpoint. Running them provisions a real project
on your Neon account, so use a key scoped to a test organization while
learning. The query in step 5 needs the project to be ready, which wait()
establishes in step 2.
The same bridge exists on Supabase, assembled from official pieces rather
than invented ones: the creation-time password (via secrets), the
database host (via raw.databaseHost(projectRef)), and full branch
credentials (via raw.branchConfig(...), secrets omitted unless you pass
includeSecrets: true). You assemble Supabase’s documented direct
connection string shape from those parts and hand it to the query adapter.
A personal access token never acts as a database password, and the SDK
never fabricates a URL from it.
Once you hold a connection string, you can also hand the dbSDK-owned
database to Drizzle ORM through dbsdk/drizzle on the same pool — see
Drizzle.
Resources and scope
Resource kinds are a shared vocabulary, normalized across providers, with honest per-provider limits:
project: the top-level unit on the providers. A Supabase project is the PostgreSQL database; a Neon project contains branches that carry databases; on PlanetScale, the database (the managed, billable unit) is theprojectkind.branch: a Neon branch. Neon branch writes are asynchronous; the result carries the provider operations thatwait()polls. PlanetScale branches are scoped to the database’s name slug, addressed by name.database: a logical PostgreSQL database. Neon-scoped to a branch and addressed by name, exactly as Neon’s API does it. Supabase has no such resource:create({ kind: "database" })on Supabase is refused withCAPABILITYbecause there is nothing for it to create. PlanetScale refuses it for the opposite reason: its database is already theprojectkind, so there is no separatedatabaseresource beneath it.- Provider-defined kinds: Neon adds
role(branch-scoped Postgres role credentials),endpoint(a branch compute, withstart/suspend/restartactions), andsnapshot(a branch snapshot, restorable to a branch). PlanetScale addsrole: Postgres role credentials scoped to{ projectId, branchId }(database slug + branch name) and addressed by uid. They exist only where the provider’s official API defines them; there is no Supabaserole,endpoint, orsnapshotequivalent in its management API. Neon has no single snapshotget: the official API offers only create, list, update, delete, and restore, andgeton a snapshot is refused withCAPABILITYsaying exactly that.
The kind set is open: a provider adapter can declare its own kinds (with required scope fields in its capabilities), so a future adapter for a non-SQL service plugs in with its own vocabulary instead of fabricated SQL semantics.
type ResourceRef = {
kind: string;
id: string;
projectId?: string;
branchId?: string;
scope?: Readonly<Record<string, string>>; // provider-defined kinds
};
type ManagementListQuery = {
cursor?: string;
limit?: number;
projectId?: string; // required for scoped list endpoints (Neon branches)
branchId?: string; // required for Neon database lists
scope?: Readonly<Record<string, string>>;
};
Lists are scoped the way the provider addresses them: Neon’s branch list
needs projectId on the query, and its database list needs both
projectId and branchId. Missing scope fails before dispatch with
CONFIGURATION.
What each provider supports today
The authoritative source at runtime is the adapter itself:
import { createManagement, describeManagementCapabilities } from "dbsdk/management";
import { neonManagement } from "dbsdk/management/neon";
const adapter = neonManagement({ apiKey: process.env.NEON_API_KEY! });
const management = createManagement({ adapter });
console.log(describeManagementCapabilities(adapter));
// {
// providerId: "neon",
// resourceKinds: ["project", "branch", "database", "role", "endpoint", "snapshot"],
// operations: { create: [...], list: [...], get: [...], update: [...], delete: [...],
// connection: [...], resetCredential: [...] },
// actions: { start: [...], suspend: [...], restart: [...], restore: [...] },
// pagination: true,
// asyncOperations: true,
// statusPolling: ["branch", "endpoint"],
// prerequisites: { ... },
// resourceScopes: { ... },
// evidence: { "create:project": "docs", ... }
// }
Neon (neonManagement) |
Supabase (supabaseManagement) |
PlanetScale (planetscaleManagement) |
|
|---|---|---|---|
| Create project | yes; name required, region and organizationId optional; no plan and no caller password (Neon generates the role password) |
yes; name and an organization scope required (organizationId or providerOptions.organization_slug; the API’s organization_id is deprecated). A spec plan is refused with CONFIGURATION: the plan is chosen at the organization level |
yes; name and providerOptions.cluster_size required (official API); the factory organization is the required owner and a mismatching spec.organizationId is refused with zero dispatch; no plan field and no create-time password — credentials come from roles |
| Branches | yes; projectId required, creation is async, a read-write compute is added by default |
yes (the Environments API); branch create is synchronous | yes; projectId (the database name slug) + name required; create is synchronous; branch update is refused (the official PATCH endpoint exists but was not verified — not guessed) |
| Databases | yes; projectId + branchId + name + owner required; branch-scoped, addressed by name |
refused: the project is the database | refused: the database is the project kind |
| Roles / compute / snapshots | yes: role (branch-scoped credentials), endpoint (compute with start/suspend/restart), snapshot (create/list/update/delete/restore); no single snapshot get (the official API has none) |
no such kinds in the official API | role only: Postgres role credentials scoped to a database + branch, addressed by uid; every mutating verb first GETs the parent database and refuses non-PostgreSQL parents before the mutation (the engine gate) |
| Connection details | connection(ref, { databaseName, roleName, pooled?, reveal? }); database name and role name are required by the official endpoint, never guessed |
connection(ref, { pooled?, reveal? }); a direct project connection exposes the host (the official payload carries no database/role fields) |
connection(ref) for project, branch, or role: resolves the official host and role username; the URI is always redacted — role passwords are one-time secrets and connection() never fabricates one |
| Lifecycle actions | start/suspend/restart on an endpoint; restore on a branch or snapshot |
pause, restart, resume on a project; reset and restore on a branch |
none declared: PlanetScale Postgres has no pause/restart-style lifecycle endpoints, so every action() is refused with CAPABILITY |
| Credential rotation | resetCredential({kind:'role'}): server-generated, caller password refused; raw.revealRolePassword re-reveals a role password |
resetCredential({kind:'project'}): adapter-generated password when omitted, returned once via secrets |
resetCredential({kind:'role'}): server-generated, caller password refused; raw.renewRole extends a role’s expiration without generating a password |
| Recover deleted project | raw.recoverProject(id) (official endpoint) |
no such endpoint: deleted projects are gone | no such endpoint |
| Update / delete | per kind, all declared kinds | yes for project and branch |
update: project and role; delete: project, branch, role |
| Pagination | projects and branches paginate; the database list does not | no server-side pagination anywhere | page-based on all implemented lists; a limit above the official maximum of 100 is refused before dispatch |
| Async operations | yes; wait() polls the operations endpoint |
no operations endpoint; wait() polls resource status |
no operations endpoint; wait() polls resource status (project, branch, and role all expose readiness) |
| Credential | Neon API key | Supabase personal access token (sbp_...) |
PlanetScale service token (tokenId + tokenSecret; sent as Authorization: <id>:<secret>, no Bearer scheme) |
Availability in this table means “implemented and declared”. It never certifies your credentials, your plan tier, or that a specific live request will succeed; the provider answers for that, with its own errors normalized as described below.
One provider-specific nuance worth knowing before you write the create
spec: Supabase’s current API does not accept a plan on project creation
(the plan is chosen at the organization level), and the adapter refuses a
spec that includes one with a CONFIGURATION error telling you to remove
it. A spec region is still accepted and mapped to the official
region_selection form, and the deprecated-but-accepted organization_id
form is supported alongside providerOptions: { organization_slug }.
Region codes come from the provider’s own endpoint
(GET /v1/projects/available-regions); the adapter’s prerequisites
state the current requirements. Region discovery works the same way on
the providers through regions(): Supabase requires the organization
scope, Neon forwards a supplied organizationId to the official endpoint
as org_id (optional, but Neon recommends it for accurate availability).
Actions, connections, and credentials
action(ref, name, options?) runs an officially declared lifecycle
mutation. Every action name/kind pair is capability-gated before dispatch.
Two semantics worth reading twice, because the names do not say what you
might guess:
- Supabase
action(project, 'resume')is the un-pause primitive. It calls the officialPOST /v1/projects/{ref}/restore(the endpoint the dashboard’s “Resume project” button uses, scopeprojects:write). The endpoint echoes no resource or operation, sowait()on the action result is refused by design; pollget()/wait(project)while the status moves throughRESTORINGback to active. - Supabase
action(branch, 'restore')cancels a scheduled branch deletion. It is not point-in-time data restore; the backups/PITR family is the one thing this adapter does not cover on Supabase yet. - Neon has no project pause or resume. Scale-to-zero is per-compute:
action({kind:'endpoint'}, 'suspend')and'start'. A Neon branch restore acceptspreserveUnderNamewhen required by Neon (children or self-source); unknown input keys are refused withCONFIGURATIONinstead of being silently dropped. - PlanetScale Postgres declares no lifecycle actions at all. There are
no pause/restart-style endpoints for its databases, branches, or roles,
so any
action()call is refused withCAPABILITYbefore dispatch rather than guessed from an unverified endpoint.
connection(ref, input?) returns provider-selected connection details:
host, port, database, role, pooled flag, and a redacted URI. Any password
segment is redacted by default; reveal: true is the explicit opt-in that
returns the credential only in secrets and additionally registers it for
redaction in later error messages. Nothing is fabricated: fields the
provider does not return are null. On PlanetScale this is even stricter:
role passwords are one-time secrets issued only by create and
resetCredential, so connection() resolves the host and role username but
can never produce a password, and its URI stays redacted unconditionally.
resetCredential(ref, options?) rotates a credential. On Neon, role
passwords are server-generated and a caller-supplied password is refused
with CONFIGURATION; on Supabase, the adapter generates a cryptographically
random project password when you omit it; on PlanetScale, role rotation is
server-generated and raw.renewRole extends a role’s expiration without
generating a new password. In all cases the new password appears only in
secrets. Supabase’s create-time password cannot be recovered, only
rotated; PlanetScale’s role passwords are likewise one-time secrets.
Create results and secrets
type ManagementWriteResult = {
resource: ManagementResource | null;
operation: ManagementOperation | null;
secrets: readonly ManagementSecret[]; // { label, value }
indeterminate: boolean;
};
Secrets surface in exactly one place: secrets. On Supabase, the create
endpoint requires a database password and never echoes it: when you omit
password, the adapter generates a cryptographically random one and
returns it through secrets (label password), shown once. If you pass
your own, it is used but never echoed back. On Neon, connection URIs and
role passwords from create responses arrive only through secrets.
Every raw provider payload is redacted before it reaches your code, and
credential values are scrubbed from error messages. Treat everything in
secrets like a password: store it, never log it.
Waiting, bounded
type WaitOptions = {
signal?: AbortSignal;
timeoutMs?: number; // overall budget, default 300_000
pollIntervalMs?: number; // default 2_000
onStatus?: (update: ManagementResource | ManagementOperation) => void;
};
wait() issues GET requests only. It polls the provider’s operations
endpoint where one exists (Neon) or the resource’s own status where one
does not (Supabase), and it never resubmits a create, update, or delete.
Rate-limited polls (429) are retried after the provider’s own hint, still
inside the same overall budget. A budget overrun throws TIMEOUT; a
caller abort throws ABORTED. Neither is indeterminate, because waiting
performs no writes.
One precondition to know: waiting on a bare ResourceRef only works for
kinds whose normalized status actually reflects provider lifecycle. Each
adapter declares which kinds those are (statusPolling): Neon’s branch
and endpoint, Supabase’s project and branch, and PlanetScale’s project,
branch, and role (role readiness respects terminal/deletion and
expired/disabled states before any ready: true). wait() on a bare Neon
project, database, role, or snapshot ref is refused before dispatch with
CAPABILITY instead of hanging until the timeout: pass the write result
or the operation returned by the write, which carries the provider
operations to poll.
Errors
ManagementError carries a stable code: CAPABILITY, CONFIGURATION,
AUTH, PERMISSION, NOT_FOUND, CONFLICT, RATE_LIMIT, VALIDATION,
ABORTED, CONNECTION, TIMEOUT, PROVIDER, or UNKNOWN, plus the HTTP
status, the adapter and resource identity, and retryable.
The mutation rule matches the query side: if a transport failure or a 5xx
response happens during a create, update, or delete, the outcome cannot be
known, so the error is marked indeterminate: true. The SDK never retries
a mutation; you reconcile (for example, by listing or getting the resource
before deciding what to do). Definitive 4xx rejections are not
indeterminate.
Testing without a provider
dbsdk/management/testing ships a deterministic fixture adapter. It is
not a simulator of any provider: it proves what the core client does with
the results, errors, and capabilities an adapter declares, with every call
recorded. See Testing and the examples in the repository.
