: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(django): rm unused management commands (#63832)
Nick Best1506106e698b
diff --git a/posthog/management/commands/backfill_personless_distinct_ids.py b/posthog/management/commands/backfill_personless_distinct_ids.pydeleted file mode 100644index 0c47049d4c43..000000000000--- a/posthog/management/commands/backfill_personless_distinct_ids.py+++ /dev/null@@ -1,180 +0,0 @@-from __future__ import annotations--import time-import logging-from collections.abc import Sequence-from dataclasses import dataclass--from django.core.management.base import BaseCommand, CommandError-from django.db import connections, router, transaction--import structlog--from posthog.clickhouse.client.execute import sync_execute as ch_execute-from posthog.models.person import PersonlessDistinctId-from posthog.models.team.team import Team--logger = structlog.get_logger(__name__)---def batch_insert_personless_distinct_ids(data, batch_size=1000):- query = """- INSERT INTO posthog_personlessdistinctid (team_id, distinct_id, is_merged, created_at)- VALUES %s- ON CONFLICT (team_id, distinct_id) DO NOTHING- """-- team_ids = {d[0] for d in data}- existing_team_ids = set(Team.objects.filter(id__in=team_ids).values_list("id", flat=True))- missing_team_ids = team_ids - existing_team_ids- original_len = len(data)- data = [d for d in data if d[0] in existing_team_ids]- if missing_team_ids:- logger.info(- f"Skipping team ids {missing_team_ids!r} because they no longer exist, skipping {original_len - len(data)} records"- )-- def chunks(lst, n):- for i in range(0, len(lst), n):- yield lst[i : i + n]-- # Use the correct database for PersonlessDistinctId writes (handles persons_db_writer routing in production)- db_alias = router.db_for_write(PersonlessDistinctId) or "default"- db_connection = connections[db_alias]-- for batch in chunks(data, batch_size):- with transaction.atomic(using=db_alias):- with db_connection.cursor() as cursor:- values = ",".join(- cursor.mogrify("(%s, %s, false, now())", (team_id, distinct_id)) for team_id, distinct_id in batch- )- full_query = query % values-- start = time.time()- cursor.execute(full_query)- logger.info("Inserted %r records in %r seconds", len(batch), time.time() - start)---@dataclass-class BackfillTeam:- team_id: int-- def execute(self, dry_run: bool = False) -> None:- logger.info("Starting %r...", self)-- query = """- SELECT team_id, distinct_id- FROM events- WHERE timestamp >= '2024-04-30'- AND timestamp < '2024-07-02'- AND person_mode = 'propertyless'- AND team_id = %(team_id)s- GROUP BY team_id, distinct_id- """-- parameters = {- "team_id": self.team_id,- }-- settings = {"max_execution_time": 300}-- if dry_run:- [(count,)] = ch_execute(f"SELECT count() FROM ({query})", parameters, settings=settings)- logger.info("%r would have inserted %r records.", self, count)- else:- distinct_ids = ch_execute(query, parameters, settings=settings)- batch_insert_personless_distinct_ids(distinct_ids)- logger.info("Completed %r (%d rows)!", self, len(distinct_ids))---@dataclass-class BackfillShard:- shard_count: int- shard_num: int-- def execute(self, dry_run: bool = False) -> None:- logger.info("Starting %r...", self)-- query = """- SELECT team_id, distinct_id- FROM events- WHERE timestamp >= '2024-04-30'- AND timestamp < '2024-07-02'- AND person_mode = 'propertyless'- AND team_id %% %(shard_count)s = %(shard_num)s- GROUP BY team_id, distinct_id- """-- parameters = {- "shard_count": self.shard_count,- "shard_num": self.shard_num,- }-- settings = {"max_execution_time": 300}-- if dry_run:- [(count,)] = ch_execute(f"SELECT count() FROM ({query})", parameters, settings=settings)- logger.info("%r would have inserted %r records.", self, count)- else:- distinct_ids = ch_execute(query, parameters, settings=settings)- batch_insert_personless_distinct_ids(distinct_ids)- logger.info("Completed %r (%d rows)!", self, len(distinct_ids))---class Command(BaseCommand):- help = "Backfill posthog_personlessdistinctid records."-- def add_arguments(self, parser):- parser.add_argument(- "--team-id",- required=False,- type=int,- dest="team_id_list",- action="append",- help="team(s) to backfill",- )- parser.add_argument(- "--shard-count",- required=False,- type=int,- dest="shard_count",- action="store",- help="number of shards",- )- parser.add_argument(- "--shard-num",- required=False,- type=int,- dest="shard_num",- action="store",- help="shard number to backfill",- )- parser.add_argument(- "--live-run", action="store_true", help="actually execute INSERT queries (default is dry-run)"- )-- def handle(- self,- *,- live_run: bool,- team_id_list: Sequence[int] | None,- shard_count: int | None,- shard_num: int | None,- **options,- ):- logger.setLevel(logging.INFO)-- if shard_count is not None and shard_num is not None:- logger.info("Starting backfill for shard %s/%s...", shard_num, shard_count)- BackfillShard(shard_count, shard_num).execute(dry_run=not live_run)- elif team_id_list is not None:- team_ids = set(team_id_list)- existing_team_ids = set(Team.objects.filter(id__in=team_ids).values_list("id", flat=True))- if existing_team_ids != team_ids:- raise CommandError(f"Teams with ids {team_ids - existing_team_ids!r} do not exist")-- logger.info("Starting backfill for %s teams...", len(team_ids))- for team_id in team_ids:- BackfillTeam(team_id).execute(dry_run=not live_run)- else:- raise CommandError("Either --team-id or --shard-count and --shard-num must be specified")diff --git a/posthog/management/commands/delete_persons_with_no_distinct_ids.py b/posthog/management/commands/delete_persons_with_no_distinct_ids.pydeleted file mode 100644index a813f911aef7..000000000000--- a/posthog/management/commands/delete_persons_with_no_distinct_ids.py+++ /dev/null@@ -1,85 +0,0 @@-import time--from django.core.management.base import BaseCommand, CommandError-from django.db import connection--from posthog.models.person import Person---class Command(BaseCommand):- help = "Delete person rows that have no associated persondistinctid rows, by team"-- def add_arguments(self, parser):- parser.add_argument("--team-id", default=None, type=int, help="Team ID to migrate from (on this instance)")- parser.add_argument("--dry-run", action="store_false", help="Dry run mode (no changes will be made)")- parser.add_argument(- "--max-delete", default=1000, type=int, help="Max number of rows to delete in one go (default 1000)"- )-- def handle(self, **options):- team_id = options["team_id"]- dry_run = options["dry_run"]- max_delete = options["max_delete"]-- if not team_id:- raise CommandError("source Team ID is required")-- print("Deleting persons with no distinct ids for team", team_id) # noqa: T201-- if dry_run:- print("Dry run mode enabled. No changes will be made.") # noqa: T201- delete_persons_without_distinct_ids_raw_sql_dry_run(team_id, max_delete)- else:- print("This is for real. Changes will be made. Sleeping for 10 seconds") # noqa: T201- time.sleep(10)- delete_persons_without_distinct_ids_raw_sql(team_id, max_delete)---def delete_persons_without_distinct_ids_raw_sql(team_id, max_delete):- person_table = Person._meta.db_table- with connection.cursor() as cursor:- cursor.execute(- f"""- WITH persons_to_delete AS (- SELECT p.id- FROM {person_table} p- LEFT JOIN posthog_persondistinctid pd ON p.id = pd.person_id AND p.team_id = pd.team_id- WHERE p.team_id = %(team_id)s AND pd.id IS NULL- LIMIT %(max_delete)s- )- DELETE FROM {person_table}- WHERE id IN (SELECT id FROM persons_to_delete)- RETURNING id;- """,- {"team_id": team_id, "max_delete": max_delete},- )-- deleted_ids = cursor.fetchall()- deleted_count = len(deleted_ids)-- print(f"Deleted {deleted_count} Person objects with no PersonDistinctIds for team {team_id}.") # noqa: T201- return deleted_count---def delete_persons_without_distinct_ids_raw_sql_dry_run(team_id, max_delete):- person_table = Person._meta.db_table- with connection.cursor() as cursor:- cursor.execute(- f"""- WITH persons_to_delete AS (- SELECT p.id- FROM {person_table} p- LEFT JOIN posthog_persondistinctid pd ON p.id = pd.person_id AND p.team_id = pd.team_id- WHERE p.team_id = %(team_id)s AND pd.id IS NULL- LIMIT %(max_delete)s- )- SELECT COUNT(*) FROM persons_to_delete;- """,- {"team_id": team_id, "max_delete": max_delete},- )-- deleted_count = cursor.fetchone()- deleted_count = deleted_count[0] if deleted_count else 0-- print(f"Would have deleted {deleted_count} Person objects with no PersonDistinctIds for team {team_id}.") # noqa: T201- return deleted_countdiff --git a/posthog/management/commands/fix_future_person_created_at.py b/posthog/management/commands/fix_future_person_created_at.pydeleted file mode 100644index b3f94661195a..000000000000--- a/posthog/management/commands/fix_future_person_created_at.py+++ /dev/null@@ -1,69 +0,0 @@-import logging-from datetime import timedelta--from django.core.management.base import BaseCommand-from django.db.models import F-from django.utils.timezone import now--import structlog-from dateutil.parser import isoparse--from posthog.kafka_client.routing import flush_all_producers-from posthog.models.person.person import Person-from posthog.models.person.util import create_person--logger = structlog.get_logger(__name__)-logger.setLevel(logging.INFO)---class Command(BaseCommand):- help = "Fix update persons created_at to not be in the future for a single team"-- def add_arguments(self, parser):- parser.add_argument("--team-id", default=None, type=int, help="Specify a team to fix data for.")- parser.add_argument("--new-date", default="2024-01-01", type=str, help="New create_at value to use")- parser.add_argument("--live-run", action="store_true", help="Run changes, default is dry-run")-- def handle(self, *args, **options):- run(options)---def run(options):- live_run = options["live_run"]-- if not options["team_id"]:- logger.error("You must specify --team-id to run this script")- exit(1)-- team_id = options["team_id"]- new_date = isoparse(options["new_date"])-- future_date = now() + timedelta(days=2)-- # Get all persons with future created_at value- persons = Person.objects.filter(team_id=team_id, created_at__gt=future_date) # nosemgrep: no-direct-persons-db-orm-- logger.info(- f"Found {len(persons)} persons with future created_at value, updating them to {new_date.strftime('%Y-%m-%d %H:%M:%S.%f')}"- )-- # If someone else updated the person at the same time these could conflict, which isn't ideal, but this is a one-off script- for person in persons:- logger.info(f"Updating person {person.uuid} created_at to {new_date.strftime('%Y-%m-%d %H:%M:%S.%f')}")- if live_run:- Person.objects.filter(pk=person.id).update( # nosemgrep: no-direct-persons-db-orm- version=F("version") + 1, created_at=new_date- ) # nosemgrep: no-direct-persons-db-orm- create_person(- uuid=str(person.uuid),- team_id=team_id,- properties=person.properties,- is_identified=person.is_identified,- is_deleted=False,- created_at=person.created_at,- version=person.version or 0,- )-- logger.info("Waiting on Kafka producer flush, for up to 5 minutes")- flush_all_producers(5 * 60)- logger.info("Kafka producer queue flushed.")