Spaces:
Running

File size: 3,734 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""One-time database bootstrap, run as a superuser (docker init, tests, ``python -m``).



Creates the two roles the app uses:



* ``workpilot_owner``: owns the schema and every table; runs migrations only.

* ``workpilot_app``: the runtime role. Not an owner, no BYPASSRLS, so RLS always applies.

"""

from __future__ import annotations

import argparse

import psycopg
from psycopg import sql

OWNER = "workpilot_owner"
APP = "workpilot_app"


def role_url(superuser_url: str, user: str, password: str, db_name: str) -> str:
    """SQLAlchemy (psycopg) URL for ``user`` on ``db_name``, on the same server as

    ``superuser_url``. Handles Unix-socket servers (e.g. pgserver on Linux/macOS, whose host

    is a socket directory): the directory goes in the query string, not the authority."""
    from psycopg.conninfo import conninfo_to_dict

    info = conninfo_to_dict(superuser_url)
    host, port = str(info.get("host") or "127.0.0.1"), str(info.get("port") or "5432")
    if host.startswith("/"):
        return f"postgresql+psycopg://{user}:{password}@/{db_name}?host={host}&port={port}"
    return f"postgresql+psycopg://{user}:{password}@{host}:{port}/{db_name}"


def bootstrap(superuser_url: str, db_name: str, owner_password: str, app_password: str) -> None:
    with psycopg.connect(superuser_url, autocommit=True) as conn:
        for role, pw, extra in (
            (OWNER, owner_password, sql.SQL("")),
            (APP, app_password, sql.SQL(" NOBYPASSRLS NOSUPERUSER")),
        ):
            exists = conn.execute("SELECT 1 FROM pg_roles WHERE rolname=%s", (role,)).fetchone()
            verb = sql.SQL("ALTER") if exists else sql.SQL("CREATE")
            conn.execute(
                sql.SQL("{} ROLE {} LOGIN PASSWORD {}{}").format(
                    verb, sql.Identifier(role), sql.Literal(pw), extra
                )
            )
        # The app database, plus DBOS's system database for durable workflows (Phase 5).
        for name in (db_name, f"{db_name}_dbos_sys"):
            if not conn.execute("SELECT 1 FROM pg_database WHERE datname=%s", (name,)).fetchone():
                conn.execute(
                    sql.SQL("CREATE DATABASE {} OWNER {}").format(
                        sql.Identifier(name), sql.Identifier(OWNER)
                    )
                )

    db_url = psycopg.conninfo.make_conninfo(superuser_url, dbname=db_name)
    with psycopg.connect(db_url, autocommit=True) as conn:
        conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
        conn.execute(sql.SQL("ALTER SCHEMA public OWNER TO {}").format(sql.Identifier(OWNER)))
        conn.execute(sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(sql.Identifier(APP)))
        conn.execute(
            sql.SQL(
                "ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA public "
                "GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {}"
            ).format(sql.Identifier(OWNER), sql.Identifier(APP))
        )
        conn.execute(
            sql.SQL(
                "ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA public "
                "GRANT USAGE, SELECT ON SEQUENCES TO {}"
            ).format(sql.Identifier(OWNER), sql.Identifier(APP))
        )


def main() -> None:
    p = argparse.ArgumentParser(description="Create WorkPilot roles and database")
    p.add_argument("--superuser-url", required=True)
    p.add_argument("--db", default="workpilot")
    p.add_argument("--owner-password", required=True)
    p.add_argument("--app-password", required=True)
    a = p.parse_args()
    bootstrap(a.superuser_url, a.db, a.owner_password, a.app_password)


if __name__ == "__main__":
    main()