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/errors.py
.py
from abc import ABC from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from .ast import Expr # Base class BaseHogQLError(Exception, ABC): message: str start: Optional[int] end: Optional[int] def __init__( self, message: str, *, start: Optional[int] = No...
98
2,077
posthog
posthog/hogql/type_system.py
.py
from __future__ import annotations import re import dataclasses from collections.abc import Sequence from dataclasses import dataclass, field from enum import StrEnum from functools import lru_cache from typing import TYPE_CHECKING, Literal, Optional, cast from posthog.hogql import ast from posthog.hogql.constants im...
1,986
82,535
posthog
posthog/hogql/utils.py
.py
import re from dataclasses import fields from typing import Any, Union, get_args, get_origin from posthog.hogql import ast from posthog.hogql.ast import AST, AST_CLASSES, Constant, Expr, HogQLXAttribute, HogQLXTag def like_matches(pattern: str, text: str) -> bool: """ Python implementation of ClickHouse LIKE...
159
5,488
posthog
posthog/hogql/metadata.py
.py
from typing import Literal, Optional, Union, cast from django.conf import settings from pydantic import BaseModel from posthog.schema import HogLanguage, HogQLMetadata, HogQLMetadataResponse, HogQLNotice, HogQLQuery from posthog.hogql import ast from posthog.hogql.base import AST from posthog.hogql.compiler.bytecod...
256
10,962
posthog
posthog/hogql/hogql.py
.py
from typing import Literal, Optional, cast from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.database import Database from posthog.hogql.errors import NotImplementedError, QueryError, SyntaxError from posthog.hogql.parser import parse_expr from posthog.hogql.print...
67
3,047
posthog
posthog/hogql/property_utils.py
.py
from typing import Any, Union from posthog.hogql import ast def create_property_condition(property_key: str, value: Any) -> ast.CompareOperation: """Creates a HogQL AST CompareOperation node for comparing a property value. Args: property_key: The key of the property to compare value: The val...
39
1,658
posthog
posthog/hogql/ast.py
.py
import sys import inspect import dataclasses from collections.abc import Sequence from dataclasses import dataclass, field from enum import StrEnum from typing import Any, Literal, Optional, Union, cast, get_args import posthog.hogql.resolver_utils as resolver_utils from posthog.hogql.base import AST, CTE, ConstantTyp...
1,417
45,834
posthog
posthog/hogql/filters.py
.py
import re import dataclasses from datetime import datetime from typing import Any, Optional, TypeVar, cast from dateutil.parser import isoparse from posthog.schema import ( BreakdownFilter, BreakdownType, EmptyPropertyFilter, HogQLFilters, IntervalType, MultipleBreakdownType, SessionProper...
612
29,404
posthog
posthog/hogql/workload.py
.py
from posthog.hogql import ast from posthog.hogql.database.models import FunctionCallTable from posthog.hogql.errors import QueryError from posthog.hogql.visitor import TraversingVisitor from posthog.clickhouse.workload import Workload class WorkloadCollector(TraversingVisitor): """Collects workload requirements ...
47
1,656
posthog
posthog/hogql/hogqlx.py
.py
from typing import Any from posthog.hogql import ast ## ::NB:: Sync this list with frontend/src/queries/nodes/HogQLX/render.tsx ## Sanitization is done on the client side, as we can never be sure what tuple('__hx_tag', 'tag_name') comes our way. HOGQLX_COMPONENTS = ["Sparkline", "RecordingButton", "ExplainCSPReport"]...
77
2,003
posthog
posthog/hogql/escape_sql.py
.py
import re import math from datetime import date, datetime from typing import Any, Literal, Optional from uuid import UUID from zoneinfo import ZoneInfo from posthog.hogql.errors import QueryError, ResolutionError from posthog.uuidt import UUIDT # Copied from clickhouse_driver.util.escape, adapted only from single qu...
395
14,116
posthog
posthog/hogql/type_diagnostics.py
.py
from __future__ import annotations import dataclasses from collections import Counter from collections.abc import Sequence from dataclasses import dataclass, field from typing import cast from posthog.hogql import ast from posthog.hogql.base import _T_AST, AST from posthog.hogql.constants import HogQLDialect from pos...
409
15,530
posthog
posthog/hogql/constants.py
.py
import sys from datetime import date, datetime from enum import StrEnum from typing import Literal, Optional from uuid import UUID from pydantic import BaseModel, ConfigDict type ConstantDataType = Literal[ "int", "float", "str", "bool", "array", "tuple", "map", "date", "datetime", "uuid", "unknown" ] type Consta...
217
10,836
posthog
posthog/hogql/snowflake_connection_cache.py
.py
"""Thread-local connection cache for direct Snowflake queries. Opening a Snowflake connection runs a full auth handshake (often hundreds of ms or more), which dominates latency for the interactive SQL editor where a user issues many small queries in sequence. This caches one open connection per (credentials + target) ...
176
6,177
posthog
posthog/hogql/metadata_heuristics.py
.py
from collections import defaultdict from dataclasses import dataclass from posthog.schema import HogQLNotice from posthog.hogql import ast @dataclass(frozen=True) class SubqueryFingerprint: table_names: tuple[str, ...] where: str | None class MetadataHeuristic: def run(self, query: ast.SelectQuery | a...
98
3,404
posthog
posthog/hogql/resolver_utils.py
.py
from __future__ import annotations import difflib from collections.abc import Generator from typing import Optional, cast from pydantic import BaseModel from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.models import ( BooleanDatabaseField, DatabaseField...
430
17,439
posthog
posthog/hogql/user_query_validator.py
.py
"""Pre-execution validation for user-submitted HogQL queries. Applied by ``HogQLQueryRunner._calculate`` when ``is_query_service`` is true — i.e. the query came in via the external ``/query`` endpoint authenticated with a personal API key. Violations raise ``QueryError`` (HTTP 400) before any database work happens. T...
92
3,985
posthog
posthog/hogql/direct_connection.py
.py
from collections.abc import Callable from typing import TYPE_CHECKING, Optional from uuid import UUID from django.db.models import Model from posthog.schema import HogQLQueryModifiers from posthog.hogql.database.database import Database from posthog.hogql.timings import HogQLTimings from posthog.ph_client import fe...
154
5,574
posthog
posthog/hogql/json_ast.py
.py
""" JSON AST Deserializer Converts JSON strings returned by the C++ HogQL parser back into Python AST objects. Performance: enum-typed fields and dict-shaped fields are precomputed per class at import time. The hot loop uses orjson for JSON parsing and avoids `get_type_hints` / `hasattr` per node. """ import inspect...
189
7,526
posthog
posthog/hogql/timings.py
.py
from contextlib import contextmanager, nullcontext from time import perf_counter from typing import TYPE_CHECKING from opentelemetry import trace if TYPE_CHECKING: from posthog.schema import QueryTiming _tracer = trace.get_tracer(__name__) TIMING_DECIMAL_PLACES = 3 # round to milliseconds # Not thread safe. ...
67
2,377
posthog
posthog/hogql/context.py
.py
from dataclasses import dataclass, field from functools import cached_property from typing import TYPE_CHECKING, Any, Literal, Optional from posthog.hogql.constants import LimitContext from posthog.hogql.timings import HogQLTimings from posthog.clickhouse.workload import Workload if TYPE_CHECKING: from posthog.s...
220
11,217
posthog
posthog/hogql/feature_extractor.py
.py
"""Extract product-attribution features from a HogQL select query. Feeds ``add_fallback_query_tags`` so HogQL queries can be attributed to a product surface (AI observability, error tracking, web analytics, replay, …) based on what tables and event filters they reference. """ from posthog.hogql import ast from postho...
87
3,709
posthog
posthog/hogql/modifiers.py
.py
from typing import TYPE_CHECKING, Optional import posthoganalytics from posthog.cloud_utils import is_cloud from posthog.schema_enums import ( BounceRatePageViewMode, InCohortVia, InlineCohortCalculation, MaterializationMode, PersonsArgMaxVersion, PropertyGroupsMode, SessionsV2JoinMode, ...
140
5,051
posthog
posthog/hogql/ai.py
.py
from typing import TYPE_CHECKING, Optional import openai from rest_framework.request import Request from posthog.hogql.context import HogQLContext from posthog.hogql.errors import ExposedHogQLError from posthog.hogql.parser import parse_select from posthog.hogql.printer import prepare_and_print_ast from posthog.even...
228
9,332
posthog
posthog/hogql/motherduck_connection_cache.py
.py
"""Thread-local connection cache for direct MotherDuck queries. Opening a MotherDuck connection loads the `motherduck` DuckDB extension and completes a WebSocket handshake — routinely seconds — which dominates latency for the interactive SQL editor where a user issues many small queries in sequence. This caches one op...
161
5,977
posthog
posthog/hogql/observability.py
.py
"""HogQL type-system observability. Measures type-inference coverage and the shape of the generated SQL during each prepare+typecheck pass, emitted as low-cardinality Prometheus metrics. Sampling is gated by ``TYPE_OBSERVABILITY_SAMPLE_RATE``. """ from __future__ import annotations import functools from collections ...
505
19,543
posthog
posthog/hogql/placeholders.py
.py
from typing import Optional from posthog.hogql import ast from posthog.hogql.errors import QueryError from posthog.hogql.utils import deserialize_hx_ast, is_simple_value from posthog.hogql.visitor import CloningVisitor, TraversingVisitor from common.hogvm.python.stl import BLOCKING_FUNCTIONS class FindBlockingCalls...
107
4,305
posthog
posthog/hogql/direct_query_metrics.py
.py
"""Prometheus metrics for direct-query execution. Direct queries run against a customer's own database over the network, so their latency and failure modes are independent of ClickHouse. These low-cardinality metrics make per-dialect error and timeout rates observable without leaking team-specific labels. The instrume...
66
2,423
posthog
posthog/hogql/taxonomy_validation.py
.py
from dataclasses import dataclass from difflib import get_close_matches from logging import getLogger from typing import Literal from django.db import DatabaseError from django.db.models import QuerySet from posthog.schema import HogQLNotice from posthog.hogql import ast from posthog.hogql.escape_sql import escape_h...
234
9,828
posthog
posthog/hogql/property_planner.py
.py
import dataclasses from dataclasses import dataclass from enum import StrEnum from typing import Literal, Optional from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.models import DatabaseField from posthog.hogql.database.schema.events import EventsPersonSubTable, ...
571
21,759
posthog
posthog/hogql/query.py
.py
import dataclasses from time import sleep from typing import Any, ClassVar, Literal, Optional, Union, cast from opentelemetry import trace from posthog.schema import ( DataWarehouseSourceUsage, HogLanguage, HogQLFilters, HogQLMetadata, HogQLMetadataResponse, HogQLQueryModifiers, HogQLQuery...
778
35,470
posthog
posthog/hogql/variables.py
.py
import re from difflib import get_close_matches from typing import TypeVar from posthog.schema import HogQLVariable from posthog.hogql import ast from posthog.hogql.errors import QueryError from posthog.hogql.visitor import CloningVisitor from posthog.models.team.team import Team from posthog.utils import relative_d...
101
4,235
posthog
posthog/hogql/cli.py
.py
import sys import json from posthog.hogql.compiler.bytecode import create_bytecode, parse_program from posthog.hogql.compiler.javascript import to_js_program from common.hogvm.python.execute import execute_bytecode modifiers = [arg for arg in sys.argv if arg.startswith("-")] args = [arg for arg in sys.argv if arg !=...
69
2,340
posthog
posthog/hogql/visitor.py
.py
from copy import deepcopy from typing import Any, Generic, Optional, TypeVar from posthog.hogql import ast from posthog.hogql.ast import SelectSetNode from posthog.hogql.base import AST, Expr from posthog.hogql.errors import BaseHogQLError from posthog.hogql.utils import is_simple_value T = TypeVar("T") T_AST = TypeV...
1,177
45,181
posthog
posthog/hogql/warehouse_warnings.py
.py
"""Cross-cutting accumulator for data warehouse sync warnings emitted during query execution. Every HogQL execution that resolves a warehouse table writes warnings into the active accumulator via ``record_warnings``. The query runner installs a fresh accumulator at the top of ``_execute_and_cache_blocking`` and attach...
76
2,913
posthog
posthog/hogql/resolver.py
.py
import re from collections.abc import Callable from datetime import date, datetime from typing import Any, Optional, cast from uuid import UUID import re2 from posthog.hogql import ast from posthog.hogql.ast import ConstantType, FieldTraverserType from posthog.hogql.base import _T_AST from posthog.hogql.constants imp...
2,794
134,818
posthog
posthog/hogql/restricted_properties.py
.py
import structlog from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.schema.events import EventsPersonSubTable, EventsTable from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable logger = structlog.get_logger(__name__) def restricted_prop...
47
2,355
posthog
posthog/hogql/base.py
.py
import re import copy from dataclasses import dataclass, field, fields from enum import Enum from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar from posthog.hogql.constants import ConstantDataType from posthog.hogql.errors import NotImplementedError if TYPE_CHECKING: from posthog.hogql.context impo...
206
8,753
posthog
posthog/hogql/property.py
.py
import re from collections.abc import Callable from typing import Literal, Optional, TypeGuard, cast from django.db import models from django.db.models import Q from django.db.models.functions.comparison import Coalesce import re2 from pydantic import BaseModel from rest_framework.exceptions import ValidationError f...
1,634
68,511
posthog
posthog/hogql/autocomplete.py
.py
import json from collections.abc import Callable from copy import deepcopy from typing import Optional, cast from django.db import models from django.db.models.functions.comparison import Coalesce from posthog.schema import ( AutocompleteCompletionItem, AutocompleteCompletionItemKind, HogLanguage, Hog...
862
37,792
posthog
posthog/hogql/functions/traffic_type.py
.py
""" Traffic type classification functions for HogQL. Implemented as HogQL functions (rather than hardcoded in specific query runners) so they can be used anywhere HogQL runs: - SQL editor for ad-hoc analysis and exploration - HogQLQuery runner for custom dashboards and insights - Trends and other query runners when fi...
239
9,526
posthog
posthog/hogql/functions/aggregations.py
.py
from collections.abc import Callable from posthog.hogql.ast import ArrayType, BooleanType, StringType from posthog.hogql.base import UnknownType from .core import HogQLFunctionMeta COMBINATORS = { "If": {"allowedSuffixes": [], "argMap": lambda min, max: [min + 1, max + 1]}, "Array": {"allowedSuffixes": ["If"...
365
23,389
posthog
posthog/hogql/functions/udfs.py
.py
from posthog.cloud_utils import is_ci, is_cloud from .core import HogQLFunctionMeta UDFS: dict[str, HogQLFunctionMeta] = { # RowBinary path (default since v12). "aggregate_funnel": HogQLFunctionMeta("aggregate_funnel", 7, 7, aggregate=False), "aggregate_funnel_array": HogQLFunctionMeta("aggregate_funnel_a...
42
2,468
posthog
posthog/hogql/functions/recording_button.py
.py
from posthog.hogql import ast def recording_button(node: ast.Expr, args: list[ast.Expr]) -> ast.Expr: return ast.Tuple( exprs=[ ast.Constant(value="__hx_tag"), ast.Constant(value="RecordingButton"), ast.Constant(value="sessionId"), args[0], ast.C...
15
466
posthog
posthog/hogql/functions/embed_text.py
.py
from typing import TYPE_CHECKING from posthog.hogql import ast if TYPE_CHECKING: from posthog.models.team.team import Team # Takes an embed text call, calls out to the embedding worker, # and then returns an embedding. def resolve_embed_text(team: "Team | int | None", node: ast.Call) -> ast.Constant: # Lazy...
43
1,588
posthog
posthog/hogql/functions/mapping.py
.py
from itertools import chain from typing import Optional from posthog.hogql import ast from posthog.hogql.ast import IntegerType, StringType from posthog.hogql.base import UnknownType from posthog.hogql.language_mappings import LANGUAGE_CODES, LANGUAGE_NAMES from .aggregations import HOGQL_AGGREGATIONS from .clickhous...
309
14,595
posthog
posthog/hogql/functions/__init__.py
.py
from .cohort import cohort from .config import ADD_OR_NULL_DATETIME_FUNCTIONS, FIRST_ARG_DATETIME_FUNCTIONS from .core import HogQLFunctionMeta, validate_function_args from .explain_csp_report import explain_csp_report from .mapping import find_hogql_aggregation, find_hogql_function, find_hogql_posthog_function from .r...
25
851
posthog
posthog/hogql/functions/typegen.py
.py
""" Type signature generator utilities for HogQL functions with variadic arguments. """ from itertools import product from typing import Optional from posthog.hogql.ast import IntegerType, StringType from posthog.hogql.functions.core import AnyConstantType def generate_variadic_signatures( fixed_types: list[Any...
75
2,888
posthog
posthog/hogql/functions/action.py
.py
from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.errors import QueryError from posthog.hogql.escape_sql import escape_clickhouse_string def matches_action(node: ast.Expr, args: list[ast.Expr], context: HogQLContext, events_alias: str) -> ast.Expr: arg = args[0] i...
45
2,176
posthog
posthog/hogql/functions/cohort.py
.py
import datetime from typing import Optional from django.utils import timezone import posthoganalytics from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.errors import QueryError from posthog.hogql.escape_sql import escape_clickhouse_string from posthog.hogql.parser import...
161
6,110
posthog
posthog/hogql/functions/explain_csp_report.py
.py
from posthog.hogql import ast def explain_csp_report(node: ast.Expr, args: list[ast.Expr]) -> ast.Expr: return ast.Tuple( exprs=[ ast.Constant(value="__hx_tag"), ast.Constant(value="ExplainCSPReport"), ast.Constant(value="properties"), args[0], ] ...
13
323
posthog
posthog/hogql/functions/survey.py
.py
from datetime import datetime from posthog.hogql import ast from posthog.hogql.errors import QueryError from posthog.hogql.parser import parse_expr def get_survey_response(node: ast.Call, args: list[ast.Expr], use_new_schema: bool = False) -> ast.Expr: """ Process getSurveyResponse() function call and return...
236
9,499
posthog
posthog/hogql/functions/sparkline.py
.py
from posthog.hogql import ast def sparkline(node: ast.Expr, args: list[ast.Expr]) -> ast.Expr: return ast.Tuple( exprs=[ ast.Constant(value="__hx_tag"), ast.Constant(value="Sparkline"), ast.Constant(value="data"), args[0], ] )
13
301
posthog
posthog/hogql/functions/config.py
.py
# The list of functions allowed in parametric functions, e.g. sum in "arrayReduce('sum', [1, 2, 3])" HOGQL_PERMITTED_PARAMETRIC_FUNCTIONS: set[str] = { "count", "countMap", "countMapState", "sum", "sumMap", "sumMapState", "min", "minMap", "minMapState", "max", "maxMap", "...
44
913
posthog
posthog/hogql/functions/posthog.py
.py
from posthog.hogql.ast import ArrayType, BooleanType, DateTimeType, DateType, DecimalType, IntegerType, StringType from .core import HogQLFunctionMeta HOGQL_POSTHOG_FUNCTIONS: dict[str, HogQLFunctionMeta] = { "matchesAction": HogQLFunctionMeta("matchesAction", 1, 1), "sparkline": HogQLFunctionMeta("sparkline"...
148
6,743
posthog
posthog/hogql/functions/core.py
.py
from dataclasses import dataclass from typing import Optional from posthog.hogql import ast from posthog.hogql.ast import ( ArrayType, BooleanType, DateTimeType, DateType, DecimalType, FloatType, IntegerType, IntervalType, StringLiteralType, StringType, TupleType, UUIDTy...
120
4,148
posthog
posthog/hogql/functions/clickhouse/geo.py
.py
from posthog.hogql.ast import ArrayType, FloatType, IntegerType, StringType, TupleType from posthog.hogql.functions.core import HogQLFunctionMeta # Keep in sync with the posthog.com repository: contents/docs/sql/clickhouse-functions.mdx GEO_FUNCTIONS: dict[str, HogQLFunctionMeta] = { "greatCircleDistance": HogQLFu...
351
8,923
posthog
posthog/hogql/functions/clickhouse/json.py
.py
from posthog.hogql.ast import ArrayType, BooleanType, FloatType, IntegerType, StringType, TupleType from ..core import HogQLFunctionMeta from ..typegen import generate_json_path_signatures # Keep in sync with the posthog.com repository: contents/docs/sql/clickhouse-functions.mdx JSON_FUNCTIONS: dict[str, HogQLFunctio...
180
5,834
posthog
posthog/hogql/functions/clickhouse/strings.py
.py
from posthog.hogql.ast import BooleanType, IntegerType, StringType from ..core import HogQLFunctionMeta # Shared return-type signatures for string search/predicate helpers. These ClickHouse functions # have a fixed return family regardless of which valid overload is used. Modeling them removes a # large share of `mis...
258
13,752
posthog
posthog/hogql/functions/clickhouse/mathematical.py
.py
from ..core import HogQLFunctionMeta # Keep in sync with the posthog.com repository: contents/docs/sql/clickhouse-functions.mdx MATHEMATICAL_FUNCTIONS: dict[str, HogQLFunctionMeta] = { "e": HogQLFunctionMeta("e"), "pi": HogQLFunctionMeta("pi"), "exp": HogQLFunctionMeta("exp", 1, 1, case_sensitive=False), ...
69
3,422
posthog
posthog/hogql/functions/clickhouse/datetime.py
.py
from posthog.hogql.ast import ( DateTimeType, DateType, FloatType, IntegerType, IntervalType, StringLiteralType, StringType, ) from posthog.hogql.base import UnknownType from ..core import HogQLFunctionMeta DATE_TRUNCATION_UNITS = frozenset({"year", "quarter", "month", "week"}) # dates an...
505
16,290
posthog
posthog/hogql/functions/clickhouse/arrays.py
.py
from posthog.hogql.ast import ( ArrayType, BooleanType, DateTimeType, DateType, DecimalType, FloatType, IntegerType, IntervalType, StringType, UUIDType, ) from ..core import HogQLFunctionMeta # arrays and strings common # Keep in sync with the posthog.com repository: contents/d...
198
6,954
posthog
posthog/hogql/functions/clickhouse/conversions.py
.py
from posthog.hogql import ast from posthog.hogql.ast import ( ArrayType, BooleanType, DateTimeType, DateType, DecimalType, FloatType, IntegerType, IntervalType, StringType, UUIDType, ) from posthog.hogql.base import UnknownType from ..core import HogQLFunctionMeta # type conver...
285
12,752
posthog
posthog/hogql/functions/clickhouse/arithmetic.py
.py
from posthog.hogql.ast import DateTimeType, DecimalType, FloatType, IntegerType, IntervalType, TupleType from ..core import HogQLFunctionMeta # Keep in sync with the posthog.com repository: contents/docs/sql/clickhouse-functions.mdx ARITHMETIC_FUNCTIONS: dict[str, HogQLFunctionMeta] = { "plus": HogQLFunctionMeta(...
198
6,315
posthog
posthog/hogql/functions/test/test_traffic_type_functions.py
.py
import ipaddress import pytest from posthog.test.base import BaseTest from parameterized import parameterized from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.errors import QueryError from posthog.hogql.functions.traffic_type import ( get_bot_name, get_bot_opera...
640
28,250
posthog
posthog/hogql/functions/test/test_sparkline.py
.py
from posthog.test.base import BaseTest from posthog.hogql.errors import QueryError from posthog.hogql.query import execute_hogql_query class TestSparkline(BaseTest): def test_sparkline(self): response = execute_hogql_query("select sparkline([1,2,3])", self.team, pretty=False) self.assertEqual( ...
27
1,412
posthog
posthog/hogql/functions/test/test_ip_functions.py
.py
from posthog.test.base import BaseTest from posthog.hogql.query import execute_hogql_query # One expression per newly allowlisted IP function, so a typo'd mapping entry # (wrong name, wrong arity) fails here instead of at user query time. IP_FUNCTION_CASES: list[tuple[str, object]] = [ ("IPv4NumToString(IPv4Strin...
40
1,973
posthog
posthog/hogql/functions/test/test_traffic_type_real_ua.py
.py
import re from ipaddress import ip_address, ip_network from uuid import uuid4 import pytest from posthog.test.base import BaseTest, _create_event, flush_persons_and_events from posthog.hogql.query import execute_hogql_query from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS from...
443
18,935
posthog
posthog/hogql/functions/test/test_explain_csp_button.py
.py
from posthog.test.base import BaseTest from posthog.hogql.errors import QueryError from posthog.hogql.query import execute_hogql_query class TestExplainCSPReport(BaseTest): def test_explain_csp_report(self): response = execute_hogql_query( "select explainCSPReport({'violated_directive': 'scri...
43
2,154
posthog
posthog/hogql/functions/test/test_action.py
.py
from typing import Any import pytest from posthog.test.base import ( BaseTest, QueryMatchingTest, _create_action, _create_event, _create_person, flush_persons_and_events, ) from django.conf import settings from posthog.hogql.query import execute_hogql_query from posthog.hogql.test.utils impor...
103
3,354
posthog
posthog/hogql/functions/test/test_typegen.py
.py
from posthog.test.base import BaseTest from posthog.hogql.ast import BooleanType, FloatType, IntegerType, StringType from posthog.hogql.functions.core import AnyConstantType from posthog.hogql.functions.typegen import generate_json_path_signatures, generate_variadic_signatures class TestTypegen(BaseTest): def te...
152
6,714
posthog
posthog/hogql/functions/test/test_cohort.py
.py
import datetime from typing import Any import pytest from posthog.test.base import BaseTest, QueryMatchingTest, _create_event, _create_person from unittest.mock import patch from django.conf import settings from django.test import override_settings from django.utils import timezone from parameterized import paramete...
337
14,927
posthog
posthog/hogql/functions/test/test_recording_button.py
.py
from posthog.test.base import BaseTest from posthog.hogql.errors import QueryError from posthog.hogql.query import execute_hogql_query class TestRecordingButton(BaseTest): def test_recording_button(self): response = execute_hogql_query("select recordingButton('12345-6789', 'active')", self.team, pretty=F...
27
1,600
posthog
posthog/hogql/printer/types.py
.py
from dataclasses import dataclass from posthog.hogql import ast @dataclass class JoinExprResponse: printed_sql: str where: ast.Expr | None = None
10
157
posthog
posthog/hogql/printer/utils.py
.py
from typing import TYPE_CHECKING, cast from posthog.schema_enums import InCohortVia, PropertyGroupsMode if TYPE_CHECKING: from posthog.schema import HogQLQueryModifiers from posthog.models.team import Team from posthog.hogql import ast from posthog.hogql.base import _T_AST from posthog.hogql.constants impor...
374
19,435
posthog
posthog/hogql/printer/hogql.py
.py
from typing import ClassVar, cast, get_args from posthog.hogql import ast from posthog.hogql.constants import HogQLDialect from posthog.hogql.errors import ImpossibleASTError, QueryError from posthog.hogql.printer.base import BasePrinter class HogQLPrinter(BasePrinter): """Prints a HogQL AST back out as HogQL te...
120
5,381
posthog
posthog/hogql/printer/redshift.py
.py
from collections.abc import Callable from typing import ClassVar from posthog.hogql import ast from posthog.hogql.constants import HogQLDialect from posthog.hogql.errors import QueryError from posthog.hogql.printer.base import BasePrinter from posthog.hogql.printer.postgres import PostgresPrinter from posthog.hogql.pr...
101
5,198
posthog
posthog/hogql/printer/duckdb.py
.py
from collections.abc import Callable from typing import ClassVar from posthog.hogql import ast from posthog.hogql.ast import AST from posthog.hogql.constants import HogQLDialect, HogQLGlobalSettings from posthog.hogql.context import HogQLContext from posthog.hogql.escape_sql import escape_duckdb_identifier from postho...
110
5,233
posthog
posthog/hogql/printer/mysql_functions.py
.py
from collections.abc import Callable from posthog.hogql.printer.postgres_functions import ( _handle_e, _handle_empty, _handle_if, _handle_is_not_null, _handle_is_null, _handle_multi_if, _handle_noop, _handle_not_empty, _handle_uniq, ) # Simple 1:1 function name renames (ClickHouse ...
405
13,556
posthog
posthog/hogql/printer/__init__.py
.py
from posthog.hogql.printer.base import BasePrinter from posthog.hogql.printer.clickhouse import ClickHousePrinter from posthog.hogql.printer.duckdb import DuckDBPrinter from posthog.hogql.printer.hogql import HogQLPrinter from posthog.hogql.printer.mysql import MySQLPrinter from posthog.hogql.printer.postgres import Po...
28
820
posthog
posthog/hogql/printer/access_control.py
.py
from collections.abc import Iterable from typing import TYPE_CHECKING, Optional import humanize from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.postgres_table import PostgresTable if TYPE_CHECKING: from posthog.schema import AccessControlFilterWarning ...
134
5,395
posthog
posthog/hogql/printer/postgres.py
.py
import re import hashlib from collections.abc import Callable from typing import ClassVar from uuid import UUID from posthog.hogql import ast from posthog.hogql.ast import AST from posthog.hogql.constants import HogQLDialect, HogQLGlobalSettings from posthog.hogql.context import HogQLContext from posthog.hogql.databas...
582
26,702
posthog
posthog/hogql/printer/postgres_functions.py
.py
from collections.abc import Callable # Simple 1:1 function name renames (ClickHouse name → Postgres name) POSTGRES_FUNCTION_RENAMES: dict[str, str] = { "ifNull": "COALESCE", "groupArray": "ARRAY_AGG", "arrayJoin": "UNNEST", "JSONExtractString": "json_extract_path_text", "JSONExtractRaw": "json_extr...
399
12,897
posthog
posthog/hogql/printer/snowflake_functions.py
.py
from collections.abc import Callable from posthog.hogql.printer.postgres_functions import ( _handle_e, _handle_empty, _handle_ends_with, _handle_if, _handle_is_not_null, _handle_is_null, _handle_log2, _handle_multi_if, _handle_noop, _handle_not_empty, _handle_to_last_day_of_...
364
12,820
posthog
posthog/hogql/printer/redshift_functions.py
.py
"""Redshift function surface, derived from the Postgres surface. Redshift is a fork of an old Postgres, so it shares most of Postgres's function surface. Rather than re-listing everything, we start from the Postgres renames / handlers / passthrough sets and remove the entries whose emitted SQL the Redshift engine woul...
120
5,040
posthog
posthog/hogql/printer/mysql.py
.py
from collections.abc import Callable from typing import ClassVar, Optional from posthog.hogql import ast from posthog.hogql.ast import AST from posthog.hogql.constants import HogQLDialect, HogQLGlobalSettings from posthog.hogql.context import HogQLContext from posthog.hogql.database.direct_mysql_table import DirectMyS...
309
13,389
posthog
posthog/hogql/printer/duckdb_functions.py
.py
"""DuckDB-specific function mappings that override the Postgres defaults. These mappings are merged on top of the Postgres mappings in ``DuckDBPrinter``. DuckDB is Postgres-wire compatible but ships a number of native functions that produce cleaner or faster output than the Postgres equivalents we emit by default. """...
94
3,236
posthog
posthog/hogql/printer/clickhouse.py
.py
import re from datetime import date, datetime from typing import ClassVar, cast from uuid import UUID from django.conf import settings as django_settings from posthog.hogql import ast from posthog.hogql.ast import AST, Constant, StringType from posthog.hogql.constants import HogQLDialect from posthog.hogql.context im...
1,163
59,408
posthog
posthog/hogql/printer/base.py
.py
import re from collections.abc import Iterable from datetime import date, datetime from difflib import get_close_matches from typing import Any, ClassVar, Optional, cast, get_args from uuid import UUID from django.conf import settings as django_settings from posthog.hogql import ast from posthog.hogql.ast import Stri...
1,661
80,740
posthog
posthog/hogql/printer/snowflake.py
.py
from collections.abc import Callable from typing import ClassVar from posthog.hogql import ast from posthog.hogql.constants import HogQLDialect from posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTable from posthog.hogql.database.models import DatabaseField from posthog.hogql.errors import QueryEr...
340
15,624
posthog
posthog/hogql/printer/test/test_within_non_hogql_delete.py
.py
"""Tests the ``within_non_hogql_query`` lightweight-DELETE-mutation path. Data deletion compiles a HogQL property predicate into a ClickHouse fragment via ``compile_hogql_predicate`` (which sets ``within_non_hogql_query=True``), and the deletion DAG splices that fragment into a lightweight ``DELETE FROM sharded_events...
229
11,647
posthog
posthog/hogql/printer/test/test_sql_injection_defenses.py
.py
"""SQL-injection-defense regression suite for the HogQL printer. Trust model: every AST string field that reaches printer output is either escape-wrapped (via `_print_identifier`, `_print_escaped_string`, or `context.add_value` parameterization) or interpolated verbatim against an allowlist enforced at both constructi...
225
11,692
posthog
posthog/hogql/printer/test/test_printer_pbt.py
.py
import os import math from collections.abc import Callable from typing import Any import pytest from hogql_parser_rs import parse_string_literal_text from hypothesis import ( assume, given, settings, strategies as st, ) from posthog.hogql.errors import QueryError from posthog.hogql.escape_sql import ...
259
10,174
posthog
posthog/hogql/printer/test/test_printer.py
.py
import json from collections.abc import Mapping from datetime import UTC, date, datetime from typing import Any, Literal, Optional, cast from uuid import UUID import pytest from posthog.test.base import ( APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, _create_person, clean_varying_q...
8,532
430,148
posthog
posthog/hogql/printer/test/test_property_access_control.py
.py
from posthog.test.base import BaseTest, ClickhouseTestMixin, cleanup_materialized_columns, materialized from django.conf import settings from parameterized import parameterized from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode from posthog.hogql.context import HogQLContext from posthog.hogql.parse...
489
22,560
posthog
posthog/hogql/printer/test/test_hogql_access_control.py
.py
from typing import cast from posthog.test.base import BaseTest from unittest.mock import Mock, patch from parameterized import parameterized from posthog.schema import HogQLQuery from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.database import Database from po...
1,162
51,584
posthog
posthog/hogql/database/direct_sql_table.py
.py
from posthog.hogql.database.models import FunctionCallTable from posthog.hogql.escape_sql import escape_hogql_identifier class DirectSQLTable(FunctionCallTable): """Shared base for tables that print into an external SQL database queried directly (Postgres, MySQL, ...). Holds the members common to every engine...
21
1,068
posthog
posthog/hogql/database/warehouse_join_resolvers.py
.py
from typing import Any, cast from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.database.models import LazyJoinToAdd from posthog.hogql.database.utils import qualify_join_key_expr from posthog.hogql.errors import QueryError, ResolutionError def _qualified_key_expr(table_k...
205
8,865
posthog
posthog/hogql/database/lazy_join_tags.py
.py
# Resolver tags. A LazyJoin stores one of these (plus JSON-able `resolver_params`) instead of # a Python closure, so a join is described as plain, serializable data. The tag → implementation # mapping lives in `lazy_join_registry.RESOLVERS` — every supported tag must be listed there. # This module is import-dependency-...
33
1,652
posthog
posthog/hogql/database/utils.py
.py
from typing import Optional from posthog.hogql import ast from posthog.hogql.parser import parse_expr from posthog.exceptions_capture import capture_exception def _extract_join_key_field(expr: ast.Expr) -> Optional[ast.Field]: if isinstance(expr, ast.Field): return expr if isinstance(expr, ast.Alia...
41
1,171