{
  "openapi": "3.1.0",
  "info": {
    "title": "db.opelly.me — Postgres over HTTPS",
    "version": "0.1.0",
    "summary": "Run SQL against one Postgres database with a per-database API key.",
    "description": "Each API key is bound to one database and one access level (`read` = SELECT only, `full` = database owner). The same key also works as the password of a postgres:// URL at `pg.opelly.me:443`. Agent-oriented docs: https://db.opelly.me/llms.txt"
  },
  "servers": [{"url": "https://db.opelly.me"}],
  "security": [{"apiKey": []}],
  "externalDocs": {"description": "Human and agent docs", "url": "https://db.opelly.me/llms.txt"},
  "paths": {
    "/api/v1/whoami": {
      "get": {
        "operationId": "whoami",
        "summary": "Describe the calling key",
        "description": "Returns the key's database, access level, effective limits, endpoint URLs and a postgres:// URL template.",
        "responses": {
          "200": {
            "description": "Key description",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Whoami"}}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "403": {"$ref": "#/components/responses/Forbidden"},
          "429": {"$ref": "#/components/responses/TooManyRequests"}
        }
      }
    },
    "/api/v1/schema": {
      "get": {
        "operationId": "getSchema",
        "summary": "Describe tables, columns, keys, indexes and enums",
        "parameters": [
          {
            "name": "schema", "in": "query", "required": false,
            "description": "Only describe this Postgres schema (e.g. `public`).",
            "schema": {"type": "string"}, "example": "public"
          }
        ],
        "responses": {
          "200": {
            "description": "Database schema visible to the key",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Schema"}}}
          },
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "403": {"$ref": "#/components/responses/Forbidden"},
          "429": {"$ref": "#/components/responses/TooManyRequests"},
          "503": {"$ref": "#/components/responses/UpstreamUnavailable"}
        }
      }
    },
    "/api/v1/query": {
      "post": {
        "operationId": "query",
        "summary": "Run one SQL statement",
        "description": "Runs exactly one statement inside its own transaction. Results larger than `max_rows` or 16 MiB are rolled back and rejected with 413. Transaction control statements are rejected; use /api/v1/transaction.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {"$ref": "#/components/schemas/QueryRequest"},
              "examples": {
                "select": {"value": {"sql": "select id, name from users where id = $1", "params": [42]}},
                "insertReturning": {"value": {"sql": "insert into users(name, tags) values ($1, $2) returning id", "params": ["Ada", ["admin", "beta"]]}},
                "arrayRows": {"value": {"sql": "select id, name from users order by id limit $1", "params": [100], "row_mode": "array"}}
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Statement result",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/QueryResponse"}}}
          },
          "400": {"$ref": "#/components/responses/BadRequest"},
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "403": {"$ref": "#/components/responses/Forbidden"},
          "408": {"$ref": "#/components/responses/Timeout"},
          "413": {"$ref": "#/components/responses/ResultTooLarge"},
          "429": {"$ref": "#/components/responses/TooManyRequests"},
          "503": {"$ref": "#/components/responses/UpstreamUnavailable"}
        }
      }
    },
    "/api/v1/transaction": {
      "post": {
        "operationId": "transaction",
        "summary": "Run up to 100 statements atomically",
        "description": "All statements run in one transaction. Any failure rolls back everything; the error carries `statement_index`.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {"$ref": "#/components/schemas/TransactionRequest"},
              "example": {
                "statements": [
                  {"sql": "insert into orders(user_id) values ($1) returning id", "params": [42]},
                  {"sql": "update users set order_count = order_count + 1 where id = $1", "params": [42]}
                ],
                "read_only": false
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "One result per statement, in order",
            "content": {"application/json": {"schema": {"$ref": "#/components/schemas/TransactionResponse"}}}
          },
          "400": {"$ref": "#/components/responses/BadRequest"},
          "401": {"$ref": "#/components/responses/Unauthorized"},
          "403": {"$ref": "#/components/responses/Forbidden"},
          "408": {"$ref": "#/components/responses/Timeout"},
          "413": {"$ref": "#/components/responses/ResultTooLarge"},
          "429": {"$ref": "#/components/responses/TooManyRequests"},
          "503": {"$ref": "#/components/responses/UpstreamUnavailable"}
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "apiKey": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "opdb_<id>_<secret>",
        "description": "`Authorization: Bearer opdb_<id>_<secret>`. The header `X-Api-Key: opdb_<id>_<secret>` is also accepted."
      }
    },
    "schemas": {
      "Access": {
        "type": "string",
        "enum": ["read", "full"],
        "description": "`read` = SELECT only; `full` = acts as the database owner (DML, DDL, migrations)."
      },
      "RowMode": {
        "type": "string",
        "enum": ["object", "array"],
        "default": "object",
        "description": "`object`: each row is `{column: value}`. `array`: each row is `[value, ...]` ordered like `columns`."
      },
      "Param": {
        "description": "null → NULL; booleans, numbers, strings as-is; objects → JSON text; arrays → Postgres array (or JSON text when the parameter type is json/jsonb). Cast in SQL when the type is ambiguous (`$1::int`).",
        "type": ["null", "boolean", "number", "string", "object", "array"]
      },
      "Statement": {
        "type": "object",
        "required": ["sql"],
        "additionalProperties": false,
        "properties": {
          "sql": {"type": "string", "description": "Exactly one SQL statement with `$1, $2, …` placeholders.", "example": "select * from users where id = $1"},
          "params": {"type": "array", "items": {"$ref": "#/components/schemas/Param"}, "default": [], "example": [42]}
        }
      },
      "QueryRequest": {
        "type": "object",
        "required": ["sql"],
        "additionalProperties": false,
        "properties": {
          "sql": {"type": "string", "description": "Exactly one SQL statement with `$1, $2, …` placeholders. No `;`-separated scripts, no transaction control."},
          "params": {"type": "array", "items": {"$ref": "#/components/schemas/Param"}, "default": []},
          "row_mode": {"$ref": "#/components/schemas/RowMode"},
          "max_rows": {"type": "integer", "minimum": 1, "description": "Lower the key's row cap for this request (cannot raise it)."},
          "timeout_ms": {"type": "integer", "minimum": 1, "description": "Lower the key's statement timeout for this request (cannot raise it)."}
        }
      },
      "TransactionRequest": {
        "type": "object",
        "required": ["statements"],
        "additionalProperties": false,
        "properties": {
          "statements": {"type": "array", "minItems": 1, "maxItems": 100, "items": {"$ref": "#/components/schemas/Statement"}},
          "read_only": {"type": "boolean", "default": false, "description": "Run as a READ ONLY transaction."},
          "row_mode": {"$ref": "#/components/schemas/RowMode"},
          "max_rows": {"type": "integer", "minimum": 1, "description": "Per-statement row cap (can only lower the key's)."},
          "timeout_ms": {"type": "integer", "minimum": 1, "description": "Timeout for the whole transaction (can only lower the key's)."}
        }
      },
      "Column": {
        "type": "object",
        "required": ["name", "type"],
        "properties": {
          "name": {"type": "string", "example": "id"},
          "type": {"type": "string", "description": "Postgres type name, e.g. int4, text, timestamptz, _int4 (int4[]).", "example": "int4"}
        }
      },
      "Notice": {
        "type": "object",
        "description": "A Postgres NOTICE/WARNING raised while running the statement.",
        "properties": {
          "severity": {"type": "string", "example": "NOTICE"},
          "sqlstate": {"type": "string", "example": "00000"},
          "message": {"type": "string", "example": "relation \"t\" already exists, skipping"}
        }
      },
      "StatementResult": {
        "type": "object",
        "required": ["command", "row_count", "columns", "rows", "notices", "warnings"],
        "properties": {
          "command": {"type": "string", "description": "Command tag verb: SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, …", "example": "SELECT"},
          "row_count": {"type": "integer", "description": "Rows returned for SELECT/RETURNING; rows affected for INSERT/UPDATE/DELETE.", "example": 1},
          "columns": {"type": "array", "items": {"$ref": "#/components/schemas/Column"}},
          "rows": {
            "type": "array",
            "description": "Objects in `object` row mode, arrays in `array` row mode. See the type mapping in the docs.",
            "items": {"oneOf": [{"type": "object"}, {"type": "array"}]}
          },
          "notices": {"type": "array", "items": {"$ref": "#/components/schemas/Notice"}},
          "warnings": {"type": "array", "items": {"type": "string"}, "description": "Proxy-side warnings, e.g. renamed duplicate columns."}
        }
      },
      "QueryResponse": {
        "allOf": [
          {"$ref": "#/components/schemas/StatementResult"},
          {"type": "object", "required": ["duration_ms"], "properties": {"duration_ms": {"type": "number", "example": 1.7}}}
        ],
        "example": {
          "command": "SELECT", "row_count": 1,
          "columns": [{"name": "id", "type": "int4"}, {"name": "name", "type": "text"}],
          "rows": [{"id": 42, "name": "Ada"}],
          "notices": [], "warnings": [], "duration_ms": 1.7
        }
      },
      "TransactionResponse": {
        "type": "object",
        "required": ["results", "duration_ms"],
        "properties": {
          "results": {"type": "array", "items": {"$ref": "#/components/schemas/StatementResult"}},
          "duration_ms": {"type": "number", "example": 3.1}
        },
        "example": {
          "results": [
            {"command": "INSERT", "row_count": 1, "columns": [{"name": "id", "type": "int8"}], "rows": [{"id": 7}], "notices": [], "warnings": []},
            {"command": "UPDATE", "row_count": 1, "columns": [], "rows": [], "notices": [], "warnings": []}
          ],
          "duration_ms": 3.1
        }
      },
      "Whoami": {
        "type": "object",
        "required": ["key_id", "database", "access", "limits", "endpoints", "postgres_url"],
        "properties": {
          "key_id": {"type": "string", "example": "k7x2m9q4ab"},
          "label": {"type": "string", "example": "blog prod"},
          "database": {"type": "string", "example": "town"},
          "access": {"$ref": "#/components/schemas/Access"},
          "expires_at": {"type": ["string", "null"], "format": "date-time"},
          "limits": {
            "type": "object",
            "properties": {
              "max_rows": {"type": "integer", "example": 10000},
              "max_response_bytes": {"type": "integer", "example": 16777216},
              "statement_timeout_ms": {"type": "integer", "example": 30000},
              "max_concurrent_requests": {"type": "integer", "example": 8},
              "max_postgres_connections": {"type": "integer", "example": 10}
            }
          },
          "endpoints": {
            "type": "object",
            "properties": {
              "query": {"type": "string", "format": "uri"},
              "transaction": {"type": "string", "format": "uri"},
              "schema": {"type": "string", "format": "uri"},
              "docs": {"type": "string", "format": "uri"}
            }
          },
          "postgres_url": {"type": "string", "description": "postgres:// URL template; substitute your key for `<key>`.", "example": "postgresql://town:<key>@pg.opelly.me:443/town?sslmode=require"}
        }
      },
      "Schema": {
        "type": "object",
        "required": ["database", "schemas", "tables", "enums"],
        "properties": {
          "database": {"type": "string", "example": "town"},
          "schemas": {"type": "array", "items": {"type": "string"}, "example": ["public"]},
          "tables": {"type": "array", "items": {"$ref": "#/components/schemas/Table"}},
          "enums": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "schema": {"type": "string"},
                "name": {"type": "string"},
                "values": {"type": "array", "items": {"type": "string"}}
              }
            },
            "example": [{"schema": "public", "name": "mood", "values": ["sad", "ok", "happy"]}]
          }
        }
      },
      "Table": {
        "type": "object",
        "required": ["schema", "name", "kind", "columns"],
        "properties": {
          "schema": {"type": "string", "example": "public"},
          "name": {"type": "string", "example": "users"},
          "kind": {"type": "string", "enum": ["table", "view", "materialized_view", "partitioned_table", "foreign_table"]},
          "comment": {"type": ["string", "null"]},
          "estimated_rows": {"type": ["integer", "null"], "description": "Planner estimate (approximate)."},
          "columns": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {"type": "string", "example": "id"},
                "type": {"type": "string", "example": "bigint"},
                "nullable": {"type": "boolean", "example": false},
                "default": {"type": ["string", "null"], "example": "nextval('users_id_seq'::regclass)"},
                "comment": {"type": ["string", "null"]}
              }
            }
          },
          "primary_key": {"type": "array", "items": {"type": "string"}, "example": ["id"]},
          "foreign_keys": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {"type": "string"},
                "columns": {"type": "array", "items": {"type": "string"}},
                "references": {
                  "type": "object",
                  "properties": {
                    "schema": {"type": "string"},
                    "table": {"type": "string"},
                    "columns": {"type": "array", "items": {"type": "string"}}
                  }
                }
              }
            }
          },
          "indexes": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {"type": "string"},
                "definition": {"type": "string"},
                "unique": {"type": "boolean"},
                "primary": {"type": "boolean"}
              }
            }
          },
          "privileges": {
            "type": "object",
            "properties": {
              "select": {"type": "boolean"},
              "insert": {"type": "boolean"},
              "update": {"type": "boolean"},
              "delete": {"type": "boolean"}
            }
          }
        }
      },
      "Error": {
        "type": "object",
        "required": ["error"],
        "properties": {
          "error": {
            "type": "object",
            "required": ["code", "message", "docs"],
            "properties": {
              "code": {
                "type": "string",
                "enum": ["invalid_request", "sql_error", "unauthorized", "forbidden", "not_found", "timeout", "result_too_large", "too_many_requests", "upstream_unavailable", "internal"]
              },
              "message": {"type": "string"},
              "sqlstate": {"type": ["string", "null"], "description": "Postgres SQLSTATE, when Postgres produced the error.", "example": "42P01"},
              "detail": {"type": ["string", "null"]},
              "hint": {"type": ["string", "null"]},
              "position": {"type": ["integer", "null"], "description": "1-based character offset into `sql`."},
              "statement_index": {"type": ["integer", "null"], "description": "0-based index of the failing statement (transactions only)."},
              "docs": {"type": "string", "format": "uri", "example": "https://db.opelly.me/#errors"}
            }
          }
        },
        "example": {
          "error": {"code": "sql_error", "message": "relation \"userz\" does not exist", "sqlstate": "42P01", "detail": null, "hint": null, "position": 15, "statement_index": null, "docs": "https://db.opelly.me/#errors"}
        }
      }
    },
    "responses": {
      "BadRequest": {
        "description": "`invalid_request` (bad JSON, multiple statements, transaction control) or `sql_error` (Postgres rejected the statement).",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
      },
      "Unauthorized": {
        "description": "`unauthorized`: missing, unknown, revoked or expired key.",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": {"code": "unauthorized", "message": "missing API key: send Authorization: Bearer opdb_...", "docs": "https://db.opelly.me/#auth"}}}}
      },
      "Forbidden": {
        "description": "`forbidden`: IP not allowed, database disabled, permission denied (42501), or write with a read key (25006).",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": {"code": "forbidden", "message": "cannot execute INSERT in a read-only transaction", "sqlstate": "25006", "docs": "https://db.opelly.me/#errors"}}}}
      },
      "Timeout": {
        "description": "`timeout`: the statement exceeded its timeout and was cancelled.",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
      },
      "ResultTooLarge": {
        "description": "`result_too_large`: result exceeded max_rows or 16 MiB; the transaction was rolled back.",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
      },
      "TooManyRequests": {
        "description": "`too_many_requests`: per-key concurrency limit or auth-failure rate limit. Back off and retry.",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
      },
      "UpstreamUnavailable": {
        "description": "`upstream_unavailable`: Postgres unreachable or connection pool exhausted. Retry with backoff.",
        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
      }
    }
  }
}
