Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(django): decouple persons migrations from django settings (#65947)

Zach Brown343d54499047
diff --git a/bin/migrate b/bin/migrate
index 6871970e8cca..1d32a1eab5e7 100755
--- a/bin/migrate
+++ b/bin/migrate
@@ -166,10 +166,9 @@ if run_scope "postgres"; then
fi
fi
-# Persons migrations via Django management command.
-# Hobby: runs against default DB, skipping partitioning migrations.
-# Local dev (DEBUG=1): runs against persons_db_writer, creating the database
-# if needed and applying all migrations including partitioning.
+# Persons migrations via Django management command (connects to PERSONS_DB_WRITER_URL).
+# Hobby: skips partitioning migrations (persons live in the main DB).
+# Local dev (DEBUG=1): creates the persons database if needed and applies all migrations.
# Production: skipped — persons migrations are handled by the sqlx-migrate K8s job.
if run_scope "persons"; then
if [ "${DEPLOYMENT:-}" = "hobby" ]; then
@@ -181,7 +180,7 @@ if run_scope "persons"; then
fi
elif [ "${DEBUG:-0}" = "1" ]; then
echo "Running persons migrations via Django management command..."
- python manage.py apply_persons_migrations --database=persons_db_writer --ensure-database
+ python manage.py apply_persons_migrations --ensure-database
if [ $? -ne 0 ]; then
echo "Error in apply_persons_migrations, exiting."
exit 1
diff --git a/posthog/management/commands/apply_persons_migrations.py b/posthog/management/commands/apply_persons_migrations.py
index 740e699735b2..b276912948ac 100644
--- a/posthog/management/commands/apply_persons_migrations.py
+++ b/posthog/management/commands/apply_persons_migrations.py
@@ -1,9 +1,9 @@
"""Apply persons SQL migrations.
-Reads SQL migration files from rust/persons_migrations/ and executes them
-against the specified database. Supports both hobby deploys (default DB,
-skipping partitioning migrations) and local dev / production (separate
-persons DB with all migrations applied).
+Reads SQL migration files from rust/persons_migrations/ and executes them against the
+persons database identified by PERSONS_DB_WRITER_URL. Hobby deploys keep persons in the
+main database and skip the partitioning migrations (via --hobby); local dev and
+production apply all migrations.
Tracks applied migrations in a _persons_migrations_applied table so each
migration is only executed once. Also bridges the sqlx _sqlx_migrations
@@ -17,10 +17,12 @@ from pathlib import Path
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
-from django.db import connections, transaction
import psycopg
from psycopg import sql
+from psycopg.conninfo import conninfo_to_dict
+
+from posthog.persons_db import persons_db_connection, persons_db_url
# Migrations that must be skipped on hobby deploys.
# These partition the posthog_person table, which is only needed in production
@@ -72,36 +74,34 @@ def _record_migration(cursor, filename: str) -> None:
cursor.execute(f"INSERT INTO {TRACKING_TABLE} (filename) VALUES (%s)", [filename])
-def _ensure_database_exists(db_alias: str) -> None:
- """Create the database for db_alias if it doesn't already exist.
+def _ensure_database_exists(persons_url: str) -> None:
+ """Create the persons database named in ``persons_url`` if it doesn't already exist.
- Connects to the 'postgres' maintenance database using the credentials
- from settings.DATABASES[db_alias] and issues CREATE DATABASE.
+ Connects to the 'postgres' maintenance database on the same host (reusing the
+ credentials from the URL, only overriding the database name) and issues CREATE
+ DATABASE. Used for local dev bootstrap.
"""
- db_settings = settings.DATABASES[db_alias]
- target_db = db_settings["NAME"]
+ params = conninfo_to_dict(persons_url)
+ dbname = params.get("dbname")
+ if not dbname:
+ raise RuntimeError("Persons database URL has no database name; cannot ensure it exists.")
+ # conninfo_to_dict types values as ``str | int``; identifiers must be ``str``.
+ target_db = str(dbname)
try:
- with psycopg.connect(
- dbname="postgres",
- host=db_settings.get("HOST") or "localhost",
- port=int(db_settings.get("PORT") or 5432),
- user=db_settings.get("USER") or "posthog",
- password=db_settings.get("PASSWORD") or "posthog",
- autocommit=True,
- ) as conn:
+ with psycopg.connect(persons_url, dbname="postgres", autocommit=True) as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (target_db,))
if cur.fetchone():
return
cur.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(target_db)))
- owner = db_settings.get("USER")
+ owner = params.get("user")
if owner:
cur.execute(
sql.SQL("GRANT ALL PRIVILEGES ON DATABASE {} TO {}").format(
sql.Identifier(target_db),
- sql.Identifier(owner),
+ sql.Identifier(str(owner)),
)
)
except psycopg.OperationalError as exc:
@@ -125,12 +125,6 @@ class Command(BaseCommand):
action="store_true",
help="Print which migrations would be applied without executing them.",
)
- parser.add_argument(
- "--database",
- type=str,
- default="default",
- help="Django database alias to run migrations against (default: 'default').",
- )
parser.add_argument(
"--hobby",
action="store_true",
@@ -143,12 +137,12 @@ class Command(BaseCommand):
)
def handle(self, *args, **options):
- db_alias = options["database"]
hobby = options["hobby"]
dry_run = options["dry_run"]
+ persons_url = persons_db_url(writer=True)
if options["ensure_database"] and not dry_run:
- _ensure_database_exists(db_alias)
+ _ensure_database_exists(persons_url)
migrations_path = self._resolve_migrations_dir(options["migrations_dir"])
sql_files = sorted(f for f in migrations_path.iterdir() if f.suffix == ".sql")
@@ -160,8 +154,7 @@ class Command(BaseCommand):
skipped_count = 0
already_applied_count = 0
- conn = connections[db_alias]
- with conn.cursor() as cursor:
+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:
if not dry_run:
_ensure_tracking_table(cursor)
already_applied = _get_applied_migrations(cursor) if not dry_run else set()
@@ -197,7 +190,7 @@ class Command(BaseCommand):
sql_content = sql_file.read_text()
self.stdout.write(f" Applying {sql_file.name}...")
- with transaction.atomic(using=db_alias):
+ with conn.transaction():
cursor.execute(sql_content)
_record_migration(cursor, sql_file.name)
applied_count += 1
diff --git a/posthog/management/commands/devbox_migrate.py b/posthog/management/commands/devbox_migrate.py
index 211f8a93b21b..44f65a24d6c8 100644
--- a/posthog/management/commands/devbox_migrate.py
+++ b/posthog/management/commands/devbox_migrate.py
@@ -10,7 +10,7 @@ class Command(BaseCommand):
call_command("migrate", "--noinput")
self.stdout.write("Running persons migrations...")
- call_command("apply_persons_migrations", "--database=persons_db_writer", "--ensure-database")
+ call_command("apply_persons_migrations", "--ensure-database")
self.stdout.write("Running ClickHouse migrations...")
call_command("migrate_clickhouse")
diff --git a/posthog/management/commands/sandbox_migrate.py b/posthog/management/commands/sandbox_migrate.py
index 0c3ecb73f405..11c2dba9bf10 100644
--- a/posthog/management/commands/sandbox_migrate.py
+++ b/posthog/management/commands/sandbox_migrate.py
@@ -39,7 +39,7 @@ class Command(BaseCommand):
),
(
"persons",
- lambda: call_command("apply_persons_migrations", "--database=persons_db_writer", "--ensure-database"),
+ lambda: call_command("apply_persons_migrations", "--ensure-database"),
),
("ClickHouse", lambda: call_command("migrate_clickhouse")),
]
diff --git a/posthog/persons_db.py b/posthog/persons_db.py
index 35987565438b..deafd7573c9c 100644
--- a/posthog/persons_db.py
+++ b/posthog/persons_db.py
@@ -26,8 +26,13 @@ import psycopg
# Local-development fallback only. Every deployment that runs this code injects
# PERSONS_DB_{WRITER,READER}_URL (charts for prod, conftest for tests), so this is
-# used solely when a developer has neither set locally.
-LOCAL_DEV_PERSONS_DB_URL = "postgres://posthog:posthog@localhost:5432/posthog_persons"
+# used solely when a developer has neither set locally. The host/credentials mirror
+# the Django persons-DB config (posthog/settings/data_stores.py), so the fallback
+# resolves to the same local database whether or not Django is in the loop.
+LOCAL_DEV_PERSONS_DB_URL = (
+ f"postgres://{os.getenv('PGUSER', 'posthog')}:{os.getenv('PGPASSWORD', 'posthog')}"
+ f"@{os.getenv('PGHOST', 'db')}:{os.getenv('PGPORT', '5432')}/posthog_persons"
+)
def persons_db_url(*, writer: bool = True) -> str:
@@ -35,8 +40,8 @@ def persons_db_url(*, writer: bool = True) -> str:
The writer uses ``PERSONS_DB_WRITER_URL``; the reader uses
``PERSONS_DB_READER_URL`` and falls back to the writer URL when no dedicated
- reader endpoint is configured (mirroring production). Falls back to a localhost
- default only when nothing is set, i.e. local development.
+ reader endpoint is configured (mirroring production). Falls back to a local
+ default (derived from the PG* env vars) only when nothing is set, i.e. local development.
"""
if writer:
return os.getenv("PERSONS_DB_WRITER_URL") or LOCAL_DEV_PERSONS_DB_URL