:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add direct-query Redshift support (#67675)
George Munyoro0f466a43fb9b
diff --git a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsxindex e0638b2b7796..f49f232027ab 100644--- a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx+++ b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx@@ -10,6 +10,7 @@ import { urls } from 'scenes/urls'import {ADD_MYSQL_DIRECT_CONNECTION,ADD_POSTGRES_DIRECT_CONNECTION,+ ADD_REDSHIFT_DIRECT_CONNECTION,ADD_SNOWFLAKE_DIRECT_CONNECTION,CONFIGURE_SOURCES,type ConnectionSelectOption,@@ -79,6 +80,11 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elemreturn}+ if (nextValue === ADD_REDSHIFT_DIRECT_CONNECTION) {+ router.actions.push(urls.dataWarehouseSourceNew('Redshift', undefined, undefined, 'direct'))+ return+ }+if (nextValue === CONFIGURE_SOURCES) {router.actions.push(urls.sources())returndiff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.tsindex 9abbc63d8b94..14d128d43ab4 100644--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts@@ -10,6 +10,7 @@ import IconPostHog from 'public/posthog-icon.svg'import IconDuckDB from 'public/services/duckdb.svg'import IconMySQL from 'public/services/mysql.png'import IconPostgres from 'public/services/postgres.png'+import IconRedshift from 'public/services/redshift.png'import IconSnowflake from 'public/services/snowflake.png'import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'@@ -21,6 +22,7 @@ export const LOADING_CONNECTIONS = '__loading_connections__'export const ADD_POSTGRES_DIRECT_CONNECTION = '__add_postgres_direct_connection__'export const ADD_MYSQL_DIRECT_CONNECTION = '__add_mysql_direct_connection__'export const ADD_SNOWFLAKE_DIRECT_CONNECTION = '__add_snowflake_direct_connection__'+export const ADD_REDSHIFT_DIRECT_CONNECTION = '__add_redshift_direct_connection__'export const CONFIGURE_SOURCES = '__configure_sources__'export interface ConnectionSelectOption {@@ -37,13 +39,14 @@ export interface ConnectionSelectOptionGroup {options: ConnectionSelectOption[]}-type ConnectionEngine = 'duckdb' | 'postgres' | 'mysql' | 'snowflake'+type ConnectionEngine = 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift'const ENGINE_LABELS: Record<ConnectionEngine, string> = {duckdb: 'DuckDB',postgres: 'Postgres',mysql: 'MySQL',snowflake: 'Snowflake',+ redshift: 'Redshift',}const ENGINE_ICONS: Record<ConnectionEngine, string> = {@@ -51,10 +54,16 @@ const ENGINE_ICONS: Record<ConnectionEngine, string> = {postgres: IconPostgres,mysql: IconMySQL,snowflake: IconSnowflake,+ redshift: IconRedshift,}function getConnectionEngine(source: Pick<ExternalDataSourceConnectionOption, 'engine'>): ConnectionEngine {- if (source.engine === 'duckdb' || source.engine === 'mysql' || source.engine === 'snowflake') {+ if (+ source.engine === 'duckdb' ||+ source.engine === 'mysql' ||+ source.engine === 'snowflake' ||+ source.engine === 'redshift'+ ) {return source.engine}return 'postgres'@@ -147,6 +156,11 @@ export const connectionSelectorLogic = kea<connectionSelectorLogicType>([label: 'Snowflake',iconSrc: IconSnowflake,},+ {+ value: ADD_REDSHIFT_DIRECT_CONNECTION,+ label: 'Redshift',+ iconSrc: IconRedshift,+ },],},],diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 8a3927325bd0..3d5b815761a0 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6135,7 +6135,7 @@ export interface ExternalDataSourceConnectionMetadata {export interface ExternalDataSourceConnectionOption {id: stringprefix: string | null- engine?: 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | null+ engine?: 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift' | null}export interface ExternalDataSource {diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.pyindex 929f02cefd57..a5672b3bfeab 100644--- a/posthog/hogql/constants.py+++ b/posthog/hogql/constants.py@@ -48,12 +48,14 @@ BREAKDOWN_VALUES_LIMIT = 25BREAKDOWN_VALUES_LIMIT_FOR_COUNTRIES = 300BREAKDOWN_VALUE_MAX_LENGTH = 400-type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb", "mysql", "snowflake"]+type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb", "mysql", "snowflake", "redshift"]# All dialects that compile to an external SQL database queried directly (as opposed to# ClickHouse / HogQL). MySQL shares the standard-SQL keyword surface (CURRENT_DATE & co.)# but not Postgres-specific features like PIVOT/UNPIVOT, TRY_CAST, or positional references.-SQL_TARGET_DIALECTS: frozenset[HogQLDialect] = frozenset({"postgres", "duckdb", "mysql"})+# Redshift is a Postgres fork: it reuses the Postgres-family lazy-table resolution and+# property lowering, then its printer blocks the constructs the Redshift engine can't run.+SQL_TARGET_DIALECTS: frozenset[HogQLDialect] = frozenset({"postgres", "duckdb", "mysql", "redshift"})type HogQLParserBackend = Literal["cpp-json", "rust-json", "rust-py"]diff --git a/posthog/hogql/database/direct_redshift_table.py b/posthog/hogql/database/direct_redshift_table.pynew file mode 100644index 000000000000..33370ab5ace1--- /dev/null+++ b/posthog/hogql/database/direct_redshift_table.py@@ -0,0 +1,14 @@+from posthog.hogql.database.direct_postgres_table import DirectPostgresTable+++class DirectRedshiftTable(DirectPostgresTable):+ """A table queried live against Amazon Redshift.++ Redshift is a fork of Postgres and shares its table-reference syntax+ (``"schema"."table"``, optionally catalog-qualified, double-quoted identifiers), so this+ reuses ``DirectPostgresTable``'s fields and ``to_printed_postgres`` rendering verbatim.+ Subclassing (rather than aliasing) keeps the ``isinstance(table, DirectPostgresTable)``+ table-printing hooks in the Postgres/Redshift printers working while leaving room for the+ dialects to diverge later. The DuckLake ``engine == "duckdb"`` catalog branch inherited+ from the parent never triggers for a Redshift connection.+ """diff --git a/posthog/hogql/direct_query_metrics.py b/posthog/hogql/direct_query_metrics.pyindex 1d6b8a3c5b0f..baa8cef5e610 100644--- a/posthog/hogql/direct_query_metrics.py+++ b/posthog/hogql/direct_query_metrics.py@@ -19,7 +19,7 @@ from prometheus_client import (Histogram,)-DirectQueryDialect = Literal["postgres", "mysql", "snowflake"]+DirectQueryDialect = Literal["postgres", "mysql", "snowflake", "redshift"]DirectQueryStatus = Literal["success", "error"]DIRECT_QUERY_TOTAL = PromCounter(diff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.pyindex 77825a7c1808..b280e33d74f2 100644--- a/posthog/hogql/direct_sql/__init__.py+++ b/posthog/hogql/direct_sql/__init__.py@@ -3,12 +3,14 @@ from posthog.hogql.direct_sql.capability import direct_capable_source_types, is_from posthog.hogql.direct_sql.mysql_adapter import MySQLAdapterfrom posthog.hogql.direct_sql.postgres_adapter import PostgresAdapterfrom posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.direct_sql.redshift_adapter import RedshiftAdapterfrom posthog.hogql.direct_sql.registry import get_adapter, register_adapter, registered_enginesfrom posthog.hogql.direct_sql.snowflake_adapter import SnowflakeAdapterregister_adapter(PostgresAdapter())register_adapter(MySQLAdapter())register_adapter(SnowflakeAdapter())+register_adapter(RedshiftAdapter())__all__ = ["DirectQueryRequest",@@ -17,6 +19,7 @@ __all__ = ["PostgresAdapter","MySQLAdapter","SnowflakeAdapter",+ "RedshiftAdapter","direct_capable_source_types","is_direct_capable","ensure_single_direct_statement",diff --git a/posthog/hogql/direct_sql/redshift_adapter.py b/posthog/hogql/direct_sql/redshift_adapter.pynew file mode 100644index 000000000000..d11a0551bb3e--- /dev/null+++ b/posthog/hogql/direct_sql/redshift_adapter.py@@ -0,0 +1,172 @@+from typing import TYPE_CHECKING, cast++import psycopg+import sqlparse+from opentelemetry import trace+from sqlparse import tokens as sqlparse_tokens++from posthog.hogql.constants import HogQLDialect+from posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_query+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult+from posthog.hogql.direct_sql.postgres_adapter import postgres_error_to_message, postgres_oid_to_clickhouse_type+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.escape_sql import escape_postgres_identifier++if TYPE_CHECKING:+ from posthog.models.team import Team++ from products.warehouse_sources.backend.facade.models import ExternalDataSource+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RedshiftSourceConfig+ from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift import (+ RedshiftImplementation,+ )++DIRECT_REDSHIFT_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600+# Hard backstop against loading an unbounded result set into memory — guards a raw passthrough+# `SELECT * FROM huge_table` with no LIMIT. HogQL-authored queries already carry a LIMIT from+# the printer.+DIRECT_REDSHIFT_MAX_ROWS = 1_000_000+DIRECT_REDSHIFT_ROW_CAP_ERROR = (+ f"Redshift query returned more than {DIRECT_REDSHIFT_MAX_ROWS:,} rows. Add a LIMIT clause."+)+RAW_REDSHIFT_READ_ONLY_ERROR = "Raw Redshift queries must be read-only SELECT statements."+RAW_REDSHIFT_BLOCKED_FUNCTION_ERROR = "This Redshift function is not allowed in direct queries."++# Redshift's system-administration functions run from a plain SELECT, so the read-only statement+# gate alone doesn't stop a viewer cancelling other queries, changing priorities, or rebooting+# the cluster when the configured credential has the privilege.+_RAW_REDSHIFT_BLOCKED_FUNCTIONS = frozenset(+ {+ "CHANGE_QUERY_PRIORITY",+ "CHANGE_SESSION_PRIORITY",+ "CHANGE_USER_PRIORITY",+ "PG_CANCEL_BACKEND",+ "PG_TERMINATE_BACKEND",+ "REBOOT_CLUSTER",+ "SET_CONFIG",+ }+)+++def _fetch_capped_redshift_rows(cursor: psycopg.Cursor) -> list:+ """Fetch up to the row cap, raising if the result would exceed it.++ Reads one row past the cap so the limit can be enforced without materializing the entire+ result set first.+ """+ rows = cursor.fetchmany(DIRECT_REDSHIFT_MAX_ROWS + 1)+ if len(rows) > DIRECT_REDSHIFT_MAX_ROWS:+ DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL.labels(dialect="redshift").inc()+ raise ExposedHogQLError(DIRECT_REDSHIFT_ROW_CAP_ERROR)+ return list(rows)+++def ensure_read_only_raw_redshift_statement(sql: str) -> str:+ """Enforce read-only for raw Redshift SQL.++ Redshift, unlike Postgres, exposes no read-only transaction switch — its settable server+ parameters don't include ``default_transaction_read_only``. So read-only is enforced our side+ (as with Snowflake): a raw statement must be a single ``SELECT``, and any DDL — or any DML+ keyword other than ``SELECT`` anywhere in the statement (e.g. a write smuggled into a+ subquery) — is rejected. ``INTO`` is rejected too: Redshift supports ``SELECT ... INTO``,+ which creates and populates a table while still tokenizing as a plain SELECT. Redshift's+ system-administration functions (``PG_CANCEL_BACKEND`` etc.) are rejected by name, as in the+ Snowflake adapter, since they're callable from a plain SELECT. HogQL-authored queries only+ ever emit SELECT. String values and quoted identifiers aren't tagged DML/DDL/keyword/name,+ so a literal or alias like ``'DELETE'`` or a quoted column ``"pg_cancel_backend"`` is+ unaffected.+ """+ sql = ensure_single_direct_statement(sql)+ statements = [statement for statement in sqlparse.parse(sql) if str(statement).strip(" \t\r\n;")]+ if len(statements) != 1 or statements[0].get_type() != "SELECT":+ raise ExposedHogQLError(RAW_REDSHIFT_READ_ONLY_ERROR)+ for token in statements[0].flatten():+ if token.ttype in sqlparse_tokens.DDL:+ raise ExposedHogQLError(RAW_REDSHIFT_READ_ONLY_ERROR)+ if token.ttype in sqlparse_tokens.DML and token.value.upper() != "SELECT":+ raise ExposedHogQLError(RAW_REDSHIFT_READ_ONLY_ERROR)+ if token.ttype in sqlparse_tokens.Keyword and token.value.upper() == "INTO":+ raise ExposedHogQLError(RAW_REDSHIFT_READ_ONLY_ERROR)+ if token.ttype in sqlparse_tokens.Name and token.value.upper() in _RAW_REDSHIFT_BLOCKED_FUNCTIONS:+ raise ExposedHogQLError(RAW_REDSHIFT_BLOCKED_FUNCTION_ERROR)+ return sql+++class RedshiftAdapter:+ engine = "redshift"+ dialect: HogQLDialect | None = "redshift"++ def validate_source_config(+ self, source: "ExternalDataSource", team: "Team"+ ) -> tuple["RedshiftImplementation", "RedshiftSourceConfig"]:+ from products.warehouse_sources.backend.facade.source_management import RedshiftSource, SourceRegistry+ from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++ if not source.is_direct_redshift:+ raise ExposedHogQLError("Invalid direct Redshift connection.")++ redshift_source = cast(RedshiftSource, SourceRegistry.get_source(ExternalDataSourceType.REDSHIFT))+ config = redshift_source.parse_config(source.job_inputs or {})++ is_ssh_valid, ssh_valid_errors = redshift_source.ssh_tunnel_is_valid(config, team.pk)+ if not is_ssh_valid:+ raise ExposedHogQLError(ssh_valid_errors or "Invalid SSH tunnel configuration.")++ valid_host, host_errors = redshift_source.is_database_host_valid(+ config.host, team.pk, using_ssh_tunnel=config.ssh_tunnel.enabled if config.ssh_tunnel else False+ )+ if not valid_host:+ raise ExposedHogQLError(host_errors or "Invalid Redshift host.")++ return redshift_source.get_implementation, config++ def prepare_raw_sql(self, sql: str) -> str:+ return ensure_read_only_raw_redshift_statement(sql)++ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:+ source = request.source+ redshift_implementation, source_config = self.validate_source_config(source, request.team)+ source_schema = source_config.schema+ settings = request.settings+ statement_timeout_ms = (+ max(settings.max_execution_time or DIRECT_REDSHIFT_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1) * 1000+ )++ span = trace.get_current_span()+ span.set_attribute("team_id", request.team.pk)+ span.set_attribute("query_type", request.query_type)+ span.set_attribute("source_id", str(source.id))++ try:+ with request.timings.measure("redshift_execute"), observe_direct_query("redshift"):+ # `connect` opens the SSH tunnel (if any) and applies the shared Redshift SSL+ # conventions in one place.+ with redshift_implementation.connect(source_config) as connection:+ # One round trip for the session setup: statement_timeout is a validated int+ # (milliseconds) so inlining it is injection-safe, and the search_path+ # identifier is escaped. Multi-statement execute is fine with no parameters.+ session_setup = f"SET statement_timeout TO {statement_timeout_ms}"+ if isinstance(source_schema, str) and source_schema.strip():+ session_setup += f"; SET search_path TO {escape_postgres_identifier(source_schema.strip())}"+ connection.execute(session_setup)+ with connection.cursor() as cursor:+ cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute+ request.sql, request.values or None+ )+ # Utility statements (SET, etc.) leave cursor.description as None; treat them+ # as an empty result instead of raising on fetch, mirroring Postgres.+ description = cursor.description or []+ results = _fetch_capped_redshift_rows(cursor) if description else []+ except (psycopg.Error, ExposedHogQLError) as error:+ span.set_attribute("error_type", error.__class__.__name__)+ if request.debug:+ return DirectQueryResult(results=[], types=[], print_columns=[], error=postgres_error_to_message(error))+ raise ExposedHogQLError(postgres_error_to_message(error)) from error++ span.set_attribute("row_count", len(results))+ types: list[tuple[str, str]] = [+ (column.name, postgres_oid_to_clickhouse_type(getattr(column, "type_code", None))) for column in description+ ]+ print_columns = [column.name for column in description]+ return DirectQueryResult(results=results, types=types, print_columns=print_columns)diff --git a/posthog/hogql/direct_sql/test/test_registry_and_capability.py b/posthog/hogql/direct_sql/test/test_registry_and_capability.pyindex 61bcd556f509..081ad4c1c45e 100644--- a/posthog/hogql/direct_sql/test/test_registry_and_capability.py+++ b/posthog/hogql/direct_sql/test/test_registry_and_capability.py@@ -24,7 +24,7 @@ class TestDirectSQLRegistry(SimpleTestCase):self.assertIsNone(get_adapter(engine))def test_registered_engines_includes_phase_one_engines(self):- self.assertEqual({"postgres", "mysql", "snowflake"}, set(registered_engines()))+ self.assertEqual({"postgres", "mysql", "snowflake", "redshift"}, set(registered_engines()))def test_register_adapter_round_trips(self):class FakeAdapter:@@ -60,6 +60,11 @@ class TestDirectSQLCapability(SimpleTestCase):def test_direct_capable_source_types(self):self.assertEqual(- {ExternalDataSourceType.POSTGRES, ExternalDataSourceType.MYSQL, ExternalDataSourceType.SNOWFLAKE},+ {+ ExternalDataSourceType.POSTGRES,+ ExternalDataSourceType.MYSQL,+ ExternalDataSourceType.SNOWFLAKE,+ ExternalDataSourceType.REDSHIFT,+ },set(direct_capable_source_types()),)diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.pyindex 9786854d3d86..522855fa48cf 100644--- a/posthog/hogql/printer/base.py+++ b/posthog/hogql/printer/base.py@@ -255,15 +255,19 @@ class BasePrinter(Visitor[str]):inner = ", ".join(self.visit(e) for e in node.exprs)return f"({inner})"+ def _visit_set_operand(self, node: ast.SelectQuery | ast.SelectSetQuery) -> str:+ """Render one operand of a set query (UNION/INTERSECT/EXCEPT). Dialects whose grammar+ needs each operand parenthesized (e.g. to carry a per-branch LIMIT) override this."""+ query = self.visit(node)+ if self.pretty:+ query = query.strip()+ return query+def visit_select_set_query(self, node: ast.SelectSetQuery):self._indent -= 1- ret = self.visit(node.initial_select_query)- if self.pretty:- ret = ret.strip()+ ret = self._visit_set_operand(node.initial_select_query)for expr in node.subsequent_select_queries:- query = self.visit(expr.select_query)- if self.pretty:- query = query.strip()+ query = self._visit_set_operand(expr.select_query)if expr.set_operator is not None:self._assert_set_operator_supported(expr.set_operator)if self.pretty:diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.pyindex e25b9a4b0ecd..8f8062aa6465 100644--- a/posthog/hogql/printer/postgres.py+++ b/posthog/hogql/printer/postgres.py@@ -85,6 +85,11 @@ class PostgresPrinter(BasePrinter):def _render_set_query_limit_percent(self, limit: ast.Expr, limit_str: str) -> str:return f"{limit_str} %"+ def _visit_set_operand(self, node: ast.SelectQuery | ast.SelectSetQuery) -> str:+ # ClickHouse accepts a bare per-branch LIMIT/ORDER BY inside a set operation; the+ # Postgres-family grammars only allow those on a parenthesized operand.+ return f"({super()._visit_set_operand(node)})"+def _render_select_query_limit_clause(self, limit: ast.Expr, is_percent: bool) -> str:rendered = f"LIMIT {self.visit(limit)}"if is_percent:@@ -166,18 +171,31 @@ class PostgresPrinter(BasePrinter):raise QueryError(f"Function '{node.name}' does not support ORDER BY in the {self.DIALECT_LABEL} dialect.")+ if node.distinct:+ # Handlers compose custom SQL from pre-rendered args; injecting DISTINCT into+ # that blindly risks silently changing what the aggregate counts.+ raise QueryError(+ f"Function '{node.name}' does not support DISTINCT in the {self.DIALECT_LABEL} dialect."+ )return handler(args)+ args_str = ", ".join(args)+ if func_name == "count" and not args and not node.distinct:+ # ClickHouse's zero-arg count() is spelled count(*) everywhere else.+ args_str = "*"+ if node.distinct:+ args_str = f"DISTINCT {args_str}"+renamed = function_renames.get(func_name)if renamed is not None:- return f"{renamed}({', '.join(args)}{order_by_part})"+ return f"{renamed}({args_str}{order_by_part})"if func_name in passthrough_functions:- return f"{func_name}({', '.join(args)}{order_by_part})"+ return f"{func_name}({args_str}{order_by_part})"if func_name in self._connection_supported_functions:# Use the validated name — never the raw node.name- return f"{func_name}({', '.join(args)})"+ return f"{func_name}({args_str})"raise QueryError(f"Function '{node.name}' is not supported in the {self.DIALECT_LABEL} dialect.")diff --git a/posthog/hogql/printer/redshift.py b/posthog/hogql/printer/redshift.pynew file mode 100644index 000000000000..025a06669402--- /dev/null+++ b/posthog/hogql/printer/redshift.py@@ -0,0 +1,94 @@+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.postgres import PostgresPrinter+from posthog.hogql.printer.redshift_functions import (+ REDSHIFT_FUNCTION_HANDLERS_LOWER,+ REDSHIFT_FUNCTION_RENAMES_LOWER,+ REDSHIFT_PASSTHROUGH_FUNCTIONS,+)+++class RedshiftPrinter(PostgresPrinter):+ """Prints a HogQL AST as Amazon Redshift SQL.++ Redshift is a fork of an old Postgres, so almost the entire ``PostgresPrinter`` surface —+ identifiers, operators (ILIKE, POSIX ``~``), date_trunc/extract, CAST, CTEs, window functions —+ is emitted unchanged. This subclass is mostly **subtractive**: it blocks the constructs the+ Redshift engine can't run, raising a clear ``QueryError`` rather than shipping SQL that would+ fail server-side. The exceptions are a few semantic-preserving rewrites where Redshift would+ otherwise silently return different results than HogQL promises: integer division is cast to+ float (Redshift ``/`` truncates), and ``avg``/``concat``/``position`` are re-rendered in+ ``redshift_functions._REDSHIFT_ONLY_HANDLERS``.++ Redshift *does* support (so they stay inherited): FULL OUTER JOIN, QUALIFY, recursive CTEs,+ ILIKE, and the POSIX regex operators. The blocked set below is what it does *not* support.+ """++ DIALECT_NAME: ClassVar[HogQLDialect] = "redshift"+ DIALECT_LABEL: ClassVar[str] = "Redshift"++ def _dialect_error_suffix(self) -> str:+ return "in the Redshift dialect"++ # --- function sets (Postgres minus the Redshift-incompatible entries) --------------++ def _get_function_renames(self) -> dict[str, str]:+ return REDSHIFT_FUNCTION_RENAMES_LOWER++ def _get_function_handlers(self) -> dict[str, Callable[[list[str]], str]]:+ return REDSHIFT_FUNCTION_HANDLERS_LOWER++ def _get_passthrough_functions(self) -> frozenset[str]:+ return REDSHIFT_PASSTHROUGH_FUNCTIONS++ # --- semantic-preserving rewrites ---------------------------------------------------++ def visit_arithmetic_operation(self, node: ast.ArithmeticOperation) -> str:+ if node.op == ast.ArithmeticOperationOp.Div:+ # Redshift `/` on two integers truncates; HogQL division is always float.+ return f"(CAST({self.visit(node.left)} AS DOUBLE PRECISION) / {self.visit(node.right)})"+ return super().visit_arithmetic_operation(node)++ # --- blocked constructs (no Redshift equivalent) -----------------------------------++ def visit_array(self, node: ast.Array):+ raise QueryError(f"Arrays are not supported {self._dialect_error_suffix()}")++ def visit_array_slice(self, node: ast.ArraySlice):+ raise QueryError(f"Array slicing is not supported {self._dialect_error_suffix()}")++ def visit_lambda(self, node: ast.Lambda):+ raise QueryError(f"Lambdas are not supported {self._dialect_error_suffix()}")++ def visit_dict(self, node: ast.Dict):+ raise QueryError(f"Dicts are not supported {self._dialect_error_suffix()}")++ def visit_try_cast(self, node: ast.TryCast):+ raise QueryError(f"TRY_CAST is not supported {self._dialect_error_suffix()}")++ def visit_tuple(self, node: ast.Tuple) -> str:+ # Redshift has no ROW() row constructor. A multi-value tuple is still valid as an+ # `IN (...)` value list / parenthesized grouping, but a single-element tuple can only be a+ # 1-column row constructor, which Redshift can't express.+ values = [self.visit(expr) for expr in node.exprs]+ if len(values) == 1:+ raise QueryError(f"Single-element tuples are not supported {self._dialect_error_suffix()}")+ return f"({', '.join(values)})"++ def _render_start_of(self, unit: str, arg: str, week_mode: int = 3) -> str:+ # The Postgres isoyear expansion uses make_date() + extract(isoyear ...), neither of which+ # Redshift supports. Every other unit expands to date_trunc()/interval arithmetic, which+ # Redshift runs unchanged.+ if unit == "isoyear":+ raise QueryError(f"toStartOfISOYear is not supported {self._dialect_error_suffix()}")+ return super()._render_start_of(unit, arg, week_mode=week_mode)++ def _unsafe_json_extract_trim_quotes(self, unsafe_field, unsafe_args):+ # Postgres renders blob property reads with the `->`/`->>` JSON operators, which Redshift+ # does not have. Block the implicit path; explicit json_extract_path_text(...) via the+ # JSONExtractString rename is still available for users who need JSON access.+ raise QueryError(f"JSON property access (-> / ->>) is not supported {self._dialect_error_suffix()}")diff --git a/posthog/hogql/printer/redshift_functions.py b/posthog/hogql/printer/redshift_functions.pynew file mode 100644index 000000000000..821cd7ea16e5--- /dev/null+++ b/posthog/hogql/printer/redshift_functions.py@@ -0,0 +1,119 @@+"""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 would reject. Anything removed here is not+silently rewritten — it falls through to ``PostgresPrinter.visit_call``'s final branch and raises a+clear ``QueryError`` ("not supported in the Redshift dialect"), per the block-everything-incompatible+policy for direct Redshift sources.++Each removed name is annotated with why Redshift rejects it. Items marked ``UNCERTAIN`` are removed+conservatively and should be re-validated against a live Redshift cluster — if supported, delete them+from the removal set to let the inherited Postgres mapping through.++On top of the subtraction, a small set of handlers rewrites functions whose Postgres rendering is+valid but means something different (or fails) on Redshift while a faithful equivalent exists —+these preserve HogQL semantics rather than blocking (see ``_REDSHIFT_ONLY_HANDLERS``).+"""++from collections.abc import Callable++from posthog.hogql.errors import QueryError+from posthog.hogql.printer.postgres_functions import (+ POSTGRES_FUNCTION_HANDLERS_LOWER,+ POSTGRES_FUNCTION_RENAMES_LOWER,+ POSTGRES_PASSTHROUGH_FUNCTIONS,+)++# Lowercased HogQL/ClickHouse function names whose Postgres rendering the Redshift engine rejects.+# Applied uniformly across renames, handlers, and passthrough.+REDSHIFT_UNSUPPORTED_FUNCTIONS: frozenset[str] = frozenset(+ {+ # No array type in Redshift: ARRAY_AGG / UNNEST / ARRAY_TO_STRING don't exist.+ "grouparray",+ "grouparrayif",+ "arrayjoin",+ "arraystringconcat",+ # Redshift has json_extract_path_text (kept) but not json_extract_path (returns JSON).+ "jsonextractraw",+ "jsonextractarrayraw",+ # pg_typeof does not exist in Redshift.+ "totypename",+ # Redshift has no UUID type, so CAST(... AS UUID) fails.+ "touuid",+ # starts_with() is a Postgres builtin absent from Redshift.+ "startswith",+ # generate_series runs on the leader node only and fails in most query contexts.+ "generateseries",+ # TO_TIMESTAMP(epoch) is not supported (Redshift only has the format-string form).+ "fromunixtimestamp",+ # Aggregate FILTER (WHERE ...) clause is not supported by Redshift.+ "countif",+ "sumif",+ "avgif",+ "minif",+ "maxif",+ "anyif",+ "uniqif",+ "uniqexactif",+ # UNCERTAIN: EXTRACT(ISODOW/ISOYEAR FROM ...) — Redshift date_part lacks isodow/isoyear.+ "todayofweek",+ "toisoyear",+ }+)+++def _without_unsupported(names: frozenset[str]) -> frozenset[str]:+ return frozenset(name for name in names if name not in REDSHIFT_UNSUPPORTED_FUNCTIONS)+++def _handle_concat(args: list[str]) -> str:+ # Redshift's CONCAT is strictly two-argument and NULL-propagating; HogQL's concat is+ # variadic and treats NULL as ''. A coalesced `||` chain preserves both properties.+ if not args:+ return "''"+ coalesced = [f"COALESCE(CAST({arg} AS VARCHAR), '')" for arg in args]+ if len(coalesced) == 1:+ return coalesced[0]+ return f"({' || '.join(coalesced)})"+++def _handle_position(args: list[str]) -> str:+ # Redshift only parses POSITION(needle IN haystack); the two-argument call form must be+ # STRPOS, which shares HogQL's (haystack, needle) argument order and 1-based result.+ if len(args) != 2:+ raise QueryError("position with a start offset is not supported in the Redshift dialect")+ return f"STRPOS({args[0]}, {args[1]})"+++def _handle_avg(args: list[str]) -> str:+ # Redshift's avg over integer inputs returns a truncated integer; HogQL's avg is a float.+ return f"avg(CAST({args[0]} AS DOUBLE PRECISION))"+++# 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]] = {+ "concat": _handle_concat,+ "position": _handle_position,+ "avg": _handle_avg,+}++REDSHIFT_FUNCTION_RENAMES_LOWER: dict[str, str] = {+ name: target+ for name, target in POSTGRES_FUNCTION_RENAMES_LOWER.items()+ if name not in REDSHIFT_UNSUPPORTED_FUNCTIONS+}++# visit_call dispatches handlers before renames and passthrough, so the Redshift-only handlers+# shadow any inherited Postgres mapping for the same name.+REDSHIFT_FUNCTION_HANDLERS_LOWER: dict[str, Callable[[list[str]], str]] = {+ **{+ name: handler+ for name, handler in POSTGRES_FUNCTION_HANDLERS_LOWER.items()+ if name not in REDSHIFT_UNSUPPORTED_FUNCTIONS+ },+ **_REDSHIFT_ONLY_HANDLERS,+}++REDSHIFT_PASSTHROUGH_FUNCTIONS: frozenset[str] = _without_unsupported(POSTGRES_PASSTHROUGH_FUNCTIONS)diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 28f33ed20a7f..ce27d7218836 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -5814,7 +5814,7 @@ class TestPostgresPrinter(BaseTest):),("SELECT count() FROM events GROUP BY event",- "SELECT count() FROM events GROUP BY events.event LIMIT 50000",+ "SELECT count(*) FROM events GROUP BY events.event LIMIT 50000",),])@@ -5944,17 +5944,17 @@ class TestPostgresPrinter(BaseTest):("basic","SELECT 1 FROM events PIVOT (count() FOR event IN ('a', 'b'))",- "SELECT 1 FROM events PIVOT (count() FOR events.event IN (%(hogql_val_0)s, %(hogql_val_1)s)) LIMIT 50000",+ "SELECT 1 FROM events PIVOT (count(*) FOR events.event IN (%(hogql_val_0)s, %(hogql_val_1)s)) LIMIT 50000",),("multiple_columns","SELECT 1 FROM events PIVOT (count() FOR event IN ('a') distinct_id IN (1, 2) GROUP BY timestamp)",- "SELECT 1 FROM events PIVOT (count() FOR events.event IN (%(hogql_val_0)s) events.distinct_id IN (1, 2) GROUP BY events.timestamp) LIMIT 50000",+ "SELECT 1 FROM events PIVOT (count(*) FOR events.event IN (%(hogql_val_0)s) events.distinct_id IN (1, 2) GROUP BY events.timestamp) LIMIT 50000",),("join","SELECT 1 FROM events JOIN events AS e2 ON 1 PIVOT (count() FOR events.event IN ('a'))",- "SELECT 1 FROM events JOIN events AS e2 ON 1 PIVOT (count() FOR events.event IN (%(hogql_val_0)s)) LIMIT 50000",+ "SELECT 1 FROM events JOIN events AS e2 ON 1 PIVOT (count(*) FOR events.event IN (%(hogql_val_0)s)) LIMIT 50000",),])@@ -6452,7 +6452,7 @@ class TestPostgresPrinter(BaseTest):query = "WITH RECURSIVE nums AS (SELECT 1 AS n UNION ALL SELECT n + 1 FROM nums WHERE n < 5) SELECT n FROM nums"self.assertEqual(self._select(query),- "WITH RECURSIVE nums AS (SELECT 1 AS n UNION ALL SELECT (nums.n + 1) FROM nums WHERE (nums.n < 5)) "+ "WITH RECURSIVE nums AS ((SELECT 1 AS n) UNION ALL (SELECT (nums.n + 1) FROM nums WHERE (nums.n < 5))) ""SELECT nums.n FROM nums LIMIT 50000",)diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex 27c1158ac978..7e429c20ef72 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -24,6 +24,7 @@ from posthog.hogql.printer.duckdb import DuckDBPrinterfrom posthog.hogql.printer.hogql import HogQLPrinterfrom posthog.hogql.printer.mysql import MySQLPrinterfrom posthog.hogql.printer.postgres import PostgresPrinter+from posthog.hogql.printer.redshift import RedshiftPrinterfrom posthog.hogql.printer.snowflake import SnowflakePrinterfrom posthog.hogql.resolver import ResolverFactory, resolve_typesfrom posthog.hogql.transforms.clickhouse_property_resolution import clickhouse_property_resolution@@ -56,6 +57,7 @@ PRINTER_CLASSES: dict[HogQLDialect, type[BasePrinter]] = {"duckdb": DuckDBPrinter,"mysql": MySQLPrinter,"snowflake": SnowflakePrinter,+ "redshift": RedshiftPrinter,"hogql": HogQLPrinter,}diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex 66bca16336cb..121721d2ed88 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -148,6 +148,78 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertNotIn(".team_id", sql)self.assertEqual(executor.direct_source_id, str(source.id))+ def _create_simple_direct_source_and_table(self) -> ExternalDataSource:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status=ExternalDataSource.Status.COMPLETED,+ source_type="Postgres",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ prefix="shop",+ job_inputs={+ "host": "localhost",+ "port": 5432,+ "database": "postgres",+ "user": "postgres",+ "password": "postgres",+ "schema": "public",+ },+ )+ DataWarehouseTable.objects.create(+ name="orders",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ url_pattern="",+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True}},+ )+ return source++ @parameterized.expand(+ [+ # Postgres has no zero-arg count(); it must print as count(*).+ ("count_star", "SELECT count() FROM orders", "count(*)"),+ # DISTINCT used to be silently dropped from function calls, returning plain counts.+ ("count_distinct", "SELECT count(DISTINCT id) FROM orders", "count(DISTINCT "),+ ]+ )+ def test_count_rendering(self, _name: str, query: str, expected_fragment: str):+ source = self._create_simple_direct_source_and_table()++ executor = HogQLQueryExecutor(query=query, team=self.team, connection_id=str(source.id))+ sql, _context = executor.generate_clickhouse_sql()++ self.assertIn(expected_fragment, sql)++ def test_set_query_operands_are_parenthesized(self):+ # The default LIMIT is injected into every branch of a set query; Postgres only+ # accepts a per-branch LIMIT on a parenthesized operand.+ source = self._create_simple_direct_source_and_table()++ executor = HogQLQueryExecutor(+ query="SELECT id FROM orders UNION ALL SELECT id FROM orders",+ team=self.team,+ connection_id=str(source.id),+ )+ sql, _context = executor.generate_clickhouse_sql()++ self.assertRegex(sql, r"\)\s*UNION ALL\s*\(")++ def test_handler_rendered_functions_reject_distinct(self):+ # Handlers compose custom SQL from pre-rendered args; DISTINCT must error rather than+ # be silently dropped from the aggregate.+ source = self._create_simple_direct_source_and_table()++ executor = HogQLQueryExecutor(+ query="SELECT uniq(DISTINCT id) FROM orders",+ team=self.team,+ connection_id=str(source.id),+ )+ with self.assertRaises(QueryError) as ctx:+ executor.generate_clickhouse_sql()+ self.assertIn("DISTINCT", str(ctx.exception))+def test_generate_sql_for_aliased_direct_postgres_table(self):source = ExternalDataSource.objects.create(team=self.team,diff --git a/posthog/hogql/test/test_direct_redshift_query.py b/posthog/hogql/test/test_direct_redshift_query.pynew file mode 100644index 000000000000..1d14062923cb--- /dev/null+++ b/posthog/hogql/test/test_direct_redshift_query.py@@ -0,0 +1,207 @@+from typing import Any+from uuid import uuid4++import unittest+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.hogql.direct_sql.redshift_adapter import ensure_read_only_raw_redshift_statement+from posthog.hogql.errors import ExposedHogQLError, QueryError+from posthog.hogql.query import HogQLQueryExecutor++from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+++class TestDirectRedshiftQuery(APIBaseTest):+ def _create_source(self, prefix: str = "shop", schema: str = "public") -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status=ExternalDataSource.Status.COMPLETED,+ source_type="Redshift",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ prefix=prefix,+ connection_metadata={"engine": "redshift", "database": "dev"},+ job_inputs={+ "host": "localhost",+ "port": 5439,+ "database": "dev",+ "user": "awsuser",+ "password": "redshift",+ "schema": schema,+ },+ )++ def _create_table(self, source: ExternalDataSource, name: str, columns: dict[str, Any] | None = None):+ return DataWarehouseTable.objects.create(+ name=name,+ format="Parquet",+ team=self.team,+ external_data_source=source,+ url_pattern="direct://redshift",+ columns=columns+ or {+ "id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True},+ "email": {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True},+ "created_at": {"hogql": "DateTimeDatabaseField", "clickhouse": "DateTime", "valid": True},+ },+ )++ def test_generate_sql_uses_redshift_dialect_and_schema_qualified_table(self):+ source = self._create_source()+ self._create_table(source, "orders")++ executor = HogQLQueryExecutor(+ query="SELECT * FROM orders",+ team=self.team,+ connection_id=str(source.id),+ )+ sql, _context = executor.generate_clickhouse_sql()++ self.assertEqual(executor.direct_dialect, "redshift")+ self.assertIn("public", sql)+ self.assertIn("orders", sql)+ self.assertNotIn(".team_id", sql)++ def test_shared_postgres_surface_compiles(self):+ # Redshift shares Postgres's date_trunc / ILIKE surface; this guards against the+ # subtractive printer over-blocking the core surface it should keep.+ source = self._create_source()+ self._create_table(source, "orders")++ executor = HogQLQueryExecutor(+ query="SELECT toStartOfDay(created_at) FROM orders WHERE email ILIKE '%test%'",+ team=self.team,+ connection_id=str(source.id),+ )+ sql, context = executor.generate_clickhouse_sql()++ self.assertIn("date_trunc('day'", sql)+ self.assertIn("ILIKE", sql)+ # String constants bind as parameters rather than inlining into the SQL.+ self.assertNotIn("%test%", sql)+ self.assertIn("%test%", context.values.values())++ @parameterized.expand(+ [+ ("array_literal", "SELECT [1, 2, 3] FROM orders"),+ ("lambda", "SELECT arrayMap(x -> x + 1, [1, 2]) FROM orders"),+ ("group_array", "SELECT groupArray(id) FROM orders"),+ ("to_start_of_isoyear", "SELECT toStartOfISOYear(created_at) FROM orders"),+ ("uuid_cast", "SELECT toUUID(id) FROM orders"),+ ("count_if_filter", "SELECT countIf(id > 0) FROM orders"),+ ]+ )+ def test_incompatible_constructs_raise(self, _name: str, query: str):+ source = self._create_source()+ self._create_table(source, "orders")++ executor = HogQLQueryExecutor(query=query, team=self.team, connection_id=str(source.id))+ with self.assertRaises(QueryError) as ctx:+ executor.generate_clickhouse_sql()+ self.assertIn("Redshift dialect", str(ctx.exception))++ @parameterized.expand(+ [+ # Redshift has no zero-arg count().+ ("count_star", "SELECT count() FROM orders", "count(*)"),+ # DISTINCT used to be silently dropped, returning plain counts.+ ("count_distinct", "SELECT count(DISTINCT id) FROM orders", "count(DISTINCT "),+ # Redshift CONCAT is two-arg and NULL-propagating; HogQL concat is variadic, NULL→''.+ ("concat_null_safe_chain", "SELECT concat(email, ' ', email) FROM orders", " || COALESCE(CAST("),+ # Redshift rejects the two-arg position() call form.+ ("position_as_strpos", "SELECT position(email, '@') FROM orders", "STRPOS("),+ # Redshift avg(int) truncates to an integer; HogQL avg is float.+ ("avg_cast_to_float", "SELECT avg(id) FROM orders", "avg(CAST("),+ # Redshift `/` on integers truncates; HogQL division is float.+ ("division_cast_to_float", "SELECT id / 2 FROM orders", "AS DOUBLE PRECISION) / "),+ ]+ )+ def test_semantic_rewrites_print_redshift_equivalents(self, _name: str, query: str, expected_fragment: str):+ source = self._create_source()+ self._create_table(source, "orders")++ executor = HogQLQueryExecutor(query=query, team=self.team, connection_id=str(source.id))+ sql, _context = executor.generate_clickhouse_sql()++ self.assertIn(expected_fragment, sql)++ def test_set_query_operands_are_parenthesized(self):+ # The default LIMIT is injected into every branch of a set query; Redshift only+ # accepts a per-branch LIMIT on a parenthesized operand.+ source = self._create_source()+ self._create_table(source, "orders")++ executor = HogQLQueryExecutor(+ query="SELECT id FROM orders UNION ALL SELECT id FROM orders",+ team=self.team,+ connection_id=str(source.id),+ )+ sql, _context = executor.generate_clickhouse_sql()++ self.assertRegex(sql, r"\)\s*UNION ALL\s*\(")++ def test_raw_query_result_row_cap(self):+ # A raw passthrough SELECT with no LIMIT must not load an unbounded result set into+ # memory; the adapter reads cap+1 rows and errors when the cap is exceeded.+ source = self._create_source()++ executor = HogQLQueryExecutor(+ query="SELECT id FROM orders",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ )++ cursor = MagicMock()+ cursor.description = [MagicMock(name="id")]+ cursor.fetchmany.return_value = [(i,) for i in range(4)]+ connection = MagicMock()+ connection.cursor.return_value.__enter__.return_value = cursor+ implementation = MagicMock()+ implementation.connect.return_value.__enter__.return_value = connection++ with patch("posthog.hogql.direct_sql.redshift_adapter.DIRECT_REDSHIFT_MAX_ROWS", 3):+ with patch(+ "posthog.hogql.direct_sql.redshift_adapter.RedshiftAdapter.validate_source_config",+ return_value=(implementation, MagicMock()),+ ):+ with patch.object(HogQLQueryExecutor, "_capture_send_raw_query_translation_error"):+ with self.assertRaisesRegex(ExposedHogQLError, "Add a LIMIT clause"):+ executor.execute()+++class TestEnsureReadOnlyRawRedshiftStatement(unittest.TestCase):+ @parameterized.expand(+ [+ ("plain_select", "SELECT salesid FROM public.sales"),+ # sqlparse must type a CTE statement as SELECT, not over-block it.+ ("cte_select", "WITH t AS (SELECT 1 AS v) SELECT v FROM t"),+ # A write keyword inside a string literal must not trip the token scan.+ ("write_word_in_string", "SELECT 'DELETE' FROM public.sales"),+ # A quoted identifier matching a blocked function name is a column, not a call.+ ("quoted_blocked_name_column", 'SELECT "pg_cancel_backend" FROM public.sales'),+ ]+ )+ def test_accepts_read_only_selects(self, _name: str, sql: str):+ self.assertEqual(ensure_read_only_raw_redshift_statement(sql), sql)++ @parameterized.expand(+ [+ # Redshift's SELECT ... INTO creates and populates a table while still+ # tokenizing as a SELECT statement — the one write shape with no DML/DDL token.+ ("select_into", "SELECT * INTO backup_sales FROM public.sales"),+ ("dml_in_cte", "WITH d AS (DELETE FROM public.sales RETURNING *) SELECT * FROM d"),+ ("update", "UPDATE public.sales SET qtysold = 0"),+ # Redshift admin functions run from a plain SELECT and must be rejected by name.+ ("cancel_backend", "SELECT PG_CANCEL_BACKEND(1234)"),+ ("reboot_cluster_lowercase", "select reboot_cluster()"),+ ("admin_fn_in_subquery", "SELECT * FROM public.sales WHERE 1 = (SELECT change_user_priority('u', 'low'))"),+ ]+ )+ def test_rejects_writes(self, _name: str, sql: str):+ with self.assertRaises(ExposedHogQLError):+ ensure_read_only_raw_redshift_statement(sql)diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex cba0bb649054..62125ad1b15f 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -17,6 +17,7 @@ from posthog.hogql import astfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.direct_mysql_table import DirectMySQLTablefrom posthog.hogql.database.direct_postgres_table import DirectPostgresTable+from posthog.hogql.database.direct_redshift_table import DirectRedshiftTablefrom posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTablefrom posthog.hogql.database.models import FieldOrTable, SavedQueryfrom posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTable@@ -345,7 +346,14 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,def hogql_definition(self, modifiers: Optional["HogQLQueryModifiers"] = None- ) -> Union[SavedQuery, HogQLDataWarehouseTable, DirectPostgresTable, DirectMySQLTable, DirectSnowflakeTable]:+ ) -> Union[+ SavedQuery,+ HogQLDataWarehouseTable,+ DirectPostgresTable,+ DirectMySQLTable,+ DirectSnowflakeTable,+ DirectRedshiftTable,+ ]:if self.table is not None and self.is_materialized and modifiers is not None and modifiers.useMaterializedViews:return self.table.hogql_definition(modifiers)diff --git a/products/data_warehouse/backend/direct_redshift.py b/products/data_warehouse/backend/direct_redshift.pynew file mode 100644index 000000000000..0e6035f6898c--- /dev/null+++ b/products/data_warehouse/backend/direct_redshift.py@@ -0,0 +1,91 @@+"""Direct-query Redshift helpers — manages the live-query `DataWarehouseTable` that lets HogQL hit+Redshift without going through Delta. Mirrors `direct_postgres.py` (Redshift is a Postgres fork);+code shared with warehouse mode lives in `redshift_helpers.py`.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++from products.warehouse_sources.backend.facade.models import ExternalDataSource++if TYPE_CHECKING:+ from products.warehouse_sources.backend.models.table import DataWarehouseTable++type DirectRedshiftColumns = dict[str, dict[str, Any]]++DIRECT_REDSHIFT_URL_PATTERN = "direct://redshift"+DIRECT_REDSHIFT_CATALOG_OPTION = "direct_redshift_catalog"+DIRECT_REDSHIFT_SCHEMA_OPTION = "direct_redshift_schema"+DIRECT_REDSHIFT_TABLE_OPTION = "direct_redshift_table"+++def get_direct_redshift_table_options(+ *, source_catalog: str | None = None, source_schema: str, source_table_name: str+) -> dict[str, str]:+ options = {+ DIRECT_REDSHIFT_SCHEMA_OPTION: source_schema,+ DIRECT_REDSHIFT_TABLE_OPTION: source_table_name,+ }+ if source_catalog:+ options[DIRECT_REDSHIFT_CATALOG_OPTION] = source_catalog+ return options+++def upsert_direct_redshift_table(+ existing_table: DataWarehouseTable | None,+ *,+ schema_name: str,+ source: ExternalDataSource,+ columns: DirectRedshiftColumns,+ source_catalog: str | None = None,+ source_schema: str,+ source_table_name: str,+) -> DataWarehouseTable:+ from products.warehouse_sources.backend.facade.models import DataWarehouseTable++ options = {+ **(existing_table.options if existing_table is not None and isinstance(existing_table.options, dict) else {}),+ **get_direct_redshift_table_options(+ source_catalog=source_catalog,+ source_schema=source_schema,+ source_table_name=source_table_name,+ ),+ }++ if existing_table is None:+ return DataWarehouseTable.objects.create(+ name=schema_name,+ format=DataWarehouseTable.TableFormat.Parquet,+ team_id=source.team_id,+ url_pattern=DIRECT_REDSHIFT_URL_PATTERN,+ external_data_source=source,+ columns=columns,+ options=options,+ )++ existing_table.name = schema_name+ existing_table.url_pattern = DIRECT_REDSHIFT_URL_PATTERN+ existing_table.external_data_source = source+ existing_table.columns = columns+ existing_table.options = options+ existing_table.deleted = False+ existing_table.deleted_at = None+ existing_table.save(+ update_fields=[+ "name",+ "url_pattern",+ "external_data_source",+ "columns",+ "options",+ "deleted",+ "deleted_at",+ "updated_at",+ ]+ )+ return existing_table+++def hide_direct_redshift_table(table: DataWarehouseTable | None) -> None:+ if table is not None and not table.deleted:+ table.soft_delete()diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex ae568086bf3d..87db67cdead4 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -66,6 +66,9 @@ _LAZY = {"reproject_direct_postgres_table": "postgres_helpers","reconcile_snowflake_schemas": "snowflake_helpers","reproject_direct_snowflake_table": "snowflake_helpers",+ "get_redshift_source_location": "redshift_helpers",+ "reconcile_redshift_schemas": "redshift_helpers",+ "reproject_direct_redshift_table": "redshift_helpers","HogQLQueryFixerTool": "hogql_fixer_ai","hide_direct_mysql_table": "direct_mysql","upsert_direct_mysql_table": "direct_mysql",@@ -73,6 +76,8 @@ _LAZY = {"upsert_direct_postgres_table": "direct_postgres","hide_direct_snowflake_table": "direct_snowflake","upsert_direct_snowflake_table": "direct_snowflake",+ "hide_direct_redshift_table": "direct_redshift",+ "upsert_direct_redshift_table": "direct_redshift","reconcile_refresh_name_substitutions": "postgres_warehouse_migration","apply_on_refresh": "sql_warehouse_migration","apply_on_schema_clear": "sql_warehouse_migration",diff --git a/products/data_warehouse/backend/facade/sources.py b/products/data_warehouse/backend/facade/sources.pyindex 580004556cf2..49e34fcb8e48 100644--- a/products/data_warehouse/backend/facade/sources.py+++ b/products/data_warehouse/backend/facade/sources.py@@ -12,6 +12,11 @@ from products.data_warehouse.backend.direct_postgres import (DIRECT_POSTGRES_SCHEMA_OPTION,DIRECT_POSTGRES_TABLE_OPTION,)+from products.data_warehouse.backend.direct_redshift import (+ DIRECT_REDSHIFT_CATALOG_OPTION,+ DIRECT_REDSHIFT_SCHEMA_OPTION,+ DIRECT_REDSHIFT_TABLE_OPTION,+)from products.data_warehouse.backend.direct_snowflake import (DIRECT_SNOWFLAKE_CATALOG_OPTION,DIRECT_SNOWFLAKE_SCHEMA_OPTION,@@ -24,6 +29,9 @@ __all__ = ["DIRECT_POSTGRES_CATALOG_OPTION","DIRECT_POSTGRES_SCHEMA_OPTION","DIRECT_POSTGRES_TABLE_OPTION",+ "DIRECT_REDSHIFT_CATALOG_OPTION",+ "DIRECT_REDSHIFT_SCHEMA_OPTION",+ "DIRECT_REDSHIFT_TABLE_OPTION","DIRECT_SNOWFLAKE_CATALOG_OPTION","DIRECT_SNOWFLAKE_SCHEMA_OPTION","DIRECT_SNOWFLAKE_TABLE_OPTION",diff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.pyindex 01e10002bd0d..49456ecc3188 100644--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py@@ -29,6 +29,7 @@ from products.data_warehouse.backend.facade.api import (get_postgres_source_location,hide_direct_mysql_table,hide_direct_postgres_table,+ hide_direct_redshift_table,hide_direct_snowflake_table,is_any_external_data_schema_paused,is_cdc_enabled_for_team,@@ -37,6 +38,7 @@ from products.data_warehouse.backend.facade.api import (reconcile_webhook_events,reproject_direct_mysql_table,reproject_direct_postgres_table,+ reproject_direct_redshift_table,reproject_direct_snowflake_table,sync_cdc_extraction_schedule,sync_external_data_job_workflow,@@ -900,6 +902,8 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):reproject = reproject_direct_postgres_tableelif source.is_direct_snowflake:reproject = reproject_direct_snowflake_table+ elif source.is_direct_redshift:+ reproject = reproject_direct_redshift_tableelse:reproject = reproject_direct_mysql_tablevalidated_data["table"] = reproject(@@ -913,6 +917,8 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):hide_direct_postgres_table(instance.table)elif source.is_direct_snowflake:hide_direct_snowflake_table(instance.table)+ elif source.is_direct_redshift:+ hide_direct_redshift_table(instance.table)else:hide_direct_mysql_table(instance.table)elif enabled_columns_changed and instance.table is not None and instance.should_sync:@@ -1372,6 +1378,8 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):hide_direct_postgres_table(instance.table)elif instance.source.is_direct_snowflake:hide_direct_snowflake_table(instance.table)+ elif instance.source.is_direct_redshift:+ hide_direct_redshift_table(instance.table)else:hide_direct_mysql_table(instance.table)instance.should_sync = Falsediff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 61d05928cc7d..df23925f27f7 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -79,6 +79,7 @@ from products.data_warehouse.backend.facade.api import (get_mysql_source_location,get_or_create_webhook_hog_function,get_postgres_source_location,+ get_redshift_source_location,get_webhook_url,is_any_external_data_schema_paused,is_cdc_enabled_for_team,@@ -87,6 +88,7 @@ from products.data_warehouse.backend.facade.api import (is_xmin_enabled_for_team,reconcile_mysql_schemas,reconcile_postgres_schemas,+ reconcile_redshift_schemas,reconcile_refresh_name_substitutions as reconcile_postgres_refresh_name_substitutions,reconcile_snowflake_schemas,source_namespace_is_blank,@@ -96,6 +98,7 @@ from products.data_warehouse.backend.facade.api import (trigger_external_data_source_workflow,upsert_direct_mysql_table,upsert_direct_postgres_table,+ upsert_direct_redshift_table,upsert_direct_snowflake_table,)from products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfig@@ -482,12 +485,31 @@ def get_snowflake_source_table_location(return catalog, normalized_default_schema or "", schema_name+def get_redshift_source_table_location(+ *,+ schema_name: str,+ source_schema: SourceSchema | None,+ default_schema: str | None,+ default_catalog: str | None = None,+) -> tuple[str | None, str, str]:+ return get_redshift_source_location(+ schema_name=schema_name,+ schema_metadata={+ "source_catalog": source_schema.source_catalog if source_schema else None,+ "source_schema": source_schema.source_schema if source_schema else None,+ "source_table_name": source_schema.source_table_name if source_schema else None,+ },+ default_catalog=default_catalog,+ default_schema=default_schema,+ )++CUSTOM_SOURCE_LIMIT_MESSAGE = f"You can create at most {MAX_CUSTOM_SOURCES_PER_TEAM} custom sources per project."DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = (- "Direct query mode is currently supported only for Postgres, MySQL, and Snowflake sources."+ "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, and Redshift sources.")# Engines surfaced on a direct connection's `connection_metadata.engine` (duckdb backs direct Postgres).-DIRECT_CONNECTION_ENGINE_CHOICES = ["duckdb", "postgres", "mysql", "snowflake"]+DIRECT_CONNECTION_ENGINE_CHOICES = ["duckdb", "postgres", "mysql", "snowflake", "redshift"]def count_active_custom_sources(team_id: int) -> int:@@ -1183,6 +1205,12 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializersource_schemas=discovered_schemas,team_id=instance.team_id,)+ elif updated_source.source_type == ExternalDataSourceType.REDSHIFT:+ reconcile_redshift_schemas(+ source=updated_source,+ source_schemas=discovered_schemas,+ team_id=instance.team_id,+ )else:reconcile_mysql_schemas(source=updated_source,@@ -1834,6 +1862,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiis_direct_query = access_method == ExternalDataSource.AccessMethod.DIRECTis_direct_mysql = is_direct_query and source_type == ExternalDataSourceType.MYSQLis_direct_snowflake = is_direct_query and source_type == ExternalDataSourceType.SNOWFLAKE+ is_direct_redshift = is_direct_query and source_type == ExternalDataSourceType.REDSHIFTif is_direct_query and source_type not in direct_capable_source_types():return Response(@@ -1945,7 +1974,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixinew_source_model.save(update_fields=["connection_metadata", "updated_at"])source_schemas_by_name = {schema.name: schema for schema in source_schemas}schema_names = [schema.name for schema in source_schemas]- default_source_schema = source_config.to_dict().get("schema")+ source_config_dict = source_config.to_dict()+ default_source_schema = source_config_dict.get("schema")+ default_source_catalog = source_config_dict.get("database")schema_label_by_name = {s.name: s.label for s in source_schemas}payload_schemas = payload.get("schemas", None)@@ -2135,7 +2166,16 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixischema_name=schema_name,source_schema=source_schema,default_schema=default_source_schema,- default_catalog=source_config.to_dict().get("database"),+ default_catalog=default_source_catalog,+ )+ )+ elif is_direct_redshift:+ metadata_source_catalog, metadata_source_schema, metadata_source_table_name = (+ get_redshift_source_table_location(+ schema_name=schema_name,+ source_schema=source_schema,+ default_schema=default_source_schema,+ default_catalog=default_source_catalog,))else:@@ -2333,6 +2373,25 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisource_table_name=cast(str, metadata_source_table_name),)schema_model.save(update_fields=["table"])+ elif new_source_model.is_direct_redshift and should_sync:+ schema_model.table = upsert_direct_redshift_table(+ None,+ schema_name=schema_name,+ source=new_source_model,+ columns=filter_dwh_columns_by_enabled_columns(+ # Redshift information_schema types are Postgres-style, so reuse the Postgres mapper.+ postgres_columns_to_dwh_columns(source_schema.columns if source_schema else []),+ enabled_columns,+ source_schema.detected_primary_keys if source_schema else None,+ incremental_field,+ # Direct-redshift columns are keyed by raw source names.+ normalize=False,+ ),+ source_catalog=metadata_source_catalog,+ source_schema=cast(str, metadata_source_schema),+ source_table_name=cast(str, metadata_source_table_name),+ )+ schema_model.save(update_fields=["table"])if should_sync and new_source_model.supports_scheduled_sync:active_schemas.append(schema_model)@@ -2735,6 +2794,14 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi)if reconciled_deleted_schemas:schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})+ elif instance.source_type == ExternalDataSourceType.REDSHIFT:+ reconciled_deleted_schemas = reconcile_redshift_schemas(+ source=instance,+ source_schemas=schemas,+ team_id=self.team_id,+ )+ if reconciled_deleted_schemas:+ schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})elif isinstance(source, (SQLSource, ClickHouseSource)) and source.supports_column_selection:# ClickHouse isn't a SQLSource but exposes the same column-selection# capability and reconcile hook, so it reuses this path.diff --git a/products/data_warehouse/backend/redshift_helpers.py b/products/data_warehouse/backend/redshift_helpers.pynew file mode 100644index 000000000000..9c62afe61506--- /dev/null+++ b/products/data_warehouse/backend/redshift_helpers.py@@ -0,0 +1,303 @@+"""Redshift source helpers shared between warehouse and direct-query modes.++Direct-query-only utilities (DataWarehouseTable upserts, the `direct://redshift`+url_pattern, the option keys that encode source location on a direct table) live+in `direct_redshift.py`. Redshift is a Postgres fork whose `information_schema.columns`+returns Postgres-style type names, so it reuses the Postgres column → DWH mappers.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++from django.db.models import Q++import structlog++from products.data_warehouse.backend.direct_redshift import (+ DIRECT_REDSHIFT_CATALOG_OPTION,+ DIRECT_REDSHIFT_SCHEMA_OPTION,+ DIRECT_REDSHIFT_TABLE_OPTION,+ hide_direct_redshift_table,+ upsert_direct_redshift_table,+)+from products.warehouse_sources.backend.facade.models import (+ ExternalDataSource,+ postgres_column_to_dwh_column,+ postgres_columns_to_dwh_columns,+)+from products.warehouse_sources.backend.facade.source_management import (+ SourceSchema,+ extract_available_column_names,+ filter_columns_by_enabled_columns,+ filter_dwh_columns_by_enabled_columns,+ normalize_namespace,+ prune_enabled_columns,+ sql_schema_metadata,+)++if TYPE_CHECKING:+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema++log = structlog.get_logger(__name__)++type RedshiftSourceLocation = tuple[str | None, str, str] # (catalog, schema, table_name)+++def get_default_redshift_schema(source: ExternalDataSource) -> str | None:+ job_inputs = source.job_inputs or {}+ if "schema" in job_inputs:+ return normalize_namespace(job_inputs.get("schema"))+ return None+++def get_default_redshift_catalog(source: ExternalDataSource) -> str | None:+ database = (source.job_inputs or {}).get("database")+ return database if isinstance(database, str) and database.strip() else None+++def redshift_schema_metadata_to_dwh_columns(schema_metadata: dict[str, Any] | None) -> dict[str, dict[str, Any]]:+ resolved: dict[str, dict[str, Any]] = {}+ if not schema_metadata:+ return resolved+ columns = schema_metadata.get("columns")+ if not isinstance(columns, list):+ return resolved+ for column in columns:+ if not isinstance(column, dict):+ continue+ column_name = column.get("name")+ redshift_type = column.get("data_type")+ nullable = bool(column.get("is_nullable"))+ if not isinstance(column_name, str) or not isinstance(redshift_type, str):+ continue+ resolved[column_name] = postgres_column_to_dwh_column(column_name, redshift_type, nullable)+ return resolved+++def reproject_direct_redshift_table(+ schema_row: Any,+ *,+ source: ExternalDataSource,+ enabled_columns: list[str] | None,+) -> Any:+ """Rebuild the direct-query `DataWarehouseTable` with a fresh column projection — used on+ column-picker save and on `should_sync` False → True. No re-sync needed in direct mode.+ """+ source_catalog, source_schema, source_table_name = get_redshift_source_location(+ schema_name=schema_row.name,+ schema_metadata=schema_row.schema_metadata,+ default_catalog=get_default_redshift_catalog(source),+ default_schema=get_default_redshift_schema(source),+ )+ return upsert_direct_redshift_table(+ schema_row.table,+ schema_name=schema_row.name,+ source=source,+ columns=filter_dwh_columns_by_enabled_columns(+ redshift_schema_metadata_to_dwh_columns(schema_row.schema_metadata),+ enabled_columns,+ schema_row.primary_key_columns,+ schema_row.incremental_field,+ # Direct-redshift columns are keyed by raw source names.+ normalize=False,+ ),+ source_catalog=source_catalog,+ source_schema=source_schema,+ source_table_name=source_table_name,+ )+++def get_redshift_source_location(+ *,+ schema_name: str,+ schema_metadata: dict[str, Any] | None = None,+ default_catalog: str | None = None,+ default_schema: str | None = None,+) -> RedshiftSourceLocation:+ """Resolve (catalog, schema, table_name) for a Redshift source."""+ source_catalog = schema_metadata.get("source_catalog") if isinstance(schema_metadata, dict) else None+ source_schema = schema_metadata.get("source_schema") if isinstance(schema_metadata, dict) else None+ source_table_name = schema_metadata.get("source_table_name") if isinstance(schema_metadata, dict) else None+ normalized_default_schema = normalize_namespace(default_schema)++ catalog = source_catalog if isinstance(source_catalog, str) and source_catalog.strip() else default_catalog+ if isinstance(source_schema, str) and isinstance(source_table_name, str):+ return catalog, source_schema, source_table_name++ if normalized_default_schema is None and "." in schema_name:+ inferred_schema, inferred_table_name = schema_name.split(".", 1)+ return catalog, inferred_schema, inferred_table_name++ return catalog, normalized_default_schema or "public", schema_name+++def get_redshift_source_location_for_schema_model(+ *,+ schema_name: str,+ sync_type_config: dict[str, Any] | None = None,+ table_options: dict[str, Any] | None = None,+ default_catalog: str | None = None,+ default_schema: str | None = None,+) -> RedshiftSourceLocation:+ schema_metadata = (+ sync_type_config.get("schema_metadata")+ if isinstance(sync_type_config, dict) and isinstance(sync_type_config.get("schema_metadata"), dict)+ else None+ )+ if schema_metadata is not None:+ return get_redshift_source_location(+ schema_name=schema_name,+ schema_metadata=schema_metadata,+ default_catalog=default_catalog,+ default_schema=default_schema,+ )++ opts = table_options if isinstance(table_options, dict) else {}+ table_source_catalog = opts.get(DIRECT_REDSHIFT_CATALOG_OPTION)+ table_source_schema = opts.get(DIRECT_REDSHIFT_SCHEMA_OPTION)+ table_source_table_name = opts.get(DIRECT_REDSHIFT_TABLE_OPTION)++ if isinstance(table_source_schema, str) and isinstance(table_source_table_name, str):+ return (+ table_source_catalog if isinstance(table_source_catalog, str) else default_catalog,+ table_source_schema,+ table_source_table_name,+ )++ return get_redshift_source_location(+ schema_name=schema_name,+ schema_metadata=None,+ default_catalog=default_catalog,+ default_schema=default_schema,+ )+++def reconcile_redshift_schemas(+ *,+ source: ExternalDataSource,+ source_schemas: list[SourceSchema],+ team_id: int,+) -> list[str]:+ """Persist `schema_metadata` on every Redshift row + (direct mode only) upsert its live-query+ `DataWarehouseTable`. Returns stale schema names that got soft-deleted (direct only)."""+ from products.warehouse_sources.backend.facade.models import ExternalDataSchema++ is_direct = source.is_direct_query+ source_schema_names = [s.name for s in source_schemas]+ default_catalog = get_default_redshift_catalog(source)+ default_schema = get_default_redshift_schema(source)+ schema_models = {+ s.name: s+ for s in ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related(+ "table"+ )+ }++ schema_models_by_location: dict[RedshiftSourceLocation, ExternalDataSchema] = {}+ for schema_model in schema_models.values():+ location = get_redshift_source_location_for_schema_model(+ schema_name=schema_model.name,+ sync_type_config=schema_model.sync_type_config,+ table_options=schema_model.table.options if schema_model.table is not None else None,+ default_catalog=default_catalog,+ default_schema=default_schema,+ )+ schema_models_by_location.setdefault(location, schema_model)++ for source_schema in source_schemas:+ resolved = get_redshift_source_location(+ schema_name=source_schema.name,+ schema_metadata={+ "source_catalog": source_schema.source_catalog,+ "source_schema": source_schema.source_schema,+ "source_table_name": source_schema.source_table_name,+ },+ default_catalog=default_catalog,+ default_schema=default_schema,+ )+ matched: ExternalDataSchema | None = schema_models.get(source_schema.name)+ if matched is None:+ matched = schema_models_by_location.get(resolved)+ if matched is None:+ continue++ resolved_catalog, resolved_schema, resolved_table = resolved++ # Metadata holds the full column list (column-picker UI); projection lives on `enabled_columns`.+ schema_metadata = sql_schema_metadata(+ source_schema.columns,+ source_schema.foreign_keys,+ source_catalog=resolved_catalog,+ source_schema=resolved_schema,+ source_table_name=resolved_table,+ )+ new_sync_type_config = {**(matched.sync_type_config or {}), "schema_metadata": schema_metadata}+ # Persist the detected primary key without clobbering a value already stored — e.g. an+ # explicit override set during creation or a prior refresh.+ if source_schema.detected_primary_keys and not new_sync_type_config.get("primary_key_columns"):+ new_sync_type_config["primary_key_columns"] = source_schema.detected_primary_keys+ matched.sync_type_config = new_sync_type_config+ update_fields = ["sync_type_config", "updated_at"]++ # Drop dead columns so next sync doesn't emit `SELECT … missing_col`.+ available_names = extract_available_column_names(schema_metadata)+ pruned_enabled_columns, removed_columns = prune_enabled_columns(matched.enabled_columns, available_names)+ if removed_columns:+ log.info(+ "redshift.reconcile_schemas.pruned_enabled_columns",+ source_id=str(source.id),+ schema_id=str(matched.id),+ schema_name=matched.name,+ removed_columns=removed_columns,+ )+ matched.enabled_columns = pruned_enabled_columns+ update_fields.append("enabled_columns")+ matched.save(update_fields=update_fields)++ if not is_direct:+ # Warehouse mode: the ingestion workflow manages `DataWarehouseTable` itself.+ continue++ if not matched.should_sync:+ hide_direct_redshift_table(matched.table)+ continue++ projected_columns = filter_columns_by_enabled_columns(+ source_schema.columns,+ matched.enabled_columns,+ source_schema.detected_primary_keys,+ matched.incremental_field,+ )+ table_model = upsert_direct_redshift_table(+ matched.table,+ schema_name=source_schema.name,+ source=source,+ columns=postgres_columns_to_dwh_columns(projected_columns),+ source_catalog=resolved_catalog,+ source_schema=resolved_schema,+ source_table_name=resolved_table,+ )+ if matched.table_id != table_model.id:+ matched.table = table_model+ matched.save(update_fields=["table"])++ if not is_direct:+ # Warehouse mode delegates add/delete to `sync_old_schemas_with_new_schemas`.+ return []++ stale_names: list[str] = []+ stale = (+ ExternalDataSchema.objects.filter(+ Q(team_id=team_id, source_id=source.id),+ Q(deleted=False) | Q(table__deleted=False),+ )+ .exclude(name__in=source_schema_names)+ .select_related("table")+ )+ for s in stale:+ hide_direct_redshift_table(s.table)+ if not s.deleted:+ s.soft_delete()+ stale_names.append(s.name)+ return stale_namesdiff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.pyindex 57d00d6d6dab..6d21fcd68acd 100644--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py@@ -3815,7 +3815,9 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json(),- {"message": "Direct query mode is currently supported only for Postgres, MySQL, and Snowflake sources."},+ {+ "message": "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, and Redshift sources."+ },)def test_source_prefix_rejects_direct_unsupported_source_type(self):@@ -3831,7 +3833,9 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json(),- {"message": "Direct query mode is currently supported only for Postgres, MySQL, and Snowflake sources."},+ {+ "message": "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, and Redshift sources."+ },)def test_source_prefix_accepts_direct_mysql(self):diff --git a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.tsindex 5259125c0a9d..8f78c1e95aa6 100644--- a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts+++ b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts@@ -1,7 +1,7 @@import { groupBy } from 'lib/utils/arrays'/** Source types that support `access_method: 'direct'` (live querying without syncing to the warehouse). */-export const DIRECT_QUERY_SOURCE_TYPES = ['Postgres', 'MySQL', 'Snowflake'] as const+export const DIRECT_QUERY_SOURCE_TYPES = ['Postgres', 'MySQL', 'Snowflake', 'Redshift'] as constexport function supportsDirectQuery(sourceType: string | null | undefined): boolean {return !!sourceType && DIRECT_QUERY_SOURCE_TYPES.includes(sourceType as (typeof DIRECT_QUERY_SOURCE_TYPES)[number])diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex 2d52c497fae7..1ebc2ada84a6 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -67,6 +67,7 @@ _LAZY = {"get_primary_key_columns": "sources.postgres.postgres","source_requires_ssl": "sources.postgres.postgres","PostgresSource": "sources.postgres.source",+ "RedshiftSource": "sources.redshift.source","SnowflakeSource": "sources.snowflake.source",}diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.pyindex b4394cbb823c..218595c46b76 100644--- a/products/warehouse_sources/backend/models/external_data_source.py+++ b/products/warehouse_sources/backend/models/external_data_source.py@@ -93,6 +93,10 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFielddef is_direct_snowflake(self) -> bool:return self.is_direct_query and self.source_type == ExternalDataSourceType.SNOWFLAKE+ @property+ def is_direct_redshift(self) -> bool:+ return self.is_direct_query and self.source_type == ExternalDataSourceType.REDSHIFT+@propertydef direct_engine(self) -> str | None:"""The direct-SQL engine for this source's type, or None if no engine maps to it.diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex eafc73a89998..ad29932d0910 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -18,6 +18,7 @@ from posthog.hogql.constants import HogQLQuerySettingsfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.direct_mysql_table import DirectMySQLTablefrom posthog.hogql.database.direct_postgres_table import DirectPostgresTable+from posthog.hogql.database.direct_redshift_table import DirectRedshiftTablefrom posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTablefrom posthog.hogql.database.models import DatabaseField, FieldOrTable, StructDatabaseFieldfrom posthog.hogql.database.s3_table import (@@ -542,7 +543,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletdef hogql_definition(self, modifiers: Optional["HogQLQueryModifiers"] = None- ) -> HogQLDataWarehouseTable | DirectPostgresTable | DirectMySQLTable | DirectSnowflakeTable:+ ) -> HogQLDataWarehouseTable | DirectPostgresTable | DirectMySQLTable | DirectSnowflakeTable | DirectRedshiftTable:# Deferred: importing data_warehouse's facade at module scope creates an import cycle# (data_warehouse models -> this model package -> data_warehouse.facade.sources -> ...).# These direct-query option keys are only needed here, at query-build time.@@ -552,6 +553,9 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletDIRECT_POSTGRES_CATALOG_OPTION,DIRECT_POSTGRES_SCHEMA_OPTION,DIRECT_POSTGRES_TABLE_OPTION,+ DIRECT_REDSHIFT_CATALOG_OPTION,+ DIRECT_REDSHIFT_SCHEMA_OPTION,+ DIRECT_REDSHIFT_TABLE_OPTION,DIRECT_SNOWFLAKE_CATALOG_OPTION,DIRECT_SNOWFLAKE_SCHEMA_OPTION,DIRECT_SNOWFLAKE_TABLE_OPTION,@@ -665,6 +669,35 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletconnection_metadata=self.external_data_source.connection_metadata,)+ if self.external_data_source and self.external_data_source.is_direct_redshift:+ # Redshift is a Postgres fork and reuses DirectPostgresTable's schema-qualified,+ # double-quoted table-reference rendering (see DirectRedshiftTable).+ job_inputs = self.external_data_source.job_inputs or {}+ redshift_catalog = (+ self.options.get(DIRECT_REDSHIFT_CATALOG_OPTION)+ if isinstance(self.options.get(DIRECT_REDSHIFT_CATALOG_OPTION), str)+ else job_inputs.get("database")+ )+ redshift_schema = (+ self.options.get(DIRECT_REDSHIFT_SCHEMA_OPTION)+ if isinstance(self.options.get(DIRECT_REDSHIFT_SCHEMA_OPTION), str)+ else job_inputs.get("schema", "public")+ )+ redshift_table_name = (+ self.options.get(DIRECT_REDSHIFT_TABLE_OPTION)+ if isinstance(self.options.get(DIRECT_REDSHIFT_TABLE_OPTION), str)+ else self.name+ )+ return DirectRedshiftTable(+ name=self.name,+ fields=fields,+ postgres_catalog=redshift_catalog,+ postgres_schema=redshift_schema,+ postgres_table_name=redshift_table_name,+ external_data_source_id=str(self.external_data_source_id),+ connection_metadata=self.external_data_source.connection_metadata,+ )+# Replace fields with any redefined fields if they existexternal_table_fields = external_tables.get(self.table_name_without_prefix())default_fields = external_tables.get("*", {})diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.pyindex e2607f605336..f4810be96c4e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py@@ -167,6 +167,15 @@ def filter_redshift_incremental_fields(return results+def get_connection_metadata(config: RedshiftSourceConfig) -> dict[str, str | None]:+ """Connection metadata persisted on a direct-query source for the HogQL executor."""+ return {+ "engine": "redshift",+ "database": config.database,+ "schema": config.schema or None,+ }++class JsonAsStringLoader(Loader):def load(self, data):if data is None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.pyindex 9443b2e10339..09a86f6c9a7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py@@ -1,4 +1,4 @@-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, castfrom psycopg import OperationalErrorfrom sshtunnel import BaseSSHTunnelForwarderError@@ -15,6 +15,7 @@ from posthog.schema import (from posthog.exceptions_capture import capture_exception+from products.data_warehouse.backend.facade.api import reconcile_redshift_schemasfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (SourceInputs,@@ -26,11 +27,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixValidateDatabaseHostMixin,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RedshiftSourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift import RedshiftImplementation+from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift import (+ RedshiftImplementation,+ get_connection_metadata as get_connection_metadata_redshift,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+_REDSHIFT_IMPLEMENTATION = RedshiftImplementation()RedshiftErrors = {@@ -205,3 +213,19 @@ class RedshiftSource(SQLSource[RedshiftSourceConfig], SSHTunnelMixin, ValidateDareturn self.get_implementation.build_pipeline(config, inputs, chunk_size_override=schema_row.chunk_size_override)++ def reconcile_schema_metadata(+ self,+ source: "ExternalDataSource",+ source_schemas: list[SourceSchema],+ team_id: int,+ ) -> list[str]:+ """Delegates to `reconcile_redshift_schemas` so direct-query mode also rebuilds DWH tables."""+ return reconcile_redshift_schemas(source=source, source_schemas=source_schemas, team_id=team_id)++ def get_connection_metadata(+ self, config: RedshiftSourceConfig, team_id: int, require_ssl: bool = False+ ) -> dict[str, str | None]:+ # `require_ssl` keeps signature parity with Postgres/MySQL; the metadata is static+ # (the engine follows from the source type), so no live connection is needed.+ return get_connection_metadata_redshift(config)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.pyindex 0e34c36a1ea3..f2cddce746cf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py@@ -1074,3 +1074,16 @@ class TestConnect:assert kwargs["keepalives_interval"] == 10assert kwargs["keepalives_count"] == 3assert kwargs["tcp_user_timeout"] == 60000+++class TestGetConnectionMetadata:+ # Source creation looks this method up by name (duck-typed) and silently persists {} when+ # it's absent — which left direct Redshift connections labeled as Postgres in the SQL editor.+ @pytest.mark.parametrize(+ "schema,expected_schema",+ [("public", "public"), ("", None), (None, None)],+ )+ def test_reports_redshift_engine_without_connecting(self, schema, expected_schema):+ metadata = RedshiftSource().get_connection_metadata(_make_config(schema=schema), team_id=1)++ assert metadata == {"engine": "redshift", "database": "dev", "schema": expected_schema}diff --git a/products/warehouse_sources/backend/types.py b/products/warehouse_sources/backend/types.pyindex 93a6b21b1bf7..d32d8644a233 100644--- a/products/warehouse_sources/backend/types.py+++ b/products/warehouse_sources/backend/types.py@@ -807,6 +807,7 @@ DIRECT_ENGINE_BY_SOURCE_TYPE: dict[str, str] = {ExternalDataSourceType.POSTGRES: "postgres",ExternalDataSourceType.MYSQL: "mysql",ExternalDataSourceType.SNOWFLAKE: "snowflake",+ ExternalDataSourceType.REDSHIFT: "redshift",}diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex bacb74c19d13..b19ad6eb0c83 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -1911,6 +1911,7 @@ export const AccessMethodEnumApi = {* * `postgres` - postgres* * `mysql` - mysql* * `snowflake` - snowflake+ * * `redshift` - redshift*/export type EngineEnumApi = (typeof EngineEnumApi)[keyof typeof EngineEnumApi]@@ -1919,6 +1920,7 @@ export const EngineEnumApi = {Postgres: 'postgres',Mysql: 'mysql',Snowflake: 'snowflake',+ Redshift: 'redshift',} as constexport interface ExternalDataSourceRevenueAnalyticsConfigApi {@@ -1966,7 +1968,8 @@ export interface ExternalDataSourceSerializersApi {* * `duckdb` - duckdb* * `postgres` - postgres* * `mysql` - mysql- * * `snowflake` - snowflake */+ * * `snowflake` - snowflake+ * * `redshift` - redshift */readonly engine: EngineEnumApi | null/** @nullable */readonly last_run_at: string | null@@ -2826,7 +2829,8 @@ export interface PatchedExternalDataSourceSerializersApi {* * `duckdb` - duckdb* * `postgres` - postgres* * `mysql` - mysql- * * `snowflake` - snowflake */+ * * `snowflake` - snowflake+ * * `redshift` - redshift */readonly engine?: EngineEnumApi | null/** @nullable */readonly last_run_at?: string | null@@ -2942,7 +2946,8 @@ export interface ExternalDataSourceConnectionOptionApi {* * `duckdb` - duckdb* * `postgres` - postgres* * `mysql` - mysql- * * `snowflake` - snowflake */+ * * `snowflake` - snowflake+ * * `redshift` - redshift */readonly engine: EngineEnumApi | null}diff --git a/products/warehouse_sources/turbo.json b/products/warehouse_sources/turbo.jsonindex f129067957b2..8ec6b920bcdb 100644--- a/products/warehouse_sources/turbo.json+++ b/products/warehouse_sources/turbo.json@@ -10,6 +10,7 @@"backend/temporal/data_imports/sources/google_search_console/**","backend/temporal/data_imports/sources/mysql/**","backend/temporal/data_imports/sources/postgres/**",+ "backend/temporal/data_imports/sources/redshift/**","backend/temporal/data_imports/sources/salesforce/**","backend/temporal/data_imports/sources/snowflake/**","backend/temporal/data_imports/sources/stripe/**"diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cf979c963684..01d18ce1fbc9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20395,6 +20395,7 @@ export namespace Schemas {* * `postgres` - postgres* * `mysql` - mysql* * `snowflake` - snowflake+ * * `redshift` - redshift*/export type EngineEnum = typeof EngineEnum[keyof typeof EngineEnum];@@ -20404,6 +20405,7 @@ export namespace Schemas {Postgres: 'postgres',Mysql: 'mysql',Snowflake: 'snowflake',+ Redshift: 'redshift',} as const;/**@@ -24305,7 +24307,8 @@ export namespace Schemas {* * `duckdb` - duckdb* * `postgres` - postgres* * `mysql` - mysql- * * `snowflake` - snowflake */+ * * `snowflake` - snowflake+ * * `redshift` - redshift */readonly engine: EngineEnum | null;}@@ -25175,7 +25178,8 @@ export namespace Schemas {* * `duckdb` - duckdb* * `postgres` - postgres* * `mysql` - mysql- * * `snowflake` - snowflake */+ * * `snowflake` - snowflake+ * * `redshift` - redshift */readonly engine: EngineEnum | null;/** @nullable */readonly last_run_at: string | null;@@ -40748,7 +40752,8 @@ export namespace Schemas {* * `duckdb` - duckdb* * `postgres` - postgres* * `mysql` - mysql- * * `snowflake` - snowflake */+ * * `snowflake` - snowflake+ * * `redshift` - redshift */readonly engine?: EngineEnum | null;/** @nullable */readonly last_run_at?: string | null;diff --git a/tach.toml b/tach.tomlindex c96df45ba0b7..7590a35ba39b 100644--- a/tach.toml+++ b/tach.toml@@ -842,6 +842,7 @@ expose = ["backend\\.temporal\\.data_imports\\.sources\\.google_search_console.*","backend\\.temporal\\.data_imports\\.sources\\.mysql.*","backend\\.temporal\\.data_imports\\.sources\\.postgres.*",+ "backend\\.temporal\\.data_imports\\.sources\\.redshift.*","backend\\.temporal\\.data_imports\\.sources\\.salesforce.*","backend\\.temporal\\.data_imports\\.sources\\.snowflake.*","backend\\.temporal\\.data_imports\\.sources\\.stripe.*",