Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hogql): expose native sha1 hashing (#116004)

Vasco de Krijgerb8bb2224c4b9
diff --git a/common/hogvm/python/test/test_crypto.py b/common/hogvm/python/test/test_crypto.py
index 8d514b19e460..f2ee882f0692 100644
--- a/common/hogvm/python/test/test_crypto.py
+++ b/common/hogvm/python/test/test_crypto.py
@@ -5,8 +5,11 @@ import pytest
from parameterized import parameterized
+from common.hogvm.python.execute import execute_bytecode
+from common.hogvm.python.operation import Operation as op
from common.hogvm.python.stl import STL
from common.hogvm.python.stl.crypto import sha1, sha1HmacChain
+from common.hogvm.python.utils import HogVMException
# RFC 2202 HMAC-SHA1 test vectors, limited to the cases whose key and message are text (the STL
# only takes strings). A two-element chain is a plain HMAC of key and message.
@@ -91,3 +94,29 @@ class TestStlRegistration:
)
def test_callable_through_stl(self, name: str, args: list, expected: str) -> None:
assert STL[name].fn(args, None, None, 10.0) == expected
+
+
+class TestHogQLSha1:
+ @parameterized.expand(
+ [
+ ("abc", "abc", "a9993e364706816aba3e25717850c26c9cd0d89d"),
+ ("empty", "", "da39a3ee5e6b4b0d3255bfef95601890afd80709"),
+ ("unicode", "🦔", "b1495135295ac36752f6579e93ba02140604590f"),
+ ("null", None, None),
+ ]
+ )
+ def test_lowercase_hex(self, _name: str, value: str | None, expected: str | None) -> None:
+ argument = [op.NULL] if value is None else [op.STRING, value]
+ assert execute_bytecode(["_H", 1, *argument, op.CALL_GLOBAL, "sha1", 1]).result == expected
+
+ @parameterized.expand(
+ [
+ ("missing", [], "Function sha1 requires at least 1 arguments"),
+ ("extra", ["abc", "hex", "extra"], "Function sha1 requires at most 2 arguments"),
+ ]
+ )
+ def test_argument_count(self, _name: str, values: list[str], expected_error: str) -> None:
+ arguments = [item for value in values for item in [op.STRING, value]]
+ with pytest.raises(HogVMException) as exc:
+ execute_bytecode(["_H", 1, *arguments, op.CALL_GLOBAL, "sha1", len(values)])
+ assert str(exc.value) == expected_error
diff --git a/common/hogvm/typescript/src/__tests__/crypto.test.ts b/common/hogvm/typescript/src/__tests__/crypto.test.ts
index 1e93f1f4a447..dd03b3f76202 100644
--- a/common/hogvm/typescript/src/__tests__/crypto.test.ts
+++ b/common/hogvm/typescript/src/__tests__/crypto.test.ts
@@ -1,5 +1,7 @@
import crypto from 'crypto'
+import { execSync } from '../execute'
+import { Operation as op } from '../operation'
import { sha1, sha1HmacChain } from '../stl/crypto'
import { STL } from '../stl/stl'
import { ExecOptions } from '../types'
@@ -7,6 +9,28 @@ import { ExecOptions } from '../types'
describe('sha1 and sha1HmacChain', () => {
const options: ExecOptions = { external: { crypto } }
+ describe('sha1 bytecode', () => {
+ test.each([
+ ['abc', 'a9993e364706816aba3e25717850c26c9cd0d89d'],
+ ['', 'da39a3ee5e6b4b0d3255bfef95601890afd80709'],
+ ['🦔', 'b1495135295ac36752f6579e93ba02140604590f'],
+ [null, null],
+ ])('sha1(%p) returns lowercase hex', (value, expected) => {
+ const argument = value === null ? [op.NULL] : [op.STRING, value]
+ expect(execSync(['_H', 1, ...argument, op.CALL_GLOBAL, 'sha1', 1], options)).toBe(expected)
+ })
+
+ test.each([
+ [[], 'Function sha1 requires at least 1 arguments'],
+ [['abc', 'hex', 'extra'], 'Function sha1 requires at most 2 arguments'],
+ ] as const)('rejects argument list %p', (values, expectedError) => {
+ const args = values.flatMap((value) => [op.STRING, value])
+ expect(() => execSync(['_H', 1, ...args, op.CALL_GLOBAL, 'sha1', values.length], options)).toThrow(
+ new Error(expectedError)
+ )
+ })
+ })
+
describe('sha1', () => {
test.each([
['', 'hex', 'da39a3ee5e6b4b0d3255bfef95601890afd80709'],
diff --git a/docs/internal/hog-function-arities.md b/docs/internal/hog-function-arities.md
index 651ff822009c..d286962471a6 100644
--- a/docs/internal/hog-function-arities.md
+++ b/docs/internal/hog-function-arities.md
@@ -4,6 +4,9 @@ Hog checks standard library argument counts for direct calls and functions store
The Python and TypeScript native function registries define the minimum and maximum accepted counts.
The HogQL parity test checks both bounds against shared HogQL function names in these registries.
+`sha1(data)` returns lowercase hex in HogQL and Hog. Hog also accepts an optional encoding argument;
+HogQL takes exactly one argument.
+
`JSONHas(json)` accepts no path components and returns `true`, preserving Hog's existing empty-path behavior.
Some Hog signatures are deliberately narrower than HogQL:
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index 7da2440ce913..f9621f2872f1 100644
--- a/posthog/api/test/test_query.py
+++ b/posthog/api/test/test_query.py
@@ -1,4 +1,5 @@
import json
+import hashlib
import time_machine
from posthog.test.base import (
@@ -87,6 +88,54 @@ class TestQueryTraceCorrelation(SimpleTestCase):
class TestQuery(ClickhouseTestMixin, APIBaseTest):
ENDPOINT = "query"
+ @parameterized.expand(
+ [
+ ("ascii", "abc"),
+ ("utf8_digest", "99937"),
+ ("trailing_nul_digest", "25"),
+ ("utf8_trailing_nul_digest", "19130574"),
+ ("empty", ""),
+ ("unicode", "ünïcødé-😀"),
+ ("nul", "a\0b"),
+ ("long", "a" * 1000),
+ ]
+ )
+ def test_hogql_sha1_results_are_json_safe_and_cached(self, _name: str, value: str) -> None:
+ query = HogQLQuery(
+ query="""
+ SELECT sha1({value}), [sha1({value})], tuple(sha1({value}), 'plain text'),
+ map('digest', sha1({value})), map(sha1({value}), 'digest'),
+ length(sha1({value})), sha1(NULL), sha1(toNullableString({value})),
+ toTypeName(sha1({value})),
+ accurateCast('abc', 'FixedString(3)'), accurateCast('abc', 'FixedString(20)')
+ """,
+ values={"value": value},
+ )
+ digest = hashlib.sha1(value.encode()).hexdigest()
+ expected = [
+ [
+ digest,
+ [digest],
+ [digest, "plain text"],
+ {"digest": digest},
+ {digest: "digest"},
+ 40,
+ None,
+ digest,
+ "String",
+ "abc",
+ "abc",
+ ]
+ ]
+ for refresh, is_cached in (("force_blocking", False), ("force_cache", True)):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/query/",
+ {"query": query.model_dump(), "refresh": refresh},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["results"], expected)
+ self.assertEqual(response.json()["is_cached"], is_cached)
+
def test_concurrency_limit_returns_friendly_message_without_internal_key(self):
# A concurrency block must surface as a 429 with a user-facing message — not str(exc),
# which embeds the limiter's internal Redis key + task id and used to leak into the UI.
diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.py
index c96963963e61..d416e0d76145 100644
--- a/posthog/hogql/database/test/test_database.py
+++ b/posthog/hogql/database/test/test_database.py
@@ -1994,6 +1994,7 @@ class TestDatabase(BaseTest, QueryMatchingTest):
source.connection_metadata = {
"engine": "postgres",
"database": "db",
+ "pgcrypto_schema": "crypto",
"available_functions": ["query_to_xml"],
"available_table_functions": ["some_set_returning_fn"],
}
@@ -2005,6 +2006,7 @@ class TestDatabase(BaseTest, QueryMatchingTest):
assert "available_functions" not in database._direct_connection_metadata
assert "available_table_functions" not in database._direct_connection_metadata
assert database._direct_connection_metadata.get("engine") == "postgres"
+ assert database._direct_connection_metadata.get("pgcrypto_schema") == "crypto"
def test_direct_source_keeps_introspected_function_passthrough(self):
# A DIRECT source is the user's own connected DB (full access by design), so introspected
diff --git a/posthog/hogql/functions/clickhouse/conversions.py b/posthog/hogql/functions/clickhouse/conversions.py
index e1f434fa0010..42ad0612fbe7 100644
--- a/posthog/hogql/functions/clickhouse/conversions.py
+++ b/posthog/hogql/functions/clickhouse/conversions.py
@@ -141,6 +141,8 @@ TYPE_CONVERSION_FUNCTIONS: dict[str, HogQLFunctionMeta] = {
"defaultValueOfTypeName": HogQLFunctionMeta("defaultValueOfTypeName", 1, 1),
"cityHash64": HogQLFunctionMeta("cityHash64", 1, 1),
"MD5": HogQLFunctionMeta("MD5", 1, 1),
+ # ClickHouse SHA1 returns a binary digest. Hex keeps API responses and cached results JSON-safe.
+ "sha1": HogQLFunctionMeta("lower(hex(SHA1({})))", 1, 1, using_placeholder_arguments=True),
"UUIDv7ToDateTime": HogQLFunctionMeta("UUIDv7ToDateTime", 1, 1, tz_aware=True),
}
diff --git a/posthog/hogql/printer/duckdb_functions.py b/posthog/hogql/printer/duckdb_functions.py
index 8f6a22c219e4..b74e69fad7f9 100644
--- a/posthog/hogql/printer/duckdb_functions.py
+++ b/posthog/hogql/printer/duckdb_functions.py
@@ -76,6 +76,7 @@ def _handle_current_timestamp(args: list[str]) -> str:
DUCKDB_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {
+ "sha1": lambda args: f"sha1({args[0]})",
"argMaxIf": _handle_arg_max_if,
"argMinIf": _handle_arg_min_if,
"dateAdd": _handle_date_add,
diff --git a/posthog/hogql/printer/hogql.py b/posthog/hogql/printer/hogql.py
index 58dcd51c6863..9a086212a636 100644
--- a/posthog/hogql/printer/hogql.py
+++ b/posthog/hogql/printer/hogql.py
@@ -120,6 +120,13 @@ class HogQLPrinter(BasePrinter):
def _expands_placeholder_macros(self) -> bool:
return False
+ def visit_call(self, node: ast.Call):
+ if node.name.lower() == "sha1":
+ connection_function = self._render_connection_supported_function(node)
+ if connection_function is not None:
+ return connection_function
+ return super().visit_call(node)
+
def _render_connection_supported_function(self, node: ast.Call) -> str | None:
if node.name.lower() in self._get_connection_supported_functions():
return f"{node.name}({', '.join([self.visit(arg) for arg in node.args])})"
diff --git a/posthog/hogql/printer/mysql_functions.py b/posthog/hogql/printer/mysql_functions.py
index 43f7920b2a3e..2b71ce85b8c6 100644
--- a/posthog/hogql/printer/mysql_functions.py
+++ b/posthog/hogql/printer/mysql_functions.py
@@ -218,6 +218,8 @@ def _handle_json_extract_bool(args: list[str]) -> str:
# MySQLPrinter._visit_to_start_of_call() / visit_call(), which intercept before this dict
# is consulted (dateDiff needs the unparameterized unit constant).
MYSQL_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {
+ # Hash UTF-8 bytes even when the column uses another character set.
+ "sha1": lambda args: f"sha1(CONVERT({args[0]} USING utf8mb4))",
# Type conversions — MySQL CAST never raises; invalid input becomes 0/NULL, which also
# covers the *OrZero variants faithfully.
"toDate": _make_cast_handler("DATE"),
diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.py
index c10202bd1e9a..0f9dddda3303 100644
--- a/posthog/hogql/printer/postgres.py
+++ b/posthog/hogql/printer/postgres.py
@@ -12,6 +12,7 @@ from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
from posthog.hogql.database.models import StructDatabaseField
from posthog.hogql.errors import ImpossibleASTError, QueryError
from posthog.hogql.escape_sql import escape_postgres_identifier
+from posthog.hogql.functions.core import validate_function_args
from posthog.hogql.printer.base import BasePrinter
from posthog.hogql.printer.postgres_functions import (
POSTGRES_FUNCTION_HANDLERS_LOWER,
@@ -169,6 +170,8 @@ class PostgresPrinter(BasePrinter):
handler = function_handlers.get(func_name)
if handler is not None:
+ if func_name == "sha1":
+ validate_function_args(node.args, 1, 1, node.name)
if node.order_by:
raise QueryError(
f"Function '{node.name}' does not support ORDER BY in the {self.DIALECT_LABEL} dialect."
@@ -220,7 +223,28 @@ class PostgresPrinter(BasePrinter):
def _get_function_handlers(self) -> dict[str, Callable[[list[str]], str]]:
"""Lowercased HogQL-name → handler-callable map for functions that need custom rendering."""
- return POSTGRES_FUNCTION_HANDLERS_LOWER
+ handlers = POSTGRES_FUNCTION_HANDLERS_LOWER.copy()
+ extension_fallbacks = {"sha1": self._render_sha1}
+ for name, handler in extension_fallbacks.items():
+ if name not in self._connection_supported_functions:
+ handlers[name] = handler
+ return handlers
+
+ def _render_sha1(self, args: list[str]) -> str:
+ metadata = self.context.direct_postgres_connection_metadata or {}
+ if "pgcrypto_schema" not in metadata:
+ raise QueryError(
+ "Refresh this PostgreSQL connection's schemas to check for the pgcrypto extension before using sha1."
+ )
+ schema = metadata["pgcrypto_schema"]
+ if not isinstance(schema, str) or not schema:
+ raise QueryError(
+ "Function 'sha1' requires the pgcrypto extension on this PostgreSQL connection. "
+ "Install pgcrypto and refresh the connection's schemas."
+ )
+ # The connection's search_path may exclude the extension's schema.
+ digest = f"{escape_postgres_identifier(schema)}.digest"
+ return f"encode({digest}(convert_to({args[0]}, 'UTF8'), 'sha1'), 'hex')"
def _get_passthrough_functions(self) -> frozenset[str]:
"""Lowercased function names that are emitted verbatim without renaming."""
diff --git a/posthog/hogql/printer/redshift_functions.py b/posthog/hogql/printer/redshift_functions.py
index 821cd7ea16e5..36f1738ce6d2 100644
--- a/posthog/hogql/printer/redshift_functions.py
+++ b/posthog/hogql/printer/redshift_functions.py
@@ -94,6 +94,7 @@ def _handle_avg(args: list[str]) -> str:
# Functions whose inherited Postgres rendering Redshift would reject or silently reinterpret;
# rewritten to a Redshift-native equivalent that keeps HogQL semantics.
_REDSHIFT_ONLY_HANDLERS: dict[str, Callable[[list[str]], str]] = {
+ "sha1": lambda args: f"sha1({args[0]})",
"concat": _handle_concat,
"position": _handle_position,
"avg": _handle_avg,
diff --git a/posthog/hogql/printer/snowflake_functions.py b/posthog/hogql/printer/snowflake_functions.py
index 4cf72b7ce367..4d42f83f7886 100644
--- a/posthog/hogql/printer/snowflake_functions.py
+++ b/posthog/hogql/printer/snowflake_functions.py
@@ -175,6 +175,7 @@ def _handle_uniq_if(args: list[str]) -> str:
# Functions needing custom rendering: lowercased-name → callable(rendered_args) → SQL.
SNOWFLAKE_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {
+ "sha1": lambda args: f"sha1({args[0]})",
# Type conversions (Snowflake type synonyms; no UUID type → VARCHAR)
"toDate": _make_cast_handler("DATE"),
"toDateTime": _make_cast_handler("TIMESTAMP"),
diff --git a/posthog/hogql/printer/test/test_mysql_printer.py b/posthog/hogql/printer/test/test_mysql_printer.py
index e351d6182696..2e3b55a586c2 100644
--- a/posthog/hogql/printer/test/test_mysql_printer.py
+++ b/posthog/hogql/printer/test/test_mysql_printer.py
@@ -120,6 +120,9 @@ class TestMySQLPrinter(BaseTest):
def test_mysql_functions(self, _name: str, expr: str, expected: str):
self.assertEqual(self._expr(expr), expected)
+ def test_sha1_converts_column_text_to_utf8(self):
+ self.assertEqual(self._expr("sha1(event)"), "sha1(CONVERT(events.event USING utf8mb4))")
+
def test_mysql_unsupported_function_raises(self):
with self.assertRaisesMessage(QueryError, "is not supported in the MySQL dialect"):
self._expr("arrayJoin([1])")
diff --git a/posthog/hogql/printer/test/test_postgres_printer.py b/posthog/hogql/printer/test/test_postgres_printer.py
index 3dd76fd70edd..e8c7c3e872be 100644
--- a/posthog/hogql/printer/test/test_postgres_printer.py
+++ b/posthog/hogql/printer/test/test_postgres_printer.py
@@ -1105,17 +1105,58 @@ class TestPostgresPrinter(BaseTest):
result = self._expr(expr)
self.assertIsNotNone(result)
- def test_connection_metadata_functions_pass_through(self):
+ @parameterized.expand(
+ [
+ (
+ "date_bin",
+ "date_bin(toIntervalHour(1), now(), now())",
+ "date_bin((1 * INTERVAL '1 hour'), NOW(), NOW())",
+ ),
+ ("sha1", "sha1(event)", "sha1(events.event)"),
+ ]
+ )
+ def test_connection_metadata_functions_pass_through(self, name, expression, expected):
context = HogQLContext(
team_id=self.team.pk,
enable_select_queries=True,
- direct_postgres_connection_metadata={"available_functions": ["date_bin"]},
+ direct_postgres_connection_metadata={"available_functions": [name]},
)
self.assertEqual(
- self._expr("date_bin(toIntervalHour(1), now(), now())", context=context),
- "date_bin((1 * INTERVAL '1 hour'), NOW(), NOW())",
+ self._expr(expression, context=context),
+ expected,
+ )
+
+ @parameterized.expand(
+ [
+ ('Crypto "Hashes"', '"Crypto ""Hashes"""'),
+ ('crypto"; SELECT 1; --', '"crypto""; SELECT 1; --"'),
+ ]
+ )
+ def test_sha1_qualifies_and_quotes_pgcrypto_schema(self, schema, quoted_schema):
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ direct_postgres_connection_metadata={"pgcrypto_schema": schema},
+ )
+
+ self.assertEqual(
+ self._expr("sha1(event)", context=context),
+ f"encode({quoted_schema}.digest(convert_to(events.event, 'UTF8'), 'sha1'), 'hex')",
+ )
+
+ def test_sha1_parameterizes_sql_in_string_argument(self):
+ value = "abc'); SELECT 1; --"
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ direct_postgres_connection_metadata={"pgcrypto_schema": "public"},
+ )
+ self.assertEqual(
+ self._expr(ast.Call(name="sha1", args=[ast.Constant(value=value)]), context=context),
+ "encode(public.digest(convert_to(%(hogql_val_0)s, 'UTF8'), 'sha1'), 'hex')",
)
+ self.assertEqual(context.values, {"hogql_val_0": value})
@parameterized.expand(
[
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index 4e295f5688e0..7df9c7ee0125 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -1890,10 +1890,95 @@ class TestPrinter(BaseTest):
)
self.assertEqual(self._expr("sumIf(1, 1 == 2)"), "sumIf(1, 0)")
+ @parameterized.expand(
+ [
+ ("hogql", "sha1('abc')"),
+ ("clickhouse", "lower(hex(SHA1(%(hogql_val_0)s)))"),
+ ("postgres", "encode(public.digest(convert_to(%(hogql_val_0)s, 'UTF8'), 'sha1'), 'hex')"),
+ ("duckdb", "sha1(%(hogql_val_0)s)"),
+ ("mysql", "sha1(CONVERT(%(hogql_val_0)s USING utf8mb4))"),
+ ("snowflake", "sha1(%(hogql_val_0)s)"),
+ ("redshift", "sha1(%(hogql_val_0)s)"),
+ ("trino", "lower(to_hex(sha1(to_utf8(CAST(%(hogql_val_0)s AS VARCHAR)))))"),
+ ]
+ )
+ def test_sha1_dialects(self, dialect: HogQLDialect, expected: str) -> None:
+ context = HogQLContext(
+ team_id=self.team.pk,
+ database=Database(),
+ restricted_properties=set(),
+ enable_select_queries=True,
+ direct_postgres_connection_metadata={"pgcrypto_schema": "public"},
+ modifiers=HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS
+ ),
+ )
+ query = parse_select("SELECT sha1('abc')")
+ prepared = prepare_ast_for_printing(query, context=context, dialect=dialect)
+ assert isinstance(prepared, ast.SelectQuery)
+ assert print_prepared_ast(prepared.select[0], context=context, dialect=dialect, stack=[prepared]) == expected
+
+ @parameterized.expand(
+ [
+ (f"{dialect}_{count}", dialect, arguments, error.format(count=count))
+ for dialect, error in (
+ ("hogql", "Function 'sha1' expects 1 argument, found {count}"),
+ ("clickhouse", "Function 'sha1' requires exactly 1 argument"),
+ ("postgres", "Function 'sha1' expects 1 argument, found {count}"),
+ ("duckdb", "Function 'sha1' expects 1 argument, found {count}"),
+ ("mysql", "Function 'sha1' expects 1 argument, found {count}"),
+ ("snowflake", "Function 'sha1' expects 1 argument, found {count}"),
+ ("redshift", "Function 'sha1' expects 1 argument, found {count}"),
+ ("trino", "[TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED] sha1 expects exactly 1 argument in Trino mode."),
+ )
+ for count, arguments in ((0, ""), (2, "'abc', 'def'"))
+ ]
+ )
+ def test_sha1_argument_count(self, _name: str, dialect: HogQLDialect, arguments: str, expected_error: str) -> None:
+ context = HogQLContext(
+ team_id=self.team.pk,
+ database=Database(),
+ restricted_properties=set(),
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS
+ ),
+ )
+ with pytest.raises(QueryError) as exc:
+ prepare_and_print_ast(parse_select(f"SELECT sha1({arguments}) AS digest"), context, dialect)
+ assert str(exc.value) == expected_error
+
+ @parameterized.expand(
+ [
+ (
+ "not_discovered",
+ {},
+ "Refresh this PostgreSQL connection's schemas to check for the pgcrypto extension before using sha1.",
+ ),
+ (
+ "not_installed",
+ {"pgcrypto_schema": None},
+ "Function 'sha1' requires the pgcrypto extension on this PostgreSQL connection. "
+ "Install pgcrypto and refresh the connection's schemas.",
+ ),
+ ]
+ )
+ def test_sha1_postgres_requires_optional_extension(self, _name, metadata, expected_error) -> None:
+ context = HogQLContext(
+ database=Database(),
+ restricted_properties=set(),
+ enable_select_queries=True,
+ direct_postgres_connection_metadata=metadata,
+ )
+ with pytest.raises(QueryError) as exc:
+ prepare_and_print_ast(parse_select("SELECT sha1('abc')"), context, "postgres")
+ assert str(exc.value) == expected_error
+
def test_functions(self):
context = HogQLContext(team_id=self.team.pk) # inline values
self.assertEqual(self._expr("abs(1)"), "abs(1)")
+ self.assertEqual(self._expr("sha1(event)"), "lower(hex(SHA1(events.event)))")
self.assertEqual(self._expr("max2(1,2)"), "max2(1, 2)")
self.assertEqual(self._expr("toInt('1')", context), "accurateCastOrNull(%(hogql_val_0)s, %(hogql_val_1)s)")
self.assertEqual(self._expr("toFloat('1.3')", context), "accurateCastOrNull(%(hogql_val_2)s, %(hogql_val_3)s)")
@@ -1967,6 +2052,8 @@ class TestPrinter(BaseTest):
"Aggregation 'quantile' expects 1 parameter, found 2",
)
self._assert_expr_error("sparkline()", "Function 'sparkline' expects 1 argument, found 0")
+ self._assert_expr_error("sha1()", "Function 'sha1' expects 1 argument, found 0")
+ self._assert_expr_error("sha1('a', 'b')", "Function 'sha1' expects 1 argument, found 2")
self._assert_expr_error("hamburger(event)", "Unsupported function call 'hamburger(...)'")
self._assert_expr_error("mad(event)", "Unsupported function call 'mad(...)'")
self._assert_expr_error(
diff --git a/posthog/hogql/printer/trino.py b/posthog/hogql/printer/trino.py
index bb57323f6bd6..5aaa9323ad75 100644
--- a/posthog/hogql/printer/trino.py
+++ b/posthog/hogql/printer/trino.py
@@ -1017,6 +1017,10 @@ class TrinoPrinter(PostgresPrinter):
if name == "md5":
rendered_value = self._visit_unary_arg(node)
return f"to_hex(md5(to_utf8(CAST({rendered_value} AS VARCHAR))))"
+ if name == "sha1":
+ rendered_value = self._visit_unary_arg(node)
+ # Trino's to_hex is uppercase; HogQL sha1 returns lowercase across dialects.
+ return f"lower(to_hex(sha1(to_utf8(CAST({rendered_value} AS VARCHAR)))))"
if name == "extract":
return self._visit_extract(node)
if name in {"quantile", "quantileif"}:
diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.py
index c819883010bf..5a555634322f 100644
--- a/posthog/hogql/test/test_direct_postgres_query.py
+++ b/posthog/hogql/test/test_direct_postgres_query.py
@@ -426,7 +426,29 @@ class TestDirectPostgresQuery(APIBaseTest):
self.assertIn('(members.membership).tier AS "membership.tier"', sql)
self.assertEqual(executor.direct_source_id, str(source.id))
- def test_generate_sql_for_direct_postgres_connection_metadata_function(self):
+ @parameterized.expand(
+ [
+ (
+ "visible_function",
+ {"available_functions": ["date_bin"]},
+ "date_bin(toIntervalHour(1), now(), now())",
+ "date_bin((1 * INTERVAL '1 hour'), NOW(), NOW())",
+ ),
+ (
+ "pgcrypto",
+ {"pgcrypto_schema": "crypto"},
+ "sha1('abc')",
+ "encode(crypto.digest(convert_to(%(hogql_val_0)s, 'UTF8'), 'sha1'), 'hex')",
+ ),
+ (
+ "visible_sha1_overload",
+ {"available_functions": ["sha1"]},
+ "sha1('abc', 'hex')",
+ "sha1(%(hogql_val_0)s, %(hogql_val_1)s)",
+ ),
+ ]
+ )
+ def test_generate_sql_for_direct_postgres_connection_metadata_function(self, _name, metadata, expression, expected):
source = ExternalDataSource.objects.create(
team=self.team,
source_id="source_id",
@@ -443,7 +465,7 @@ class TestDirectPostgresQuery(APIBaseTest):
"password": "postgres",
"schema": "ph3",
},
- connection_metadata={"available_functions": ["date_bin"]},
+ connection_metadata=metadata,
)
DataWarehouseTable.objects.create(
@@ -456,14 +478,14 @@ class TestDirectPostgresQuery(APIBaseTest):
)
executor = HogQLQueryExecutor(
- query="SELECT date_bin(toIntervalHour(1), now(), now()) FROM without_team_id",
+ query=f"SELECT {expression} FROM without_team_id",
team=self.team,
connection_id=str(source.id),
)
sql, _context = executor.generate_clickhouse_sql()
- self.assertIn("date_bin((1 * INTERVAL '1 hour'), NOW(), NOW())", sql)
+ self.assertIn(expected, sql)
self.assertEqual(executor.direct_source_id, str(source.id))
def test_generate_sql_for_direct_postgres_custom_connection_metadata_function(self):
diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.py
index ded2c3f27120..45f4766fd756 100644
--- a/posthog/hogql/test/test_type_system.py
+++ b/posthog/hogql/test/test_type_system.py
@@ -884,6 +884,8 @@ class TestHogQLTypeSystem:
def test_resolver_infers_common_string_function_types(self) -> None:
self._assert_first_column_type("SELECT base64Encode('test')", ast.StringType(nullable=False))
self._assert_first_column_type("SELECT hex(unhex('DEADBEEF'))", ast.StringType(nullable=False))
+ self._assert_first_column_type("SELECT sha1('abc')", ast.StringType(nullable=False))
+ self._assert_first_column_type("SELECT sha1(toNullableString('abc'))", ast.StringType(nullable=True))
self._assert_first_column_type(
"SELECT splitByChar('.', '1.2.3')",
ast.ArrayType(nullable=False, item_type=ast.StringType(nullable=False)),
diff --git a/posthog/hogql/transforms/trino/validate.py b/posthog/hogql/transforms/trino/validate.py
index 007173b937ae..e206ba84fb63 100644
--- a/posthog/hogql/transforms/trino/validate.py
+++ b/posthog/hogql/transforms/trino/validate.py
@@ -134,6 +134,7 @@ _SPECIAL_CALLS = frozenset(
"jsonlength",
"match",
"md5",
+ "sha1",
"notempty",
"notin",
"parsedatetime",
diff --git a/posthog/hogql/type_system.py b/posthog/hogql/type_system.py
index bee8cb102bfc..40cdc0ba16e4 100644
--- a/posthog/hogql/type_system.py
+++ b/posthog/hogql/type_system.py
@@ -205,6 +205,7 @@ _STRING_RESULT_FUNCTIONS = frozenset(
"reverseutf8",
"rightpad",
"rightpadutf8",
+ "sha1",
"substring",
"substringutf8",
"tostring",
diff --git a/products/cdp/backend/test/test_filters.py b/products/cdp/backend/test/test_filters.py
index 151259ea6317..797b399dddad 100644
--- a/products/cdp/backend/test/test_filters.py
+++ b/products/cdp/backend/test/test_filters.py
@@ -439,6 +439,19 @@ class TestHogFunctionFilters(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
)
assert "bytecode_error" not in called_directly
+ def test_filters_can_use_hogql_sha1(self) -> None:
+ compiled = compile_filters_bytecode(
+ {
+ "properties": [
+ {"type": "hogql", "key": "sha1(properties.value) = 'a9993e364706816aba3e25717850c26c9cd0d89d'"}
+ ]
+ },
+ self.team,
+ )
+ assert "bytecode_error" not in compiled
+ assert execute_bytecode(compiled["bytecode"], {"properties": {"value": "abc"}}).result is True
+ assert execute_bytecode(compiled["bytecode"], {"properties": {"value": "def"}}).result is False
+
def test_filters_reject_a_function_the_runtime_does_not_have(self):
# max2 exists in the Python standard library and not in the Node VM. A data global such as
# event is not callable either, because the VM resolves a direct call against its function
diff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
index b6a6b3610018..89e95a50d29f 100644
--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
@@ -64,7 +64,7 @@
HogQL defines what functions are available with most (but not all) having a 1:1 mapping to ClickHouse functions.
These are the non-aggregated HogQL functions:
```
- ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'dynamicType', 'toTypeName', 'defaultValueOfTypeName', 'cityHash64', 'MD5', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', '_caseWithExpression', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapExists', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'grouping', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', '_finalizeAggregation', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']
+ ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'dynamicType', 'toTypeName', 'defaultValueOfTypeName', 'cityHash64', 'MD5', 'sha1', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', '_caseWithExpression', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapExists', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'grouping', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', '_finalizeAggregation', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']
```
These are the aggregated HogQL functions:
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
index c2ead35a76c3..05613ccae919 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
@@ -14,6 +14,8 @@ from rest_framework.exceptions import APIException, PermissionDenied, Validation
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.hogql.direct_sql.capability import is_direct_capable
+
from posthog.api.utils import action
from posthog.permissions import is_service_auth
@@ -235,7 +237,7 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
source_model=instance,
fallback=instance.connection_metadata,
)
- if instance.is_direct_query
+ if is_direct_capable(instance)
else instance.connection_metadata
)
schema_names = {s.name: s.label for s in schemas}
@@ -274,7 +276,7 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
descriptions = {s.name: s.description for s in schemas}
with transaction.atomic():
ExternalDataSource._base_manager.filter(pk=instance.pk).select_for_update().get()
- if instance.is_direct_query and connection_metadata != instance.connection_metadata:
+ if connection_metadata != instance.connection_metadata:
instance.connection_metadata = connection_metadata
instance.save(update_fields=["connection_metadata", "updated_at"])
# Migrate/dedupe legacy rows before sync_old_schemas; non-Postgres only once namespace cleared.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index 9a9a6ce269ed..0a8b4670aab3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -1885,6 +1885,18 @@ def get_foreign_keys(
return _foreign_keys_from_conn(connection, schema, names)
+def _get_connection_functions(cursor: psycopg.Cursor, query: str) -> list[str]:
+ try:
+ cursor.execute(query)
+ functions = _normalize_function_names([row[0] for row in cursor.fetchall()])
+ return [fn for fn in functions if not is_dangerous_table_function(fn)]
+ except Exception as error:
+ # Even a failed SELECT aborts PostgreSQL's transaction; reset it before the next catalog query.
+ cursor.connection.rollback()
+ capture_exception(error)
+ return []
+
+
def get_connection_metadata(
host: str,
database: str,
@@ -1911,42 +1923,42 @@ def get_connection_metadata(
is_duckdb = "duckdb" in version.lower() or "duckgres" in version.lower()
function_source = "duckdb_functions" if is_duckdb else "pg_proc"
- available_functions: list[str] = []
- available_table_functions: list[str] = []
-
- try:
- if is_duckdb:
- cursor.execute("SELECT DISTINCT function_name FROM duckdb_functions()")
- else:
- cursor.execute("SELECT DISTINCT proname FROM pg_proc WHERE pg_function_is_visible(oid)")
- available_functions = _normalize_function_names([row[0] for row in cursor.fetchall()])
- except Exception as error:
- capture_exception(error)
-
- try:
- if is_duckdb:
- cursor.execute(
- "SELECT DISTINCT function_name FROM duckdb_functions() WHERE function_type = 'table'"
- )
- else:
- # prokind='f' excludes aggregates/windows/procedures; proretset=true selects set-returning fns,
- # which is how Postgres exposes table functions in pg_proc.
- cursor.execute(
- "SELECT DISTINCT proname FROM pg_proc "
- "WHERE pg_function_is_visible(oid) AND proretset = true AND prokind = 'f'"
- )
- available_table_functions = _normalize_function_names([row[0] for row in cursor.fetchall()])
- except Exception as error:
- capture_exception(error)
-
- available_functions = [fn for fn in available_functions if not is_dangerous_table_function(fn)]
- available_table_functions = [fn for fn in available_table_functions if not is_dangerous_table_function(fn)]
-
- return {
+ metadata: dict[str, Any] = {
"database": current_database,
"version": version,
"engine": "duckdb" if is_duckdb else "postgres",
"function_source": function_source,
+ }
+ if is_duckdb:
+ available_functions = _get_connection_functions(
+ cursor, "SELECT DISTINCT function_name FROM duckdb_functions()"
+ )
+ available_table_functions = _get_connection_functions(
+ cursor, "SELECT DISTINCT function_name FROM duckdb_functions() WHERE function_type = 'table'"
+ )
+ else:
+ available_functions = _get_connection_functions(
+ cursor, "SELECT DISTINCT proname FROM pg_proc WHERE pg_function_is_visible(oid)"
+ )
+ # prokind='f' excludes aggregates/windows/procedures; proretset=true selects set-returning fns,
+ # which is how Postgres exposes table functions in pg_proc.
+ available_table_functions = _get_connection_functions(
+ cursor,
+ "SELECT DISTINCT proname FROM pg_proc "
+ "WHERE pg_function_is_visible(oid) AND proretset = true AND prokind = 'f'",
+ )
+ try:
+ cursor.execute(
+ "SELECT n.nspname FROM pg_extension e "
+ "JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'pgcrypto'"
+ )
+ extension = cursor.fetchone()
+ metadata["pgcrypto_schema"] = extension[0] if extension else None
+ except Exception as error:
+ capture_exception(error)
+
+ return {
+ **metadata,
"available_functions": available_functions,
"available_table_functions": available_table_functions,
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index 289a4e427ec8..d1e1dc3354e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -153,6 +153,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
_tunnel_with_handshake_translation,
_xmin_capable_tables_from_conn,
filter_postgres_incremental_fields,
+ get_connection_metadata,
get_enforced_unique_keys,
get_foreign_keys,
get_leading_index_columns,
@@ -6505,6 +6506,64 @@ class TestGetSslmode:
assert _get_sslmode(True) == "prefer"
+class TestPostgresConnectionMetadata:
+ @pytest.mark.django_db
+ @pytest.mark.parametrize("table_functions", [False, True])
+ def test_failed_function_probe_does_not_block_extension_discovery(self, autocommit_pg_connection, table_functions):
+ connection = autocommit_pg_connection
+ connection.autocommit = False
+ execute = psycopg.Cursor.execute
+
+ def execute_with_failed_probe(cursor, query, *args, **kwargs):
+ if "FROM pg_proc" in query and ("proretset" in query) == table_functions:
+ return execute(cursor, "SELECT 1 / 0")
+ return execute(cursor, query, *args, **kwargs)
+
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"
+ with (
+ patch(f"{module}.pg_connection") as connect,
+ patch(f"{module}.capture_exception"),
+ patch.object(psycopg.Cursor, "execute", execute_with_failed_probe),
+ ):
+ connect.return_value.__enter__.return_value = connection
+ metadata = get_connection_metadata(
+ host="db.example.com", port=5432, database="analytics", user="reader", password="test"
+ )
+
+ assert "pgcrypto_schema" in metadata
+ assert metadata["available_table_functions" if table_functions else "available_functions"] == []
+
+ @pytest.mark.parametrize(
+ "version,extension,expected",
+ [
+ ("PostgreSQL 15.12", ("crypto",), {"pgcrypto_schema": "crypto"}),
+ ("PostgreSQL 15.12", None, {"pgcrypto_schema": None}),
+ ("PostgreSQL 15.0 (Duckgres/DuckDB)", ("crypto",), {}),
+ ("PostgreSQL 15.12", psycopg.errors.InsufficientPrivilege("catalog access denied"), {}),
+ ],
+ )
+ def test_discovers_pgcrypto_without_losing_other_metadata(self, version, extension, expected):
+ cursor = MagicMock()
+ cursor.fetchone.side_effect = [("analytics", version), extension]
+ cursor.fetchall.side_effect = [[("count",)], []]
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"
+ with patch(f"{module}.pg_connection") as connect, patch(f"{module}.capture_exception"):
+ connect.return_value.__enter__.return_value.cursor.return_value.__enter__.return_value = cursor
+ metadata = get_connection_metadata(
+ host="db.example.com", port=5432, database="analytics", user="reader", password="test"
+ )
+
+ assert metadata == {
+ "database": "analytics",
+ "version": version,
+ "engine": "duckdb" if "DuckDB" in version else "postgres",
+ "function_source": "duckdb_functions" if "DuckDB" in version else "pg_proc",
+ "available_functions": ["count"],
+ "available_table_functions": [],
+ **expected,
+ }
+
+
class TestNormalizeFunctionNames:
def test_valid_identifiers(self):
result = _normalize_function_names(["foo", "bar_baz", "_private", "CamelCase"])
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 7418dfa98b95..b7b86904a254 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -4212,8 +4212,37 @@ class TestExternalDataSource(APIBaseTest):
assert table is not None
self.assertEqual(table.name, "Accounts")
+ @parameterized.expand(
+ [
+ (
+ "duckdb_direct",
+ ExternalDataSource.AccessMethod.DIRECT,
+ {
+ "database": "ducklake",
+ "version": "PostgreSQL 15.0 (Duckgres/DuckDB)",
+ "engine": "duckdb",
+ "function_source": "duckdb_functions",
+ "available_functions": ["duckdb_functions", "date_bin"],
+ },
+ ),
+ (
+ "pgcrypto_synced_live",
+ ExternalDataSource.AccessMethod.WAREHOUSE,
+ {
+ "database": "analytics",
+ "version": "PostgreSQL 15.12",
+ "engine": "postgres",
+ "function_source": "pg_proc",
+ "available_functions": ["count", "digest"],
+ "pgcrypto_schema": "crypto",
+ },
+ ),
+ ]
+ )
@patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")
- def test_refresh_schemas_direct_postgres_updates_connection_metadata(self, mock_get_source):
+ def test_refresh_schemas_direct_postgres_updates_connection_metadata(
+ self, _name, access_method, expected_metadata, mock_get_source
+ ):
source = ExternalDataSource.objects.create(
team_id=self.team.pk,
source_id=str(uuid.uuid4()),
@@ -4222,19 +4251,14 @@ class TestExternalDataSource(APIBaseTest):
source_type="Postgres",
created_by=self.user,
prefix="test",
- access_method=ExternalDataSource.AccessMethod.DIRECT,
+ access_method=access_method,
+ direct_query_enabled=access_method == ExternalDataSource.AccessMethod.WAREHOUSE,
job_inputs={"host": "localhost", "port": 5432},
connection_metadata={"database": "old_db", "available_functions": ["count"]},
)
mock_get_source.return_value.parse_config.return_value = None
- mock_get_source.return_value.get_connection_metadata.return_value = {
- "database": "ducklake",
- "version": "PostgreSQL 15.0 (Duckgres/DuckDB)",
- "engine": "duckdb",
- "function_source": "duckdb_functions",
- "available_functions": ["duckdb_functions", "date_bin"],
- }
+ mock_get_source.return_value.get_connection_metadata.return_value = expected_metadata
mock_get_source.return_value.get_schemas.return_value = [
SourceSchema(
name="Accounts",
@@ -4251,10 +4275,7 @@ class TestExternalDataSource(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
source.refresh_from_db()
- connection_metadata = source.connection_metadata
- assert connection_metadata is not None
- self.assertEqual(connection_metadata["database"], "ducklake")
- self.assertEqual(connection_metadata["available_functions"], ["duckdb_functions", "date_bin"])
+ self.assertEqual(source.connection_metadata, expected_metadata)
@patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")
def test_create_direct_postgres_preserves_numeric_as_decimal(self, mock_get_source):
diff --git a/rust/common/hogvm/tests/stl.rs b/rust/common/hogvm/tests/stl.rs
index 881aca5a28b0..779771dd0ba2 100644
--- a/rust/common/hogvm/tests/stl.rs
+++ b/rust/common/hogvm/tests/stl.rs
@@ -115,6 +115,18 @@ fn crypto_and_encoding_known_answers() {
}
}
+#[test]
+fn hogql_sha1_returns_lowercase_hex_or_null() {
+ for (input, expected) in [
+ ("abc", "a9993e364706816aba3e25717850c26c9cd0d89d"),
+ ("", "da39a3ee5e6b4b0d3255bfef95601890afd80709"),
+ ("🦔", "b1495135295ac36752f6579e93ba02140604590f"),
+ ] {
+ assert_eq!(call_str("sha1", input), json!(expected));
+ }
+ assert_eq!(run(call("sha1", &[vec![json!(31)]])), Value::Null);
+}
+
#[test]
fn hmac_sha1_matches_rfc_2202_vectors() {
// RFC 2202 HMAC-SHA1 test vectors. A two-element chain is a plain HMAC of key and message, so
diff --git a/services/hogql-language-service/internal/completion/functions.go b/services/hogql-language-service/internal/completion/functions.go
index e08cf9d346b9..1ee709237db1 100644
--- a/services/hogql-language-service/internal/completion/functions.go
+++ b/services/hogql-language-service/internal/completion/functions.go
@@ -51,17 +51,17 @@ ngrams not notEmpty notEquals notILike notIn notLike now nowInBlock nth_value nu
pointInEllipses pointInPolygon port position positionCaseInsensitive positionCaseInsensitiveUTF8 positionUTF8 positiveModulo pow power protocol quantile quantileExact quantileIf quantiles quantilesIf quantilesMerge quantilesMergeIf quantilesState quantilesStateIf
queryString queryStringAndFragment radians rand range rank recordingButton regexpExtract regexpQuoteMeta reinterpretAsFloat32 reinterpretAsFloat64 reinterpretAsInt128 reinterpretAsInt16 reinterpretAsInt256 reinterpretAsInt32 reinterpretAsInt64 reinterpretAsInt8 reinterpretAsUInt128 reinterpretAsUInt16 reinterpretAsUInt256
reinterpretAsUInt32 reinterpretAsUInt64 reinterpretAsUInt8 reinterpretAsUUID repeat replace replaceAll replaceOne replaceRegexpAll replaceRegexpOne reverse reverseUTF8 right rightPad rightPadUTF8 round roundAge roundBankers roundDown roundDuration
-roundToExp2 rowNumberInAllBlocks rowNumberInBlock row_number rpad rtrim sign simpleLinearRegression simpleLinearRegressionIf sin sinh skewPop skewPopIf skewSamp skewSampIf sortablesemver sparkline splitByChar splitByNonAlpha splitByRegexp
-splitByString splitByWhitespace split_part sqrt startsWith stddevPop stddevPopIf stddevSamp stddevSampIf stringToH3 string_agg subBitmap substring substringUTF8 subtractDays subtractHours subtractMinutes subtractMonths subtractQuarters subtractSeconds
-subtractWeeks subtractYears sum sumArgMax sumArgMaxIf sumArgMaxOrDefault sumArgMaxOrDefaultIf sumArgMaxOrNull sumArgMaxOrNullIf sumArgMin sumArgMinIf sumArgMinOrDefault sumArgMinOrDefaultIf sumArgMinOrNull sumArgMinOrNullIf sumArray sumArrayIf sumArrayOrDefault sumArrayOrDefaultIf sumArrayOrNull
-sumArrayOrNullIf sumForEach sumForEachIf sumForEachMerge sumForEachOrDefault sumForEachOrDefaultIf sumForEachOrNull sumForEachOrNullIf sumForEachState sumIf sumMap sumMapIf sumMapMerge sumMapMergeIf sumMapOrDefault sumMapOrDefaultIf sumMapOrNull sumMapOrNullIf sumMerge sumMergeIf
-sumMergeOrDefault sumMergeOrDefaultIf sumMergeOrNull sumMergeOrNullIf sumOrDefault sumOrDefaultIf sumOrNull sumOrNullIf sumState sumStateIf sumStateOrDefault sumStateOrDefaultIf sumStateOrNull sumStateOrNullIf sumWithOverflow sumWithOverflowIf tan tgamma theilsU theilsUIf
-throwIf timeSlot timeSlots timeStampAdd timeStampSub timeZoneOf timeZoneOffset timezone toBool toDate toDateTime toDateTime64 toDateTimeUS toDayOfMonth toDayOfWeek toDayOfYear toDecimal toFloat toFloat64OrNull toFloatOrDefault
-toFloatOrNull toFloatOrZero toHour toIPv4 toIPv4OrDefault toIPv4OrNull toIPv4OrZero toIPv6 toIPv6OrDefault toIPv6OrNull toIPv6OrZero toISOWeek toISOYear toInt toIntOrDefault toIntOrZero toIntervalDay toIntervalHour toIntervalMinute toIntervalMonth
-toIntervalQuarter toIntervalSecond toIntervalWeek toIntervalYear toJSONString toLastDayOfMonth toLastDayOfWeek toMinute toModifiedJulianDay toMonday toMonth toNullable toNullableString toQuarter toSecond toStartOfDay toStartOfFifteenMinutes toStartOfFiveMinutes toStartOfHour toStartOfISOYear
-toStartOfInterval toStartOfMinute toStartOfMonth toStartOfQuarter toStartOfSecond toStartOfTenMinutes toStartOfWeek toStartOfYear toString toTime toTimeZone toTypeName toUUID toUUIDOrDefault toUnixTimestamp toUnixTimestamp64Milli toValidUTF8 toWeek toYYYYMM toYYYYMMDD
-toYYYYMMDDhhmmss toYear toYearWeek to_char to_date to_timestamp today tokens topK topLevelDomain transform translate translateUTF8 trim trimLeft trimRight trunc tryBase58Decode tryBase64Decode tumble
-tumbleEnd tumbleStart tuple tupleDivide tupleDivideByNumber tupleElement tupleHammingDistance tupleMinus tupleMultiply tupleMultiplyByNumber tupleNegate tuplePlus tupleToNameValuePairs unhex uniq uniqCombined uniqCombined64 uniqExact uniqExactIf uniqExactMerge
-uniqExactState uniqHLL12 uniqHLL12If uniqIf uniqMap uniqMapMerge uniqMapMergeIf uniqMerge uniqMergeIf uniqState uniqStateIf uniqTheta uniqThetaIf uniqUpToMerge uniqueSurveySubmissionsFilter untuple upper upperUTF8 varPop varPopIf
-varSamp varSampIf width_bucket windowFunnel xor yesterday
+roundToExp2 rowNumberInAllBlocks rowNumberInBlock row_number rpad rtrim sha1 sign simpleLinearRegression simpleLinearRegressionIf sin sinh skewPop skewPopIf skewSamp skewSampIf sortablesemver sparkline splitByChar splitByNonAlpha
+splitByRegexp splitByString splitByWhitespace split_part sqrt startsWith stddevPop stddevPopIf stddevSamp stddevSampIf stringToH3 string_agg subBitmap substring substringUTF8 subtractDays subtractHours subtractMinutes subtractMonths subtractQuarters
+subtractSeconds subtractWeeks subtractYears sum sumArgMax sumArgMaxIf sumArgMaxOrDefault sumArgMaxOrDefaultIf sumArgMaxOrNull sumArgMaxOrNullIf sumArgMin sumArgMinIf sumArgMinOrDefault sumArgMinOrDefaultIf sumArgMinOrNull sumArgMinOrNullIf sumArray sumArrayIf sumArrayOrDefault sumArrayOrDefaultIf
+sumArrayOrNull sumArrayOrNullIf sumForEach sumForEachIf sumForEachMerge sumForEachOrDefault sumForEachOrDefaultIf sumForEachOrNull sumForEachOrNullIf sumForEachState sumIf sumMap sumMapIf sumMapMerge sumMapMergeIf sumMapOrDefault sumMapOrDefaultIf sumMapOrNull sumMapOrNullIf sumMerge
+sumMergeIf sumMergeOrDefault sumMergeOrDefaultIf sumMergeOrNull sumMergeOrNullIf sumOrDefault sumOrDefaultIf sumOrNull sumOrNullIf sumState sumStateIf sumStateOrDefault sumStateOrDefaultIf sumStateOrNull sumStateOrNullIf sumWithOverflow sumWithOverflowIf tan tgamma theilsU
+theilsUIf throwIf timeSlot timeSlots timeStampAdd timeStampSub timeZoneOf timeZoneOffset timezone toBool toDate toDateTime toDateTime64 toDateTimeUS toDayOfMonth toDayOfWeek toDayOfYear toDecimal toFloat toFloat64OrNull
+toFloatOrDefault toFloatOrNull toFloatOrZero toHour toIPv4 toIPv4OrDefault toIPv4OrNull toIPv4OrZero toIPv6 toIPv6OrDefault toIPv6OrNull toIPv6OrZero toISOWeek toISOYear toInt toIntOrDefault toIntOrZero toIntervalDay toIntervalHour toIntervalMinute
+toIntervalMonth toIntervalQuarter toIntervalSecond toIntervalWeek toIntervalYear toJSONString toLastDayOfMonth toLastDayOfWeek toMinute toModifiedJulianDay toMonday toMonth toNullable toNullableString toQuarter toSecond toStartOfDay toStartOfFifteenMinutes toStartOfFiveMinutes toStartOfHour
+toStartOfISOYear toStartOfInterval toStartOfMinute toStartOfMonth toStartOfQuarter toStartOfSecond toStartOfTenMinutes toStartOfWeek toStartOfYear toString toTime toTimeZone toTypeName toUUID toUUIDOrDefault toUnixTimestamp toUnixTimestamp64Milli toValidUTF8 toWeek toYYYYMM
+toYYYYMMDD toYYYYMMDDhhmmss toYear toYearWeek to_char to_date to_timestamp today tokens topK topLevelDomain transform translate translateUTF8 trim trimLeft trimRight trunc tryBase58Decode tryBase64Decode
+tumble tumbleEnd tumbleStart tuple tupleDivide tupleDivideByNumber tupleElement tupleHammingDistance tupleMinus tupleMultiply tupleMultiplyByNumber tupleNegate tuplePlus tupleToNameValuePairs unhex uniq uniqCombined uniqCombined64 uniqExact uniqExactIf
+uniqExactMerge uniqExactState uniqHLL12 uniqHLL12If uniqIf uniqMap uniqMapMerge uniqMapMergeIf uniqMerge uniqMergeIf uniqState uniqStateIf uniqTheta uniqThetaIf uniqUpToMerge uniqueSurveySubmissionsFilter untuple upper upperUTF8 varPop
+varPopIf varSamp varSampIf width_bucket windowFunnel xor yesterday
`)