repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
posthog | posthog/models/element_group.py | .py | import json
import hashlib
from typing import Any
from django.db import models, transaction
from django.forms.models import model_to_dict
from posthog.models.element import Element
from posthog.models.team import Team
def hash_elements(elements: list) -> str:
elements_list: list[dict] = []
for element in el... | 54 | 1,992 |
posthog | posthog/models/group_type_mapping.py | .py | from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from posthog.models.project import Project
from posthog.models.team.team import Team
from posthog.personhog_client.client import PersonHogClient
from django.conf import settings
from django.contrib.post... | 753 | 33,516 |
posthog | posthog/models/webauthn_credential.py | .py | from django.db import models
from posthog.models.utils import UUIDModel
class WebAuthnCredentialManager(models.Manager):
def get_verified_for_user(self, user_id: int):
"""
Returns all verified credentials for a user.
"""
return self.filter(user_id=user_id, verified=True)
def ... | 67 | 2,672 |
posthog | posthog/models/linked_identity_provider_config.py | .py | from django.db import models
from posthog.models.utils import UUIDModel
class LinkedIdentityProviderConfig(UUIDModel):
organization_domain = models.ForeignKey(
"posthog.OrganizationDomain", on_delete=models.CASCADE, related_name="linked_identity_provider_configs"
)
identity_provider_config = mode... | 21 | 698 |
posthog | posthog/models/uploaded_media.py | .py | from typing import Optional
from django.conf import settings
from django.db import models
import structlog
from posthog.exceptions_capture import capture_exception
from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import RootTeamMixin, UUIDTModel
from posthog.storage... | 86 | 3,028 |
posthog | posthog/models/oauth_provisioning.py | .py | """Storage shape for ``OAuthApplication.provisioning_config``.
A provisioning partner's capabilities and quotas live in one JSONB column rather than
a column each. The column is internal storage, not a public DTO: nothing in the API surface
serializes it directly, so it is free to change shape here without a schema mi... | 78 | 3,554 |
posthog | posthog/models/host_definition.py | .py | from django.db import models
from django.utils import timezone
from posthog.models.utils import UniqueConstraintByExpression, UUIDTModel
# NOTE: This model is deprecated. It was created as an attempt to track all of the domains that are using PostHog.
# This wasn't very performant inside propdefs, and for that reaso... | 46 | 1,653 |
posthog | posthog/models/deletion_targets.py | .py | """Which physical ClickHouse tables a data deletion has to sweep.
Erasing a person's data is not a property of the events table β it is a property of every table
that stores rows attributable to a person. This module is the one list of those tables, so a table
that starts carrying person data gets registered here rath... | 238 | 10,238 |
posthog | posthog/models/personal_api_key.py | .py | from typing import TYPE_CHECKING, Optional
from django.contrib.auth.hashers import PBKDF2PasswordHasher
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models import Q, QuerySet
from django.utils import timezone
from django_deprecate_fields import deprecate_field
from... | 102 | 4,268 |
posthog | posthog/models/health_issue.py | .py | import json
import hashlib
from typing import Any, Optional
from django.db import connection, models, transaction
from django.utils import timezone
import structlog
from posthog.models.utils import UUIDModel
logger = structlog.get_logger(__name__)
def _filter_existing_team_ids(team_ids: set[int]) -> set[int]:
... | 294 | 10,772 |
posthog | posthog/models/object_media_preview.py | .py | from django.core.exceptions import ValidationError
from django.db import models
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
class ObjectMediaPreview(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
"""
Links media to objects like event definitions, property definitions, ... | 111 | 3,925 |
posthog | posthog/models/proxy_record.py | .py | import re
from django.db import models
from posthog.models import Organization
from posthog.models.utils import UUIDTModel
MAX_PROXY_DOMAIN_LENGTH = 253
MAX_PROXY_DOMAIN_LABEL_LENGTH = 63
_LABEL = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"
_PROXY_DOMAIN_RE = re.compile(rf"{_LABEL}(?:\.{_LABEL})*")
def is_valid_p... | 72 | 2,676 |
posthog | posthog/models/organization_integration.py | .py | from django.db import models
from posthog.helpers.encrypted_fields import EncryptedJSONField
from posthog.models.organization import Organization
from posthog.models.utils import UUIDModel
class OrganizationIntegration(UUIDModel):
class OrganizationIntegrationKind(models.TextChoices):
VERCEL = "vercel"
... | 33 | 1,207 |
posthog | posthog/models/flag_evaluations/sql.py | .py | from django.conf import settings
from posthog.clickhouse.kafka_engine import (
CONSUMER_GROUP_FLAG_EVALUATIONS,
KAFKA_COLUMNS_WITH_PARTITION,
kafka_engine,
trim_quotes_expr,
ttl_period,
)
from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme
from posthog.kafka... | 288 | 14,415 |
posthog | posthog/models/performance/sql.py | .py | """https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry"""
from posthog import settings
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
from posthog.clickhouse.kafka_engine import KAFKA_COLUMNS_WITH_PARTITION, STORAGE_POLICY, kafka_engine, ttl_period
from posthog.clickhouse.table_engines import D... | 216 | 6,873 |
posthog | posthog/models/user_group/__init__.py | .py | from .user_group import UserGroup, UserGroupMembership
__all__ = ["UserGroup", "UserGroupMembership"]
| 4 | 103 |
posthog | posthog/models/user_group/user_group.py | .py | from django.db import models
from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import UUIDTModel
# !!! DEPRECATED !!!
# Please use the ee.Role model instead
class UserGroup(UUIDTModel):
team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="user_... | 31 | 906 |
posthog | posthog/models/person_overrides/sql.py | .py | # XXX: The tables defined in this module are not used and are only retained for migration consistency reasons. See
# `person_distinct_id_overrides` in `posthog.models.person.sql` for its replacement tables, or
# https://github.com/PostHog/posthog/pull/23616 for additional context.
from posthog.clickhouse.client.connec... | 175 | 7,715 |
posthog | posthog/models/comment/utils.py | .py | from typing import TYPE_CHECKING, Any, Optional
from urllib.parse import quote
from django.conf import settings
import structlog
from posthog.cdp.internal_events import InternalEventEvent, InternalEventPerson, produce_internal_event
from posthog.exceptions_capture import capture_exception
from posthog.models import ... | 216 | 7,932 |
posthog | posthog/models/comment/comment.py | .py | from typing import cast
from django.contrib.postgres.indexes import GinIndex, OpClass
from django.db import models
from django.db.models.functions import Upper
from posthog.models.activity_logging.activity_log import (
AuditableScope,
Change,
Detail,
field_with_masked_contents,
log_activity,
)
fro... | 131 | 6,117 |
posthog | posthog/models/comment/__init__.py | .py | from .comment import Comment
from .slack_thread import CommentSlackThread
__all__ = ["Comment", "CommentSlackThread"]
| 5 | 119 |
posthog | posthog/models/comment/slack_thread.py | .py | from django.db import models, transaction
from posthog.models.comment.comment import COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API, Comment
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.signals import mutable_receiver
from posthog.models.utils import UUIDModel
# Gates creating new mi... | 98 | 5,193 |
posthog | posthog/models/comment/test_utils.py | .py | from uuid import uuid4
from unittest.mock import MagicMock, patch
from django.test import TestCase
from parameterized import parameterized
from posthog.models import Organization, Team, User
from posthog.models.comment.utils import SCOPE_TO_SOURCE_TYPE, send_mention_notifications
from products.notifications.backen... | 72 | 3,010 |
posthog | posthog/models/tophog/sql.py | .py | from django.conf import settings
from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_TOPHOG, CONSUMER_GROUP_TOPHOG_WS, kafka_engine, ttl_period
from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme
from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_TOPHOG
TOPHOG_TTL... | 165 | 4,243 |
posthog | posthog/models/tophog/queries.py | .py | from datetime import datetime
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.dataclasses import frozen
TOPHOG_QUERY = """
WITH filtered AS (
SELECT *
FROM tophog
WHERE timestamp >= %(date_from)s AND timestamp <= %... | 99 | 2,711 |
posthog | posthog/models/tophog/test/test_tophog_queries.py | .py | from datetime import UTC, datetime
from posthog.test.base import BaseTest, ClickhouseTestMixin
from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
from posthog.models.tophog.queries import query_tophog_filter_options, query_tophog_metrics
from posthog.models.tophog.sql import D... | 149 | 5,761 |
posthog | posthog/models/usage_report_events_preagg/sql.py | .py | from django.conf import settings
from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_USAGE_REPORT_EVENTS_PREAGG, kafka_engine
from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme
from posthog.kafka_client.topics import KAFKA_EVENTS_JSON
USAGE_REPORT_EVENTS_PREAGG_TA... | 125 | 4,334 |
posthog | posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py | .py | """End-to-end test that produces an event to the dedicated usage-report-preagg Kafka
table and verifies the usage_report_events_preagg materialized view aggregates it correctly.
Mirrors the test_kafka_insert pattern in ee/clickhouse/models/test/test_dead_letter_queue.py.
Requires a running Kafka broker reachable via s... | 158 | 7,423 |
posthog | posthog/models/query_metrics/sql.py | .py | # Note: These tables are not (yet) created automatically, as they're considered experimental on cloud and exact schema is in flux.
from posthog.clickhouse.kafka_engine import KAFKA_COLUMNS_WITH_PARTITION, kafka_engine
from posthog.clickhouse.table_engines import MergeTreeEngine
from posthog.kafka_client.topics import ... | 234 | 7,965 |
posthog | posthog/models/person/point_in_time_properties.py | .py | """
Module for building person properties from ClickHouse events at a specific point in time.
This module provides functionality to reconstruct person properties as they existed
at a specific timestamp by querying ClickHouse events and applying property updates
chronologically.
"""
import json
from datetime import UT... | 215 | 8,694 |
posthog | posthog/models/person/deletion.py | .py | import datetime as dt
from dataclasses import dataclass, field
from typing import Optional
import structlog
from rest_framework.exceptions import NotFound
from posthog.clickhouse.client import sync_execute
from posthog.models.person import Person
from posthog.models.person.util import create_person, create_person_dis... | 397 | 15,322 |
posthog | posthog/models/person/sql.py | .py | from django.conf import settings
from posthog.clickhouse.base_sql import COPY_ROWS_BETWEEN_TEAMS_BASE_SQL
from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
from posthog.clickhouse.indexes import index_by_kafka_timestamp
from p... | 766 | 24,685 |
posthog | posthog/models/person/util.py | .py | from __future__ import annotations
import json
import datetime
import contextvars
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional, Union
from uuid import UUID
from zoneinfo import ZoneInfo
from django.conf import settings
from django.utils... | 669 | 25,342 |
posthog | posthog/models/person/__init__.py | .py | from .person import Person, PersonDistinctId, PersonlessDistinctId, PersonOverride, PersonOverrideMapping
from .point_in_time_properties import build_person_properties_at_time
__all__ = [
"Person",
"PersonDistinctId",
"PersonOverride",
"PersonOverrideMapping",
"PersonlessDistinctId",
"build_per... | 12 | 347 |
posthog | posthog/models/person/bulk_delete.py | .py | import uuid as uuid_lib
import asyncio
import builtins
from collections.abc import Iterator
from dataclasses import dataclass, field
from datetime import timedelta
from typing import cast
from django.conf import settings
import structlog
from temporalio import common
from posthog.helpers.impersonation import is_impe... | 215 | 7,791 |
posthog | posthog/models/person/person.py | .py | from datetime import UTC, datetime
from typing import Any, NamedTuple, Optional
from uuid import UUID
from django.conf import settings
from django.core.exceptions import EmptyResultSet
from django.db import connections, models
from django.db.models import F, Q
import structlog
from posthog.models.utils import UUIDT
... | 596 | 24,503 |
posthog | posthog/models/person/missing_person.py | .py | from uuid import UUID, uuid5
PERSON_UUIDV5_NAMESPACE = UUID("932979b4-65c3-4424-8467-0b66ec27bc22")
def uuidFromDistinctId(team_id: int, distinct_id: str) -> UUID:
"""
Deterministically create a UUIDv5 based on the (team_id, distinct_id) pair.
"""
return uuid5(PERSON_UUIDV5_NAMESPACE, f"{team_id}:{di... | 27 | 828 |
posthog | posthog/models/person/test/test_point_in_time_properties.py | .py | """
Tests for point-in-time person properties building functionality.
"""
import json
from datetime import UTC, datetime
from typing import cast
from posthog.test.base import BaseTest
from unittest.mock import patch
from django.test import SimpleTestCase
from posthog.models.person.point_in_time_properties import (
... | 348 | 14,850 |
posthog | posthog/models/person/test/test_util_personhog.py | .py | from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from posthog.models.person.util import (
_fetch_person_by_distinct_id_via_personhog,
_fetch_person_by_id_via_personhog,
_fetch_person_by_uuid_via_personhog,
_fetch_persons_by_distin... | 594 | 24,118 |
posthog | posthog/models/person/test/test_delete_persons_personhog.py | .py | """Tests for person deletion via personhog RPC.
Covers routing and RPC behavior for:
- delete_persons_from_postgres (API delete path)
- _delete_persons_for_teams (team deletion path)
"""
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from pos... | 127 | 5,247 |
posthog | posthog/models/person/test/test_point_in_time_properties_integration.py | .py | """
Real-ClickHouse integration tests for point-in-time person properties.
This file used to mock ``sync_execute``, which made the file's name a lie and
let SQL typos / column-order mistakes / UNION-ALL ordering bugs sail through
green. Each test now seeds events into ClickHouse and exercises the real query.
"""
from... | 240 | 8,552 |
posthog | posthog/models/person/test/test_split_person.py | .py | from datetime import UTC, datetime
from posthog.test.base import BaseTest
from unittest.mock import patch
from posthog.models import Person
from posthog.models.person.missing_person import uuidFromDistinctId
from posthog.models.person.util import get_person_by_distinct_id, get_person_by_id
from posthog.personhog_clie... | 349 | 16,648 |
posthog | posthog/models/person/test/test_orphaned_ch_persons.py | .py | from uuid import uuid4
from posthog.test.base import BaseTest, ClickhouseTestMixin
from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
from posthog.models.person.deletion import find_orphaned_ch_persons, tombstone_orphaned_ch_persons
from posthog.models.person.util import (
... | 161 | 6,738 |
posthog | posthog/models/person/test/test_bulk_delete_helpers.py | .py | from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
from parameterized import parameterized
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person import Person
from posthog.models.person.bulk_delete import (
_start_recording_workf... | 194 | 9,317 |
posthog | posthog/models/person/test/test_reset_distinct_ids_personhog.py | .py | """Tests for the undelete-repair version writes via personhog RPC.
Covers the two personhog RPC writes in the repair flow:
- _update_distinct_id_in_postgres β SetPersonDistinctIdVersionFloor
- _set_person_version_floor (used by _reset_person_in_clickhouse) β SetPersonVersionFloor
"""
from uuid import uuid4
from djan... | 56 | 2,146 |
posthog | posthog/models/person/test/test_delete_personless_personhog.py | .py | """Tests for personless distinct ID deletion via personhog RPC.
Covers routing and RPC behavior for _delete_personless_distinct_ids_for_teams
(team deletion path), which routes through delete_personless_distinct_ids_batch_for_team.
"""
from posthog.test.base import BaseTest
from unittest.mock import MagicMock
from d... | 49 | 2,289 |
posthog | posthog/models/person/test/test_batched_personhog_helpers.py | .py | from unittest.mock import ANY, MagicMock, patch
from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.models.person.util import (
_batched_get_distinct_ids_for_persons,
_batched_get_persons_by_distinct_ids,
_batched_get_persons_by_uuids,
get_persons_mapped_by_dis... | 359 | 16,063 |
posthog | posthog/models/ai/utils.py | .py | import json
from typing import Any
from pydantic import BaseModel, Field
from posthog.clickhouse.client.execute import sync_execute
from posthog.hogql_queries.ai.vector_search_query_runner import LATEST_ACTIONS_EMBEDDING_VERSION
from posthog.models.ai.pg_embeddings import INSERT_BULK_PG_EMBEDDINGS_SQL
class PgEmbed... | 63 | 1,867 |
posthog | posthog/models/ai/pg_embeddings.py | .py | from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
from posthog.clickhouse.table_engines import ReplacingMergeTree, ReplicationScheme
def PG_EMBEDDINGS_DATA_TABLE():
return "pg_embeddings"
PG_EMBEDDINGS_TABLE_BASE_SQL = """
CREATE TABLE IF NOT EXISTS {table_name} {on_cluster_clause}
(
domain String,
... | 56 | 1,592 |
posthog | posthog/models/dmat_slot_assignments/sql.py | .py | """ClickHouse schema for the dmat slot-assignments dictionary.
The weekly dmat backfill workflow writes the current `(team_id, column_index) β
property_name` mapping into `dmat_slot_assignments` and then reloads the
`dmat_slot_assignments_dict` dictionary on every host. The mutation that
follows reads the mapping via ... | 115 | 4,851 |
posthog | posthog/models/element/__init__.py | .py | from .element import Element, chain_to_elements, elements_to_string
__all__ = ["Element", "chain_to_elements", "elements_to_string"]
| 4 | 134 |
posthog | posthog/models/element/element.py | .py | import re
from collections.abc import Callable
from django.contrib.postgres.fields import ArrayField
from django.db import models
class Element(models.Model):
USEFUL_ELEMENTS = ["a", "button", "input", "select", "textarea", "label"]
text = models.CharField(max_length=10_000, null=True, blank=True)
tag_na... | 197 | 7,931 |
posthog | posthog/models/entity/util.py | .py | from collections.abc import Sequence
from typing import Any
from posthog.hogql.hogql import HogQLContext
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
from posthog.models.entity import Entity
from posthog.queries.util import PersonPropertiesMode
from products.actions.backend.models.util import format_actio... | 67 | 2,742 |
posthog | posthog/models/entity/__init__.py | .py | from .entity import Entity, ExclusionEntity, MathType
__all__ = ["Entity", "ExclusionEntity", "MathType"]
| 4 | 107 |
posthog | posthog/models/entity/entity.py | .py | import inspect
from collections import Counter
from typing import TYPE_CHECKING, Any, Literal, Optional
from django.conf import settings
from rest_framework.exceptions import ValidationError
from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE, TREND_FILTER_TYPE_EVENTS
from posth... | 219 | 7,804 |
posthog | posthog/models/file_system/file_system_shortcut.py | .py | from django.db import models
from django.db.models.expressions import F
from django.db.models.functions import Lower
from django.utils import timezone
from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import uuid7
class FileSystemShortcut(models.Model):
"""
A... | 38 | 1,507 |
posthog | posthog/models/file_system/file_system.py | .py | from datetime import datetime
from typing import Optional
from django.db import models
from django.db.models import Q
from django.db.models.expressions import F
from django.utils import timezone
from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q
from posthog.models.file_system.file_system_sho... | 152 | 5,195 |
posthog | posthog/models/file_system/file_system_mixin.py | .py | import dataclasses
from typing import TYPE_CHECKING, Any, Optional
from django.db.models import CharField, Exists, F, Model, OuterRef, Q, QuerySet
from django.db.models.functions import Cast
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from posthog.exceptions_captur... | 130 | 5,618 |
posthog | posthog/models/file_system/persisted_folder.py | .py | from django.db import models
from django.db.models import Value
from django.db.models.expressions import F
from django.db.models.functions import Coalesce
from django.utils import timezone
from posthog.models.file_system.constants import DEFAULT_SURFACE
from posthog.models.team import Team
from posthog.models.user imp... | 69 | 2,805 |
posthog | posthog/models/file_system/unfiled_file_saver.py | .py | # posthog/models/file_system/unfiled_file_saver.py
from datetime import datetime
from typing import Optional
from django.utils import timezone
from posthog.models.file_system.constants import DEFAULT_SURFACE
from posthog.models.file_system.file_system import FileSystem, escape_path, split_path
from posthog.models.fil... | 120 | 4,729 |
posthog | posthog/models/file_system/constants.py | .py | from django.db.models import Q
# The product surface a FileSystem row belongs to. Legacy rows predate this column and are
# stored as NULL; they are read as the default ("web"). New rows always store an explicit value.
DEFAULT_SURFACE = "web"
def surface_q(surface: str) -> Q:
"""Build the read filter for a surfa... | 13 | 511 |
posthog | posthog/models/file_system/file_system_view_log.py | .py | from __future__ import annotations
from collections.abc import Sequence
from dataclasses import is_dataclass
from datetime import datetime
from typing import TYPE_CHECKING, Optional, cast
from django.db import IntegrityError, models
from django.db.models import Q, QuerySet
from django.db.models.signals import post_de... | 215 | 8,620 |
posthog | posthog/models/file_system/user_product_list.py | .py | from typing import TYPE_CHECKING, Any, ClassVar, cast
from django.conf import settings
from django.db import models, transaction
from django.db.models import Count
from django.db.models.expressions import F
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
from django.utils... | 416 | 17,545 |
posthog | posthog/models/file_system/file_system_representation.py | .py | # posthog/models/file_system/file_system_representation.py
from dataclasses import dataclass
from typing import Any
from posthog.models.file_system.constants import DEFAULT_SURFACE
@dataclass
class FileSystemRepresentation:
"""
Defines the minimal data needed to create/update a FileSystem entry:
- bas... | 31 | 729 |
posthog | posthog/models/file_system/test/test_file_system_mixin.py | .py | from django.test import TestCase
from posthog.models import FileSystem, Organization, Team, User
from posthog.models.file_system.file_system_view_log import FileSystemViewLog
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from p... | 266 | 12,641 |
posthog | posthog/models/file_system/test/test_file_system.py | .py | from django.test import TestCase
from posthog.models import Organization, Team, User
from posthog.models.file_system.file_system import (
DEFAULT_SURFACE,
FileSystem,
create_or_update_file,
delete_file,
escape_path,
join_path,
split_path,
surface_q,
)
from posthog.models.file_system.unf... | 293 | 14,027 |
posthog | posthog/models/file_system/test/test_user_product_list.py | .py | from posthog.test.base import BaseTest
from posthog.schema import ProductItemCategory
from posthog.models import User
from posthog.models.file_system.user_product_list import (
DEFAULT_PRODUCT_PATHS,
UserProductList,
add_default_products_for_user,
get_user_product_list_count,
)
from posthog.products i... | 382 | 18,739 |
posthog | posthog/models/file_system/test/test_file_system_view_log.py | .py | from datetime import UTC, datetime
from typing import Protocol, cast
from freezegun import freeze_time
from django.test import TestCase
from posthog.models import FileSystem, FileSystemViewLog, Organization, Team, User
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
from po... | 145 | 6,702 |
posthog | posthog/models/app_metrics2/sql.py | .py | from django.conf import settings
from posthog.clickhouse.kafka_engine import (
CONSUMER_GROUP_APP_METRICS2,
CONSUMER_GROUP_APP_METRICS2_WS,
KAFKA_COLUMNS_WITH_PARTITION,
kafka_engine,
ttl_period,
)
from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme
fro... | 207 | 5,690 |
posthog | posthog/models/activity_logging/utils.py | .py | import traceback
from typing import TYPE_CHECKING, Any, Optional, cast
from django.db import models
from django.db.models import Q, QuerySet
import structlog
from asgiref.local import Local
from posthog.dataclasses import frozen
if TYPE_CHECKING:
from posthog.models.activity_logging.activity_log import Activity... | 235 | 8,189 |
posthog | posthog/models/activity_logging/notification_viewed.py | .py | from django.db import models
from posthog.models.utils import UUIDTModel
class NotificationViewed(UUIDTModel):
user = models.ForeignKey("posthog.User", null=True, on_delete=models.SET_NULL)
# when viewing notifications made by viewing the activity log we count unread notifications
# as any after the last... | 14 | 522 |
posthog | posthog/models/activity_logging/tag_utils.py | .py | from posthog.dataclasses import frozen
from posthog.models.tagged_item import RELATED_OBJECTS
@frozen
class RelatedObjectInfo:
type: str | None
id: str | None
name: str | None
def get_tagged_item_related_object_info(tagged_item) -> RelatedObjectInfo:
related_object_type = None
related_object_id ... | 36 | 1,173 |
posthog | posthog/models/activity_logging/serializers.py | .py | from drf_spectacular.utils import extend_schema_field, extend_schema_serializer
from rest_framework import serializers
from posthog.models import User
from posthog.models.activity_logging.activity_log import ActivityLog
class UserMinimalSerializer(serializers.ModelSerializer):
class Meta:
model = User
... | 72 | 2,871 |
posthog | posthog/models/activity_logging/project_secret_api_key_utils.py | .py | import uuid
import dataclasses
from collections import namedtuple
from typing import Optional
from posthog.models.activity_logging.activity_log import (
ActivityContextBase,
Detail,
LogActivityEntry,
bulk_log_activity,
)
from posthog.models.activity_logging.personal_api_key_utils import get_organizatio... | 91 | 3,170 |
posthog | posthog/models/activity_logging/external_data_utils.py | .py | from posthog.models.activity_logging.utils import CreatedByInfo
from products.warehouse_sources.backend.facade.models import ExternalDataSource
def get_external_data_source_detail_name(external_data_source: ExternalDataSource) -> str:
"""Generate detail name for ExternalDataSource activity"""
source_type = e... | 32 | 1,258 |
posthog | posthog/models/activity_logging/personal_api_key_utils.py | .py | import uuid
import dataclasses
from collections import namedtuple
from typing import Optional
from django.db.models import Count
from posthog.models import PersonalAPIKey
from posthog.models.activity_logging.activity_log import (
ActivityContextBase,
Detail,
LogActivityEntry,
bulk_log_activity,
)
from... | 270 | 10,099 |
posthog | posthog/models/activity_logging/model_activity.py | .py | from typing import Any
from django.db import models
from posthog.models.activity_logging.utils import activity_storage, get_changed_fields_local
from posthog.models.signals import model_activity_signal
def get_was_impersonated():
return activity_storage.get_was_impersonated()
def get_current_user():
retur... | 216 | 7,778 |
posthog | posthog/models/activity_logging/signal_handlers.py | .py | import sys
import time
import dataclasses
from collections.abc import Callable
from datetime import timedelta
from typing import Literal, Optional
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.core.sig... | 943 | 35,065 |
posthog | posthog/models/activity_logging/activity_log.py | .py | import json
import dataclasses
from typing import TYPE_CHECKING, Any, Literal, Optional, Required, TypedDict, Union, cast
from uuid import UUID
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.contrib.postgres.indexes import GinIndex
from django.core.exceptions import F... | 1,359 | 47,320 |
posthog | posthog/models/activity_logging/batch_export_utils.py | .py | from posthog.models.activity_logging.utils import CreatedByInfo
def get_batch_export_destination_type(batch_export) -> str:
"""Get destination type from BatchExport"""
destination_type = ""
try:
if batch_export.destination:
destination_type = batch_export.destination.type
except Ex... | 33 | 1,269 |
posthog | posthog/models/activity_logging/activity_page.py | .py | from rest_framework import request, response, serializers, status
from posthog.models.activity_logging.activity_log import ActivityPage
from posthog.models.activity_logging.serializers import ActivityLogSerializer
from posthog.utils import format_query_params_absolute_url
class ActivityLogPaginatedResponseSerializer... | 33 | 1,300 |
posthog | posthog/models/event/deletion.py | .py | """Helpers for applying event deletions and mutations to every physical events table.
While the legacy String-properties events table and the native-JSON events table coexist
(dual-write via ``events_json_table_mv``), every delete or mutation applied to
``sharded_events`` must also be applied to ``sharded_events_json`... | 44 | 2,067 |
posthog | posthog/models/event/sql.py | .py | from django.conf import settings
from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_clickhouse_string
from posthog.clickhouse.base_sql import COPY_ROWS_BETWEEN_TEAMS_BASE_SQL
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
# The events-JSON schema declarations (table names, JSON subco... | 926 | 34,180 |
posthog | posthog/models/event/new_events_schema.py | .py | from django.conf import settings
from posthog.models.instance_setting import get_instance_setting
def use_new_events_schema(team_id: int | None = None) -> bool:
"""Whether HogQL reads should target the native-JSON events tables.
The instance setting flips it globally at runtime, and the *_TEAMS instance set... | 37 | 1,673 |
posthog | posthog/models/event/util.py | .py | import json
import uuid
from datetime import UTC, datetime
from typing import Any, Literal, Optional, Union
from zoneinfo import ZoneInfo
from django.conf import settings
from django.utils import timezone
from dateutil.parser import isoparse
from drf_spectacular.utils import extend_schema_field, extend_schema_seriali... | 512 | 20,398 |
posthog | posthog/models/event/__init__.py | .py | from .event import DEFAULT_EARLIEST_TIME_DELTA, Event, Selector, SelectorPart
__all__ = ["DEFAULT_EARLIEST_TIME_DELTA", "Event", "Selector", "SelectorPart"]
| 4 | 158 |
posthog | posthog/models/event/event.py | .py | import re
import copy
import datetime
from collections import defaultdict
from typing import Optional, Union
from django.db import models
from django.utils import timezone
from dateutil.relativedelta import relativedelta
from posthog.models.team import Team
SELECTOR_ATTRIBUTE_REGEX = r"([a-zA-Z]*)\[(.*)=[\'|\"](.*)... | 155 | 6,471 |
posthog | posthog/models/event/legacy_events_query.py | .py | import uuid
import random
import builtins
from datetime import datetime, timedelta
from typing import Optional, cast
from django.conf import settings
from django.core.cache import cache
from posthog.schema import EventsQuery, HogQLQueryModifiers
from posthog.hogql import ast
from posthog.hogql.constants import HogQL... | 302 | 13,971 |
posthog | posthog/models/web_preaggregated/migrations.py | .py | # Attribution fields addition for migration 0126
ADD_ATTRIBUTION_FIELDS_SQL = """
ALTER TABLE {table_name}
ADD COLUMN IF NOT EXISTS
has_gclid Bool,
ADD COLUMN IF NOT EXISTS
has_gad_source_paid_search Bool,
ADD COLUMN IF NOT EXISTS
has_fbclid Bool
AFTER region_name
"""
def add_attribution_fields_to_table(table_name: s... | 35 | 893 |
posthog | posthog/models/web_preaggregated/sql.py | .py | import uuid
from django.conf import settings
from posthog.hogql.database.schema.web_analytics_s3 import get_s3_function_args
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
from posthog.clickhouse.table_engines import MergeTreeEngine, ReplicationScheme
from posthog.models.web_preaggregated.team_selection im... | 897 | 34,109 |
posthog | posthog/models/web_preaggregated/team_selection.py | .py | from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
from posthog.clickhouse.table_engines import ReplacingMergeTree
from posthog.settings.data_stores import CLICKHOUSE_DATABASE
WEB_PRE_AGGREGATED_TEAM_SELECTION_TABLE_NAME = "web... | 153 | 5,190 |
posthog | posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py | .py | from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from parameterized import parameterized
from posthog.schema import DateRange, HogQLQueryModifiers, WebStatsBreakdown, WebStatsTableQuery
from posthog.clickhouse.client.execute import sync_execute
from p... | 469 | 22,892 |
posthog | posthog/models/web_preaggregated/team_selection_strategies.py | .py | import os
from abc import ABC, abstractmethod
import dagster
from posthog.clickhouse.client import sync_execute
from posthog.models.team.team import Team
from posthog.models.web_preaggregated.team_selection import (
DEFAULT_TOP_TEAMS_BY_PAGEVIEWS_LIMIT,
DEFAULT_WEEKLY_PAGEVIEWS_THRESHOLD,
get_teams_by_wee... | 152 | 5,519 |
posthog | posthog/models/web_preaggregated/test_web_preaggregated_sql.py | .py | import pytest
from freezegun import freeze_time
from posthog.test.base import _create_event, _create_person
from posthog.clickhouse.client.execute import sync_execute
from posthog.models.utils import uuid7
from posthog.models.web_preaggregated.sql import (
DROP_PARTITION_SQL,
HOURLY_TABLE_TEMPLATE,
TABLE_T... | 418 | 16,621 |
posthog | posthog/models/web_preaggregated/test/test_team_selection_strategies.py | .py | from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import Mock
from posthog.models import Team
from posthog.models.web_preaggregated.team_selection_strategies import ProjectSettingsStrategy
class TestProjectSettingsStrategyIntegration(ClickhouseTestMixin, APIBaseTest):
def setUp(se... | 80 | 3,379 |
posthog | posthog/models/kafka_debug/sql.py | .py | from dataclasses import dataclass
from posthog.clickhouse.kafka_engine import kafka_engine
from posthog.clickhouse.table_engines import MergeTreeEngine
from posthog.settings import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE
@dataclass
class KafkaDebugKafkaTable:
brokers: list[str]
topic: str
consumer_group:... | 102 | 2,961 |
posthog | posthog/models/precalculated_person_properties/sql.py | .py | from django.conf import settings
from posthog.clickhouse.kafka_engine import (
CONSUMER_GROUP_PRECALCULATED_PERSON_PROPERTIES,
CONSUMER_GROUP_PRECALCULATED_PERSON_PROPERTIES_WS,
kafka_engine,
)
from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme
from posthog.sett... | 211 | 7,270 |
posthog | posthog/models/message_assets/sql.py | .py | from django.conf import settings
from posthog.clickhouse.kafka_engine import (
CONSUMER_GROUP_MESSAGE_ASSETS,
KAFKA_COLUMNS_WITH_PARTITION,
kafka_engine,
ttl_period,
)
from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme
from posthog.kafka_client.topics import... | 211 | 5,668 |
posthog | posthog/models/duplicate_events/sql.py | .py | from django.conf import settings
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
from posthog.clickhouse.indexes import index_by_kafka_timestamp
from posthog.clickhouse.kafka_engine import KAFKA_COLUMNS_WITH_PARTITION, kafka_engine
from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine
DUP... | 153 | 4,720 |
posthog | posthog/models/exchange_rate/sql.py | .py | import os
import re
import csv
import datetime
from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
from posthog.clickhouse.table_engines import ReplacingMergeTree
from posthog.settings.data_stores import CLICKHOUSE_DATABASE
fro... | 250 | 10,225 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.