v0.166.0
  1"""Cluster-level database management — CREATE/DROP DATABASE and friends.
  2
  3Everything else in `plain.postgres` operates *inside* the database that
  4`POSTGRES_URL` points at. This module is the exception: it operates on the
  5cluster, which means it needs a role with `CREATEDB` and a connection to the
  6`postgres` maintenance database.
  7
  8That makes it a **development and test** capability, not a production one —
  9most managed Postgres providers hand your app a role that owns exactly one
 10database and cannot create more. Nothing on the runtime path imports this
 11module, and `tests/internal/test_databases_not_on_runtime_path.py` enforces
 12that.
 13
 14This module provides mechanism only. Policy — whether to prompt before
 15clobbering, how to name databases, what to store in a comment, when to fork
 16via `TEMPLATE` versus `pg_dump` — belongs to the caller.
 17"""
 18
 19from collections.abc import Generator
 20from contextlib import contextmanager
 21from dataclasses import dataclass
 22
 23import psycopg
 24from plain.postgres.database_url import DatabaseConfig
 25from plain.postgres.sources import build_connection_params
 26from psycopg import sql
 27
 28__all__ = [
 29    "DatabaseInfo",
 30    "connection_count",
 31    "create_database",
 32    "database_exists",
 33    "drop_database",
 34    "get_database_comment",
 35    "list_databases",
 36    "maintenance_cursor",
 37    "set_database_comment",
 38    "terminate_connections",
 39]
 40
 41
 42@dataclass(frozen=True)
 43class DatabaseInfo:
 44    """A row from `list_databases()`."""
 45
 46    name: str
 47    comment: str | None
 48    size_bytes: int
 49
 50
 51@contextmanager
 52def maintenance_cursor(config: DatabaseConfig) -> Generator[psycopg.Cursor]:
 53    """Yield a cursor on the `postgres` maintenance database.
 54
 55    CREATE DATABASE / DROP DATABASE can't run against the target database
 56    itself and can't run inside a transaction — so connect to `postgres`
 57    with autocommit and use a raw psycopg cursor (no wrapper machinery,
 58    no pool).
 59    """
 60    maintenance_config: DatabaseConfig = {**config, "DATABASE": "postgres"}
 61    params = build_connection_params(maintenance_config)
 62    with psycopg.connect(**params, autocommit=True) as conn, conn.cursor() as cursor:
 63        yield cursor
 64
 65
 66def create_database(
 67    config: DatabaseConfig, *, name: str, template: str | None = None
 68) -> None:
 69    """CREATE DATABASE, optionally copying an existing one via TEMPLATE.
 70
 71    `TEMPLATE` is a file-level copy, so it's near-instant regardless of data
 72    size — but Postgres requires the template database to have no other
 73    connections. Call `terminate_connections()` first, or fall back to
 74    dump/restore, if the source may be in use.
 75
 76    Raises `psycopg.errors.DuplicateDatabase` if `name` already exists.
 77    """
 78    if template:
 79        statement = sql.SQL("CREATE DATABASE {} TEMPLATE {}").format(
 80            sql.Identifier(name), sql.Identifier(template)
 81        )
 82    else:
 83        statement = sql.SQL("CREATE DATABASE {}").format(sql.Identifier(name))
 84
 85    with maintenance_cursor(config) as cursor:
 86        cursor.execute(statement)
 87
 88
 89def drop_database(config: DatabaseConfig, *, name: str, force: bool = False) -> None:
 90    """DROP DATABASE IF EXISTS.
 91
 92    `force` adds `WITH (FORCE)`, which terminates other connections to the
 93    database instead of failing.
 94    """
 95    if force:
 96        statement = sql.SQL("DROP DATABASE IF EXISTS {} WITH (FORCE)").format(
 97            sql.Identifier(name)
 98        )
 99    else:
100        statement = sql.SQL("DROP DATABASE IF EXISTS {}").format(sql.Identifier(name))
101
102    with maintenance_cursor(config) as cursor:
103        cursor.execute(statement)
104
105
106def database_exists(config: DatabaseConfig, *, name: str) -> bool:
107    with maintenance_cursor(config) as cursor:
108        cursor.execute("SELECT 1 FROM pg_database WHERE datname = %s", [name])
109        return cursor.fetchone() is not None
110
111
112def list_databases(config: DatabaseConfig) -> list[DatabaseInfo]:
113    """List every user database on the cluster, ordered by name.
114
115    Postgres' own `postgres`, `template0` and `template1` are always excluded —
116    they're cluster furniture, never something a caller is managing. Any finer
117    selection is the caller's job: name-pattern filtering in SQL can't express
118    the ownership rules callers actually have (see how plain-dev matches on
119    metadata as well as names).
120    """
121    with maintenance_cursor(config) as cursor:
122        cursor.execute(
123            "SELECT datname, shobj_description(oid, 'pg_database'), "
124            "pg_database_size(datname) "
125            "FROM pg_database "
126            "WHERE NOT datistemplate AND datname <> 'postgres' "
127            "ORDER BY datname"
128        )
129        rows = cursor.fetchall()
130
131    return [
132        DatabaseInfo(name=name, comment=comment, size_bytes=size)
133        for name, comment, size in rows
134    ]
135
136
137def get_database_comment(config: DatabaseConfig, *, name: str) -> str | None:
138    """Return the database's COMMENT as raw text, or None if unset.
139
140    Callers that store structured data are responsible for their own encoding.
141    """
142    with maintenance_cursor(config) as cursor:
143        cursor.execute(
144            "SELECT shobj_description(oid, 'pg_database') "
145            "FROM pg_database WHERE datname = %s",
146            [name],
147        )
148        row = cursor.fetchone()
149
150    return row[0] if row else None
151
152
153def set_database_comment(config: DatabaseConfig, *, name: str, comment: str) -> None:
154    """Set the database's COMMENT to raw text."""
155    with maintenance_cursor(config) as cursor:
156        cursor.execute(
157            sql.SQL("COMMENT ON DATABASE {} IS {}").format(
158                sql.Identifier(name), sql.Literal(comment)
159            )
160        )
161
162
163def connection_count(config: DatabaseConfig, *, name: str) -> int:
164    """Count backends currently connected to `name`, excluding our own."""
165    with maintenance_cursor(config) as cursor:
166        cursor.execute(
167            "SELECT count(*) FROM pg_stat_activity "
168            "WHERE datname = %s AND pid <> pg_backend_pid()",
169            [name],
170        )
171        row = cursor.fetchone()
172        return row[0] if row else 0
173
174
175def terminate_connections(config: DatabaseConfig, *, name: str) -> None:
176    """Terminate every other backend connected to `name`.
177
178    Needed before `CREATE DATABASE … TEMPLATE`, which requires the source to
179    be idle.
180    """
181    with maintenance_cursor(config) as cursor:
182        cursor.execute(
183            "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
184            "WHERE datname = %s AND pid <> pg_backend_pid()",
185            [name],
186        )