|
| 1 | +"""Hand-rolled reference FastAPI app for the ``Document`` entity from the |
| 2 | +``api-contract-conformance/jsonb/`` corpus. |
| 3 | +
|
| 4 | +The contract under test is the ``field.string @dbColumnType:jsonb`` open bag: |
| 5 | +a posted JSON object must round-trip as an object (never a JSON-encoded |
| 6 | +string). Pared down from ``api_contract_server.py`` (the Author reference) — |
| 7 | +the jsonb scenario only POSTs + GETs by id, so this server implements just |
| 8 | +those verbs. |
| 9 | +
|
| 10 | +Backend: pg8000 (pure-python DB-API; same driver as ``api_contract_server.py``). |
| 11 | +``payload`` is a bare ``JSONB`` column — the open bag holds any JSON value. |
| 12 | +pg8000 auto-decodes jsonb to a native Python object on read; on write the |
| 13 | +value is ``json.dumps``-serialized and bound with a ``::jsonb`` cast. |
| 14 | +""" |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import json |
| 18 | +from contextlib import closing |
| 19 | +from typing import Any |
| 20 | + |
| 21 | +import pg8000.dbapi as pg8000 |
| 22 | +from fastapi import FastAPI, Request, status |
| 23 | +from fastapi.responses import JSONResponse |
| 24 | + |
| 25 | +from .postgres_container import PostgresInfo |
| 26 | + |
| 27 | + |
| 28 | +class DocumentRepository: |
| 29 | + """Direct-JDBC-equivalent repo against the test Postgres instance.""" |
| 30 | + |
| 31 | + def __init__(self, info: PostgresInfo) -> None: |
| 32 | + self._info = info |
| 33 | + |
| 34 | + def create_schema(self) -> None: |
| 35 | + self._exec( |
| 36 | + 'CREATE TABLE IF NOT EXISTS "documents" (' |
| 37 | + " id BIGSERIAL PRIMARY KEY," |
| 38 | + " title VARCHAR(200) NOT NULL," |
| 39 | + " payload JSONB" |
| 40 | + ")" |
| 41 | + ) |
| 42 | + |
| 43 | + def truncate(self) -> None: |
| 44 | + self._exec('TRUNCATE TABLE "documents" RESTART IDENTITY') |
| 45 | + |
| 46 | + def apply_seed(self, rows: list[dict[str, Any]]) -> None: |
| 47 | + """Insert seed rows with explicit ids, then bump the sequence so the |
| 48 | + next implicit-id POST lands at max(id) + 1 (the GET-after-POST |
| 49 | + contract relies on a deterministic id).""" |
| 50 | + self.truncate() |
| 51 | + with closing(self._connect()) as conn: |
| 52 | + cur = conn.cursor() |
| 53 | + try: |
| 54 | + for r in rows: |
| 55 | + cur.execute( |
| 56 | + 'INSERT INTO "documents" (id, title, payload) ' |
| 57 | + "VALUES (%s, %s, %s::jsonb)", |
| 58 | + (int(r["id"]), r["title"], _dump_payload(r.get("payload"))), |
| 59 | + ) |
| 60 | + cur.execute( |
| 61 | + "SELECT setval(pg_get_serial_sequence('documents', 'id'), " |
| 62 | + "COALESCE((SELECT MAX(id) FROM documents), 1))" |
| 63 | + ) |
| 64 | + conn.commit() |
| 65 | + finally: |
| 66 | + cur.close() |
| 67 | + |
| 68 | + def find_by_id(self, ident: int) -> dict[str, Any] | None: |
| 69 | + with closing(self._connect()) as conn: |
| 70 | + cur = conn.cursor() |
| 71 | + try: |
| 72 | + cur.execute( |
| 73 | + 'SELECT id, title, payload FROM "documents" WHERE id = %s', |
| 74 | + (int(ident),), |
| 75 | + ) |
| 76 | + row = cur.fetchone() |
| 77 | + return _row_to_dict(row) if row is not None else None |
| 78 | + finally: |
| 79 | + cur.close() |
| 80 | + |
| 81 | + def create(self, dto: dict[str, Any]) -> dict[str, Any]: |
| 82 | + with closing(self._connect()) as conn: |
| 83 | + cur = conn.cursor() |
| 84 | + try: |
| 85 | + cur.execute( |
| 86 | + 'INSERT INTO "documents" (title, payload) ' |
| 87 | + "VALUES (%s, %s::jsonb) RETURNING id", |
| 88 | + (dto.get("title"), _dump_payload(dto.get("payload"))), |
| 89 | + ) |
| 90 | + new_id = int(cur.fetchone()[0]) |
| 91 | + conn.commit() |
| 92 | + finally: |
| 93 | + cur.close() |
| 94 | + created = self.find_by_id(new_id) |
| 95 | + if created is None: |
| 96 | + raise RuntimeError("create: row vanished between INSERT and SELECT") |
| 97 | + return created |
| 98 | + |
| 99 | + def _connect(self) -> Any: |
| 100 | + return pg8000.connect( |
| 101 | + host=self._info.host, |
| 102 | + port=self._info.port, |
| 103 | + user=self._info.user, |
| 104 | + password=self._info.password, |
| 105 | + database=self._info.database, |
| 106 | + ) |
| 107 | + |
| 108 | + def _exec(self, sql: str) -> None: |
| 109 | + with closing(self._connect()) as conn: |
| 110 | + cur = conn.cursor() |
| 111 | + try: |
| 112 | + cur.execute(sql) |
| 113 | + conn.commit() |
| 114 | + finally: |
| 115 | + cur.close() |
| 116 | + |
| 117 | + |
| 118 | +def make_jsonb_app(repo: DocumentRepository) -> FastAPI: |
| 119 | + app = FastAPI() |
| 120 | + |
| 121 | + @app.exception_handler(404) |
| 122 | + async def _default_404(_req: Request, _exc: Any) -> JSONResponse: |
| 123 | + return JSONResponse(status_code=404, content={"error": "not_found"}) |
| 124 | + |
| 125 | + @app.get("/api/documents/{document_id}") |
| 126 | + def get_document(document_id: int) -> Any: |
| 127 | + row = repo.find_by_id(document_id) |
| 128 | + if row is None: |
| 129 | + return JSONResponse(status_code=404, content={"error": "not_found"}) |
| 130 | + return row |
| 131 | + |
| 132 | + @app.post("/api/documents", status_code=status.HTTP_201_CREATED) |
| 133 | + def create_document(dto: dict[str, Any]) -> Any: |
| 134 | + return repo.create(dto) |
| 135 | + |
| 136 | + return app |
| 137 | + |
| 138 | + |
| 139 | +def _dump_payload(value: Any) -> Any: |
| 140 | + """jsonb bind: a dict/list is ``json.dumps``-serialized for the ``::jsonb`` |
| 141 | + cast; ``None`` stays ``None`` (SQL NULL); a pre-serialized string passes |
| 142 | + through.""" |
| 143 | + if value is None: |
| 144 | + return None |
| 145 | + if isinstance(value, str): |
| 146 | + return value |
| 147 | + return json.dumps(value) |
| 148 | + |
| 149 | + |
| 150 | +def _row_to_dict(row: Any) -> dict[str, Any]: |
| 151 | + ident, title, payload = row |
| 152 | + # pg8000 auto-decodes jsonb → native Python object; if a driver returned raw |
| 153 | + # text we'd parse it, but the open-bag contract is "parsed value", so a str |
| 154 | + # that is JSON is decoded here defensively. |
| 155 | + if isinstance(payload, str): |
| 156 | + try: |
| 157 | + payload = json.loads(payload) |
| 158 | + except json.JSONDecodeError: |
| 159 | + pass |
| 160 | + return {"id": int(ident), "title": title, "payload": payload} |
0 commit comments