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(demo_data): create persons demo data w/ raw sql (#66205)

Nick Best9863cb282a58
diff --git a/posthog/demo/legacy/data_generator.py b/posthog/demo/legacy/data_generator.py
index 856d744b2f6c..36d8e9c5b470 100644
--- a/posthog/demo/legacy/data_generator.py
+++ b/posthog/demo/legacy/data_generator.py
@@ -1,7 +1,13 @@
from uuid import uuid4
-from posthog.models import Person, PersonDistinctId, Team
+from django.conf import settings
+
+from psycopg import sql
+from psycopg.types.json import Jsonb
+
+from posthog.models import Person, Team
from posthog.models.utils import UUIDT
+from posthog.persons_db import persons_db_connection
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
@@ -30,13 +36,31 @@ class DataGenerator:
def create_people(self):
self.people = [self.make_person(i) for i in range(self.n_people)]
self.distinct_ids = [str(UUIDT()) for _ in self.people]
- self.people = Person.objects.bulk_create(self.people) # nosemgrep: no-direct-persons-db-orm
- pids = [
- PersonDistinctId(team=self.team, person=person, distinct_id=distinct_id)
- for person, distinct_id in zip(self.people, self.distinct_ids)
- ]
- PersonDistinctId.objects.bulk_create(pids) # nosemgrep: no-direct-persons-db-orm
+ with persons_db_connection(writer=True) as conn:
+ with conn.cursor() as cur:
+ insert_query = sql.SQL(
+ "INSERT INTO {} (team_id, uuid, properties, is_identified, created_at) "
+ "VALUES (%s, %s, %s, %s, now()) RETURNING id"
+ ).format(sql.Identifier(settings.PERSON_TABLE_NAME))
+ for person in self.people:
+ cur.execute(
+ insert_query,
+ (self.team.pk, str(person.uuid), Jsonb(person.properties), person.is_identified),
+ )
+ row = cur.fetchone()
+ assert row is not None
+ person.pk = row[0]
+
+ cur.executemany(
+ "INSERT INTO posthog_persondistinctid (team_id, distinct_id, person_id, version) "
+ "VALUES (%s, %s, %s, %s)",
+ [
+ (self.team.pk, distinct_id, person.pk, 0)
+ for person, distinct_id in zip(self.people, self.distinct_ids)
+ ],
+ )
+
from posthog.models.person.util import create_person, create_person_distinct_id
for person in self.people:
@@ -47,8 +71,8 @@ class DataGenerator:
is_identified=person.is_identified,
version=0,
)
- for pid in pids:
- create_person_distinct_id(pid.team.pk, pid.distinct_id, str(pid.person.uuid)) # use dummy number for id
+ for person, distinct_id in zip(self.people, self.distinct_ids):
+ create_person_distinct_id(person.team.pk, distinct_id, str(person.uuid))
def make_person(self, index):
return Person(team=self.team, properties={"is_demo": True})
diff --git a/posthog/demo/matrix/manager.py b/posthog/demo/matrix/manager.py
index 151254f6562e..a99864c8a8d3 100644
--- a/posthog/demo/matrix/manager.py
+++ b/posthog/demo/matrix/manager.py
@@ -1,26 +1,22 @@
# ruff: noqa: T201 allow print statements
-import json
import datetime as dt
from time import sleep
from typing import Any, Literal, cast
from django.conf import settings
from django.core import exceptions
-from django.db import IntegrityError, transaction
-
-from posthog.clickhouse.client import query_with_columns, sync_execute
-from posthog.demo.matrix.taxonomy_inference import infer_taxonomy_for_team
-from posthog.models import (
- Group,
- GroupTypeMapping,
- Organization,
- OrganizationMembership,
- Person,
- PersonDistinctId,
- Team,
- User,
+from django.db import transaction
+
+from posthog.clickhouse.client import sync_execute
+from posthog.demo.matrix.persons_db_sync import (
+ bulk_create_group_type_mappings,
+ copy_group_type_mappings,
+ delete_group_type_mappings,
+ sync_persons_to_postgres,
)
+from posthog.demo.matrix.taxonomy_inference import infer_taxonomy_for_team
+from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.utils import UUIDT, generate_random_token_project
from products.cohorts.backend.models.cohort import Cohort
@@ -166,18 +162,16 @@ class MatrixManager:
if self.print_steps:
print(f"Saving simulated data...")
sim_persons = self.matrix.people
- bulk_group_type_mappings = []
+ group_type_mapping_dicts: list[dict[str, Any]] = []
if len(self.matrix.groups.keys()) + self.matrix.group_type_index_offset > 5:
raise ValueError("Too many group types! The maximum for a project is 5.")
for group_type_index, (group_type, groups) in enumerate(self.matrix.groups.items()):
group_type_index += self.matrix.group_type_index_offset # Adjust
- bulk_group_type_mappings.append(
- GroupTypeMapping(
- team_id=data_team.id,
- project_id=data_team.project_id,
- group_type_index=group_type_index,
- group_type=group_type,
- )
+ group_type_mapping_dicts.append(
+ {
+ "group_type_index": group_type_index,
+ "group_type": group_type,
+ }
)
for group_key, group in groups.items():
self._save_sim_group(
@@ -187,10 +181,7 @@ class MatrixManager:
group,
self.matrix.now,
)
- try:
- GroupTypeMapping.objects.bulk_create(bulk_group_type_mappings) # nosemgrep: no-direct-persons-db-orm
- except IntegrityError as e:
- print(f"SKIPPING GROUP TYPE MAPPING CREATION: {e}")
+ bulk_create_group_type_mappings(data_team.id, data_team.project_id, group_type_mapping_dicts)
for sim_person in sim_persons:
self._save_sim_person(data_team, sim_person)
# We need to wait a bit for data just queued into Kafka to show up in CH
@@ -224,7 +215,7 @@ class MatrixManager:
# )
# ]
# )
- GroupTypeMapping.objects.filter(project_id=cls.MASTER_TEAM_ID).delete() # nosemgrep: no-direct-persons-db-orm
+ delete_group_type_mappings(cls.MASTER_TEAM_ID)
def _copy_analytics_data_from_master_team(self, target_team: Team):
from posthog.models.event.sql import COPY_EVENTS_BETWEEN_TEAMS
@@ -242,93 +233,11 @@ class MatrixManager:
sync_execute(COPY_PERSON_DISTINCT_ID2S_BETWEEN_TEAMS, copy_params)
sync_execute(COPY_EVENTS_BETWEEN_TEAMS, copy_params)
sync_execute(COPY_GROUPS_BETWEEN_TEAMS, copy_params)
- GroupTypeMapping.objects.filter( # nosemgrep: no-direct-persons-db-orm
- project_id=target_team.project_id
- ).delete() # nosemgrep: no-direct-persons-db-orm
- GroupTypeMapping.objects.bulk_create( # nosemgrep: no-direct-persons-db-orm
- (
- GroupTypeMapping(team_id=target_team.id, project_id=target_team.project_id, **record)
- for record in GroupTypeMapping.objects.filter( # nosemgrep: no-direct-persons-db-orm
- project_id=self.MASTER_TEAM_ID
- ).values( # nosemgrep: no-direct-persons-db-orm
- "group_type", "group_type_index", "name_singular", "name_plural"
- )
- ),
- )
+ copy_group_type_mappings(self.MASTER_TEAM_ID, target_team.id, target_team.project_id)
@classmethod
def _sync_postgres_with_clickhouse_data(cls, source_team_id: int, target_team_id: int):
- from posthog.models.group.sql import SELECT_GROUPS_OF_TEAM
- from posthog.models.person.sql import SELECT_PERSON_DISTINCT_ID2S_OF_TEAM, SELECT_PERSONS_OF_TEAM
-
- list_params = {"source_team_id": source_team_id}
- # Persons
- clickhouse_persons = query_with_columns(
- SELECT_PERSONS_OF_TEAM,
- list_params,
- columns_to_rename={"id": "uuid"},
- )
- bulk_persons: dict[str, Person] = {}
- person_fields = {f.name for f in Person._meta.get_fields()}
- for row in clickhouse_persons:
- filtered_row = {k: v for k, v in row.items() if k in person_fields}
- properties = json.loads(filtered_row.pop("properties", "{}"))
- bulk_persons[row["uuid"]] = Person(team_id=target_team_id, properties=properties, **filtered_row)
- # This sets the pk in the bulk_persons dict so we can use them later
- Person.objects.bulk_create(bulk_persons.values()) # nosemgrep: no-direct-persons-db-orm
- # Person distinct IDs
- pre_existing_id_count = PersonDistinctId.objects.filter( # nosemgrep: no-direct-persons-db-orm
- team_id=target_team_id
- ).count() # nosemgrep: no-direct-persons-db-orm
- clickhouse_distinct_ids = query_with_columns(
- SELECT_PERSON_DISTINCT_ID2S_OF_TEAM,
- list_params,
- ["team_id", "is_deleted", "_timestamp", "_offset", "_partition"],
- {"person_id": "person_uuid"},
- )
- bulk_person_distinct_ids = []
- person_distinct_id_fields = {f.name for f in PersonDistinctId._meta.get_fields()}
- for row in clickhouse_distinct_ids:
- person_uuid = row.pop("person_uuid")
- try:
- filtered_row = {k: v for k, v in row.items() if k in person_distinct_id_fields}
- bulk_person_distinct_ids.append(
- PersonDistinctId(
- team_id=target_team_id,
- person_id=bulk_persons[person_uuid].pk,
- **filtered_row,
- )
- )
- except KeyError:
- pre_existing_id_count -= 1
- if pre_existing_id_count > 0:
- print(f"{pre_existing_id_count} IDS UNACCOUNTED FOR")
- PersonDistinctId.objects.bulk_create( # nosemgrep: no-direct-persons-db-orm
- bulk_person_distinct_ids, ignore_conflicts=True
- ) # nosemgrep: no-direct-persons-db-orm
- # Groups
- clickhouse_groups = query_with_columns(
- SELECT_GROUPS_OF_TEAM,
- list_params,
- ["team_id", "_timestamp", "_offset", "is_deleted"],
- )
- bulk_groups = []
- group_fields = {f.name for f in Group._meta.get_fields()}
- for row in clickhouse_groups:
- filtered_row = {k: v for k, v in row.items() if k in group_fields}
- group_properties = json.loads(filtered_row.pop("group_properties", "{}"))
- bulk_groups.append(
- Group(
- team_id=target_team_id,
- version=0,
- group_properties=group_properties,
- **filtered_row,
- )
- )
- try:
- Group.objects.bulk_create(bulk_groups) # nosemgrep: no-direct-persons-db-orm
- except IntegrityError as e:
- print(f"SKIPPING GROUP CREATION: {e}")
+ sync_persons_to_postgres(source_team_id, target_team_id, person_table_name=settings.PERSON_TABLE_NAME)
def _save_sim_person(self, team: Team, subject: SimPerson):
# We only want to save directly if there are past events
diff --git a/posthog/demo/matrix/persons_db_sync.py b/posthog/demo/matrix/persons_db_sync.py
new file mode 100644
index 000000000000..eea311041d51
--- /dev/null
+++ b/posthog/demo/matrix/persons_db_sync.py
@@ -0,0 +1,221 @@
+# ruff: noqa: T201 allow print statements
+"""
+Syncs person/group data from ClickHouse into the persons Postgres database
+using raw psycopg, bypassing Django ORM and Django's database configuration.
+
+Uses the persons_db_connection utility from posthog.persons_db for connections,
+keeping Django completely decoupled from the persons database.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import psycopg
+from psycopg import sql
+from psycopg.types.json import Jsonb
+
+from posthog.clickhouse.client import query_with_columns
+from posthog.persons_db import persons_db_connection
+
+
+def sync_persons_to_postgres(
+ source_team_id: int, target_team_id: int, person_table_name: str = "posthog_person"
+) -> None:
+ from posthog.models.group.sql import SELECT_GROUPS_OF_TEAM
+ from posthog.models.person.sql import SELECT_PERSON_DISTINCT_ID2S_OF_TEAM, SELECT_PERSONS_OF_TEAM
+
+ list_params = {"source_team_id": source_team_id}
+
+ clickhouse_persons = query_with_columns(
+ SELECT_PERSONS_OF_TEAM,
+ list_params,
+ columns_to_rename={"id": "uuid"},
+ )
+
+ clickhouse_distinct_ids = query_with_columns(
+ SELECT_PERSON_DISTINCT_ID2S_OF_TEAM,
+ list_params,
+ ["team_id", "is_deleted", "_timestamp", "_offset", "_partition"],
+ {"person_id": "person_uuid"},
+ )
+
+ clickhouse_groups = query_with_columns(
+ SELECT_GROUPS_OF_TEAM,
+ list_params,
+ ["team_id", "_timestamp", "_offset", "is_deleted"],
+ )
+
+ with persons_db_connection(writer=True) as conn:
+ with conn.cursor() as cur:
+ uuid_to_pk = _insert_persons(cur, clickhouse_persons, target_team_id, person_table_name)
+ _insert_person_distinct_ids(cur, clickhouse_distinct_ids, target_team_id, uuid_to_pk)
+ _insert_groups(cur, clickhouse_groups, target_team_id)
+
+
+def _insert_persons(
+ cur: psycopg.Cursor[Any],
+ clickhouse_persons: list[dict[str, Any]],
+ target_team_id: int,
+ person_table_name: str,
+) -> dict[str, int]:
+ if not clickhouse_persons:
+ return {}
+
+ insert_query = sql.SQL(
+ "INSERT INTO {} (team_id, uuid, properties, is_identified, created_at, version, last_seen_at) "
+ "VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id"
+ ).format(sql.Identifier(person_table_name))
+
+ uuid_to_pk: dict[str, int] = {}
+ for row in clickhouse_persons:
+ uuid = str(row["uuid"])
+ properties = row.get("properties", "{}")
+ if isinstance(properties, str):
+ properties = json.loads(properties)
+
+ cur.execute(
+ insert_query,
+ (
+ target_team_id,
+ uuid,
+ Jsonb(properties),
+ bool(row.get("is_identified", False)),
+ row.get("created_at"),
+ row.get("version"),
+ row.get("last_seen_at"),
+ ),
+ )
+ result = cur.fetchone()
+ assert result is not None
+ uuid_to_pk[uuid] = result[0]
+
+ return uuid_to_pk
+
+
+def _insert_person_distinct_ids(
+ cur: psycopg.Cursor[Any],
+ clickhouse_distinct_ids: list[dict[str, Any]],
+ target_team_id: int,
+ uuid_to_pk: dict[str, int],
+) -> None:
+ if not clickhouse_distinct_ids:
+ return
+
+ rows = []
+ for row in clickhouse_distinct_ids:
+ person_uuid = str(row["person_uuid"])
+ person_pk = uuid_to_pk.get(person_uuid)
+ if person_pk is None:
+ continue
+
+ rows.append((target_team_id, row["distinct_id"], person_pk, row["version"]))
+
+ if rows:
+ cur.executemany(
+ "INSERT INTO posthog_persondistinctid (team_id, distinct_id, person_id, version) "
+ "VALUES (%s, %s, %s, %s) ON CONFLICT DO NOTHING",
+ rows,
+ )
+
+
+def _insert_groups(
+ cur: psycopg.Cursor[Any],
+ clickhouse_groups: list[dict[str, Any]],
+ target_team_id: int,
+) -> None:
+ if not clickhouse_groups:
+ return
+
+ for row in clickhouse_groups:
+ group_properties = row.get("group_properties", "{}")
+ if isinstance(group_properties, str):
+ group_properties = json.loads(group_properties)
+
+ cur.execute(
+ "INSERT INTO posthog_group "
+ "(team_id, group_type_index, group_key, group_properties, created_at, version, "
+ "properties_last_updated_at, properties_last_operation) "
+ "VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING",
+ (
+ target_team_id,
+ row["group_type_index"],
+ row["group_key"],
+ Jsonb(group_properties),
+ row["created_at"],
+ 0,
+ Jsonb({}),
+ Jsonb({}),
+ ),
+ )
+
+
+def bulk_create_group_type_mappings(
+ team_id: int,
+ project_id: int,
+ mappings: list[dict[str, Any]],
+) -> None:
+ if not mappings:
+ return
+
+ rows = [
+ (
+ team_id,
+ project_id,
+ m["group_type_index"],
+ m["group_type"],
+ m.get("name_singular"),
+ m.get("name_plural"),
+ )
+ for m in mappings
+ ]
+
+ try:
+ with persons_db_connection(writer=True) as conn:
+ with conn.cursor() as cur:
+ cur.executemany(
+ "INSERT INTO posthog_grouptypemapping "
+ "(team_id, project_id, group_type_index, group_type, name_singular, name_plural) "
+ "VALUES (%s, %s, %s, %s, %s, %s)",
+ rows,
+ )
+ except psycopg.errors.IntegrityError as e:
+ print(f"SKIPPING GROUP TYPE MAPPING CREATION: {e}")
+
+
+def delete_group_type_mappings(project_id: int) -> None:
+ with persons_db_connection(writer=True) as conn:
+ with conn.cursor() as cur:
+ cur.execute(
+ "DELETE FROM posthog_grouptypemapping WHERE project_id = %s",
+ (project_id,),
+ )
+
+
+def copy_group_type_mappings(source_project_id: int, target_team_id: int, target_project_id: int) -> None:
+ with persons_db_connection(writer=True) as conn:
+ with conn.cursor() as cur:
+ cur.execute(
+ "DELETE FROM posthog_grouptypemapping WHERE project_id = %s",
+ (target_project_id,),
+ )
+ cur.execute(
+ "INSERT INTO posthog_grouptypemapping "
+ "(team_id, project_id, group_type, group_type_index, name_singular, name_plural) "
+ "SELECT %s, %s, group_type, group_type_index, name_singular, name_plural "
+ "FROM posthog_grouptypemapping "
+ "WHERE project_id = %s",
+ (target_team_id, target_project_id, source_project_id),
+ )
+
+
+def get_group_type_mapping_count(project_id: int) -> int:
+ with persons_db_connection(writer=False) as conn:
+ with conn.cursor() as cur:
+ cur.execute(
+ "SELECT COUNT(*) FROM posthog_grouptypemapping WHERE project_id = %s",
+ (project_id,),
+ )
+ result = cur.fetchone()
+ return result[0] if result else 0
diff --git a/posthog/demo/test/test_persons_db_sync.py b/posthog/demo/test/test_persons_db_sync.py
new file mode 100644
index 000000000000..5f65ad8549d0
--- /dev/null
+++ b/posthog/demo/test/test_persons_db_sync.py
@@ -0,0 +1,268 @@
+from typing import Any
+
+import pytest
+
+from django.conf import settings
+
+import psycopg
+
+from posthog.demo.matrix.persons_db_sync import (
+ _insert_groups,
+ _insert_person_distinct_ids,
+ _insert_persons,
+ bulk_create_group_type_mappings,
+ copy_group_type_mappings,
+ delete_group_type_mappings,
+ get_group_type_mapping_count,
+)
+from posthog.persons_db import persons_db_connection
+
+SYNC_TEST_TEAM_ID = 2_000_000_010
+SYNC_TEST_PROJECT_ID = 2_000_000_010
+SYNC_TEST_TARGET_TEAM_ID = 2_000_000_011
+SYNC_TEST_TARGET_PROJECT_ID = 2_000_000_011
+
+pytestmark = pytest.mark.django_db(databases=["persons_db_writer", "persons_db_reader"])
+
+
+def _cleanup(conn: psycopg.Connection[Any]) -> None:
+ with conn.cursor() as cur:
+ for team_id in (SYNC_TEST_TEAM_ID, SYNC_TEST_TARGET_TEAM_ID):
+ cur.execute("DELETE FROM posthog_persondistinctid WHERE team_id = %s", (team_id,))
+ cur.execute(f"DELETE FROM {settings.PERSON_TABLE_NAME} WHERE team_id = %s", (team_id,))
+ cur.execute("DELETE FROM posthog_group WHERE team_id = %s", (team_id,))
+ for project_id in (SYNC_TEST_PROJECT_ID, SYNC_TEST_TARGET_PROJECT_ID):
+ cur.execute("DELETE FROM posthog_grouptypemapping WHERE project_id = %s", (project_id,))
+
+
+class TestInsertPersons:
+ def test_inserts_persons_and_returns_uuid_to_pk_mapping(self):
+ with persons_db_connection(writer=True) as conn:
+ try:
+ with conn.cursor() as cur:
+ uuid_to_pk = _insert_persons(
+ cur,
+ [
+ {
+ "uuid": "00000000-0000-0000-0000-000000000001",
+ "properties": '{"email": "[email protected]"}',
+ "is_identified": True,
+ "created_at": "2024-01-01T00:00:00Z",
+ "version": 0,
+ "last_seen_at": None,
+ },
+ {
+ "uuid": "00000000-0000-0000-0000-000000000002",
+ "properties": {"name": "Test"},
+ "is_identified": False,
+ "created_at": "2024-01-02T00:00:00Z",
+ "version": 1,
+ "last_seen_at": None,
+ },
+ ],
+ SYNC_TEST_TEAM_ID,
+ settings.PERSON_TABLE_NAME,
+ )
+
+ assert len(uuid_to_pk) == 2
+ assert "00000000-0000-0000-0000-000000000001" in uuid_to_pk
+ assert "00000000-0000-0000-0000-000000000002" in uuid_to_pk
+ assert isinstance(uuid_to_pk["00000000-0000-0000-0000-000000000001"], int)
+
+ with conn.cursor() as cur:
+ cur.execute(
+ f"SELECT uuid, properties, is_identified FROM {settings.PERSON_TABLE_NAME} WHERE team_id = %s ORDER BY uuid",
+ (SYNC_TEST_TEAM_ID,),
+ )
+ rows = cur.fetchall()
+ assert len(rows) == 2
+ assert rows[0][1] == {"email": "[email protected]"}
+ assert rows[0][2] is True
+ assert rows[1][1] == {"name": "Test"}
+ assert rows[1][2] is False
+ finally:
+ _cleanup(conn)
+
+ def test_empty_list_returns_empty_dict(self):
+ with persons_db_connection(writer=True) as conn:
+ with conn.cursor() as cur:
+ result = _insert_persons(cur, [], SYNC_TEST_TEAM_ID, settings.PERSON_TABLE_NAME)
+ assert result == {}
+
+
+class TestInsertPersonDistinctIds:
+ def test_inserts_distinct_ids_linked_to_persons(self):
+ with persons_db_connection(writer=True) as conn:
+ try:
+ with conn.cursor() as cur:
+ uuid_to_pk = _insert_persons(
+ cur,
+ [
+ {
+ "uuid": "00000000-0000-0000-0000-000000000010",
+ "properties": "{}",
+ "is_identified": False,
+ "created_at": "2024-01-01T00:00:00Z",
+ "version": 0,
+ "last_seen_at": None,
+ },
+ ],
+ SYNC_TEST_TEAM_ID,
+ settings.PERSON_TABLE_NAME,
+ )
+
+ _insert_person_distinct_ids(
+ cur,
+ [
+ {
+ "person_uuid": "00000000-0000-0000-0000-000000000010",
+ "distinct_id": "user-abc",
+ "version": 0,
+ },
+ ],
+ SYNC_TEST_TEAM_ID,
+ uuid_to_pk,
+ )
+
+ cur.execute(
+ "SELECT distinct_id, person_id FROM posthog_persondistinctid WHERE team_id = %s",
+ (SYNC_TEST_TEAM_ID,),
+ )
+ rows = cur.fetchall()
+ assert len(rows) == 1
+ assert rows[0][0] == "user-abc"
+ assert rows[0][1] == uuid_to_pk["00000000-0000-0000-0000-000000000010"]
+ finally:
+ _cleanup(conn)
+
+ def test_skips_distinct_ids_with_unknown_person_uuid(self):
+ with persons_db_connection(writer=True) as conn:
+ try:
+ with conn.cursor() as cur:
+ _insert_person_distinct_ids(
+ cur,
+ [{"person_uuid": "nonexistent-uuid", "distinct_id": "orphan", "version": 0}],
+ SYNC_TEST_TEAM_ID,
+ {},
+ )
+ cur.execute(
+ "SELECT COUNT(*) FROM posthog_persondistinctid WHERE team_id = %s",
+ (SYNC_TEST_TEAM_ID,),
+ )
+ row = cur.fetchone()
+ assert row is not None
+ assert row[0] == 0
+ finally:
+ _cleanup(conn)
+
+
+class TestInsertGroups:
+ def test_inserts_groups_with_properties(self):
+ with persons_db_connection(writer=True) as conn:
+ try:
+ with conn.cursor() as cur:
+ _insert_groups(
+ cur,
+ [
+ {
+ "group_type_index": 0,
+ "group_key": "acme-inc",
+ "group_properties": '{"name": "Acme"}',
+ "created_at": "2024-01-01T00:00:00Z",
+ },
+ ],
+ SYNC_TEST_TEAM_ID,
+ )
+
+ cur.execute(
+ "SELECT group_key, group_properties, group_type_index FROM posthog_group WHERE team_id = %s",
+ (SYNC_TEST_TEAM_ID,),
+ )
+ rows = cur.fetchall()
+ assert len(rows) == 1
+ assert rows[0][0] == "acme-inc"
+ assert rows[0][1] == {"name": "Acme"}
+ assert rows[0][2] == 0
+ finally:
+ _cleanup(conn)
+
+
+class TestGroupTypeMappingHelpers:
+ def test_bulk_create_and_count(self):
+ try:
+ bulk_create_group_type_mappings(
+ SYNC_TEST_TEAM_ID,
+ SYNC_TEST_PROJECT_ID,
+ [
+ {"group_type_index": 0, "group_type": "company"},
+ {"group_type_index": 1, "group_type": "project"},
+ ],
+ )
+
+ assert get_group_type_mapping_count(SYNC_TEST_PROJECT_ID) == 2
+ finally:
+ with persons_db_connection(writer=True) as conn:
+ _cleanup(conn)
+
+ def test_delete_removes_mappings(self):
+ try:
+ bulk_create_group_type_mappings(
+ SYNC_TEST_TEAM_ID,
+ SYNC_TEST_PROJECT_ID,
+ [{"group_type_index": 0, "group_type": "company"}],
+ )
+ assert get_group_type_mapping_count(SYNC_TEST_PROJECT_ID) == 1
+
+ delete_group_type_mappings(SYNC_TEST_PROJECT_ID)
+ assert get_group_type_mapping_count(SYNC_TEST_PROJECT_ID) == 0
+ finally:
+ with persons_db_connection(writer=True) as conn:
+ _cleanup(conn)
+
+ def test_copy_transfers_mappings_between_projects(self):
+ try:
+ bulk_create_group_type_mappings(
+ SYNC_TEST_TEAM_ID,
+ SYNC_TEST_PROJECT_ID,
+ [
+ {"group_type_index": 0, "group_type": "company", "name_singular": "Company"},
+ {"group_type_index": 1, "group_type": "team"},
+ ],
+ )
+
+ copy_group_type_mappings(SYNC_TEST_PROJECT_ID, SYNC_TEST_TARGET_TEAM_ID, SYNC_TEST_TARGET_PROJECT_ID)
+
+ assert get_group_type_mapping_count(SYNC_TEST_TARGET_PROJECT_ID) == 2
+
+ with persons_db_connection(writer=False) as conn:
+ with conn.cursor() as cur:
+ cur.execute(
+ "SELECT team_id, group_type, name_singular FROM posthog_grouptypemapping "
+ "WHERE project_id = %s ORDER BY group_type_index",
+ (SYNC_TEST_TARGET_PROJECT_ID,),
+ )
+ rows = cur.fetchall()
+ assert rows[0][0] == SYNC_TEST_TARGET_TEAM_ID
+ assert rows[0][1] == "company"
+ assert rows[0][2] == "Company"
+ assert rows[1][1] == "team"
+ finally:
+ with persons_db_connection(writer=True) as conn:
+ _cleanup(conn)
+
+ def test_bulk_create_handles_integrity_error_gracefully(self):
+ try:
+ bulk_create_group_type_mappings(
+ SYNC_TEST_TEAM_ID,
+ SYNC_TEST_PROJECT_ID,
+ [{"group_type_index": 0, "group_type": "company"}],
+ )
+ bulk_create_group_type_mappings(
+ SYNC_TEST_TEAM_ID,
+ SYNC_TEST_PROJECT_ID,
+ [{"group_type_index": 0, "group_type": "company"}],
+ )
+ assert get_group_type_mapping_count(SYNC_TEST_PROJECT_ID) == 1
+ finally:
+ with persons_db_connection(writer=True) as conn:
+ _cleanup(conn)
diff --git a/posthog/management/commands/generate_demo_data.py b/posthog/management/commands/generate_demo_data.py
index 223c7357b4d7..f41648d0541c 100644
--- a/posthog/management/commands/generate_demo_data.py
+++ b/posthog/management/commands/generate_demo_data.py
@@ -16,13 +16,13 @@ from django.db.utils import OperationalError
from posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
from posthog.demo.dashboard_template_seeds import seed_dev_dashboard_templates
from posthog.demo.matrix import Matrix, MatrixManager
+from posthog.demo.matrix.persons_db_sync import get_group_type_mapping_count
from posthog.demo.products.hedgebox import HedgeboxMatrix
from posthog.demo.products.spikegpt import SpikeGPTMatrix
from posthog.health import get_pending_postgres_migrations
from posthog.management.commands.sync_feature_flags_from_api import sync_feature_flags_from_api
from posthog.models import User
from posthog.models.file_system.user_product_list import UserProductList
-from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.team.setup_tasks import SetupTaskId
from posthog.models.team.team import Team
from posthog.products import Products
@@ -166,9 +166,7 @@ class Command(BaseCommand):
days_past=options["days_past"],
days_future=options["days_future"],
n_clusters=options["n_clusters"],
- group_type_index_offset=(
- len(get_group_types_for_project(existing_team.project_id)) if existing_team else 0
- ),
+ group_type_index_offset=(get_group_type_mapping_count(existing_team.project_id) if existing_team else 0),
)
print("Running simulation...")
matrix.simulate()