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): add common person db connection util (#65841)

Zach Browna5de33f58657
diff --git a/bin/start b/bin/start
index f15208877d7e..833d153f0c1e 100755
--- a/bin/start
+++ b/bin/start
@@ -123,6 +123,10 @@ export PERSONS_READONLY_DATABASE_URL=${PERSONS_READONLY_DATABASE_URL:-postgres:/
export PERSONS_WRITE_DATABASE_URL=${PERSONS_WRITE_DATABASE_URL:-$PERSONS_DATABASE_URL}
# nosemgrep: env-default-belongs-in-env-development -- bash variable ref in default
export PERSONS_READ_DATABASE_URL=${PERSONS_READ_DATABASE_URL:-$PERSONS_READONLY_DATABASE_URL}
+# nosemgrep: env-default-belongs-in-env-development -- bash variable ref in default
+export PERSONS_DB_WRITER_URL=${PERSONS_DB_WRITER_URL:-$PERSONS_DATABASE_URL}
+# nosemgrep: env-default-belongs-in-env-development -- bash variable ref in default
+export PERSONS_DB_READER_URL=${PERSONS_DB_READER_URL:-$PERSONS_READONLY_DATABASE_URL}
export BEHAVIORAL_COHORTS_DATABASE_URL=${BEHAVIORAL_COHORTS_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/behavioral_cohorts}
export FLAGS_READ_STORE_DATABASE_URL=${FLAGS_READ_STORE_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/flags_read_store}
export CYCLOTRON_DATABASE_URL=${CYCLOTRON_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/cyclotron}
diff --git a/docker-compose.base.yml b/docker-compose.base.yml
index 650e28e18d20..bec587dab433 100644
--- a/docker-compose.base.yml
+++ b/docker-compose.base.yml
@@ -347,6 +347,10 @@ services:
DEPLOYMENT: hobby
CDP_API_URL: 'http://plugins:6738'
FLAGS_REDIS_ENABLED: false
+ # Off-ORM persons_db util (posthog/persons_db.py). Hobby keeps persons in
+ # the main posthog DB, so both point there.
+ PERSONS_DB_WRITER_URL: 'postgres://posthog:posthog@db:5432/posthog'
+ PERSONS_DB_READER_URL: 'postgres://posthog:posthog@db:5432/posthog'
web:
<<: *worker
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 57d4c4e8cb38..60910631da81 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -245,6 +245,22 @@ def _django_db_setup(django_db_keepdb, django_db_blocker):
settings.DATABASES["persons_db_writer"]["NAME"] = test_persons_db_name
settings.DATABASES["persons_db_reader"]["NAME"] = test_persons_db_name
+ # Point the off-ORM persons_db util (posthog/persons_db.py) at the test persons DB.
+ # It reads only PERSONS_DB_{WRITER,READER}_URL from the environment, never Django
+ # settings, so the test database has to be exposed to it via those env vars.
+ _persons_db = settings.DATABASES["persons_db_writer"]
+ _persons_user = quote_plus(_persons_db.get("USER") or "")
+ _persons_password = f":{quote_plus(_persons_db['PASSWORD'])}" if _persons_db.get("PASSWORD") else ""
+ # HOST/PORT can be empty strings in Django's config (empty HOST means Unix socket);
+ # fall back to localhost:5432 so the URL is always well-formed for psycopg.
+ _persons_host = _persons_db.get("HOST") or "localhost"
+ _persons_port = _persons_db.get("PORT") or "5432"
+ _persons_db_url = (
+ f"postgres://{_persons_user}{_persons_password}@{_persons_host}:{_persons_port}/{test_persons_db_name}"
+ )
+ os.environ["PERSONS_DB_WRITER_URL"] = _persons_db_url
+ os.environ["PERSONS_DB_READER_URL"] = _persons_db_url
+
# Update product database NAMEs to use test-prefixed names
from posthog.product_db_config import load_product_db_routes
diff --git a/posthog/persons_db.py b/posthog/persons_db.py
new file mode 100644
index 000000000000..35987565438b
--- /dev/null
+++ b/posthog/persons_db.py
@@ -0,0 +1,59 @@
+"""Direct, off-ORM connections to the persons database.
+
+Cold admin/utility paths — Temporal activities, management commands, Dagster jobs —
+that are too bespoke for the personhog gRPC client connect to the persons database
+through this module. It returns raw psycopg connections that do **not** go through
+Django's ORM, connection pool, or database router, so the persons database can be
+dropped from Django's ``DATABASES`` without affecting these paths.
+
+The connection URL is sourced only from the environment:
+
+- ``PERSONS_DB_WRITER_URL`` — primary read/write endpoint
+- ``PERSONS_DB_READER_URL`` — read replica, falling back to the writer URL
+
+Production injects these via the Helm charts and the test suite sets them in
+``conftest``; only local development relies on the localhost default below.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager, contextmanager
+from typing import Any
+
+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"
+
+
+def persons_db_url(*, writer: bool = True) -> str:
+ """Resolve the persons-database connection URL from the environment.
+
+ 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.
+ """
+ if writer:
+ return os.getenv("PERSONS_DB_WRITER_URL") or LOCAL_DEV_PERSONS_DB_URL
+ return os.getenv("PERSONS_DB_READER_URL") or os.getenv("PERSONS_DB_WRITER_URL") or LOCAL_DEV_PERSONS_DB_URL
+
+
+@contextmanager
+def persons_db_connection(*, writer: bool = True, autocommit: bool = False) -> Iterator[psycopg.Connection[Any]]:
+ """Synchronous raw psycopg connection to the persons database (context-managed)."""
+ with psycopg.connect(persons_db_url(writer=writer), autocommit=autocommit) as conn:
+ yield conn
+
+
+@asynccontextmanager
+async def persons_db_aconnection(
+ *, writer: bool = True, autocommit: bool = False
+) -> AsyncIterator[psycopg.AsyncConnection[Any]]:
+ """Asynchronous raw psycopg connection to the persons database (context-managed)."""
+ async with await psycopg.AsyncConnection.connect(persons_db_url(writer=writer), autocommit=autocommit) as conn:
+ yield conn
diff --git a/posthog/temporal/sync_person_distinct_ids/activities.py b/posthog/temporal/sync_person_distinct_ids/activities.py
index 54678f2ced62..b69650a4bc09 100644
--- a/posthog/temporal/sync_person_distinct_ids/activities.py
+++ b/posthog/temporal/sync_person_distinct_ids/activities.py
@@ -1,45 +1,18 @@
-import os
import json
import dataclasses
-from urllib.parse import quote_plus
-from django.conf import settings
-
-import psycopg
import temporalio.activity
from psycopg import sql
from structlog import get_logger
from posthog.models.person.util import create_person, create_person_distinct_id
+from posthog.persons_db import persons_db_aconnection
from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.common.heartbeat import Heartbeater
LOGGER = get_logger(__name__)
-def get_persons_database_url() -> str:
- """Get the connection URL for the persons database reader.
-
- Falls back to DATABASE_URL for hobby deployments without separate persons DB.
- """
- url = os.getenv("PERSONS_DB_READER_URL")
- if url:
- return url
-
- if "persons_db_reader" in settings.DATABASES:
- db = settings.DATABASES["persons_db_reader"]
- user = db.get("USER", "")
- password = db.get("PASSWORD", "")
- host = db.get("HOST", "localhost")
- port = db.get("PORT", "5432")
- name = db.get("NAME", "")
- if password:
- return f"postgres://{quote_plus(user)}:{quote_plus(password)}@{host}:{port}/{name}"
- return f"postgres://{quote_plus(user)}@{host}:{port}/{name}"
-
- return settings.DATABASE_URL
-
-
@dataclasses.dataclass
class OrphanedPerson:
"""Represents an orphaned person from ClickHouse."""
@@ -197,9 +170,7 @@ async def lookup_pg_distinct_ids(inputs: LookupPgDistinctIdsInputs) -> LookupPgD
"""
params = [inputs.team_id, inputs.person_uuids]
- persons_db_url = get_persons_database_url()
- conn = await psycopg.AsyncConnection.connect(persons_db_url)
- async with conn:
+ async with persons_db_aconnection(writer=False) as conn:
# Set statement timeout to avoid long-running queries
timeout_stmt = sql.SQL("SET statement_timeout = {}").format(
sql.Literal(f"{inputs.pg_statement_timeout_seconds}s")
@@ -246,8 +217,7 @@ async def lookup_pg_distinct_ids(inputs: LookupPgDistinctIdsInputs) -> LookupPgD
"""
params = [inputs.team_id, persons_not_found]
- conn = await psycopg.AsyncConnection.connect(persons_db_url)
- async with conn:
+ async with persons_db_aconnection(writer=False) as conn:
timeout_stmt = sql.SQL("SET statement_timeout = {}").format(
sql.Literal(f"{inputs.pg_statement_timeout_seconds}s")
)
diff --git a/posthog/test/test_persons_db.py b/posthog/test/test_persons_db.py
new file mode 100644
index 000000000000..c3e7c9038e9e
--- /dev/null
+++ b/posthog/test/test_persons_db.py
@@ -0,0 +1,53 @@
+import os
+
+import pytest
+from unittest.mock import patch
+
+from posthog.persons_db import LOCAL_DEV_PERSONS_DB_URL, persons_db_aconnection, persons_db_connection, persons_db_url
+
+
+class TestPersonsDbUrl:
+ def test_writer_uses_writer_env(self):
+ with patch.dict(os.environ, {"PERSONS_DB_WRITER_URL": "postgres://w@host:5432/db"}):
+ assert persons_db_url(writer=True) == "postgres://w@host:5432/db"
+
+ def test_reader_uses_reader_env(self):
+ with patch.dict(os.environ, {"PERSONS_DB_READER_URL": "postgres://r@host:5432/db"}):
+ assert persons_db_url(writer=False) == "postgres://r@host:5432/db"
+
+ def test_reader_falls_back_to_writer_when_no_reader_env(self):
+ with patch.dict(os.environ, {"PERSONS_DB_WRITER_URL": "postgres://w@host:5432/db"}):
+ os.environ.pop("PERSONS_DB_READER_URL", None)
+ assert persons_db_url(writer=False) == "postgres://w@host:5432/db"
+
+ def test_local_default_when_unset(self):
+ with patch.dict(os.environ):
+ os.environ.pop("PERSONS_DB_WRITER_URL", None)
+ os.environ.pop("PERSONS_DB_READER_URL", None)
+ assert persons_db_url(writer=True) == LOCAL_DEV_PERSONS_DB_URL
+ assert persons_db_url(writer=False) == LOCAL_DEV_PERSONS_DB_URL
+
+
[email protected]_db(databases=["persons_db_writer", "persons_db_reader"])
+def test_sync_connection_targets_persons_db():
+ with persons_db_connection() as conn, conn.cursor() as cursor:
+ cursor.execute("SELECT current_database()")
+ row = cursor.fetchone()
+ assert row is not None
+ assert row[0].endswith("_persons")
+
+
[email protected]_db(databases=["persons_db_writer", "persons_db_reader"])
+def test_sync_reader_connection_works():
+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:
+ cursor.execute("SELECT 1")
+ assert cursor.fetchone() == (1,)
+
+
[email protected]_db(databases=["persons_db_writer", "persons_db_reader"])
+async def test_async_connection_targets_persons_db():
+ async with persons_db_aconnection() as conn, conn.cursor() as cursor:
+ await cursor.execute("SELECT current_database()")
+ row = await cursor.fetchone()
+ assert row is not None
+ assert row[0].endswith("_persons")