resource_not_found.
Install the exact npm alias from runtime.packages.customerRuntime in ohmyhost init --dry-run --json, under the import name @ohmyhost/customer-runtime: npm:@amerged/ohmyhost-runtime@<version>. This applies to every framework; update/commit the lockfile. Use the current CLI/runtime release together. For nested JSON results, depth is measured from each row, while the response envelope and all rows still share the same total budgets.
Application requests use createPrivateDatabaseClient(env.OHMYHOST_DATABASE) from @ohmyhost/customer-runtime/database. query() executes one statement, transaction() atomically runs up to 25 statements chosen in advance, and withConnection() holds a real connection for read-decide-write; one scope permits 100 statements, 30 seconds total and five seconds idle, with two active transaction/auth connections per physical data area. Shared Dev/Prod use the same lanes. Standalone statements commit before their response; use explicit BEGIN and COMMIT for an atomic sequence. Closing rolls back an unfinished transaction, and transaction-local server timeouts release its slot if the caller disappears.
Inside a withConnection callback that performs an atomic transaction, pass its current connection and SQL executor to every participating repository and identity lookup. Do not open another database connection for those reads. Complete the short transaction and close the connection before a file transfer, email or AI call, then open a new short transaction to store the result.
For application-user or organization row permissions, use withRls and PostgreSQL policies. RLS is explicit per table and requires the coordinated 0.1.30 or later runtime and deployed service. The backend verifies the session first; the service then owns the transaction and supplies its local identity. Existing unprotected tables keep their current behavior.
JSON/JSONB object parameters work with the current runtime. Pass ordinary JavaScript objects, including nested objects and arrays, as parameters:
__proto__, constructor and prototype are refused. Upgrade the alias/lockfile together if an older client rejects valid JSON. For an application that stores JSON, verify a JSON write/read through the hosted application, since a scalar-only health query does not exercise that path.
SQL DATE values and date[] elements are YYYY-MM-DD strings. Keep calendar days free of timezone conversion; timestamp values retain their existing decoding. Application database examples.
Verified statement failures expose their five-character PostgreSQL SQLSTATE on error.code, so applications can distinguish duplicate (23505) and exclusion (23P01) conflicts. SQL, row values and provider messages stay private. Only serialization failures (40001) and deadlocks (40P01) are marked retryable; retry the whole transaction within a bound. Transport failures remain database_unavailable and do not prove that a write was rejected.
The offline init scans all source: database_binding_private marks DATABASE_URL, HYPERDRIVE, connectionString or postgres URLs; database_driver_unsupported marks pg, postgres, pg-native or mysql2. Tests/bootstrap can also be reported. Source planning rejects these in reachable hosted routes, middleware, Worker/companion modules as framework_conversion_required naming the file. Inspect each reported file and the actual hosted entrypoint before changing it: offline tools may use temporary direct credentials, while hosted requests must use the private binding. A local development adapter needs an explicit local-only mode and validated loopback configuration. An RPC import alone does not establish that another driver is unreachable; verify the built artifact and the real hosted request. Do not remove required bootstrap or tests merely to silence the scan. An unreachable offline script can remain, but init still reports it and cannot write a new config while blocked; document that exception without claiming clean init.
Application connection and result limits
Standalone queries have one connection per physical data identity; transaction() and held scopes share two further connections. Shared Dev/Prod consume the same capacity. Each lane admits 32 waiting acquisitions with a ten-second connection/wait bound. PostgreSQL statements time out after ten seconds (SQLSTATE 57014); a cold database may need about five seconds to wake.
A call has one SQL statement up to 64 KiB, 100 parameters and 1 MiB aggregate parameter data; a JSON parameter is at most 64 KiB. JSON depth is at most eight; a result is at most 1,000 rows, 10,000 values/nodes and 1 MiB. Multiple statements, SET/RESET/DISCARD and oversized input fail before RPC as database_query_invalid (not retryable). PREPARE is refused outside withConnection, and chained COMMIT/ROLLBACK … [NO] CHAIN inside it. Use BEGIN/COMMIT/ROLLBACK/savepoints only through a held scope; for transaction-local state use SELECT set_config('app.user_id', $1, true).
Oversized results and the 101st held statement throw CustomerDatabaseError (root package export), error.code === "54000", retryable: false. Page reads/split writes or open a new held scope. An idle 5-second or expired 30-second scope closes and rolls back uncommitted work as database_unavailable; open a new scope. A write with RETURNING, or a WITH statement, rolls back on an oversized result through query(), transaction() or a held autocommit statement. Inside your own BEGIN, those effects remain until you ROLLBACK or end the callback without COMMIT; do not catch 54000 and commit or retry that write inside the same transaction.
A missing database binding is database_binding_missing, not a retryable query failure. Read it from Worker env or Next.js getCloudflareContext({ async: true }).env, only in source declaring database.enabled:true; it is neither a process.env string nor a browser capability.
Optional Kysely dialect
The optional@ohmyhost/customer-runtime/database-kysely adapter targets Kysely 0.29.5 over the private binding, including its leased transaction protocol:
AppDatabase, table names and values are your application’s types/data. The adapter implements BEGIN/COMMIT or ROLLBACK through the held-connection API and releases that scope; the same limits apply. Library tests cover that protocol, but do not establish real hosted RPC/PostgreSQL behavior or signup/mail. Verify the application on its deployed private binding. It is not a Drizzle support claim or a pg-proxy transaction substitute. Keep network calls outside the transaction.
Database sizes
Active time is prorated at the selected RAM size. Total disk includes PostgreSQL files, WAL and filesystem overhead, so application records have less than the nominal space. Seven-day operational backups are included, also while asleep. There are no separate database CPU, network, connection, disk or backup charges. Application Worker usage and customer files retain their separate rates.
Databases sleep after 300 idle seconds. Sleeping has no active-RAM charge; the next query wakes the database and can take longer. Avoid periodic SQL health queries.
provisioning means initial creation, cold means an existing sleeping database, and warm means running. Shared Dev/Prod uses one physical database; isolated databases are billed independently.
Databases run on PGCF, the open-source PostgreSQL platform behind ohmyho.st.
New managed PGCF databases follow the project’s selected US or EU region. Existing projects moved to US with their owner’s authorization use US databases. database compute get reports the actual database region. Existing R2 file and backup locations remain recorded through an authorized database or project-region migration; read storage jurisdiction separately through project context.
Change the size
database_compute_set with memory_mib and confirm: true; REST uses memory_mib. Explain the price and possible brief connection interruption first. Choose prod only when intended; shared data changes both environments. Keep one idempotency key, poll the original operation, and read actual compute after it succeeds.
An increase preserves SQL data. In-place volume shrink is refused; choosing a smaller disk requires a separate authorized data migration. Never reset data to satisfy a resize, and do not assume loss of Paid access permits shrinking an existing volume. Larger sizes require Paid. Do not send the old profile input of the retired previous database provider; select the RAM size explicitly.
Query Dev or Prod
Use your existing CLI login or load your user API token from a private environment file. The token must have the selected organization’s Owner project permissions.OHMYHOST_ENVIRONMENT chooses the independent hosting platform; --environment dev|prod chooses this project’s database.
--environment prod for the project’s production database. For application records, discover the actual schema and use parameters rather than interpolating values into SQL:
items, its columns and item-123 are examples: use the application’s actual table and record ID. Reads accept one read-only SELECT/WITH query, at most 32 scalar parameters, 100 rows and five seconds. Both queries and writes wake suspended compute and use ordinary database metering.
Update application data
Review the intended rows and environment before an update. Put one parameterized INSERT, UPDATE or DELETE in a UTF-8 file of at most 64 KiB starting with that keyword, no leading comment or WITH; ordinaryINSERT … ON CONFLICT … upserts are supported. For example, approved-update.sql:
statement_file_invalid (exit 2, not retryable), without sending; fix it and reuse the same key. Execute only the chosen update:
operation_id, environment, state, command, affected_rows and error. It does not return rows, including rows produced by a SQL RETURNING clause. Fetch records with a separate query. One write has a five-second SQL timeout and at most 1,000 directly affected rows; triggers and cascades can affect additional rows. Existing credit grace and project Stop budgets apply.
Check the receipt’s state: HTTP 200 alone is not success. succeeded confirms the reported command and count; running means inspect the original operation; failed carries the error and next action.
database_write_outcome_unknown, first inspect the data and keep the operation ID; never automatically choose a new key or execute a second write. Even an error can mean the original commit result was not received.
Connect with psql or a SQL client
For interactive work you can issue a temporary PostgreSQL login for your own project database. Each credential is time-bound, revocable and returned exactly once:connection_uri is returned once and is never retrievable again. Keep it and its password out of command arguments, files, notes, source and logs. The credential also carries provider: "pgcf", transport: "wss" and websocket_url: its PostgreSQL URI is a credential carrier, not a public TCP endpoint for an arbitrary SQL client. The returned psql_command is the secret-free CLI helper below, which creates its own access. Later reads show metadata only:
psql. It issues the credential, opens a local loopback bridge over verified WSS, passes the password to psql through its private environment, and closes the bridge and revokes the credential when you exit:
database_access_create (mode: "write" requires confirmed: true), database_access_list and database_access_revoke; REST uses POST/GET /v1/projects/{project_id}/database/access and DELETE /v1/projects/{project_id}/database/access/{access_id}.
Historical entries from before the move to PGCF can still appear in
database access list as expired or revoked, with database: "neondb". They cannot be used; every new credential is a PGCF credential over WSS.
No mode can change schema or roles: schema changes remain versioned GitHub migrations, and application row-level security applies to these sessions exactly as it does to database query and database write. After expiry PostgreSQL refuses new logins and the platform ends remaining sessions and removes the role within 15 minutes. An open session wakes compute and is metered like any other database use, under the same credit grace and project Stop budgets. Revoke as soon as you are finished instead of waiting for expiry.
Use MCP or an automation platform
MCPdatabase_query requires project_id, environment, statement and optional scalar parameters. database_write uses the same project/environment with JSON parameters, the saved idempotency_key and confirmed: true for an authorized write. These are individually named local and remote tools; check the connected host’s actual schemas. Use remote api_reference to inspect API coverage or an unfamiliar operation. A pending host check can delay a new tool’s availability.
REST uses your token in the Authorization header:
POST /v1/projects/{project_id}/database/write; supply the Idempotency-Key header and JSON environment, statement and parameters. An automation should keep the same key for retries of one event and use a new key only for a deliberately new write. Download the exact OpenAPI schema.
Webhooks, schedules and executions
Client 0.1.42 or newer manages three things per Dev or Prod database. All of them are tied to the one database of the selected environment; another project’s webhook, schedule or delivery answersresource_not_found.
Webhooks send a signed HTTPS POST when the database changes state: database.created, database.ready, database.woke, database.slept, database.suspended, database.resized and database.deleted. The data events data.<topic> come from table watches instead. Each resolved database can have five webhooks, so shared Dev and Prod use the same limit.
With client 0.1.57 or newer, choose a new subscription ULID and activate generation 1. Choose an existing private directory outside the repository, or a Git-ignored directory, and a new output filename. The CLI creates an owner-private file for the signing secret; it returns the path as secret_file without printing the secret. Install it securely in your receiver and keep it out of chat, logs and source.
provider_id, but never the secret. Use provider_id as the webhook ID when testing. If the activation answer is lost, retry the identical URL, event types and optional headers with the same subscription, generation and idempotency key, but choose a new output filename. Existing files and links are never replaced. An unresolved provider activation can remain pending; keep its original identity while checking status.
ohmyhost database webhook subscription deactivate --project "$PROJECT_ID" --environment dev --subscription "$SUBSCRIPTION_ID" --generation 1 --idempotency-key "$DEACTIVATION_KEY" --yes --json. After uncertainty, retry the same deactivation key. Only after the previous generation is confirmed inactive may you activate the next generation with the same subscription ULID, a new key and a new output file. Pending deliveries are not guaranteed during or after deactivation.
Local MCP offers database_webhook_subscription_activate and database_webhook_subscription_deactivate with confirmed: true; activation takes out_file and, if needed, an absolute owner-private headers_file. Local and remote MCP provide database_webhook_subscription_status. The older database webhook create returns its signing secret in the response and cannot recover it through this lifecycle; an exact retry can be refused at the webhook limit. Use a stable subscription for a new integration.
Every request carries PGCF-Signature: t=<unix seconds>,v1=<hex>, where v1 is the HMAC-SHA256 of <t>.<raw body> with the secret. Reject a signature more than five minutes from the current time, compare in constant time, and answer a 2xx status within a few seconds. PGCF-Event-Id and PGCF-Delivery-Id identify the event and the attempt; a retried delivery repeats the event id, so deduplicate on it. A failed delivery is retried with growing delays for up to 24 hours, then it stays visible as dead-lettered for a week and can be replayed. webhook test sends one signed request and stores nothing; it is limited to one call per five seconds.
Schedules run SQL on a timer, in the database, as the runtime role of your application, so row-level security applies and schema changes are refused. A schedule has a cron expression (five fields, UTC) or an interval of 60 to 2,678,400 seconds, one to twenty statements that run in one transaction, and a timeout of 1,000 to 30,000 milliseconds.
succeeded, failed (with the SQLSTATE), timed_out, rejected, outcome_unknown or one of the skipped_* states, and the last fifty runs are kept. A run whose answer was lost is outcome_unknown and is not repeated, so write statements that are safe to run twice. A run wakes a sleeping database and counts as database use, like a query. A project that reaches its Stop budget has its schedules turned off automatically, within about an hour; a Continue budget never does this. To stop one schedule sooner, delete or disable it. Turning them on again is manual: raise the budget (or wait for the next UTC month), then run database schedule set --enabled true with the schedule’s body, which you read with schedule get.
Executions count schedule runs, webhook attempts and events per hour or day:
final once it is complete. They are counters without a separate price; the cost of a run is the time its database is awake.
MCP offers these operations as database_webhook_*, database_schedule_* and database_execution_usage_get; the remote server offers supported reads, while database event changes need the local server or the CLI. REST reads a subscription at /v1/projects/{project_id}/database/webhook-subscriptions/{subscription_id} and activates or deactivates /activations/{generation} under it. The other paths include /database/webhooks, /database/schedules, /database/execution-usage, /database/watches (table watches) and /database/tables (create a table); see the OpenAPI schema.
Table watches
Client 0.1.45 or newer. A watch publishes the row changes (insert, update and delete) of one table as signed webhook events of typedata.<topic>. Only the columns you list leave the database; the list is an explicit allowlist of 1 to 32 column names.
A watch can also be attached to a table created with ohmyhost database table create; see Create a table.
Data events need the platform’s event schema in the database. If a watch answer carries database_watch_events_unavailable (409, “Database events not installed yet”), run any read on that environment once, for example database query, wait for its answer and repeat the request with the same idempotency key. The database sleeps again when idle. Every watch call, including list, wakes a sleeping database.
Create the watch first. --schema defaults to public and --operations to insert,update,delete. The answer carries id, schema, table, columns, operations, topic and event_type:
--event-types is the printed event_type, for example data.orders. For a table that already takes writes, create the webhook before the watch: events committed while no webhook subscribes to the topic are discarded and never replayed. Verify with a real change. database webhook test sends a test event, not a data event, so it proves only the receiver and signature handling. Make one harmless change in Dev with the MCP tool database_write, then read database webhook deliveries for an event of type data.orders in state delivered. Events normally leave within seconds of the commit.
ohmyhost database watch list --project ID --environment dev lists the watches of an environment and does not list triggers declared by migrations. ohmyhost database watch delete --project ID --environment dev --watch WATCH_ID --idempotency-key KEY --yes removes one. The named MCP tools are database_watch_create, database_watch_list and database_watch_delete; check actual availability in the connected local or remote host. Create and delete need confirmed: true and a saved idempotency key. REST uses POST and GET /v1/projects/{project_id}/database/watches (operations createProjectDatabaseWatch and listProjectDatabaseWatches) and DELETE /v1/projects/{project_id}/database/watches/{watch_id} (deleteProjectDatabaseWatch).
Topic. The topic is the table name in lower case, with every character outside a-z, 0-9 and _ replaced by _, prefixed with t_ when the first character is not a letter, and cut to 48 characters. The schema is not part of the topic, so two tables with the same name in different schemas share one; tell them apart by data.schema and data.table.
Subscriptions. Subscribe with data.<topic> for one table or data.* for every watched table. A bare * and database.* do not include data events. A pattern that matches no existing topic never fires, so copy the event_type from the watch answer.
Event. Each delivery has this shape:
id is <database_id>:<epoch>:<seq>. epoch rises after a move or an in-place recovery, and seq rises per database. An insert has old_record: null, a delete has record: null, and an update that changes none of the listed columns publishes nothing.
Eligibility. A database holds one watch per table, at most 100 in all. Creating the same watch again returns it; different columns or operations replace its trigger. The table must be an ordinary permanent table owned by the project’s migration role, created by a migration or with database table create, not a view, partition, temporary or unlogged table. The schemas pgcf, ohmyhost, information_schema and pg_* cannot be watched. Every listed column must exist, with its name written exactly. A table whose migration already declares a capture trigger cannot also have a watch.
Outcomes. Each answer below refuses the request. Fix its cause, then repeat the request:
database_watch_table_unavailable(409): the table is not eligible.database_watch_column_unavailable(409): a listed column does not exist.database_watch_events_unavailable(409): the event schema is not installed yet; see above.database_watch_conflict(409): a migration already attaches a capture trigger to the table.database_watch_limit(409): the database has 100 watches; delete one first.project_budget_exceeded(402): the project’s Stop budget is reached. Create and delete are refused; reads are not.
id stays the same across retries, so deduplicate on it. Arrival order is not guaranteed, because retries reorder events; order by (epoch, seq) at the receiver. Answer with a 2xx status within five seconds. An event is sent only if the application’s transaction commits, and each subscription gets its own delivery. Retries and replay work as for the other webhooks above.
Limits. A watch filters columns, not rows. Rows written before the watch existed produce no events; read the initial state with database_query. TRUNCATE is not published. A restore or point-in-time recovery starts with an empty outbox, so undelivered events from before are not sent. Watch only columns the receiver may see, because their row data leaves the database.
Undelivered events are held in an outbox of 10,000 per database. When it is full, the application’s write fails with SQLSTATE 53400 and nothing is lost; retry after a pause. Delete the watch before a bulk import or backfill and create it afterwards. Each event is limited to 16 KiB, counting the listed columns in record and old_record (an update counts them twice); a larger write fails with SQLSTATE 54000. Watch ids, status and counters, not large text or JSON.
Billing. Events have no separate price. A database with undelivered events stays awake and is billed as awake time, and the event counts (events_emitted and event_bytes) appear in database executions. A logical pg_dump of the database needs --exclude-schema=pgcf, because project roles cannot read the platform schema.
Create a table
Client 0.1.46 or newer. Use this when Zapier, Make or another automation, or any caller, needs a new table and no source migration is wanted. The CLI creates it in one call:--columns-file names a UTF-8 JSON array of 1 to 64 column objects, at most 64 KiB:
database_table_create; it needs confirmed: true and a saved idempotency key, and primary_key takes the column names. Check the connected host’s actual tool schema; remote chat supplies column objects rather than a local file path. REST uses POST /v1/projects/{project_id}/database/tables (operation createProjectDatabaseTable) with an Idempotency-Key header and the same permission as the other database changes. The body is environment, table, columns and an optional primary_key:
name, a type and the optional nullable (default true), identity and default fields. Types are text, integer, bigint, boolean, numeric, double precision, timestamptz, date, uuid and jsonb.
- Identifiers. Table and column names are lower-case: a letter or underscore first, then letters, digits or underscores, at most 63 characters. Names starting with
pg_and PostgreSQL reserved words are refused. Column names are unique. - Identity.
identityneedsintegerorbigint, takes nodefault, and makes the columnNOT NULL. A table has at most one identity column. - Defaults.
default: "now"needstimestamptzand setsnow();default: "uuid"needsuuidand setsgen_random_uuid(). - Primary key. Name 1 to 8 of the table’s columns with
--primary-key(CLI, comma-separated) orprimary_key(REST and MCP). Key columns areNOT NULL, sonullable: trueon one is refused.
201 with the table and created set to true. Repeating an identical request answers 200 with created set to false, so a retry after a lost answer is safe with the same idempotency key. The request can fail with these codes:
database_table_conflict(409): a table of that name already exists with another definition. Repeating the request does not help.database_table_limit(409): the database has 100 tables. Repeating the request does not help.project_budget_exceeded(402): the project’s Stop budget is reached. See Project budget exceeded.