11import {
22 executeTSQL ,
3+ type ClickHouseSettings ,
34 type ExecuteTSQLOptions ,
45 type FieldMappings ,
56 type TSQLQueryResult ,
@@ -21,6 +22,33 @@ const scopeToEnum = {
2122 environment : "ENVIRONMENT" ,
2223} as const ;
2324
25+ /**
26+ * Default ClickHouse settings for query protection
27+ * Based on PostHog's HogQL settings to prevent expensive queries
28+ */
29+ function getDefaultClickhouseSettings ( ) : ClickHouseSettings {
30+ return {
31+ // Query execution limits
32+ max_execution_time : env . QUERY_CLICKHOUSE_MAX_EXECUTION_TIME ,
33+ timeout_overflow_mode : "throw" ,
34+ max_memory_usage : String ( env . QUERY_CLICKHOUSE_MAX_MEMORY_USAGE ) ,
35+
36+ // AST complexity limits to prevent extremely complex queries
37+ max_ast_elements : String ( env . QUERY_CLICKHOUSE_MAX_AST_ELEMENTS ) ,
38+ max_expanded_ast_elements : String ( env . QUERY_CLICKHOUSE_MAX_EXPANDED_AST_ELEMENTS ) ,
39+
40+ // Memory management for GROUP BY operations
41+ max_bytes_before_external_group_by : String (
42+ env . QUERY_CLICKHOUSE_MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY
43+ ) ,
44+
45+ // Safety settings
46+ allow_experimental_object_type : 1 ,
47+ format_csv_allow_double_quotes : 0 ,
48+ readonly : "1" , // Ensure queries are read-only
49+ } ;
50+ }
51+
2452export type ExecuteQueryOptions < TOut extends z . ZodSchema > = Omit <
2553 ExecuteTSQLOptions < TOut > ,
2654 "tableSchema" | "organizationId" | "projectId" | "environmentId" | "fieldMappings"
@@ -89,6 +117,10 @@ export async function executeQuery<TOut extends z.ZodSchema>(
89117 ...baseOptions ,
90118 ...tenantOptions ,
91119 fieldMappings,
120+ clickhouseSettings : {
121+ ...getDefaultClickhouseSettings ( ) ,
122+ ...baseOptions . clickhouseSettings , // Allow caller overrides if needed
123+ } ,
92124 } ) ;
93125
94126 // If query succeeded and history options provided, save to history
0 commit comments