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/hogql/database/schema/test/base.py
.py
import csv import tempfile from datetime import datetime from pathlib import Path from freezegun import freeze_time from posthog.test.base import BaseTest, ClickhouseTestMixin from unittest.mock import patch from posthog.schema import HogQLQueryModifiers from posthog.hogql.parser import parse_select from posthog.hog...
179
7,552
posthog
posthog/hogql/database/schema/test/test_sessions_v1.py
.py
import pytest from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, ClickhouseTestMixin, _create_event from django.db.utils import IntegrityError from parameterized import parameterized from posthog.schema import BounceRatePageViewMode, HogQLQueryModifiers, SessionTableVersion from posthog.hogql ...
388
12,973
posthog
posthog/hogql/database/schema/test/test_persons_revenue_analytics.py
.py
from decimal import Decimal from freezegun import freeze_time from posthog.test.base import _create_event, _create_person, snapshot_clickhouse_queries from parameterized import parameterized from posthog.schema import ( CurrencyCode, DateRange, HogQLQueryModifiers, PersonsOnEventsMode, RevenueAna...
588
25,401
posthog
posthog/hogql/database/schema/util/uuid.py
.py
from posthog.hogql import ast def uuid_string_expr_to_uuid_expr(uuid_expr: ast.Expr) -> ast.Expr: return ast.Call(name="toUUID", args=[uuid_expr]) def uuid_string_expr_to_uint128_expr(uuid_expr: ast.Expr) -> ast.Expr: return ast.Call(name="_toUInt128", args=[(uuid_string_expr_to_uuid_expr(uuid_expr))]) de...
76
2,196
posthog
posthog/hogql/database/schema/util/where_clause_extractor.py
.py
import random import string from collections.abc import Callable from datetime import datetime from typing import Optional, cast from django.core.cache import cache from posthog.hogql import ast from posthog.hogql.ast import CompareOperationOp from posthog.hogql.context import HogQLContext from posthog.hogql.database...
1,388
60,429
posthog
posthog/hogql/database/schema/util/revenue_analytics.py
.py
from typing import Literal from posthog.schema_enums import DatabaseSchemaManagedViewTableKind from products.revenue_analytics.backend.views.schemas import SCHEMAS as VIEW_SCHEMAS def get_table_kind( view_name: str, ) -> ( Literal[ DatabaseSchemaManagedViewTableKind.REVENUE_ANALYTICS_CUSTOMER, ...
53
1,905
posthog
posthog/hogql/database/schema/util/test/test_session_v3_where_clause_extractor.py
.py
from datetime import UTC, datetime from typing import Any, Optional, Union import pytest from posthog.test.base import APIBaseTest, ClickhouseTestMixin from django.conf import settings from posthog.schema import SessionTableVersion from posthog.hogql import ast from posthog.hogql.context import HogQLContext from po...
653
27,809
posthog
posthog/hogql/database/schema/util/test/test_predicate_pushdown.py
.py
from typing import Optional from parameterized import parameterized from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.lazy_join_tags import FOREIGN_KEY from posthog.hogql.database.models import LazyJoin from posthog.hogql.database.schema.events import EventsTable...
265
11,796
posthog
posthog/hogql/database/schema/util/test/test_session_where_clause_extractor.py
.py
from typing import Any, Optional, Union import pytest from posthog.test.base import APIBaseTest, ClickhouseTestMixin from django.conf import settings from parameterized import parameterized from posthog.schema import SessionTableVersion from posthog.hogql import ast from posthog.hogql.context import HogQLContext f...
522
23,170
posthog
posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.py
.py
from datetime import UTC, datetime from typing import Any, Optional, Union import pytest from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event from django.conf import settings from parameterized import parameterized from posthog.schema import SessionTableVersion from posthog.hogql import as...
1,175
55,793
posthog
posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.py
.py
from typing import Optional, Union from posthog.test.base import APIBaseTest, ClickhouseTestMixin from posthog.schema import PersonsArgMaxVersion, PersonsOnEventsMode from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.modifiers import create_default_modifiers_for_team fro...
226
9,905
posthog
posthog/hogql/transforms/logical_property_lowering.py
.py
"""First pass: turn every `properties.x` read into a plain `PropertyAccess` node. A property read starts life as a `Field` tagged with a `PropertyType` ("this is a property"). This pass rewrites each one into a `PropertyAccess` — "read this key path out of this JSON blob". It makes no decision about *how* to read the ...
81
5,036
posthog
posthog/hogql/transforms/order_by_pushdown.py
.py
from collections.abc import Callable from typing import Optional from posthog.hogql import ast from posthog.hogql.visitor import CloningVisitor def unwrap_alias(node: ast.Expr) -> ast.Expr: if isinstance(node, ast.Alias): return unwrap_alias(node.expr) return node def resolve_alias(expr: ast.Expr, ...
77
2,668
posthog
posthog/hogql/transforms/type_aware_simplification.py
.py
from __future__ import annotations import json import math from datetime import date, datetime, timedelta from typing import cast from uuid import UUID from posthog.hogql import ast from posthog.hogql.base import _T_AST from posthog.hogql.constants import HogQLDialect from posthog.hogql.context import HogQLContext fr...
585
22,656
posthog
posthog/hogql/transforms/lazy_tables.py
.py
import dataclasses from typing import Optional, cast from posthog.hogql import ast from posthog.hogql.base import _T_AST from posthog.hogql.constants import HogQLDialect from posthog.hogql.context import HogQLContext from posthog.hogql.database.models import LazyJoinToAdd, LazyTableToAdd from posthog.hogql.errors impo...
747
36,364
posthog
posthog/hogql/transforms/property_types.py
.py
from datetime import datetime from typing import Literal, Optional from posthog.hogql import ast from posthog.hogql.constants import EXCEPTION_STRING_ARRAY_PROPERTIES from posthog.hogql.context import HogQLContext from posthog.hogql.database.models import BooleanDatabaseField, DateTimeDatabaseField, StringJSONDatabase...
825
38,448
posthog
posthog/hogql/transforms/in_cohort.py
.py
from typing import Literal, Optional, cast from posthog.hogql import ast from posthog.hogql.base import _T_AST from posthog.hogql.constants import HogQLDialect from posthog.hogql.context import HogQLContext from posthog.hogql.errors import QueryError from posthog.hogql.escape_sql import escape_clickhouse_string from p...
477
20,511
posthog
posthog/hogql/transforms/federated_join_merge.py
.py
"""Merge sibling aggregating LEFT JOINs over federated Postgres tables into one join. A select like `accounts LEFT JOIN (agg₁) LEFT JOIN (agg₂) LEFT JOIN (agg₃)`, where each right side is a `GROUP BY <key>` subquery over `postgresql(...)` reads joined on the same base key, executes its federated scans sequentially, on...
340
13,688
posthog
posthog/hogql/transforms/state_aggregations.py
.py
from typing import Union, cast from posthog.hogql import ast from posthog.hogql.functions.mapping import HOGQL_AGGREGATIONS from posthog.hogql.parser import parse_select from posthog.hogql.visitor import CloningVisitor QueryType = Union[ast.SelectQuery, ast.SelectSetQuery] """ This module provides utilities for tran...
321
15,011
posthog
posthog/hogql/transforms/clickhouse_property_resolution.py
.py
"""ClickHouse pass: read each property from a faster precomputed column when one exists. Lowering has already turned every `properties.x` read into a `PropertyAccess` node — "pull these keys out of this JSON blob". This pass looks each one up. If the property is backed by a precomputed column (a materialized column, a...
1,734
82,000
posthog
posthog/hogql/transforms/projection_pushdown.py
.py
from collections import defaultdict from typing import cast from posthog.hogql import ast from posthog.hogql.base import _T_AST from posthog.hogql.context import HogQLContext from posthog.hogql.visitor import TraversingVisitor class ProjectionPushdownOptimizer(TraversingVisitor): """ Top-down projection push...
315
13,845
posthog
posthog/hogql/transforms/preaggregated_table_transformation.py
.py
"""This module contains an AST-to-AST transformation that converts queries on the `events` table to queries on predefined pre-aggregated tables. These tables are populated by a background process (running in dagster) that aggregates data from the `events` table, making heavy use of ClickHouse's -state suffix functions...
597
26,014
posthog
posthog/hogql/transforms/uuid_timestamp_bounds.py
.py
"""Add timestamp bounds to events queries that look up rows by UUIDv7 constants. Event uuids are UUIDv7, so the uuid constant in `uuid = '<constant>'` carries the row's approximate timestamp in its high 48 bits. When every row a WHERE clause can match is pinned to known UUIDv7 constants, we AND a buffered constant tim...
265
11,044
posthog
posthog/hogql/transforms/json_property_pushdown.py
.py
from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.models import StringJSONDatabaseField from posthog.hogql.visitor import CloningVisitor, TraversingVisitor # JSON-string extraction calls that are equivalent to a HogQL string property access. # Other JSONExtract* v...
104
4,381
posthog
posthog/hogql/transforms/events_predicate_pushdown.py
.py
"""Events predicate pushdown. Wraps a `FROM events <JOIN…> WHERE p LIMIT n` query's events scan in a pre-filtering subquery so the events table is read once, filtered and `LIMIT`-bounded, before the joins fan out: FROM events <JOIN…> WHERE <p> LIMIT n -> FROM (SELECT <needed cols> FROM events WHERE <pusha...
649
34,080
posthog
posthog/hogql/transforms/test/test_preaggregated_table_transformation.py
.py
from datetime import UTC, datetime import unittest from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, QueryMatchingTest, snapshot_clickhouse_queries from parameterized import parameterized from posthog.schema import BaseMathType, DateRange, EventsNode, HogQLQueryModifiers, TrendsQuery from po...
1,001
44,872
posthog
posthog/hogql/transforms/test/test_property_types.py
.py
import re import json from dataclasses import dataclass from datetime import datetime from typing import Any, cast import pytest from posthog.test.base import ( BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events, get_indexes_from_explain, materialized, ) from unittest.mock i...
1,599
78,314
posthog
posthog/hogql/transforms/test/test_json_property_pushdown.py
.py
from posthog.test.base import BaseTest from parameterized import parameterized from posthog.hogql.context import HogQLContext from posthog.hogql.parser import parse_select from posthog.hogql.printer import prepare_and_print_ast class TestJSONPropertyPushdown(BaseTest): def _print(self, query: str) -> str: ...
44
2,019
posthog
posthog/hogql/transforms/test/test_projection_pushdown.py
.py
import pytest from posthog.test.base import BaseTest from parameterized import parameterized from posthog.schema import HogQLQueryModifiers from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.parser import parse_select from posthog.hogql.printer import prepare_ast_for_prin...
634
27,117
posthog
posthog/hogql/transforms/test/test_state_aggregations.py
.py
from datetime import datetime from typing import Any import pytest from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events from django.conf import settings from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.parser ...
1,131
42,273
posthog
posthog/hogql/transforms/test/test_uuid_timestamp_bounds.py
.py
from posthog.test.base import BaseTest from parameterized import parameterized from posthog.schema import HogQLQueryModifiers from posthog.hogql.constants import HogQLDialect from posthog.hogql.context import HogQLContext from posthog.hogql.parser import parse_select from posthog.hogql.printer.utils import prepare_a...
124
5,049
posthog
posthog/hogql/transforms/test/test_lazy_tables.py
.py
from typing import Any import pytest from posthog.test.base import BaseTest from django.conf import settings from django.test import override_settings from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode from posthog.hogql.context import HogQLContext from posthog.hogql.parser import parse_select from...
265
12,382
posthog
posthog/hogql/transforms/test/test_events_predicate_pushdown.py
.py
import re import json from typing import Any, cast from uuid import uuid4 import pytest from posthog.test.base import ( APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events, materialized, ) from unittest.mock import patch from django.conf impo...
2,078
113,332
posthog
posthog/hogql/transforms/test/test_property_types_dmat.py
.py
"""Tests for dmat (dynamic materialized columns) integration in property type resolution.""" import json import uuid from dataclasses import dataclass from typing import Any import pytest from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events from django.con...
286
12,109
posthog
posthog/hogql/transforms/test/test_order_by_pushdown.py
.py
from typing import Any import pytest from posthog.test.base import BaseTest from posthog.hogql import ast from posthog.hogql.parser import parse_select from posthog.hogql.transforms.order_by_pushdown import push_down_order_by class TestOrderByPushdown(BaseTest): snapshot: Any maxDiff = None def _apply_...
90
3,545
posthog
posthog/hogql/transforms/test/test_in_cohort.py
.py
from typing import Any import pytest from posthog.test.base import BaseTest, QueryMatchingTest, _create_event, _create_person, flush_persons_and_events from django.conf import settings from django.test import override_settings from parameterized import parameterized from posthog.schema import HogQLQueryModifiers, I...
414
18,278
posthog
posthog/hogql/transforms/test/test_range_rewrite_observability.py
.py
"""Integration coverage for the materialized-range-rewrite observability counter. These run the real ClickHouse property-resolution transform (not the record_* hooks in isolation) so they pin the counter to the query shapes that reach it. The accumulator is injected in place of the sampling draw. The dominant producti...
159
7,183
posthog
posthog/hogql/transforms/test/test_federated_join_merge.py
.py
from posthog.test.base import BaseTest from parameterized import parameterized from posthog.schema import HogQLQueryModifiers from posthog.hogql.context import HogQLContext from posthog.hogql.parser import parse_select from posthog.hogql.printer import prepare_and_print_ast from posthog.hogql.transforms.federated_jo...
137
5,908
posthog
posthog/hogql/scripts/hog_corpus_diagnostic.py
.py
# ruff: noqa: T201, E402 """Hog-program corpus parser-parity diagnostic. Pulls real Hog program source from the `posthog_hogfunction` table on Aurora Postgres (the `hog` column — destinations, transformations and other CDP functions), runs both the oracle and candidate parsers over each, and reports where they disagre...
301
11,978
posthog
posthog/hogql/scripts/_shrink.py
.py
"""shrinkray-backed test-case minimiser for the parser-parity diagnostics. The diagnostics in this directory find queries where two parser backends disagree, then reduce each one to a minimal repro a human can paste into a regression test. The reduction used to be a hand-rolled greedy delete-one-token pass; this modul...
81
3,950
posthog
posthog/hogql/scripts/parser_bench.py
.py
# ruff: noqa: T201, I001 # CLI benchmark tool: print() is the report channel. """Side-by-side parser performance benchmark — backend-agnostic. `--oracle` defaults to `cpp-json`. `--candidate` is REQUIRED (no default) so the backend under test is always stated explicitly — pass e.g. `rust-py` or `rust-json`. The query...
632
28,734
posthog
posthog/hogql/scripts/__init__.py
.py
"""Standalone scripts and supporting tooling for HogQL development. Currently houses the grammar-driven PBT strategy generator. Anything that's runnable from the command line (rather than imported by production code) belongs here. """
7
236
posthog
posthog/hogql/scripts/log_corpus_diagnostic.py
.py
# ruff: noqa: T201, E402 """HogQL log-corpus parser-parity diagnostic. Pulls the last 7 days of HogQL queries run against production ClickHouse by any team that has opted into AI data processing (`log_comment.ai_data_processing_approved`), runs both the oracle and candidate parsers over each, and reports where they di...
332
13,686
posthog
posthog/hogql/scripts/shrink_query.py
.py
# ruff: noqa: T201, E402 """Shrink one HogQL query, read from stdin, to a minimal parser-parity repro. Reads a query on stdin, checks whether the oracle and candidate backends disagree on it, and — if they do — writes the smallest variant that still triggers the same divergence to **stdout** (via shrinkray). All diagn...
113
4,918
posthog
posthog/hogql/scripts/pbt_corpus.py
.py
"""Regression corpus tool for parser-parity divergences. Companion to `pbt_diagnostic.py`. Two subcommands: extract Read a divergences JSONL (produced by `pbt_diagnostic.py --write-divergences`) and write a deduplicated corpus — one entry per (kind, oracle_root, candidate_root, ter...
254
11,560
posthog
posthog/hogql/scripts/_diagnostic_common.py
.py
# ruff: noqa: T201 """Shared helpers for the HogQL parser-parity diagnostic scripts. Imported by `pbt_diagnostic.py`, `pbt_corpus.py`, `parser_bench.py`, and `log_corpus_diagnostic.py` in this directory. Not a CLI itself — the leading underscore marks it as a private helper module. Holds the cross-script vocabulary: ...
953
41,495
posthog
posthog/hogql/scripts/build_grammar_strategies.py
.py
#!/usr/bin/env python3 """Regenerate the HogQL grammar PBT strategies module. Reads ``posthog/hogql/grammar/HogQLParser.g4`` and ``posthog/hogql/grammar/HogQLLexer.common.g4`` and emits ``posthog/hogql/test/_generated_grammar_strategies.py``. The output is a Python module of Hypothesis strategies — one per parser rul...
1,362
56,214
posthog
posthog/hogql/direct_sql/redshift_adapter.py
.py
from typing import TYPE_CHECKING, cast import psycopg import sqlparse from opentelemetry import trace from sqlparse import tokens as sqlparse_tokens from sshtunnel import BaseSSHTunnelForwarderError from posthog.hogql.constants import HogQLDialect from posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EX...
178
9,538
posthog
posthog/hogql/direct_sql/clickhouse_adapter.py
.py
from collections.abc import Iterator from time import perf_counter from typing import TYPE_CHECKING, Any, cast import sqlparse from opentelemetry import trace from sqlparse import tokens as sqlparse_tokens from sqlparse.sql import TokenList from sshtunnel import BaseSSHTunnelForwarderError from posthog.hogql.constant...
316
15,990
posthog
posthog/hogql/direct_sql/__init__.py
.py
from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, DirectSQLAdapter from posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capable from posthog.hogql.direct_sql.clickhouse_adapter import ClickHouseAdapter from posthog.hogql.direct_sql.motherduck_adapter i...
36
1,408
posthog
posthog/hogql/direct_sql/raw_sql.py
.py
import sqlparse from posthog.hogql.errors import ExposedHogQLError def ensure_single_direct_statement(sql: str) -> str: """Reject multi-statement raw SQL. Raw queries run without bound parameters, so psycopg uses the simple query protocol, which runs every ``;``-separated statement in one round trip. A ...
20
832
posthog
posthog/hogql/direct_sql/registry.py
.py
from posthog.hogql.direct_sql.adapter import DirectSQLAdapter _ADAPTERS: dict[str, DirectSQLAdapter] = {} def register_adapter(adapter: DirectSQLAdapter) -> None: _ADAPTERS[adapter.engine] = adapter def get_adapter(engine: str | None) -> DirectSQLAdapter | None: if engine is None: return None r...
18
433
posthog
posthog/hogql/direct_sql/capability.py
.py
from products.warehouse_sources.backend.facade.models import ExternalDataSource from products.warehouse_sources.backend.facade.types import DIRECT_ENGINE_BY_SOURCE_TYPE def direct_capable_source_types() -> frozenset[str]: """Source types that map to a direct-SQL engine (the static capability surface).""" retu...
32
1,382
posthog
posthog/hogql/direct_sql/adapter.py
.py
import dataclasses from typing import TYPE_CHECKING, Any, Protocol from posthog.hogql.constants import HogQLDialect, HogQLGlobalSettings from posthog.hogql.timings import HogQLTimings if TYPE_CHECKING: from posthog.models.team import Team from products.warehouse_sources.backend.facade.models import ExternalD...
55
1,731
posthog
posthog/hogql/direct_sql/mysql_adapter.py
.py
from typing import TYPE_CHECKING, cast import pymysql import sqlparse from opentelemetry import trace from pymysql.constants import FIELD_TYPE as MYSQL_FIELD_TYPE from sqlparse import tokens as sqlparse_tokens from sqlparse.sql import Statement from sshtunnel import BaseSSHTunnelForwarderError from posthog.hogql.cons...
192
8,649
posthog
posthog/hogql/direct_sql/motherduck_adapter.py
.py
from __future__ import annotations import re import threading from typing import TYPE_CHECKING, cast import sqlparse from opentelemetry import trace from sqlparse import tokens as sqlparse_tokens from sqlparse.sql import Token from posthog.hogql.constants import HogQLDialect from posthog.hogql.direct_query_metrics i...
284
13,100
posthog
posthog/hogql/direct_sql/postgres_adapter.py
.py
from contextlib import ExitStack from datetime import date, datetime from typing import TYPE_CHECKING, TypedDict, cast import psycopg from opentelemetry import trace from psycopg.types.datetime import DateLoader from sshtunnel import BaseSSHTunnelForwarderError from posthog.hogql.constants import HogQLDialect from po...
340
14,823
posthog
posthog/hogql/direct_sql/snowflake_adapter.py
.py
from __future__ import annotations import re from typing import TYPE_CHECKING, cast import sqlparse from opentelemetry import trace from sqlparse import tokens as sqlparse_tokens from posthog.hogql.constants import HogQLDialect from posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, obser...
239
12,344
posthog
posthog/hogql/direct_sql/test/test_clickhouse_adapter.py
.py
from typing import Any from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.test import SimpleTestCase from parameterized import parameterized from sshtunnel import BaseSSHTunnelForwarderError from posthog.hogql.constants import HogQLGlobalSettings from posthog.hogql.context...
240
11,219
posthog
posthog/hogql/direct_sql/test/test_motherduck_adapter.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from django.test import SimpleTestCase import duckdb from parameterized import parameterized from posthog.hogql.constants import HogQLDialect from posthog.hogql.context import HogQLContext from posthog.hogql.database.database import Database from...
302
13,393
posthog
posthog/hogql/direct_sql/test/test_registry_and_capability.py
.py
from django.test import SimpleTestCase from parameterized import parameterized from posthog.hogql.direct_sql import ( ClickHouseAdapter, MySQLAdapter, PostgresAdapter, registry as registry_module, ) from posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capable from pos...
90
4,222
posthog
posthog/hogql/test/test_autocomplete.py
.py
from typing import Optional from posthog.test.base import APIBaseTest, ClickhouseTestMixin from parameterized import parameterized from posthog.schema import ( AutocompleteCompletionItemKind, HogLanguage, HogQLAutocomplete, HogQLAutocompleteResponse, HogQLQuery, ) from posthog.hogql import ast f...
596
24,718
posthog
posthog/hogql/test/_test_parse_string.py
.py
from collections.abc import Callable from posthog.test.base import BaseTest from hogql_parser import parse_string_literal_text as parse_string_cpp from hogql_parser_rs import parse_string_literal_text as parse_string_rust from posthog.hogql.constants import HogQLParserBackend from posthog.hogql.errors import SyntaxE...
72
3,287
posthog
posthog/hogql/test/test_type_system.py
.py
from datetime import date from typing import Optional, cast import pytest from posthog.hogql import ast from posthog.hogql.constants import HogQLDialect from posthog.hogql.context import HogQLContext from posthog.hogql.database.database import Database from posthog.hogql.database.models import FloatArrayDatabaseField...
1,328
65,600
posthog
posthog/hogql/test/test_mapping.py
.py
from datetime import UTC, date, datetime from typing import Any, Optional import pytest from freezegun import freeze_time from posthog.test.base import BaseTest, ClickhouseTestMixin from posthog.hogql import ast from posthog.hogql.ast import DateType, FloatType, IntegerType, StringLiteralType, StringType from posthog...
483
23,066
posthog
posthog/hogql/test/test_direct_postgres_query.py
.py
from datetime import date, timedelta from typing import Any, cast from uuid import uuid4 from posthog.test.base import APIBaseTest from unittest.mock import MagicMock, patch from django.test import override_settings import psycopg from parameterized import parameterized from sshtunnel import BaseSSHTunnelForwarderEr...
2,052
79,622
posthog
posthog/hogql/test/test_visitor.py
.py
from posthog.test.base import BaseTest from parameterized import parameterized from posthog.hogql import ast from posthog.hogql.ast import AST_CLASSES, HogQLXAttribute, HogQLXTag, UUIDType from posthog.hogql.base import _VISIT_NAME_REPLACEMENTS, AST, camel_case_pattern from posthog.hogql.errors import ( InternalH...
252
10,553
posthog
posthog/hogql/test/test_direct_mysql_query.py
.py
from typing import Any from uuid import uuid4 from posthog.test.base import APIBaseTest from unittest.mock import MagicMock, patch import pymysql from parameterized import parameterized from sshtunnel import BaseSSHTunnelForwarderError from posthog.hogql.direct_sql.mysql_adapter import mysql_error_to_message, mysql_...
503
19,578
posthog
posthog/hogql/test/test_parse_string_cpp.py
.py
from ._test_parse_string import parse_string_test_factory class TestParseStringCpp(parse_string_test_factory("cpp-json")): # type: ignore pass
6
150
posthog
posthog/hogql/test/utils.py
.py
import re import json import dataclasses from typing import Any from posthog.test.base import clean_varying_query_parts from pydantic import BaseModel from posthog.schema import HogQLQueryModifiers from posthog.hogql.query import execute_hogql_query def execute_hogql_query_with_timings(*args, **kwargs): modif...
164
6,452
posthog
posthog/hogql/test/test_log_query_settings.py
.py
import pytest from posthog.test.base import APIBaseTest, ClickhouseTestMixin from unittest import TestCase from clickhouse_driver.errors import ServerException from parameterized import parameterized from posthog.hogql.constants import HogQLGlobalSettings from posthog.hogql.errors import QueryError from posthog.hogql...
185
8,355
posthog
posthog/hogql/test/test_timings.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from posthog.hogql.timings import HogQLTimings EPSILON = 1e-10 counter_values: list[float] = [0] def fake_perf_counter(): counter_values[0] += 0.05 return counter_values[0] class TestHogQLTimings(BaseTest): def setUp(self): ...
91
2,961
posthog
posthog/hogql/test/test_parser_mode.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from parameterized import parameterized from posthog.schema import ParserMode from posthog.hogql import ( ast, parser as parser_module, ) from posthog.hogql.errors import SyntaxError as HogQLSyntaxError from posthog.hogql.parser import ( ...
245
12,870
posthog
posthog/hogql/test/test_parser_pbt.py
.py
"""Property-based tests for the HogQL parser ↔ printer roundtrip. We generate random AST expression trees, print them to HogQL strings, then parse them back and verify the result matches the original. Because the printer normalises some constructs (e.g. ``1 + 2`` → ``plus(1, 2)``), we compare at the *printed-string* l...
616
22,744
posthog
posthog/hogql/test/test_get_lowercase_index_hint.py
.py
import os import json from typing import cast from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, get_index_from_explain from posthog.schema import ( DateRange, FilterLogicalOperator, LogPropertyFilter, LogPropertyFilterType, LogsQuery, PropertyGroupFilter, PropertyGr...
276
10,633
posthog
posthog/hogql/test/test_parser_cpp_json.py
.py
import gc import tracemalloc from posthog.test.base import BaseTest from posthog.hogql.errors import ExposedHogQLError from posthog.hogql.parser import parse_program from ._test_parser import parser_test_factory class TestParserCppJson(parser_test_factory("cpp-json")): # type: ignore def test_empty(self): ...
46
1,946
posthog
posthog/hogql/test/test_parser_cache.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from parameterized import parameterized from posthog.hogql import ast from posthog.hogql.errors import BaseHogQLError from posthog.hogql.parser import ( _MAX_CACHEABLE_STATEMENT_LEN, _MIN_CACHEABLE_STATEMENT_LEN, CacheOrigin, _buil...
234
11,264
posthog
posthog/hogql/test/test_observability.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from django.test import SimpleTestCase from parameterized import parameterized from prometheus_client import REGISTRY from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.database import Databas...
281
13,768
posthog
posthog/hogql/test/test_metadata.py
.py
from typing import Optional from posthog.test.base import APIBaseTest, ClickhouseTestMixin from unittest.mock import patch from django.conf import settings from django.db import DatabaseError from django.test import override_settings from posthog.schema import ( HogLanguage, HogQLMetadata, HogQLMetadataR...
1,151
44,606
posthog
posthog/hogql/test/test_parser_rust_json.py
.py
"""Tests for the hand-rolled Rust HogQL parser (`rust-json` backend). The full parser-behaviour suite lives in `_test_parser.py` and runs against every backend via `parser_test_factory`. This file only wires the `rust-json` backend into that suite. """ from ._test_parser import parser_test_factory class TestParserR...
16
554
posthog
posthog/hogql/test/test_property.py
.py
from collections.abc import Iterable from typing import Any, Literal, Optional, Union, cast from freezegun import freeze_time from posthog.test.base import APIBaseTest, BaseTest, _create_event, cleanup_materialized_columns from unittest.mock import MagicMock, patch from django.conf import settings from parameterized...
2,185
95,919
posthog
posthog/hogql/test/test_warehouse_warnings.py
.py
from posthog.test.base import BaseTest from posthog.schema import DataWarehouseSyncWarning from posthog.hogql.warehouse_warnings import accumulator_scope, install_accumulator, record_warnings, reset_accumulator def _make_warning(table_name: str = "t", schema_name: str = "s") -> DataWarehouseSyncWarning: return ...
82
3,163
posthog
posthog/hogql/test/test_modifiers.py
.py
from typing import NamedTuple from posthog.test.base import BaseTest from unittest.mock import patch from django.conf import settings from django.test import override_settings from posthog.schema import HogQLQueryModifiers, MaterializationMode, PersonsArgMaxVersion, PersonsOnEventsMode from posthog.hogql.modifiers ...
343
15,567
posthog
posthog/hogql/test/_grammar_token_strategies.py
.py
"""Hand-written Hypothesis strategies for variable-content HogQL tokens. The grammar codegen (``posthog/hogql/scripts/build_grammar_strategies.py``) can resolve keyword and punctuation tokens to literal text by reading the lexer .g4. Variable-content tokens (identifiers, numbers, strings) need real strategies; this fi...
289
9,715
posthog
posthog/hogql/test/test_resolver.py
.py
from datetime import UTC, date, datetime from typing import Any, ClassVar, Optional, cast from uuid import UUID import pytest from freezegun import freeze_time from posthog.test.base import BaseTest from unittest.mock import patch from django.test import override_settings from parameterized import parameterized fro...
2,126
102,064
posthog
posthog/hogql/test/test_hogqlx.py
.py
from posthog.test.base import BaseTest from posthog.hogql import ast from posthog.hogql.hogqlx import convert_dict_to_hx, convert_tag_to_hx, convert_to_hx class TestHogQLX(BaseTest): def test_convert_tag_to_hx(self): tag = ast.HogQLXTag(kind="Sparkline", attributes=[]) self.assertEqual( ...
70
2,819
posthog
posthog/hogql/test/test_group_filtering.py
.py
""" Tests for created_at filtering of group fields based on GroupTypeMapping creation time. """ from datetime import UTC, datetime from posthog.test.base import APIBaseTest from django.conf import settings from parameterized import parameterized from posthog.hogql.context import HogQLContext from posthog.hogql.dat...
236
9,470
posthog
posthog/hogql/test/test_base.py
.py
import gc import copy import weakref import dataclasses from typing import Any import pytest from posthog.test.base import BaseTest import pydantic from parameterized import parameterized from posthog.hogql import ast from posthog.hogql.base import AST from posthog.hogql.context import HogQLContext from posthog.hogq...
463
18,579
posthog
posthog/hogql/test/test_placeholders.py
.py
from typing import cast from posthog.test.base import BaseTest from parameterized import parameterized from posthog.hogql import ast from posthog.hogql.errors import QueryError from posthog.hogql.parser import parse_expr, parse_select from posthog.hogql.placeholders import find_placeholders, replace_placeholders fro...
244
10,126
posthog
posthog/hogql/test/test_direct_snowflake_query.py
.py
from types import SimpleNamespace from typing import TYPE_CHECKING, cast from uuid import uuid4 import unittest from posthog.test.base import APIBaseTest from unittest.mock import MagicMock, patch import snowflake.connector from parameterized import parameterized from posthog.hogql.direct_sql.snowflake_adapter impor...
398
16,958
posthog
posthog/hogql/test/test_filters.py
.py
from typing import Any, Optional from freezegun import freeze_time from posthog.test.base import BaseTest from parameterized import parameterized from posthog.schema import ( Breakdown, BreakdownFilter, CohortPropertyFilter, DateRange, ElementPropertyFilter, EventMetadataPropertyFilter, E...
1,005
44,755
posthog
posthog/hogql/test/test_direct_connection_discovery.py
.py
from uuid import uuid4 from posthog.test.base import APIBaseTest, ClickhouseTestMixin from parameterized import parameterized from posthog.hogql.database.database import Database from posthog.hogql.errors import ExposedHogQLError from posthog.hogql.query import execute_hogql_query from products.warehouse_sources.ba...
135
5,505
posthog
posthog/hogql/test/test_escape_sql.py
.py
from datetime import datetime from posthog.test.base import BaseTest, ClickhouseTestMixin from parameterized import parameterized from posthog.hogql import ast from posthog.hogql.errors import QueryError, ResolutionError from posthog.hogql.escape_sql import ( escape_clickhouse_identifier, escape_clickhouse_s...
223
11,943
posthog
posthog/hogql/test/test_property_skip_indexes.py
.py
"""Verify property_to_expr emits SQL that uses ClickHouse skip indexes. Cross product of (operator) × (skip index type) × (materialization strategy) × (property scope), checked via ``EXPLAIN PLAN indexes=1``. We assert on the plan instead of diffing the printed SQL because the SQL can look fine but still defeat index ...
977
43,762
posthog
posthog/hogql/test/test_diagnostic_common.py
.py
"""Regression tests for the shadow-mismatch fail-fast guard shared by the PBT parser tooling (``_diagnostic_common`` helpers and the ``parser_bench`` timing harness). The guard under test: when an oracle/candidate backend raises ``HogQLParserShadowMismatch`` it is not a single pure parser (it ran a primary plus a shad...
56
2,464
posthog
posthog/hogql/test/test_workload.py
.py
import pytest from posthog.hogql import ast from posthog.hogql.database.schema.events import EventsTable from posthog.hogql.database.schema.logs import LogAttributesTable, LogsKafkaMetricsTable, LogsTable from posthog.hogql.errors import QueryError from posthog.hogql.workload import WorkloadCollector from posthog.cli...
99
3,988
posthog
posthog/hogql/test/test_action_to_expr.py
.py
from typing import Any, Optional from posthog.test.base import BaseTest, _create_event from posthog.hogql import ast from posthog.hogql.parser import parse_expr, parse_select from posthog.hogql.property import action_to_expr, steps_to_expr from posthog.hogql.query import execute_hogql_query from posthog.hogql.visitor...
179
7,150
posthog
posthog/hogql/test/_pbt_corpus_db.py
.py
"""Shared Hypothesis example-database wiring for the HogQL parser/printer PBTs. ``parser_pbt_corpus/<hypothesis-version>/`` is a per-machine, per-Hypothesis ``DirectoryBasedExampleDatabase`` — the parent directory is tracked but every subdirectory under it is ``.gitignore``\\ d. Each dev can populate their own seed lo...
117
5,725
posthog
posthog/hogql/test/test_parse_string_rust.py
.py
from unittest import TestCase from hogql_parser_rs import parse_string_literal_text from posthog.hogql.errors import ParsingError from ._test_parse_string import parse_string_test_factory class TestParseStringRust(parse_string_test_factory("rust-json")): # type: ignore pass class TestParseStringRustEmptyInp...
19
595
posthog
posthog/hogql/test/test_parser_rust_py.py
.py
"""Tests for the hand-rolled Rust HogQL parser via the direct-Python-object path (`rust-py`). The full parser-behaviour suite lives in `_test_parser.py` and runs against every backend via `parser_test_factory`. This file only wires the `rust-py` backend into that suite. Same parser core as `rust-json`; only difference...
18
733