SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
refactor(qb): quote field names with the ClickHouse quoting helpers (#12593)
Srikanth Chekuri8e00c0405697
diff --git a/.claude/rules/go-contrib.md b/.claude/rules/go-contrib.mdindex 1d67a81a0c..746c93d735 100644--- a/.claude/rules/go-contrib.md+++ b/.claude/rules/go-contrib.md@@ -7,6 +7,7 @@ paths:- When making Go changes, always ensure they follow the contributing guildelines in [`docs/contributing/go/`](../../docs/contributing/go/).- Look for existing patterns in the codebase for any change before implementing the changes.+- Any ClickHouse identifier or literal built from a name or a value goes through `pkg/clickhousesql`; compiled sqlbuilder text is wrapped with `sqlbuilder.Escape` once. See [`docs/contributing/go/clickhousesql.md`](../../docs/contributing/go/clickhousesql.md).- If any API contract is modified, generate the OpenAPI specs with `make gen-openapi-specs`.- Always keep the OpenAPI spec generated in a separate commit, so the whole commit can be dropped in case of conflicts during merge. Do not try to resolve conflict in generated files, instead just generate them again.- Avoid breaking function calls unncessarily into multilines for couple of arguments.diff --git a/docs/contributing/go/clickhousesql.md b/docs/contributing/go/clickhousesql.mdnew file mode 100644index 0000000000..1b50a1c74b--- /dev/null+++ b/docs/contributing/go/clickhousesql.md@@ -0,0 +1,48 @@+# ClickHouse SQL++Telemetry queries are generated as ClickHouse SQL text, most of it through [go-sqlbuilder](https://github.com/huandu/go-sqlbuilder) and executed with [clickhouse-go](https://github.com/ClickHouse/clickhouse-go). Attribute names, label names, body keys, aliases and dashboard variable values are user or telemetry input, so every one of them has to be quoted before it becomes part of the text.++## How do I quote a name or a value?++Use [pkg/clickhousesql](/pkg/clickhousesql/clickhousesql.go). Never build a quoted token with `fmt.Sprintf`, string concatenation or `strings.ReplaceAll`.++| You need | Use | Example |+| --- | --- | --- |+| a column, alias or JSON sub-column name | `clickhousesql.Identifier(name)` | `` body_v2.`user.name` `` |+| a string in a map read, a function argument, an `IN` list | `clickhousesql.StringLiteral(value)` | `attributes_string['http.method']` |+| a Go scalar or list rendered as a literal | `clickhousesql.Literal(value)` | `['a','b']` |+| a needle for `LIKE` | `clickhousesql.LikePattern(value)` | `"%" + clickhousesql.LikePattern(name) + "%"` |++```go+expr := fmt.Sprintf("multiIf(mapContains(%s, %s), %s[%s], NULL)", column, clickhousesql.StringLiteral(key.Name), column, clickhousesql.StringLiteral(key.Name))+alias := clickhousesql.Identifier(fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, key.Name))+```++Values compared against a column are bound as arguments (`sb.E(column, value)`), never rendered into the text.++Filter expressions are a different language. A value placed into a filter expression string goes through `querybuilder.FilterStringLiteral`, which quotes for that grammar.++## Where does `sqlbuilder.Escape` go?++go-sqlbuilder compiles the text it is given: `$0`, `$1`, `${name}` and `$?` are read as argument references and `$$` as a single `$`. The compiled text is everything passed to `Select`, `SelectMore`, `GroupBy`, `OrderBy`, `Having`, `From`, a raw string passed to `Where`, `And` or `Or`, and a compiled subquery joined or selected from another builder, which is compiled a second time. The `Cond` helpers (`sb.E`, `sb.Like`, `sb.In`, `sb.IsNotNull`, ...) write their field argument verbatim.++- A name or expression that ends up in compiled text is wrapped with `sqlbuilder.Escape` once, at the point where it enters that text. Materialized column names carry `$$`, so this is what keeps them intact.+- A field passed to a `Cond` helper is not escaped.+- Text that never passes through a builder is not escaped: CTE fragments joined with `querybuilder.CombineCTEs`, a `UNION` assembled with `fmt.Sprintf` from already compiled statements, raw queries sent straight to the store.+- Bind placeholders produced by `sb.Var` or the `Cond` helpers must not be escaped, so escape the identifier-bearing part before combining it with them: `fmt.Sprintf("match(%s, %s)", sqlbuilder.Escape(fieldExpr), sb.Var(value))`.++## How do I check SQL a user wrote?++A statement typed into a ClickHouse query panel is validated with `clickhousesql.ErrIfStatementIsNotValid`. It parses the text with [clickhouse-sql-parser](https://github.com/AfterShip/clickhouse-sql-parser) and refuses anything but a single `SELECT`, a table function other than the row generators (`numbers`, `zeros`, `generate_series`), a function that reads a file, a dictionary or the server binary, the `system` and `information_schema` databases, and a `SETTINGS readonly` override. Each refusal carries one of the package's `Code*` values.++## Why is `$` written as `\x24`?++Inside an identifier or a literal, `clickhousesql` writes a `$` as `\x24` when a digit, `{` or `?` follows; ClickHouse decodes the escape, so the name is unchanged on the server. Two tools between the builder and ClickHouse read such a `$` as a placeholder: go-sqlbuilder resolves `$0` in a compiled fragment to its own WHERE clause and recurses, and clickhouse-go refuses a query that mixes a `$<digits>` numeric placeholder with `?` arguments. Any other `$` stays literal, so `resource_string_service$$name` renders exactly as written.++## What should I remember?++- Every identifier and literal built from a name or a value goes through `pkg/clickhousesql`.+- `sqlbuilder.Escape` wraps compiled text once; `Cond` fields and text assembled outside the builder are left alone.+- Filter expression literals use `querybuilder.FilterStringLiteral`.+- A statement written by a user is validated with `clickhousesql.ErrIfStatementIsNotValid`.+- When adding a builder or a module that emits SQL, run its queries with a name containing a backtick, a quote, a backslash and `$0`; the integration suites under `tests/integration/tests/queriercommon` do this for the query builder.diff --git a/docs/contributing/go/readme.md b/docs/contributing/go/readme.mdindex fb3c1f3235..d984fa46df 100644--- a/docs/contributing/go/readme.md+++ b/docs/contributing/go/readme.md@@ -12,6 +12,7 @@ We **recommend** (almost enforce) reviewing these guides before contributing to- [Abstractions](abstractions.md) - When to introduce new types and intermediate representations- [Authz](authz.md) - Authorization, roles, and access control+- [ClickHouse SQL](clickhousesql.md) - Quoting names and values in generated ClickHouse queries- [Errors](errors.md) - Structured error handling- [Endpoint](endpoint.md) - HTTP endpoint patterns- [Flagger](flagger.md) - Feature flag patternsdiff --git a/pkg/clickhousesql/clickhousesql.go b/pkg/clickhousesql/clickhousesql.gonew file mode 100644index 0000000000..f63ef1b7ef--- /dev/null+++ b/pkg/clickhousesql/clickhousesql.go@@ -0,0 +1,107 @@+package clickhousesql++import (+ "fmt"+ "reflect"+ "strings"+)++var likePatternEscaper = strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`)++func StringLiteral(value string) string {+ return quote(value, '\'')+}++func Identifier(value string) string {+ return quote(value, '`')+}++// LikePattern escapes value so LIKE matches it verbatim; the caller adds the wildcards.+func LikePattern(value string) string {+ return likePatternEscaper.Replace(value)+}++// Literal renders a Go scalar or a list of scalars as a ClickHouse literal. Pointers+// are dereferenced first; a nil or an unsupported value renders as an empty string.+func Literal(value any) string {+ switch x := deref(value).(type) {+ case uint8, uint16, uint32, uint64, int, int8, int16, int32, int64:+ return fmt.Sprintf("%d", x)+ case float32, float64:+ return fmt.Sprintf("%f", x)+ case string:+ return StringLiteral(x)+ case bool:+ return fmt.Sprintf("%v", x)+ case []any:+ if len(x) == 0 {+ return "[]"+ }+ switch x[0].(type) {+ case string:+ return stringArray(x)+ case uint8, uint16, uint32, uint64, int, int8, int16, int32, int64, float32, float64, bool:+ return strings.Join(strings.Fields(fmt.Sprint(x)), ",")+ default:+ return "[]"+ }+ case []string:+ items := make([]any, len(x))+ for i, s := range x {+ items[i] = s+ }+ return stringArray(items)+ default:+ return ""+ }+}++// A "$" followed by a digit, "{" or "?" is written as "\x24"; any other "$" stays as is.+func quote(value string, delimiter byte) string {+ var b strings.Builder+ b.Grow(len(value) + 2)+ b.WriteByte(delimiter)+ for i := 0; i < len(value); i++ {+ c := value[i]+ switch {+ case c == '\\' || c == delimiter:+ b.WriteByte('\\')+ b.WriteByte(c)+ case c == '$' && i+1 < len(value) && (value[i+1] == '{' || value[i+1] == '?' || (value[i+1] >= '0' && value[i+1] <= '9')):+ b.WriteString(`\x24`)+ default:+ b.WriteByte(c)+ }+ }+ b.WriteByte(delimiter)+ return b.String()+}++func stringArray(items []any) string {+ quoted := make([]string, len(items))+ for i, item := range items {+ quoted[i] = StringLiteral(fmt.Sprint(item))+ }+ return "[" + strings.Join(quoted, ",") + "]"+}++func deref(value any) any {+ if value == nil {+ return nil+ }+ if list, ok := value.([]any); ok {+ out := make([]any, len(list))+ for i, item := range list {+ out[i] = deref(item)+ }+ return out+ }+ rv := reflect.ValueOf(value)+ if rv.Kind() != reflect.Pointer {+ return value+ }+ if rv.IsNil() {+ return nil+ }+ return rv.Elem().Interface()+}diff --git a/pkg/clickhousesql/clickhousesql_test.go b/pkg/clickhousesql/clickhousesql_test.gonew file mode 100644index 0000000000..f67cb0832e--- /dev/null+++ b/pkg/clickhousesql/clickhousesql_test.go@@ -0,0 +1,103 @@+package clickhousesql++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestStringLiteral(t *testing.T) {+ testCases := []struct {+ name string+ input string+ expected string+ }{+ {name: "Plain", input: "service.name", expected: `'service.name'`},+ {name: "SingleQuote", input: "a'b", expected: `'a\'b'`},+ {name: "TrailingBackslash", input: `a\`, expected: `'a\\'`},+ {name: "Backtick", input: "a`b", expected: "'a`b'"},+ {name: "DollarDigit", input: "a$0b", expected: `'a\x240b'`},+ {name: "Empty", input: "", expected: `''`},+ {name: "Injection", input: "x' OR '1'='1", expected: `'x\' OR \'1\'=\'1'`},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Equal(t, testCase.expected, StringLiteral(testCase.input))+ })+ }+}++func TestIdentifier(t *testing.T) {+ testCases := []struct {+ name string+ input string+ expected string+ }{+ {name: "Plain", input: "http.status_code", expected: "`http.status_code`"},+ {name: "Backtick", input: "a`b", expected: "`a\\`b`"},+ {name: "TrailingBackslash", input: `a\`, expected: "`a\\\\`"},+ {name: "SingleQuote", input: "k'v", expected: "`k'v`"},+ {name: "DollarBrace", input: "${x}", expected: "`\\x24{x}`"},+ {name: "DollarQuestion", input: "$?", expected: "`\\x24?`"},+ {name: "DollarLetter", input: "$ref", expected: "`$ref`"},+ {name: "TrailingDollar", input: "a$", expected: "`a$`"},+ {name: "MaterializedColumn", input: "resource_string_service$$name", expected: "`resource_string_service$$name`"},+ {name: "MaterializedColumn_DollarDigit", input: "attribute_string_http$$2xx", expected: "`attribute_string_http$\\x242xx`"},+ {name: "Empty", input: "", expected: "``"},+ {name: "Injection", input: "x` OR 1=1 --", expected: "`x\\` OR 1=1 --`"},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Equal(t, testCase.expected, Identifier(testCase.input))+ })+ }+}++func TestLikePattern(t *testing.T) {+ testCases := []struct {+ name string+ input string+ expected string+ }{+ {name: "Plain", input: "k8s.pod.name", expected: `k8s.pod.name`},+ {name: "Percent", input: "100%", expected: `100\%`},+ {name: "Underscore", input: "a_b", expected: `a\_b`},+ {name: "Backslash", input: `a\b`, expected: `a\\b`},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Equal(t, testCase.expected, LikePattern(testCase.input))+ })+ }+}++func TestLiteral(t *testing.T) {+ n := 42+ testCases := []struct {+ name string+ input any+ expected string+ }{+ {name: "Int", input: 42, expected: "42"},+ {name: "IntPointer", input: &n, expected: "42"},+ {name: "Float", input: 1.5, expected: "1.500000"},+ {name: "Bool", input: true, expected: "true"},+ {name: "String", input: "a'b", expected: `'a\'b'`},+ {name: "StringSlice", input: []string{"a", "b'c"}, expected: `['a','b\'c']`},+ {name: "AnySlice_Strings", input: []any{"a", "b"}, expected: `['a','b']`},+ {name: "AnySlice_Ints", input: []any{1, 2, 3}, expected: "[1,2,3]"},+ {name: "AnySlice_Empty", input: []any{}, expected: "[]"},+ {name: "Nil", input: nil, expected: ""},+ {name: "NilPointer", input: (*string)(nil), expected: ""},+ {name: "Unsupported", input: struct{}{}, expected: ""},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Equal(t, testCase.expected, Literal(testCase.input))+ })+ }+}diff --git a/pkg/querybuilder/clickhouse_sql.go b/pkg/clickhousesql/statement.gosimilarity index 73%rename from pkg/querybuilder/clickhouse_sql.gorename to pkg/clickhousesql/statement.goindex 70ddc73c43..4f8cf3a6ee 100644--- a/pkg/querybuilder/clickhouse_sql.go+++ b/pkg/clickhousesql/statement.go@@ -1,4 +1,4 @@-package querybuilder+package clickhousesqlimport ("context"@@ -12,14 +12,14 @@ import ()var (- CodeClickHouseSQLParserPanic = errors.MustNewCode("clickhouse_sql_parser_panic")- CodeClickHouseSQLUnparseable = errors.MustNewCode("clickhouse_sql_unparseable")- CodeClickHouseSQLNotSingleStatement = errors.MustNewCode("clickhouse_sql_not_single_statement")- CodeClickHouseSQLNotSelect = errors.MustNewCode("clickhouse_sql_not_select")- CodeClickHouseSQLTableFunction = errors.MustNewCode("clickhouse_sql_table_function")- CodeClickHouseSQLReadingFunction = errors.MustNewCode("clickhouse_sql_reading_function")- CodeClickHouseSQLInternalDatabase = errors.MustNewCode("clickhouse_sql_internal_database")- CodeClickHouseSQLReadonlyOverride = errors.MustNewCode("clickhouse_sql_readonly_override")+ CodeParserPanic = errors.MustNewCode("clickhouse_sql_parser_panic")+ CodeUnparseable = errors.MustNewCode("clickhouse_sql_unparseable")+ CodeNotSingleStatement = errors.MustNewCode("clickhouse_sql_not_single_statement")+ CodeNotSelect = errors.MustNewCode("clickhouse_sql_not_select")+ CodeTableFunction = errors.MustNewCode("clickhouse_sql_table_function")+ CodeReadingFunction = errors.MustNewCode("clickhouse_sql_reading_function")+ CodeInternalDatabase = errors.MustNewCode("clickhouse_sql_internal_database")+ CodeReadonlyOverride = errors.MustNewCode("clickhouse_sql_readonly_override"))// internalDatabases hold server metadata, credentials and grants rather than telemetry.@@ -68,23 +68,23 @@ func ErrIfStatementIsNotValid(query string) (err error) {defer func() {// The parser has a history of panicking on malformed input rather than returning an error.if recovered := recover(); recovered != nil {- err = errors.NewInvalidInputf(CodeClickHouseSQLParserPanic, "invalid ClickHouse SQL (recovered): %v", recovered)+ err = errors.NewInvalidInputf(CodeParserPanic, "invalid ClickHouse SQL (recovered): %v", recovered)}}()stmts, parseErr := chparser.NewParser(query).ParseStmts()if parseErr != nil {// Wrapped rather than formatted in, so that callers can recover the parser's *ParseError and read the position off it.- return errors.WrapInvalidInputf(parseErr, CodeClickHouseSQLUnparseable, "invalid ClickHouse SQL: %s", parseErr.Error())+ return errors.WrapInvalidInputf(parseErr, CodeUnparseable, "invalid ClickHouse SQL: %s", parseErr.Error())}if len(stmts) != 1 {- return errors.NewInvalidInputf(CodeClickHouseSQLNotSingleStatement, "ClickHouse SQL must contain exactly one statement, found %d statements", len(stmts))+ return errors.NewInvalidInputf(CodeNotSingleStatement, "ClickHouse SQL must contain exactly one statement, found %d statements", len(stmts))}selectQuery, ok := stmts[0].(*chparser.SelectQuery)if !ok {- return errors.NewInvalidInputf(CodeClickHouseSQLNotSelect, "only SELECT statements are allowed in ClickHouse SQL queries")+ return errors.NewInvalidInputf(CodeNotSelect, "only SELECT statements are allowed in ClickHouse SQL queries")}visitor := &chparser.DefaultASTVisitor{Visit: func(node chparser.Expr) error {@@ -111,7 +111,7 @@ func ErrIfStatementIsNotValid(query string) (err error) {}return errors.- NewInvalidInputf(CodeClickHouseSQLTableFunction, "ClickHouse table functions are not allowed in SQL queries: %s", name).+ NewInvalidInputf(CodeTableFunction, "ClickHouse table functions are not allowed in SQL queries: %s", name).WithAdditional(generatorTableFunctionsMessage)case *chparser.FunctionExpr:@@ -130,7 +130,7 @@ func ErrIfStatementIsNotValid(query string) (err error) {}if _, ok := internalDatabases[strings.ToLower(expr.Fields[0].Name)]; ok {- return errors.NewInvalidInputf(CodeClickHouseSQLInternalDatabase, "the ClickHouse %s database is not allowed in SQL queries", expr.Fields[0].Name)+ return errors.NewInvalidInputf(CodeInternalDatabase, "the ClickHouse %s database is not allowed in SQL queries", expr.Fields[0].Name)}case *chparser.TableIdentifier:@@ -140,13 +140,13 @@ func ErrIfStatementIsNotValid(query string) (err error) {}if _, ok := internalDatabases[strings.ToLower(expr.Database.Name)]; ok {- return errors.NewInvalidInputf(CodeClickHouseSQLInternalDatabase, "the ClickHouse %s database is not allowed in SQL queries", expr.Database.Name)+ return errors.NewInvalidInputf(CodeInternalDatabase, "the ClickHouse %s database is not allowed in SQL queries", expr.Database.Name)}case *chparser.SettingExpr:// A query-level setting takes precedence over the context setting.if strings.EqualFold(expr.Name.Name, "readonly") {- return errors.NewInvalidInputf(CodeClickHouseSQLReadonlyOverride, "the ClickHouse readonly setting cannot be overridden")+ return errors.NewInvalidInputf(CodeReadonlyOverride, "the ClickHouse readonly setting cannot be overridden")}}@@ -169,7 +169,7 @@ func errIfFunctionReads(name string) error {return nil}- return errors.NewInvalidInputf(CodeClickHouseSQLReadingFunction, "ClickHouse functions that read outside the telemetry tables are not allowed in SQL queries: %s", name)+ return errors.NewInvalidInputf(CodeReadingFunction, "ClickHouse functions that read outside the telemetry tables are not allowed in SQL queries: %s", name)}// The parser spells a call's name as an Ident everywhere it can. Reading the field rather thandiff --git a/pkg/querybuilder/clickhouse_sql_test.go b/pkg/clickhousesql/statement_test.gosimilarity index 82%rename from pkg/querybuilder/clickhouse_sql_test.gorename to pkg/clickhousesql/statement_test.goindex 78e28449a5..fa137d02af 100644--- a/pkg/querybuilder/clickhouse_sql_test.go+++ b/pkg/clickhousesql/statement_test.go@@ -1,13 +1,13 @@-package querybuilder+package clickhousesqlimport ("testing""time"- "github.com/SigNoz/signoz/pkg/errors"-"github.com/stretchr/testify/assert""github.com/stretchr/testify/require"++ "github.com/SigNoz/signoz/pkg/errors")func TestErrIfStatementIsNotValid_Pass(t *testing.T) {@@ -107,67 +107,67 @@ func TestErrIfStatementIsNotValid_Fail(t *testing.T) {query stringexpectedCode errors.Code}{- {"Empty", "", CodeClickHouseSQLNotSingleStatement},- {"UnterminatedBlockCommentOnly", "/* x", CodeClickHouseSQLUnparseable},- {"Unparseable", "SELECT FROM WHERE", CodeClickHouseSQLUnparseable},- {"MultipleStatements", "SELECT 1; DROP TABLE signoz_logs.logs_v2", CodeClickHouseSQLNotSingleStatement},- {"Drop", "DROP TABLE signoz_logs.logs_v2", CodeClickHouseSQLNotSelect},- {"Insert", "INSERT INTO signoz_logs.logs_v2 SELECT * FROM signoz_logs.logs_v2", CodeClickHouseSQLNotSelect},- {"AlterDelete", "ALTER TABLE signoz_logs.logs_v2 DELETE WHERE 1 = 1", CodeClickHouseSQLNotSelect},- {"CreateTable", "CREATE TABLE evil (a Int) ENGINE = Memory", CodeClickHouseSQLNotSelect},- {"Grant", "GRANT ALL ON *.* TO admin", CodeClickHouseSQLNotSelect},- {"Set", "SET readonly = 0", CodeClickHouseSQLNotSelect},+ {"Empty", "", CodeNotSingleStatement},+ {"UnterminatedBlockCommentOnly", "/* x", CodeUnparseable},+ {"Unparseable", "SELECT FROM WHERE", CodeUnparseable},+ {"MultipleStatements", "SELECT 1; DROP TABLE signoz_logs.logs_v2", CodeNotSingleStatement},+ {"Drop", "DROP TABLE signoz_logs.logs_v2", CodeNotSelect},+ {"Insert", "INSERT INTO signoz_logs.logs_v2 SELECT * FROM signoz_logs.logs_v2", CodeNotSelect},+ {"AlterDelete", "ALTER TABLE signoz_logs.logs_v2 DELETE WHERE 1 = 1", CodeNotSelect},+ {"CreateTable", "CREATE TABLE evil (a Int) ENGINE = Memory", CodeNotSelect},+ {"Grant", "GRANT ALL ON *.* TO admin", CodeNotSelect},+ {"Set", "SET readonly = 0", CodeNotSelect},// Both panicked before v0.5.5. https://github.com/AfterShip/clickhouse-sql-parser/pull/306- {"UnparseableDefaultExpression", "CREATE TABLE t (a String DEFAULT foo(b FROM 2)) ENGINE = Memory", CodeClickHouseSQLUnparseable},- {"TrailingOperatorInDefaultExpression", "CREATE TABLE t (a String DEFAULT 1 +) ENGINE = Memory", CodeClickHouseSQLUnparseable},+ {"UnparseableDefaultExpression", "CREATE TABLE t (a String DEFAULT foo(b FROM 2)) ENGINE = Memory", CodeUnparseable},+ {"TrailingOperatorInDefaultExpression", "CREATE TABLE t (a String DEFAULT 1 +) ENGINE = Memory", CodeUnparseable},// Rejected outright rather than classified.- {"ShowGrants", "SHOW GRANTS", CodeClickHouseSQLUnparseable},- {"IntoOutfile", "SELECT * FROM t INTO OUTFILE '/tmp/x.csv'", CodeClickHouseSQLUnparseable},- {"UrlTableFunction", "SELECT * FROM url('http://attacker.example/x', CSV, 'a String')", CodeClickHouseSQLTableFunction},+ {"ShowGrants", "SHOW GRANTS", CodeUnparseable},+ {"IntoOutfile", "SELECT * FROM t INTO OUTFILE '/tmp/x.csv'", CodeUnparseable},+ {"UrlTableFunction", "SELECT * FROM url('http://attacker.example/x', CSV, 'a String')", CodeTableFunction},// file is also a scalar function, so the reading rule reaches it before the table rule does.- {"FileTableFunction", "SELECT * FROM file('/etc/passwd', CSV, 'a String')", CodeClickHouseSQLReadingFunction},- {"ExecutableTableFunction", "SELECT * FROM executable('script.sh', CSV, 'a String')", CodeClickHouseSQLTableFunction},- {"TableFunctionInJoin", "SELECT * FROM t1 JOIN url('http://x', CSV, 'a String') u ON 1 = 1", CodeClickHouseSQLTableFunction},- {"TableFunctionInCommonTableExpression", "WITH c AS (SELECT * FROM url('http://x', CSV, 'a String')) SELECT * FROM c", CodeClickHouseSQLTableFunction},- {"TableFunctionInWhereSubquery", "SELECT * FROM t WHERE a IN (SELECT * FROM url('http://x', CSV, 'a String'))", CodeClickHouseSQLTableFunction},- {"TableFunctionInUnion", "SELECT * FROM t UNION ALL SELECT * FROM url('http://x', CSV, 'a String')", CodeClickHouseSQLTableFunction},+ {"FileTableFunction", "SELECT * FROM file('/etc/passwd', CSV, 'a String')", CodeReadingFunction},+ {"ExecutableTableFunction", "SELECT * FROM executable('script.sh', CSV, 'a String')", CodeTableFunction},+ {"TableFunctionInJoin", "SELECT * FROM t1 JOIN url('http://x', CSV, 'a String') u ON 1 = 1", CodeTableFunction},+ {"TableFunctionInCommonTableExpression", "WITH c AS (SELECT * FROM url('http://x', CSV, 'a String')) SELECT * FROM c", CodeTableFunction},+ {"TableFunctionInWhereSubquery", "SELECT * FROM t WHERE a IN (SELECT * FROM url('http://x', CSV, 'a String'))", CodeTableFunction},+ {"TableFunctionInUnion", "SELECT * FROM t UNION ALL SELECT * FROM url('http://x', CSV, 'a String')", CodeTableFunction},// Reach an internal database without naming one, so only the table-function rule sees them.- {"MergeTableFunction", "SELECT * FROM merge('system', '.*')", CodeClickHouseSQLTableFunction},- {"RemoteTableFunction", "SELECT * FROM remote('other-host', 'system.users')", CodeClickHouseSQLTableFunction},- {"ClusterTableFunction", "SELECT * FROM cluster('c', 'system.users')", CodeClickHouseSQLTableFunction},+ {"MergeTableFunction", "SELECT * FROM merge('system', '.*')", CodeTableFunction},+ {"RemoteTableFunction", "SELECT * FROM remote('other-host', 'system.users')", CodeTableFunction},+ {"ClusterTableFunction", "SELECT * FROM cluster('c', 'system.users')", CodeTableFunction},// Pure, but excluded: generateRandom is unbounded, and values adds nothing over an array literal.- {"GenerateRandomTableFunction", "SELECT * FROM generateRandom('a UInt64')", CodeClickHouseSQLTableFunction},- {"ValuesTableFunction", "SELECT * FROM values('a UInt64', 1, 2)", CodeClickHouseSQLTableFunction},+ {"GenerateRandomTableFunction", "SELECT * FROM generateRandom('a UInt64')", CodeTableFunction},+ {"ValuesTableFunction", "SELECT * FROM values('a UInt64', 1, 2)", CodeTableFunction},// Arguments are visited first, so an allowed generator is not a wrapper to smuggle a read through.- {"InternalDatabaseInsideAllowedTableFunction", "SELECT * FROM numbers((SELECT count() FROM system.users))", CodeClickHouseSQLInternalDatabase},- {"InternalDatabaseJoinedOntoAllowedTableFunction", "SELECT * FROM numbers(31) AS n JOIN system.users AS u ON 1 = 1", CodeClickHouseSQLInternalDatabase},- {"InternalDatabaseUnionedWithAllowedTableFunction", "SELECT number FROM numbers(31) UNION ALL SELECT name FROM system.users", CodeClickHouseSQLInternalDatabase},- {"RefusedTableFunctionJoinedOntoAllowedTableFunction", "SELECT * FROM numbers(31) AS n JOIN url('http://x', CSV, 'a String') AS u ON 1 = 1", CodeClickHouseSQLTableFunction},- {"RefusedTableFunctionInsideAllowedTableFunction", "SELECT * FROM numbers((SELECT count() FROM url('http://x', CSV, 'a String')))", CodeClickHouseSQLTableFunction},- {"InternalDatabaseInsideAllowedTableFunctionCommonTableExpression", "WITH axis AS (SELECT * FROM numbers((SELECT count() FROM system.users))) SELECT * FROM axis", CodeClickHouseSQLInternalDatabase},+ {"InternalDatabaseInsideAllowedTableFunction", "SELECT * FROM numbers((SELECT count() FROM system.users))", CodeInternalDatabase},+ {"InternalDatabaseJoinedOntoAllowedTableFunction", "SELECT * FROM numbers(31) AS n JOIN system.users AS u ON 1 = 1", CodeInternalDatabase},+ {"InternalDatabaseUnionedWithAllowedTableFunction", "SELECT number FROM numbers(31) UNION ALL SELECT name FROM system.users", CodeInternalDatabase},+ {"RefusedTableFunctionJoinedOntoAllowedTableFunction", "SELECT * FROM numbers(31) AS n JOIN url('http://x', CSV, 'a String') AS u ON 1 = 1", CodeTableFunction},+ {"RefusedTableFunctionInsideAllowedTableFunction", "SELECT * FROM numbers((SELECT count() FROM url('http://x', CSV, 'a String')))", CodeTableFunction},+ {"InternalDatabaseInsideAllowedTableFunctionCommonTableExpression", "WITH axis AS (SELECT * FROM numbers((SELECT count() FROM system.users))) SELECT * FROM axis", CodeInternalDatabase},// Read a file, a dictionary or the server binary without naming a table, so neither the table rule nor the database rule sees them. The row count alone is an oracle: numbers(length(file(x))) returns one row per byte.- {"ScalarFileFunction", "SELECT file('/etc/passwd')", CodeClickHouseSQLReadingFunction},- {"ScalarFileFunctionInWhere", "SELECT * FROM t WHERE length(file('/etc/passwd')) > 0", CodeClickHouseSQLReadingFunction},- {"ScalarFileFunctionInGeneratorTableFunctionArgument", "SELECT * FROM numbers(length(file('/etc/passwd')))", CodeClickHouseSQLReadingFunction},- {"DictionaryFunction", "SELECT dictGetUInt64('d', 'k', toUInt64(1))", CodeClickHouseSQLReadingFunction},- {"DictionaryFunctionUppercase", "SELECT DICTGETSTRING('d', 'k', toUInt64(1))", CodeClickHouseSQLReadingFunction},- {"DictionaryFunctionInGeneratorTableFunctionArgument", "SELECT * FROM numbers(dictGetUInt64('d', 'k', toUInt64(1)))", CodeClickHouseSQLReadingFunction},- {"IntrospectionFunction", "SELECT demangle(addressToSymbol(toUInt64(1)))", CodeClickHouseSQLReadingFunction},- {"ModelEvaluationFunction", "SELECT catboostEvaluate('/model.bin', 1)", CodeClickHouseSQLReadingFunction},+ {"ScalarFileFunction", "SELECT file('/etc/passwd')", CodeReadingFunction},+ {"ScalarFileFunctionInWhere", "SELECT * FROM t WHERE length(file('/etc/passwd')) > 0", CodeReadingFunction},+ {"ScalarFileFunctionInGeneratorTableFunctionArgument", "SELECT * FROM numbers(length(file('/etc/passwd')))", CodeReadingFunction},+ {"DictionaryFunction", "SELECT dictGetUInt64('d', 'k', toUInt64(1))", CodeReadingFunction},+ {"DictionaryFunctionUppercase", "SELECT DICTGETSTRING('d', 'k', toUInt64(1))", CodeReadingFunction},+ {"DictionaryFunctionInGeneratorTableFunctionArgument", "SELECT * FROM numbers(dictGetUInt64('d', 'k', toUInt64(1)))", CodeReadingFunction},+ {"IntrospectionFunction", "SELECT demangle(addressToSymbol(toUInt64(1)))", CodeReadingFunction},+ {"ModelEvaluationFunction", "SELECT catboostEvaluate('/model.bin', 1)", CodeReadingFunction},// ClickHouse reads `x IN table` as `x IN (SELECT * FROM table)`, and a qualified name there is a Path rather than a TableIdentifier.- {"InternalDatabaseInInOperator", "SELECT * FROM t WHERE a IN system.users", CodeClickHouseSQLInternalDatabase},- {"InternalDatabaseInGlobalInOperator", "SELECT * FROM t WHERE a GLOBAL IN system.users", CodeClickHouseSQLInternalDatabase},- {"InternalDatabaseInNotInOperator", "SELECT * FROM t WHERE a NOT IN system.users", CodeClickHouseSQLInternalDatabase},- {"SystemUsers", "SELECT * FROM system.users", CodeClickHouseSQLInternalDatabase},- {"SystemUppercase", "SELECT * FROM SYSTEM.USERS", CodeClickHouseSQLInternalDatabase},- {"SystemQuoted", "SELECT count() FROM `system`.`tables`", CodeClickHouseSQLInternalDatabase},- {"SystemInSubquery", "SELECT * FROM (SELECT name FROM system.parts)", CodeClickHouseSQLInternalDatabase},- {"SystemInJoin", "SELECT * FROM signoz_logs.distributed_logs_v2 AS l JOIN system.users AS u ON 1 = 1", CodeClickHouseSQLInternalDatabase},- {"SystemInIntersect", "SELECT * FROM t INTERSECT SELECT * FROM system.users", CodeClickHouseSQLInternalDatabase},- {"InformationSchema", "SELECT * FROM information_schema.tables", CodeClickHouseSQLInternalDatabase},+ {"InternalDatabaseInInOperator", "SELECT * FROM t WHERE a IN system.users", CodeInternalDatabase},+ {"InternalDatabaseInGlobalInOperator", "SELECT * FROM t WHERE a GLOBAL IN system.users", CodeInternalDatabase},+ {"InternalDatabaseInNotInOperator", "SELECT * FROM t WHERE a NOT IN system.users", CodeInternalDatabase},+ {"SystemUsers", "SELECT * FROM system.users", CodeInternalDatabase},+ {"SystemUppercase", "SELECT * FROM SYSTEM.USERS", CodeInternalDatabase},+ {"SystemQuoted", "SELECT count() FROM `system`.`tables`", CodeInternalDatabase},+ {"SystemInSubquery", "SELECT * FROM (SELECT name FROM system.parts)", CodeInternalDatabase},+ {"SystemInJoin", "SELECT * FROM signoz_logs.distributed_logs_v2 AS l JOIN system.users AS u ON 1 = 1", CodeInternalDatabase},+ {"SystemInIntersect", "SELECT * FROM t INTERSECT SELECT * FROM system.users", CodeInternalDatabase},+ {"InformationSchema", "SELECT * FROM information_schema.tables", CodeInternalDatabase},// Takes precedence over the setting the caller applies.- {"ReadonlySettingOverride", "SELECT * FROM t SETTINGS readonly = 0", CodeClickHouseSQLReadonlyOverride},- {"ReadonlySettingOverrideAmongOthers", "SELECT * FROM t SETTINGS max_threads = 4, readonly = 0", CodeClickHouseSQLReadonlyOverride},+ {"ReadonlySettingOverride", "SELECT * FROM t SETTINGS readonly = 0", CodeReadonlyOverride},+ {"ReadonlySettingOverrideAmongOthers", "SELECT * FROM t SETTINGS max_threads = 4, readonly = 0", CodeReadonlyOverride},}for _, testCase := range testCases {@@ -188,9 +188,9 @@ func TestErrIfStatementIsNotValid_ShouldPassButFails(t *testing.T) {expectedCode errors.Code}{// The one keyword PR 305 left behind, because ON also opens a join condition.- {"UnquotedOnAsColumnName", "SELECT on + 1 FROM t", CodeClickHouseSQLUnparseable},+ {"UnquotedOnAsColumnName", "SELECT on + 1 FROM t", CodeUnparseable},// ClickHouse accepts NULLS FIRST|LAST as an ORDER BY modifier; the parser's grammar has no rule for it.- {"OrderByNullsLast", "SELECT x FROM t ORDER BY x DESC NULLS LAST", CodeClickHouseSQLUnparseable},+ {"OrderByNullsLast", "SELECT x FROM t ORDER BY x DESC NULLS LAST", CodeUnparseable},}for _, testCase := range testCases {diff --git a/pkg/contextlinks/alert_link_visitor.go b/pkg/contextlinks/alert_link_visitor.goindex e9b3f9d6d2..0b3a0974b9 100644--- a/pkg/contextlinks/alert_link_visitor.go+++ b/pkg/contextlinks/alert_link_visitor.go@@ -9,6 +9,7 @@ import ("github.com/antlr4-go/antlr/v4""golang.org/x/exp/maps"+ "github.com/SigNoz/signoz/pkg/querybuilder"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5")@@ -459,7 +460,5 @@ func escapeValueIfNeeded(value string) string {return value}- // For all other values (strings), escape single quotes and wrap in single quotes- escaped := strings.ReplaceAll(value, "'", "\\'")- return fmt.Sprintf("'%s'", escaped)+ return querybuilder.FilterStringLiteral(value)}diff --git a/pkg/modules/inframonitoring/implinframonitoring/containers.go b/pkg/modules/inframonitoring/implinframonitoring/containers.goindex 087073cc14..7e11c0010a 100644--- a/pkg/modules/inframonitoring/implinframonitoring/containers.go+++ b/pkg/modules/inframonitoring/implinframonitoring/containers.go@@ -6,6 +6,7 @@ import ("slices""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetryschema/metricstelemetryschema""github.com/SigNoz/signoz/pkg/types/inframonitoringtypes"@@ -394,7 +395,7 @@ func (m *module) getPerGroupContainerStatusCounts(}for _, key := range groupBy {stateFpsCols = append(stateFpsCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", stateFps.Var(key.Name), quoteIdentifier(key.Name)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", stateFps.Var(key.Name), sqlbuilder.Escape(clickhousesql.Identifier(key.Name))),)}stateFps.Select(stateFpsCols...)@@ -409,7 +410,7 @@ func (m *module) getPerGroupContainerStatusCounts(}stateFpsGroupBy := []string{"fingerprint", "pod_uid", "container_name", "state"}for _, key := range groupBy {- stateFpsGroupBy = append(stateFpsGroupBy, quoteIdentifier(key.Name))+ stateFpsGroupBy = append(stateFpsGroupBy, sqlbuilder.Escape(clickhousesql.Identifier(key.Name)))}stateFps.GroupBy(stateFpsGroupBy...)stateFpsSQL, stateFpsArgs := stateFps.BuildWithFlavor(sqlbuilder.ClickHouse)@@ -421,7 +422,7 @@ func (m *module) getPerGroupContainerStatusCounts("fps.container_name AS container_name",}for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))containerStateCols = append(containerStateCols, fmt.Sprintf("argMax(fps.%s, samples.unix_milli) AS %s", col, col))}containerStateCols = append(containerStateCols,@@ -508,7 +509,7 @@ func (m *module) getPerGroupContainerStatusCounts("st.container_name AS container_name",}for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := clickhousesql.Identifier(key.Name)containerStatusSelectCols = append(containerStatusSelectCols, fmt.Sprintf("st.%s AS %s", col, col))}containerStatusSelectCols = append(containerStatusSelectCols, displayStatusExpr+" AS display_status")@@ -537,7 +538,7 @@ func (m *module) getPerGroupContainerStatusCounts(countSelectCols := make([]string, 0, len(groupBy)+len(statusCountCols))countGroupBy := make([]string, 0, len(groupBy))for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))countSelectCols = append(countSelectCols, col)countGroupBy = append(countGroupBy, col)}@@ -660,7 +661,7 @@ func (m *module) getPerGroupContainerRestartCounts(}for _, key := range groupBy {restartFpsCols = append(restartFpsCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", restartFps.Var(key.Name), quoteIdentifier(key.Name)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", restartFps.Var(key.Name), sqlbuilder.Escape(clickhousesql.Identifier(key.Name))),)}restartFps.Select(restartFpsCols...)@@ -675,7 +676,7 @@ func (m *module) getPerGroupContainerRestartCounts(}restartFpsGroupBy := []string{"fingerprint", "pod_uid", "container_name"}for _, key := range groupBy {- restartFpsGroupBy = append(restartFpsGroupBy, quoteIdentifier(key.Name))+ restartFpsGroupBy = append(restartFpsGroupBy, sqlbuilder.Escape(clickhousesql.Identifier(key.Name)))}restartFps.GroupBy(restartFpsGroupBy...)restartFpsSQL, restartFpsArgs := restartFps.BuildWithFlavor(sqlbuilder.ClickHouse)@@ -687,7 +688,7 @@ func (m *module) getPerGroupContainerRestartCounts("fps.container_name AS container_name",}for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))containerRestartsCols = append(containerRestartsCols, fmt.Sprintf("argMax(fps.%s, samples.unix_milli) AS %s", col, col))}containerRestartsCols = append(containerRestartsCols, fmt.Sprintf("argMax(samples.%s, samples.unix_milli) AS restart_count", valueCol))@@ -709,7 +710,7 @@ func (m *module) getPerGroupContainerRestartCounts(sumSelectCols := make([]string, 0, len(groupBy)+1)sumGroupBy := make([]string, 0, len(groupBy))for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := clickhousesql.Identifier(key.Name)sumSelectCols = append(sumSelectCols, col)sumGroupBy = append(sumGroupBy, col)}@@ -804,7 +805,7 @@ func (m *module) getPerGroupContainerReadyCounts(}for _, key := range groupBy {readyFpsCols = append(readyFpsCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", readyFps.Var(key.Name), quoteIdentifier(key.Name)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", readyFps.Var(key.Name), sqlbuilder.Escape(clickhousesql.Identifier(key.Name))),)}readyFps.Select(readyFpsCols...)@@ -819,7 +820,7 @@ func (m *module) getPerGroupContainerReadyCounts(}readyFpsGroupBy := []string{"fingerprint", "pod_uid", "container_name"}for _, key := range groupBy {- readyFpsGroupBy = append(readyFpsGroupBy, quoteIdentifier(key.Name))+ readyFpsGroupBy = append(readyFpsGroupBy, sqlbuilder.Escape(clickhousesql.Identifier(key.Name)))}readyFps.GroupBy(readyFpsGroupBy...)readyFpsSQL, readyFpsArgs := readyFps.BuildWithFlavor(sqlbuilder.ClickHouse)@@ -831,7 +832,7 @@ func (m *module) getPerGroupContainerReadyCounts("fps.container_name AS container_name",}for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))containerReadyCols = append(containerReadyCols, fmt.Sprintf("argMax(fps.%s, samples.unix_milli) AS %s", col, col))}containerReadyCols = append(containerReadyCols, fmt.Sprintf("argMax(samples.%s, samples.unix_milli) AS ready_value", valueCol))@@ -853,7 +854,7 @@ func (m *module) getPerGroupContainerReadyCounts(countSelectCols := make([]string, 0, len(groupBy)+2)countGroupBy := make([]string, 0, len(groupBy))for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := clickhousesql.Identifier(key.Name)countSelectCols = append(countSelectCols, col)countGroupBy = append(countGroupBy, col)}diff --git a/pkg/modules/inframonitoring/implinframonitoring/helpers.go b/pkg/modules/inframonitoring/implinframonitoring/helpers.goindex 72d8930586..50d83ddc7f 100644--- a/pkg/modules/inframonitoring/implinframonitoring/helpers.go+++ b/pkg/modules/inframonitoring/implinframonitoring/helpers.go@@ -6,6 +6,7 @@ import ("sort""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/flagger""github.com/SigNoz/signoz/pkg/querybuilder"@@ -19,12 +20,6 @@ import ("github.com/huandu/go-sqlbuilder")-// quoteIdentifier wraps s in backticks for use as a ClickHouse identifier,-// escaping any embedded backticks by doubling them.-func quoteIdentifier(s string) string {- return fmt.Sprintf("`%s`", strings.ReplaceAll(s, "`", "``"))-}-func isKeyInGroupByAttrs(groupByAttrs []qbtypes.GroupByKey, key string) bool {for _, groupBy := range groupByAttrs {if groupBy.Name == key {@@ -241,7 +236,7 @@ func buildPageGroupsFilterExpr(pageGroups []map[string]string) string {for key, values := range groupValues {quoted := make([]string, len(values))for i, v := range values {- quoted[i] = fmt.Sprintf("'%s'", v)+ quoted[i] = querybuilder.FilterStringLiteral(v)}inClauses = append(inClauses, fmt.Sprintf("%s IN (%s)", key, strings.Join(quoted, ", ")))}@@ -652,7 +647,7 @@ func (m *module) getMetadata(innerSelectCols := make([]string, 0, len(groupByCols)+1)for _, col := range groupByCols {innerSelectCols = append(innerSelectCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", innerSB.Var(col), quoteIdentifier(col)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", innerSB.Var(col), sqlbuilder.Escape(clickhousesql.Identifier(col))),)}@@ -731,7 +726,7 @@ func (m *module) getMetadata(groupByAliases := make([]string, 0, len(groupByCols))for _, col := range groupByCols {- groupByAliases = append(groupByAliases, quoteIdentifier(col))+ groupByAliases = append(groupByAliases, sqlbuilder.Escape(clickhousesql.Identifier(col)))}innerSB.GroupBy(groupByAliases...)@@ -741,11 +736,11 @@ func (m *module) getMetadata(// Outer SELECT columns: groupBy cols directly + tupleElement(latest_attrs, N) for each additionalColouterSelectCols := make([]string, 0, len(allCols))for _, col := range groupByCols {- outerSelectCols = append(outerSelectCols, quoteIdentifier(col))+ outerSelectCols = append(outerSelectCols, sqlbuilder.Escape(clickhousesql.Identifier(col)))}for i, col := range additionalCols {outerSelectCols = append(outerSelectCols,- fmt.Sprintf("tupleElement(latest_attrs, %d) AS %s", i+1, quoteIdentifier(col)),+ fmt.Sprintf("tupleElement(latest_attrs, %d) AS %s", i+1, sqlbuilder.Escape(clickhousesql.Identifier(col))),)}@@ -858,7 +853,7 @@ func (m *module) getPerGroupDistinctCounts(selectCols := make([]string, 0, len(groupByCols)+len(attrNames))for _, col := range groupByCols {selectCols = append(selectCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", sb.Var(col), quoteIdentifier(col)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", sb.Var(col), sqlbuilder.Escape(clickhousesql.Identifier(col))),)}for _, attr := range attrNames {@@ -880,7 +875,7 @@ func (m *module) getPerGroupDistinctCounts(// Prefix the alias so it never collides with a groupBy col alias// (e.g. clusters grouped by k8s.node.name, which is also counted).selectCols = append(selectCols,- fmt.Sprintf("uniqExactIf(%s, %s != '') AS %s", valueExpr, extract, quoteIdentifier(fmt.Sprintf("__count_%s", attr))),+ fmt.Sprintf("uniqExactIf(%s, %s != '') AS %s", valueExpr, extract, sqlbuilder.Escape(clickhousesql.Identifier(fmt.Sprintf("__count_%s", attr)))),)}sb.Select(selectCols...)@@ -945,7 +940,7 @@ func (m *module) getPerGroupDistinctCounts(groupByAliases := make([]string, 0, len(groupByCols))for _, col := range groupByCols {- groupByAliases = append(groupByAliases, quoteIdentifier(col))+ groupByAliases = append(groupByAliases, sqlbuilder.Escape(clickhousesql.Identifier(col)))}sb.GroupBy(groupByAliases...)diff --git a/pkg/modules/inframonitoring/implinframonitoring/helpers_test.go b/pkg/modules/inframonitoring/implinframonitoring/helpers_test.goindex 95fe2c8add..d085168627 100644--- a/pkg/modules/inframonitoring/implinframonitoring/helpers_test.go+++ b/pkg/modules/inframonitoring/implinframonitoring/helpers_test.go@@ -446,3 +446,22 @@ func TestIntersectRankedGroups(t *testing.T) {})}}++func TestBuildPageGroupsFilterExprQuotesValues(t *testing.T) {+ testCases := []struct {+ name string+ pageGroups []map[string]string+ expected string+ }{+ {name: "SingleQuote", pageGroups: []map[string]string{{"host.name": `h'1`}}, expected: `host.name IN ('h\'1')`},+ {name: "TrailingBackslash", pageGroups: []map[string]string{{"host.name": `h\`}}, expected: `host.name IN ('h\\')`},+ {name: "Injection", pageGroups: []map[string]string{{"host.name": `h') OR 1=1 --`}}, expected: `host.name IN ('h\') OR 1=1 --')`},+ {name: "MultipleGroups", pageGroups: []map[string]string{{"host.name": `h'1`}, {"host.name": `h'2`}}, expected: `host.name IN ('h\'1', 'h\'2')`},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Equal(t, testCase.expected, buildPageGroupsFilterExpr(testCase.pageGroups))+ })+ }+}diff --git a/pkg/modules/inframonitoring/implinframonitoring/hosts.go b/pkg/modules/inframonitoring/implinframonitoring/hosts.goindex 3cdefa38d1..3885a46f1a 100644--- a/pkg/modules/inframonitoring/implinframonitoring/hosts.go+++ b/pkg/modules/inframonitoring/implinframonitoring/hosts.go@@ -6,7 +6,9 @@ import ("slices""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/flagger"+ "github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetryschema/metricstelemetryschema""github.com/SigNoz/signoz/pkg/types/featuretypes""github.com/SigNoz/signoz/pkg/types/inframonitoringtypes"@@ -49,7 +51,7 @@ func (m *module) getPerGroupHostStatusCounts(selectCols := make([]string, 0, len(req.GroupBy)+2)for _, key := range req.GroupBy {selectCols = append(selectCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", sb.Var(key.Name), quoteIdentifier(key.Name)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", sb.Var(key.Name), sqlbuilder.Escape(clickhousesql.Identifier(key.Name))),)}@@ -124,7 +126,7 @@ func (m *module) getPerGroupHostStatusCounts(// GROUP BYgroupByAliases := make([]string, 0, len(req.GroupBy))for _, key := range req.GroupBy {- groupByAliases = append(groupByAliases, quoteIdentifier(key.Name))+ groupByAliases = append(groupByAliases, sqlbuilder.Escape(clickhousesql.Identifier(key.Name)))}sb.GroupBy(groupByAliases...)@@ -345,7 +347,7 @@ func (m *module) applyHostsActiveStatusFilter(req *inframonitoringtypes.PostableactiveHosts := make([]string, 0, len(activeHostsMap))for host := range activeHostsMap {- activeHosts = append(activeHosts, fmt.Sprintf("'%s'", host))+ activeHosts = append(activeHosts, querybuilder.FilterStringLiteral(host))}if len(activeHosts) == 0 {diff --git a/pkg/modules/inframonitoring/implinframonitoring/nodes.go b/pkg/modules/inframonitoring/implinframonitoring/nodes.goindex d06a86e74f..ae3bdcc095 100644--- a/pkg/modules/inframonitoring/implinframonitoring/nodes.go+++ b/pkg/modules/inframonitoring/implinframonitoring/nodes.go@@ -5,6 +5,7 @@ import ("fmt""slices"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetryschema/metricstelemetryschema""github.com/SigNoz/signoz/pkg/types/inframonitoringtypes"@@ -304,7 +305,7 @@ func (m *module) getPerGroupNodeConditionCounts(}for _, key := range groupBy {timeSeriesFPsSelectCols = append(timeSeriesFPsSelectCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", timeSeriesFPs.Var(key.Name), quoteIdentifier(key.Name)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", timeSeriesFPs.Var(key.Name), sqlbuilder.Escape(clickhousesql.Identifier(key.Name))),)}timeSeriesFPs.Select(timeSeriesFPsSelectCols...)@@ -325,7 +326,7 @@ func (m *module) getPerGroupNodeConditionCounts(}timeSeriesFPsGroupBy := []string{"fingerprint", "node_name"}for _, key := range groupBy {- timeSeriesFPsGroupBy = append(timeSeriesFPsGroupBy, quoteIdentifier(key.Name))+ timeSeriesFPsGroupBy = append(timeSeriesFPsGroupBy, sqlbuilder.Escape(clickhousesql.Identifier(key.Name)))}timeSeriesFPs.GroupBy(timeSeriesFPsGroupBy...)timeSeriesFPsSQL, timeSeriesFPsArgs := timeSeriesFPs.BuildWithFlavor(sqlbuilder.ClickHouse)@@ -335,7 +336,7 @@ func (m *module) getPerGroupNodeConditionCounts(latestConditionPerNodeSelectCols := []string{"tsfp.node_name AS node_name"}latestConditionPerNodeGroupBy := []string{"node_name"}for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))latestConditionPerNodeSelectCols = append(latestConditionPerNodeSelectCols, fmt.Sprintf("tsfp.%s AS %s", col, col))latestConditionPerNodeGroupBy = append(latestConditionPerNodeGroupBy, col)}@@ -360,7 +361,7 @@ func (m *module) getPerGroupNodeConditionCounts(countNodesPerConditionSelectCols := make([]string, 0, len(groupBy)+2)countNodesPerConditionGroupBy := make([]string, 0, len(groupBy))for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))countNodesPerConditionSelectCols = append(countNodesPerConditionSelectCols, col)countNodesPerConditionGroupBy = append(countNodesPerConditionGroupBy, col)}diff --git a/pkg/modules/inframonitoring/implinframonitoring/pods.go b/pkg/modules/inframonitoring/implinframonitoring/pods.goindex 18037bc84c..8207c2e561 100644--- a/pkg/modules/inframonitoring/implinframonitoring/pods.go+++ b/pkg/modules/inframonitoring/implinframonitoring/pods.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetryschema/metricstelemetryschema""github.com/SigNoz/signoz/pkg/types/inframonitoringtypes"@@ -398,7 +399,7 @@ func (m *module) getPerGroupPodStatusCounts(}for _, key := range groupBy {phaseFpsCols = append(phaseFpsCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", phaseFps.Var(key.Name), quoteIdentifier(key.Name)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", phaseFps.Var(key.Name), sqlbuilder.Escape(clickhousesql.Identifier(key.Name))),)}phaseFps.Select(phaseFpsCols...)@@ -413,7 +414,7 @@ func (m *module) getPerGroupPodStatusCounts(}phaseFpsGroupBy := []string{"fingerprint", "pod_uid"}for _, key := range groupBy {- phaseFpsGroupBy = append(phaseFpsGroupBy, quoteIdentifier(key.Name))+ phaseFpsGroupBy = append(phaseFpsGroupBy, sqlbuilder.Escape(clickhousesql.Identifier(key.Name)))}phaseFps.GroupBy(phaseFpsGroupBy...)phaseFpsSQL, phaseFpsArgs := phaseFps.BuildWithFlavor(sqlbuilder.ClickHouse)@@ -422,7 +423,7 @@ func (m *module) getPerGroupPodStatusCounts(phasePerPod := sqlbuilder.NewSelectBuilder()phasePerPodCols := []string{"fps.pod_uid AS pod_uid"}for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))phasePerPodCols = append(phasePerPodCols, fmt.Sprintf("argMax(fps.%s, samples.unix_milli) AS %s", col, col))}phasePerPodCols = append(phasePerPodCols, fmt.Sprintf("argMax(samples.%s, samples.unix_milli) AS phase_value", valueCol))@@ -555,7 +556,7 @@ func (m *module) getPerGroupPodStatusCounts("'Unknown')"podStatusSelectCols := []string{"pp.pod_uid AS pod_uid"}for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := clickhousesql.Identifier(key.Name)podStatusSelectCols = append(podStatusSelectCols, fmt.Sprintf("pp.%s AS %s", col, col))}podStatusSelectCols = append(podStatusSelectCols, displayStatusExpr+" AS display_status")@@ -592,7 +593,7 @@ func (m *module) getPerGroupPodStatusCounts(countSelectCols := make([]string, 0, len(groupBy)+len(statusCountCols))countGroupBy := make([]string, 0, len(groupBy))for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))countSelectCols = append(countSelectCols, col)countGroupBy = append(countGroupBy, col)}@@ -726,7 +727,7 @@ func (m *module) getPerGroupPodRestartCounts(}for _, key := range groupBy {restartFpsCols = append(restartFpsCols,- fmt.Sprintf("JSONExtractString(labels, %s) AS %s", restartFps.Var(key.Name), quoteIdentifier(key.Name)),+ fmt.Sprintf("JSONExtractString(labels, %s) AS %s", restartFps.Var(key.Name), sqlbuilder.Escape(clickhousesql.Identifier(key.Name))),)}restartFps.Select(restartFpsCols...)@@ -741,7 +742,7 @@ func (m *module) getPerGroupPodRestartCounts(}restartFpsGroupBy := []string{"fingerprint", "pod_uid", "container_name"}for _, key := range groupBy {- restartFpsGroupBy = append(restartFpsGroupBy, quoteIdentifier(key.Name))+ restartFpsGroupBy = append(restartFpsGroupBy, sqlbuilder.Escape(clickhousesql.Identifier(key.Name)))}restartFps.GroupBy(restartFpsGroupBy...)restartFpsSQL, restartFpsArgs := restartFps.BuildWithFlavor(sqlbuilder.ClickHouse)@@ -753,7 +754,7 @@ func (m *module) getPerGroupPodRestartCounts("fps.container_name AS container_name",}for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := sqlbuilder.Escape(clickhousesql.Identifier(key.Name))containerRestartsCols = append(containerRestartsCols, fmt.Sprintf("argMax(fps.%s, samples.unix_milli) AS %s", col, col))}containerRestartsCols = append(containerRestartsCols, fmt.Sprintf("argMax(samples.%s, samples.unix_milli) AS restart_count", valueCol))@@ -775,7 +776,7 @@ func (m *module) getPerGroupPodRestartCounts(sumSelectCols := make([]string, 0, len(groupBy)+1)sumGroupBy := make([]string, 0, len(groupBy))for _, key := range groupBy {- col := quoteIdentifier(key.Name)+ col := clickhousesql.Identifier(key.Name)sumSelectCols = append(sumSelectCols, col)sumGroupBy = append(sumGroupBy, col)}diff --git a/pkg/modules/rulestatehistory/implrulestatehistory/field_mapper.go b/pkg/modules/rulestatehistory/implrulestatehistory/field_mapper.goindex 075335f83a..2793747a52 100644--- a/pkg/modules/rulestatehistory/implrulestatehistory/field_mapper.go+++ b/pkg/modules/rulestatehistory/implrulestatehistory/field_mapper.go@@ -6,7 +6,7 @@ import ("strings"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"- "github.com/SigNoz/signoz/pkg/querybuilder"+ "github.com/SigNoz/signoz/pkg/clickhousesql"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes""github.com/SigNoz/signoz/pkg/valuer"@@ -52,7 +52,7 @@ func (m *fieldMapper) FieldFor(ctx context.Context, _ valuer.UUID, _, _ uint64,return "", err}if col.Name == "labels" && key.Name != "labels" {- return fmt.Sprintf("JSONExtractString(labels, %s)", querybuilder.ClickHouseStringLiteral(key.Name)), nil+ return fmt.Sprintf("JSONExtractString(labels, %s)", clickhousesql.StringLiteral(key.Name)), nil}return col.Name, nil}@@ -74,7 +74,7 @@ func (m *fieldMapper) ExistsFor(ctx context.Context, _ valuer.UUID, _, _ uint64,return "", err}if col.Name == "labels" && key.Name != "labels" {- pred := fmt.Sprintf("JSONHas(labels, %s)", querybuilder.ClickHouseStringLiteral(key.Name))+ pred := fmt.Sprintf("JSONHas(labels, %s)", clickhousesql.StringLiteral(key.Name))if exists {return pred, nil}@@ -88,5 +88,5 @@ func (m *fieldMapper) ColumnExpressionFor(ctx context.Context, orgID valuer.UUIDif err != nil {return "", err}- return fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(colName), field.Name), nil+ return sqlbuilder.Escape(fmt.Sprintf("%s AS %s", colName, clickhousesql.Identifier(field.Name))), nil}diff --git a/pkg/modules/spanpercentile/implspanpercentile/statement_builder.go b/pkg/modules/spanpercentile/implspanpercentile/statement_builder.goindex c44caa1b3e..f6a2814956 100644--- a/pkg/modules/spanpercentile/implspanpercentile/statement_builder.go+++ b/pkg/modules/spanpercentile/implspanpercentile/statement_builder.go@@ -6,6 +6,7 @@ import ("sort""strings"+ "github.com/SigNoz/signoz/pkg/querybuilder"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/spanpercentiletypes""github.com/SigNoz/signoz/pkg/types/telemetrytypes"@@ -26,14 +27,14 @@ func buildSpanPercentileQuery(sort.Strings(attrKeys)filterConditions := []string{- fmt.Sprintf("service.name = '%s'", strings.ReplaceAll(req.ServiceName, "'", `\'`)),- fmt.Sprintf("name = '%s'", strings.ReplaceAll(req.Name, "'", `\'`)),+ fmt.Sprintf("service.name = %s", querybuilder.FilterStringLiteral(req.ServiceName)),+ fmt.Sprintf("name = %s", querybuilder.FilterStringLiteral(req.Name)),}for _, key := range attrKeys {value := req.ResourceAttributes[key]filterConditions = append(filterConditions,- fmt.Sprintf("%s = '%s'", key, strings.ReplaceAll(value, "'", `\'`)))+ fmt.Sprintf("%s = %s", key, querybuilder.FilterStringLiteral(value)))}filterExpr := strings.Join(filterConditions, " AND ")diff --git a/pkg/modules/spanpercentile/implspanpercentile/statement_builder_test.go b/pkg/modules/spanpercentile/implspanpercentile/statement_builder_test.goindex 55fda9e1a6..3af19ef1f3 100644--- a/pkg/modules/spanpercentile/implspanpercentile/statement_builder_test.go+++ b/pkg/modules/spanpercentile/implspanpercentile/statement_builder_test.go@@ -9,6 +9,7 @@ import (qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/spanpercentiletypes""github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -147,3 +148,51 @@ func getSortedKeys(m map[string]string) []string {sort.Strings(keys)return keys}++func TestBuildSpanPercentileQueryQuotesFilterValues(t *testing.T) {+ testCases := []struct {+ name string+ serviceName string+ spanName string+ resourceAttributes map[string]string+ expected string+ }{+ {+ name: "QuoteInSpanName",+ serviceName: "svc",+ spanName: `GET /api' OR '1'='1`,+ expected: `service.name = 'svc' AND name = 'GET /api\' OR \'1\'=\'1'`,+ },+ {+ name: "TrailingBackslashInServiceName",+ serviceName: `svc\`,+ spanName: "GET /api",+ expected: `service.name = 'svc\\' AND name = 'GET /api'`,+ },+ {+ name: "EscapedQuoteInResourceAttribute",+ serviceName: "api-gateway",+ spanName: "GET /users",+ resourceAttributes: map[string]string{"deployment.environment": `prod\'`},+ expected: `service.name = 'api-gateway' AND name = 'GET /users' AND deployment.environment = 'prod\\\''`,+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ result, err := buildSpanPercentileQuery(context.Background(), &spanpercentiletypes.SpanPercentileRequest{+ DurationNano: 100000,+ Name: testCase.spanName,+ ServiceName: testCase.serviceName,+ ResourceAttributes: testCase.resourceAttributes,+ Start: 1640995200000,+ End: 1640995800000,+ })+ require.NoError(t, err)++ query, ok := result.CompositeQuery.Queries[0].Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])+ require.True(t, ok)+ assert.Equal(t, testCase.expected, query.Filter.Expression)+ })+ }+}diff --git a/pkg/modules/tracedetail/impltracedetail/store.go b/pkg/modules/tracedetail/impltracedetail/store.goindex 8233bebb2b..f58e7a67f5 100644--- a/pkg/modules/tracedetail/impltracedetail/store.go+++ b/pkg/modules/tracedetail/impltracedetail/store.go@@ -8,6 +8,7 @@ import (sqlbuilder "github.com/huandu/go-sqlbuilder"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/telemetrystore""github.com/SigNoz/signoz/pkg/types/spantypes"@@ -20,7 +21,7 @@ func buildFieldExpr(fieldKey telemetrytypes.TelemetryFieldKey) (string, error) {switch fieldKey.FieldContext {case telemetrytypes.FieldContextResource:// String cast required — Variant/Dynamic is rejected by GROUP BY.- return fmt.Sprintf("resource.`%s`::String", fieldKey.Name), nil+ return sqlbuilder.Escape(fmt.Sprintf("resource.%s::String", clickhousesql.Identifier(fieldKey.Name))), nil}return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "unsupported field context: %v", fieldKey.FieldContext)}diff --git a/pkg/modules/tracedetail/impltracedetail/store_internal_test.go b/pkg/modules/tracedetail/impltracedetail/store_internal_test.gonew file mode 100644index 0000000000..15eaf6d044--- /dev/null+++ b/pkg/modules/tracedetail/impltracedetail/store_internal_test.go@@ -0,0 +1,51 @@+package impltracedetail++import (+ "testing"++ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/huandu/go-sqlbuilder"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestBuildFieldExprQuotesResourceKey(t *testing.T) {+ testCases := []struct {+ name string+ key string+ expectedExpr string+ expectedQuery string+ }{+ {+ name: "Backtick",+ key: "svc` OR 1=1 --",+ expectedExpr: "resource.`svc\\` OR 1=1 --`::String",+ expectedQuery: "SELECT resource.`svc\\` OR 1=1 --`::String AS field_value FROM t WHERE trace_id = ? AND notEmpty(resource.`svc\\` OR 1=1 --`::String)",+ },+ {+ name: "DollarLetter",+ key: "a$b",+ expectedExpr: "resource.`a$$b`::String",+ expectedQuery: "SELECT resource.`a$b`::String AS field_value FROM t WHERE trace_id = ? AND notEmpty(resource.`a$b`::String)",+ },+ {+ name: "DollarDigit",+ key: "a$0b",+ expectedExpr: "resource.`a\\x240b`::String",+ expectedQuery: "SELECT resource.`a\\x240b`::String AS field_value FROM t WHERE trace_id = ? AND notEmpty(resource.`a\\x240b`::String)",+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ expr, err := buildFieldExpr(telemetrytypes.TelemetryFieldKey{Name: testCase.key, FieldContext: telemetrytypes.FieldContextResource})+ require.NoError(t, err)+ assert.Equal(t, testCase.expectedExpr, expr)++ sb := sqlbuilder.NewSelectBuilder().Select(expr + " AS field_value").From("t")+ sb.Where(sb.E("trace_id", "x"), "notEmpty("+expr+")")+ query, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)+ assert.Equal(t, testCase.expectedQuery, query)+ })+ }+}diff --git a/pkg/modules/tracefunnel/clickhouse_queries.go b/pkg/modules/tracefunnel/clickhouse_queries.goindex 409210c2df..1e5b756e59 100644--- a/pkg/modules/tracefunnel/clickhouse_queries.go+++ b/pkg/modules/tracefunnel/clickhouse_queries.go@@ -3,6 +3,8 @@ package tracefunnelimport ("fmt""strings"++ "github.com/SigNoz/signoz/pkg/clickhousesql")// BuildFunnelValidationQuery builds a validation query for n-step funnels.@@ -27,7 +29,7 @@ func BuildFunnelValidationQuery(// Add contains_error and step definitionsfor i, step := range steps {withParts = append(withParts, fmt.Sprintf("%d AS contains_error_t%d", step.ContainsError, i+1))- withParts = append(withParts, fmt.Sprintf("('%s','%s') AS step%d", step.ServiceName, step.SpanName, i+1))+ withParts = append(withParts, fmt.Sprintf("(%s,%s) AS step%d", clickhousesql.StringLiteral(step.ServiceName), clickhousesql.StringLiteral(step.SpanName), i+1))}// Build SELECT fields for each step time@@ -97,8 +99,8 @@ func BuildFunnelOverviewQuery(// Add contains_error, latency_pointer and step definitionsfor i, step := range steps {withParts = append(withParts, fmt.Sprintf("%d AS contains_error_t%d", step.ContainsError, i+1))- withParts = append(withParts, fmt.Sprintf("'%s' AS latency_pointer_t%d", step.LatencyPointer, i+1))- withParts = append(withParts, fmt.Sprintf("('%s','%s') AS step%d", step.ServiceName, step.SpanName, i+1))+ withParts = append(withParts, fmt.Sprintf("%s AS latency_pointer_t%d", clickhousesql.StringLiteral(step.LatencyPointer), i+1))+ withParts = append(withParts, fmt.Sprintf("(%s,%s) AS step%d", clickhousesql.StringLiteral(step.ServiceName), clickhousesql.StringLiteral(step.SpanName), i+1))}// Build funnel CTE select fields@@ -238,7 +240,7 @@ func BuildFunnelCountQuery(// Add contains_error and step definitionsfor i, step := range steps {withParts = append(withParts, fmt.Sprintf("%d AS contains_error_t%d", step.ContainsError, i+1))- withParts = append(withParts, fmt.Sprintf("('%s','%s') AS step%d", step.ServiceName, step.SpanName, i+1))+ withParts = append(withParts, fmt.Sprintf("(%s,%s) AS step%d", clickhousesql.StringLiteral(step.ServiceName), clickhousesql.StringLiteral(step.SpanName), i+1))}// Build funnel subquery select fields@@ -350,7 +352,7 @@ func BuildFunnelStepOverviewQuery(// Add contains_error and step definitions for all stepsfor i, step := range steps {withParts = append(withParts, fmt.Sprintf("%d AS contains_error_t%d", step.ContainsError, i+1))- withParts = append(withParts, fmt.Sprintf("('%s','%s') AS step%d", step.ServiceName, step.SpanName, i+1))+ withParts = append(withParts, fmt.Sprintf("(%s,%s) AS step%d", clickhousesql.StringLiteral(step.ServiceName), clickhousesql.StringLiteral(step.SpanName), i+1))}// Build funnel CTE select fieldsdiff --git a/pkg/modules/tracefunnel/clickhouse_queries_test.go b/pkg/modules/tracefunnel/clickhouse_queries_test.goindex b2273a1c0d..7eada2a637 100644--- a/pkg/modules/tracefunnel/clickhouse_queries_test.go+++ b/pkg/modules/tracefunnel/clickhouse_queries_test.go@@ -3,6 +3,8 @@ package tracefunnelimport ("strings""testing"++ "github.com/stretchr/testify/assert")func TestBuildFunnelValidationQuery(t *testing.T) {@@ -390,3 +392,43 @@ func TestTemporalOrderingLogic(t *testing.T) {}}}++func TestBuildFunnelQueriesQuoteStepNames(t *testing.T) {+ validationQuery := BuildFunnelValidationQuery([]struct {+ ServiceName string+ SpanName string+ ContainsError int+ Clause string+ }{+ {ServiceName: "svc'1') OR 1=1 --", SpanName: `span\`},+ }, 1000000000, 2000000000)++ overviewQuery := BuildFunnelOverviewQuery([]struct {+ ServiceName string+ SpanName string+ ContainsError int+ LatencyPointer string+ Clause string+ }{+ {ServiceName: "svc'1", SpanName: "span'1", LatencyPointer: "end' OR '1'='1"},+ {ServiceName: "svc2", SpanName: "span2", ContainsError: 1, LatencyPointer: "start"},+ }, 1000000000, 2000000000)++ testCases := []struct {+ name string+ query string+ expected string+ }{+ {name: "ValidationQuery_QuoteInStepNames", query: validationQuery, expected: `('svc\'1\') OR 1=1 --','span\\') AS step1`},+ {name: "OverviewQuery_QuoteInStepNames", query: overviewQuery, expected: `('svc\'1','span\'1') AS step1`},+ {name: "OverviewQuery_QuoteInLatencyPointer", query: overviewQuery, expected: `'end\' OR \'1\'=\'1' AS latency_pointer_t1`},+ {name: "OverviewQuery_PlainStepNames", query: overviewQuery, expected: `('svc2','span2') AS step2`},+ {name: "OverviewQuery_PlainLatencyPointer", query: overviewQuery, expected: `'start' AS latency_pointer_t2`},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Contains(t, testCase.query, testCase.expected)+ })+ }+}diff --git a/pkg/prometheus/clickhouseprometheusv2/transpiler_sql.go b/pkg/prometheus/clickhouseprometheusv2/transpiler_sql.goindex 922706cd58..4bf33ca341 100644--- a/pkg/prometheus/clickhouseprometheusv2/transpiler_sql.go+++ b/pkg/prometheus/clickhouseprometheusv2/transpiler_sql.go@@ -4,6 +4,7 @@ import ("fmt""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/telemetryschema/metricstelemetryschema""github.com/huandu/go-sqlbuilder")@@ -409,7 +410,7 @@ func groupKeyExpr(unit *coreUnit) string {func quotedList(items []string) string {quoted := make([]string, len(items))for i, s := range items {- quoted[i] = "'" + strings.ReplaceAll(s, "'", "\\'") + "'"+ quoted[i] = clickhousesql.StringLiteral(s)}return strings.Join(quoted, ", ")}diff --git a/pkg/querier/clickhouse_query.go b/pkg/querier/clickhouse_query.goindex f31d2395dc..de659d9165 100644--- a/pkg/querier/clickhouse_query.go+++ b/pkg/querier/clickhouse_query.go@@ -11,6 +11,7 @@ import ("time""github.com/ClickHouse/clickhouse-go/v2"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetrystore"@@ -66,7 +67,7 @@ func (q *chSQLQuery) Window() (uint64, uint64) { return q.fromMS, q.toMS }func (q *chSQLQuery) renderVars(query string, vars map[string]qbtypes.VariableItem, start, end uint64) (string, error) {varsData := map[string]any{}for k, v := range vars {- varsData[k] = formatValueForCH(v.Value)+ varsData[k] = clickhousesql.Literal(v.Value)}querybuilder.AssignReservedVars(varsData, start, end)@@ -106,7 +107,7 @@ func (q *chSQLQuery) render(ctx context.Context) (string, error) {return "", err}- querybuilder.LogIfStatementIsNotValid(ctx, q.logger, rendered)+ clickhousesql.LogIfStatementIsNotValid(ctx, q.logger, rendered)return rendered, nil}diff --git a/pkg/querier/format.go b/pkg/querier/format.goindex aea2a1391a..8971c90cfd 100644--- a/pkg/querier/format.go+++ b/pkg/querier/format.go@@ -6,52 +6,6 @@ import ("strings")-func toStrArrayString(strs ...string) string {- return fmt.Sprintf("[%s]", strings.Join(strs, ","))-}--// formatValue formats the value to be used in clickhouse query.-func formatValueForCH(v any) string {- // if it's pointer convert it to a value- v = getPointerValue(v)-- switch x := v.(type) {- case uint8, uint16, uint32, uint64, int, int8, int16, int32, int64:- return fmt.Sprintf("%d", x)- case float32, float64:- return fmt.Sprintf("%f", x)- case string:- return fmt.Sprintf("'%s'", quoteEscapedString(x))- case bool:- return fmt.Sprintf("%v", x)-- case []any:- if len(x) == 0 {- return "[]"- }- switch x[0].(type) {- case string:- strs := []string{}- for _, sVal := range x {- strs = append(strs, fmt.Sprintf("'%s'", quoteEscapedString(sVal.(string))))- }- return toStrArrayString(strs...)- case uint8, uint16, uint32, uint64, int, int8, int16, int32, int64, float32, float64, bool:- return strings.Join(strings.Fields(fmt.Sprint(x)), ",")- default:- return toStrArrayString()- }- case []string:- strs := []string{}- for _, sVal := range x {- strs = append(strs, fmt.Sprintf("'%s'", quoteEscapedString(sVal)))- }- return toStrArrayString(strs...)- default:- return ""- }-}-func getPointerValue(v any) any {// Check if the interface value is nil@@ -142,13 +96,6 @@ func getPointerValue(v any) any {}}-func quoteEscapedString(str string) string {- // https://clickhouse.com/docs/en/sql-reference/syntax#string- str = strings.ReplaceAll(str, `\`, `\\`)- str = strings.ReplaceAll(str, `'`, `\'`)- return str-}-// formatValueForProm formats the value to be used in promql.func formatValueForProm(v any) string {switch x := v.(type) {diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.goindex 249d4caeb5..e9befa737a 100644--- a/pkg/query-service/app/http_handler.go+++ b/pkg/query-service/app/http_handler.go@@ -8,10 +8,10 @@ import ("fmt""io"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/flagger""github.com/SigNoz/signoz/pkg/modules/thirdpartyapi"- "github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/queryparser""log/slog"@@ -961,7 +961,7 @@ func (aH *APIHandler) queryDashboardVarsV2(w http.ResponseWriter, r *http.Requesreturn}- querybuilder.LogIfStatementIsNotValid(r.Context(), aH.logger, query)+ clickhousesql.LogIfStatementIsNotValid(r.Context(), aH.logger, query)dashboardVars, err := aH.reader.QueryDashboardVars(r.Context(), query)if err != nil {diff --git a/pkg/query-service/app/resource/resource_query_builder.go b/pkg/query-service/app/resource/resource_query_builder.goindex 196cc6541a..d85e920708 100644--- a/pkg/query-service/app/resource/resource_query_builder.go+++ b/pkg/query-service/app/resource/resource_query_builder.go@@ -4,9 +4,9 @@ import ("fmt""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql"v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3""github.com/SigNoz/signoz/pkg/query-service/utils"- "github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/semconv""github.com/SigNoz/signoz/pkg/types/telemetrytypes")@@ -35,17 +35,17 @@ var resourceLogOperators = map[v3.FilterOperator]string{// buildResourceFilter builds a clickhouse filter string for resource labelsfunc buildResourceFilter(logsOp string, key string, op v3.FilterOperator, value interface{}, members []string) string {// for all operators except contains and like- searchKey := fmt.Sprintf("simpleJSONExtractString(labels, %s)", querybuilder.ClickHouseStringLiteral(key))+ searchKey := fmt.Sprintf("simpleJSONExtractString(labels, %s)", clickhousesql.StringLiteral(key))if len(members) > 1 {values := make([]string, 0, len(members))for _, member := range members {- values = append(values, fmt.Sprintf("NULLIF(simpleJSONExtractString(labels, %s), '')", querybuilder.ClickHouseStringLiteral(member)))+ values = append(values, fmt.Sprintf("NULLIF(simpleJSONExtractString(labels, %s), '')", clickhousesql.StringLiteral(member)))}searchKey = "COALESCE(" + strings.Join(values, ", ") + ", '')"}// for contains and like it will be case insensitive- lowerSearchKey := fmt.Sprintf("simpleJSONExtractString(lower(labels), %s)", querybuilder.ClickHouseStringLiteral(key))+ lowerSearchKey := fmt.Sprintf("simpleJSONExtractString(lower(labels), %s)", clickhousesql.StringLiteral(key))if len(members) > 1 {lowerSearchKey = "lower(" + searchKey + ")"}@@ -59,16 +59,16 @@ func buildResourceFilter(logsOp string, key string, op v3.FilterOperator, valueexists := op == v3.FilterOperatorExistsif len(members) == 1 {if exists {- return fmt.Sprintf("simpleJSONHas(labels, %s)", querybuilder.ClickHouseStringLiteral(key))+ return fmt.Sprintf("simpleJSONHas(labels, %s)", clickhousesql.StringLiteral(key))}- return fmt.Sprintf("not simpleJSONHas(labels, %s)", querybuilder.ClickHouseStringLiteral(key))+ return fmt.Sprintf("not simpleJSONHas(labels, %s)", clickhousesql.StringLiteral(key))}presence := make([]string, 0, len(members))for _, member := range members {if exists {- presence = append(presence, fmt.Sprintf("simpleJSONHas(labels, %s)", querybuilder.ClickHouseStringLiteral(member)))+ presence = append(presence, fmt.Sprintf("simpleJSONHas(labels, %s)", clickhousesql.StringLiteral(member)))} else {- presence = append(presence, fmt.Sprintf("not simpleJSONHas(labels, %s)", querybuilder.ClickHouseStringLiteral(member)))+ presence = append(presence, fmt.Sprintf("not simpleJSONHas(labels, %s)", clickhousesql.StringLiteral(member)))}}separator := " OR "diff --git a/pkg/querybuilder/clickhouse_quote.go b/pkg/querybuilder/clickhouse_quote.godeleted file mode 100644index c94e7e7504..0000000000--- a/pkg/querybuilder/clickhouse_quote.go+++ /dev/null@@ -1,17 +0,0 @@-package querybuilder--import "strings"--// ClickHouseStringLiteral quotes a value for a ClickHouse string literal.-func ClickHouseStringLiteral(value string) string {- escaped := strings.ReplaceAll(value, `\`, `\\`)- escaped = strings.ReplaceAll(escaped, `'`, `\'`)- return "'" + escaped + "'"-}--// ClickHouseIdentifier quotes a value for a ClickHouse identifier.-func ClickHouseIdentifier(value string) string {- escaped := strings.ReplaceAll(value, `\`, `\\`)- escaped = strings.ReplaceAll(escaped, "`", "\\`")- return "`" + escaped + "`"-}diff --git a/pkg/querybuilder/clickhouse_quote_test.go b/pkg/querybuilder/clickhouse_quote_test.godeleted file mode 100644index 6181c869f8..0000000000--- a/pkg/querybuilder/clickhouse_quote_test.go+++ /dev/null@@ -1,17 +0,0 @@-package querybuilder--import (- "testing"-- "github.com/stretchr/testify/assert"-)--func TestClickHouseQuoting(t *testing.T) {- t.Run("string literal", func(t *testing.T) {- assert.Equal(t, `'name\'\\); SELECT 1 --'`, ClickHouseStringLiteral(`name'\); SELECT 1 --`))- })-- t.Run("identifier", func(t *testing.T) {- assert.Equal(t, "`name\\`\\\\); SELECT 1 --`", ClickHouseIdentifier("name`\\); SELECT 1 --"))- })-}diff --git a/pkg/querybuilder/exists_expr.go b/pkg/querybuilder/exists_expr.goindex bc1ec70ca5..1f87441634 100644--- a/pkg/querybuilder/exists_expr.go+++ b/pkg/querybuilder/exists_expr.go@@ -4,6 +4,7 @@ import ("fmt"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes"@@ -43,7 +44,7 @@ func ExistsExpression(columns []*schema.Column, key *telemetrytypes.TelemetryFieif len(evolutionsEntries) > 0 && evolutionsEntries[0] != nil {columnName = evolutionsEntries[0].ColumnName}- rawPath := fmt.Sprintf("%s.`%s`", columnName, key.Name)+ rawPath := fmt.Sprintf("%s.%s", columnName, clickhousesql.Identifier(key.Name))if exists {return rawPath + " IS NOT NULL", nil}@@ -88,7 +89,7 @@ func ExistsExpression(columns []*schema.Column, key *telemetrytypes.TelemetryFieswitch valueType := column.Type.(schema.MapColumnType).ValueType; valueType.GetType() {case schema.ColumnTypeEnumString, schema.ColumnTypeEnumBool, schema.ColumnTypeEnumFloat64:- leftOperand := fmt.Sprintf("mapContains(%s, '%s')", column.Name, key.Name)+ leftOperand := fmt.Sprintf("mapContains(%s, %s)", column.Name, clickhousesql.StringLiteral(key.Name))if key.Materialized {leftOperand = telemetrytypes.FieldKeyToMaterializedColumnNameForExists(key)}diff --git a/pkg/querybuilder/fallback_expr.go b/pkg/querybuilder/fallback_expr.goindex 6516c2c61c..c3918dabf3 100644--- a/pkg/querybuilder/fallback_expr.go+++ b/pkg/querybuilder/fallback_expr.go@@ -9,14 +9,16 @@ import ("strconv"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/huandu/go-sqlbuilder")func GroupByKeys(keys []qbtypes.GroupByKey) []string {- k := []string{}+ k := make([]string, 0, len(keys))for _, key := range keys {- k = append(k, "`"+key.Name+"`")+ k = append(k, sqlbuilder.Escape(clickhousesql.Identifier(key.Name)))}return k}diff --git a/pkg/querybuilder/where_clause_normalizer.go b/pkg/querybuilder/where_clause_normalizer.goindex 44f9ad8aba..9308c5e4ed 100644--- a/pkg/querybuilder/where_clause_normalizer.go+++ b/pkg/querybuilder/where_clause_normalizer.go@@ -406,14 +406,14 @@ func (visitor *whereClauseNormalizer) visitFullText(ctx grammar.IFullTextContextfunc (visitor *whereClauseNormalizer) fullTextTerm(term string) string {visitor.appendCondition("", WhereClauseOperatorFullText, []string{term})- return quoteValue(term)+ return FilterStringLiteral(term)}func (visitor *whereClauseNormalizer) normalizeValue(ctx grammar.IValueContext) normalizedValue {switch {case ctx.QUOTED_TEXT() != nil:raw := trimQuotes(ctx.QUOTED_TEXT().GetText())- return normalizedValue{text: quoteValue(raw), raw: raw}+ return normalizedValue{text: FilterStringLiteral(raw), raw: raw}case ctx.NUMBER() != nil:text := ctx.NUMBER().GetText()return normalizedValue{text: text, raw: text}@@ -425,7 +425,7 @@ func (visitor *whereClauseNormalizer) normalizeValue(ctx grammar.IValueContext)if strings.HasPrefix(raw, "$") {return normalizedValue{text: raw, raw: raw}}- return normalizedValue{text: quoteValue(raw), raw: raw}+ return normalizedValue{text: FilterStringLiteral(raw), raw: raw}}}@@ -522,7 +522,7 @@ func (visitor *whereClauseNormalizer) resolveVariable(raw string) (qbtypes.Variafunc formatVariableValue(value any) normalizedValue {switch typed := value.(type) {case string:- return normalizedValue{text: quoteValue(typed), raw: typed}+ return normalizedValue{text: FilterStringLiteral(typed), raw: typed}case bool:text := strconv.FormatBool(typed)return normalizedValue{text: text, raw: text}@@ -537,7 +537,9 @@ func normalizeKeyText(keyText string) string {return telemetrytypes.TelemetryFieldKeyToText(&fieldKey)}-func quoteValue(value string) string {+// FilterStringLiteral quotes value for the filter expression grammar, not for+// ClickHouse: the grammar's quoted text takes backslash escapes and no hex escapes.+func FilterStringLiteral(value string) string {escaped := strings.ReplaceAll(value, `\`, `\\`)escaped = strings.ReplaceAll(escaped, `'`, `\'`)return "'" + escaped + "'"diff --git a/pkg/querybuilder/where_clause_normalizer_test.go b/pkg/querybuilder/where_clause_normalizer_test.goindex 297dba95d1..39b8e8b66b 100644--- a/pkg/querybuilder/where_clause_normalizer_test.go+++ b/pkg/querybuilder/where_clause_normalizer_test.go@@ -419,3 +419,23 @@ func TestNormalizeWhereClauseVariablesEmptyList(t *testing.T) {_, err := NormalizeWhereClause("status IN $statuses", variables)require.Error(t, err)}++func TestFilterStringLiteral(t *testing.T) {+ testCases := []struct {+ name string+ input string+ expected string+ }{+ {name: "Plain", input: "svc", expected: `'svc'`},+ {name: "SingleQuote", input: "a'b", expected: `'a\'b'`},+ {name: "TrailingBackslash", input: `a\`, expected: `'a\\'`},+ {name: "DollarDigit_Unchanged", input: "a$0b", expected: `'a$0b'`},+ {name: "Injection", input: "x' OR '1'='1", expected: `'x\' OR \'1\'=\'1'`},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Equal(t, testCase.expected, FilterStringLiteral(testCase.input))+ })+ }+}diff --git a/pkg/statementbuilder/auditstatementbuilder/statement_builder.go b/pkg/statementbuilder/auditstatementbuilder/statement_builder.goindex 5da0394c8d..0a140a3a59 100644--- a/pkg/statementbuilder/auditstatementbuilder/statement_builder.go+++ b/pkg/statementbuilder/auditstatementbuilder/statement_builder.go@@ -6,6 +6,7 @@ import ("log/slog""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/flagger"@@ -346,9 +347,9 @@ func (b *auditQueryStatementBuilder) buildTimeSeriesQuery(return nil, err}- colExpr := fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), gb.Name)+ colExpr := sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, clickhousesql.Identifier(gb.Name)))sb.SelectMore(colExpr)- fieldNames = append(fieldNames, fmt.Sprintf("`%s`", gb.Name))+ fieldNames = append(fieldNames, sqlbuilder.Escape(clickhousesql.Identifier(gb.Name)))}allAggChArgs := make([]any, 0)@@ -399,7 +400,7 @@ func (b *auditQueryStatementBuilder) buildTimeSeriesQuery(for _, orderBy := range query.Order {_, ok := aggOrderBy(orderBy, query)if !ok {- sb.OrderBy(fmt.Sprintf("`%s` %s", orderBy.Key.Name, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(clickhousesql.Identifier(orderBy.Key.Name)), orderBy.Direction.StringValue()))}}sb.OrderBy("ts desc")@@ -426,7 +427,7 @@ func (b *auditQueryStatementBuilder) buildTimeSeriesQuery(for _, orderBy := range query.Order {_, ok := aggOrderBy(orderBy, query)if !ok {- sb.OrderBy(fmt.Sprintf("`%s` %s", orderBy.Key.Name, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(clickhousesql.Identifier(orderBy.Key.Name)), orderBy.Direction.StringValue()))}}sb.OrderBy("ts desc")@@ -481,7 +482,7 @@ func (b *auditQueryStatementBuilder) buildScalarQuery(return nil, err}- colExpr := fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), gb.Name)+ colExpr := sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, clickhousesql.Identifier(gb.Name)))sb.SelectMore(colExpr)}@@ -522,7 +523,7 @@ func (b *auditQueryStatementBuilder) buildScalarQuery(if ok {sb.OrderBy(fmt.Sprintf("__result_%d %s", idx, orderBy.Direction.StringValue()))} else {- sb.OrderBy(fmt.Sprintf("`%s` %s", orderBy.Key.Name, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(clickhousesql.Identifier(orderBy.Key.Name)), orderBy.Direction.StringValue()))}}diff --git a/pkg/statementbuilder/logsstatementbuilder/statement_builder.go b/pkg/statementbuilder/logsstatementbuilder/statement_builder.goindex d698caccd9..19deff28a3 100644--- a/pkg/statementbuilder/logsstatementbuilder/statement_builder.go+++ b/pkg/statementbuilder/logsstatementbuilder/statement_builder.go@@ -6,6 +6,7 @@ import ("log/slog""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/flagger"@@ -368,7 +369,7 @@ func (b *logQueryStatementBuilder) buildListQuery(if err != nil {return nil, err}- sb.SelectMore(fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(colExpr), selectColumnAlias(index, query.SelectFields[index].Name)))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("%s AS %s", colExpr, selectColumnAlias(index, query.SelectFields[index].Name))))}}@@ -459,8 +460,8 @@ func (b *logQueryStatementBuilder) buildTimeSeriesQuery(}fieldAlias := groupByColumnAlias(i, gb.Name)- sb.SelectMore(fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), fieldAlias))- fieldNames = append(fieldNames, fmt.Sprintf("`%s`", fieldAlias))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, fieldAlias)))+ fieldNames = append(fieldNames, sqlbuilder.Escape(fieldAlias))}// Aggregations@@ -522,11 +523,11 @@ func (b *logQueryStatementBuilder) buildTimeSeriesQuery(for _, orderBy := range query.Order {_, ok := aggOrderBy(orderBy, query)if !ok {- orderCol := orderBy.Key.Name+ orderCol := clickhousesql.Identifier(orderBy.Key.Name)if alias, ok := groupByOrderAlias(orderBy.Key.Name, query.GroupBy); ok {orderCol = alias}- sb.OrderBy(fmt.Sprintf("`%s` %s", orderCol, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderCol), orderBy.Direction.StringValue()))}}sb.OrderBy("ts desc")@@ -555,11 +556,11 @@ func (b *logQueryStatementBuilder) buildTimeSeriesQuery(for _, orderBy := range query.Order {_, ok := aggOrderBy(orderBy, query)if !ok {- orderCol := orderBy.Key.Name+ orderCol := clickhousesql.Identifier(orderBy.Key.Name)if alias, ok := groupByOrderAlias(orderBy.Key.Name, query.GroupBy); ok {orderCol = alias}- sb.OrderBy(fmt.Sprintf("`%s` %s", orderCol, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderCol), orderBy.Direction.StringValue()))}}sb.OrderBy("ts desc")@@ -624,8 +625,8 @@ func (b *logQueryStatementBuilder) buildScalarQuery(}fieldAlias := groupByColumnAlias(i, gb.Name)- sb.SelectMore(fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), fieldAlias))- fieldNames = append(fieldNames, fmt.Sprintf("`%s`", fieldAlias))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, fieldAlias)))+ fieldNames = append(fieldNames, sqlbuilder.Escape(fieldAlias))}// for scalar queries, the rate would be end-start@@ -676,11 +677,11 @@ func (b *logQueryStatementBuilder) buildScalarQuery(if ok {sb.OrderBy(fmt.Sprintf("__result_%d %s", idx, orderBy.Direction.StringValue()))} else {- orderCol := orderBy.Key.Name+ orderCol := clickhousesql.Identifier(orderBy.Key.Name)if alias, ok := groupByOrderAlias(orderBy.Key.Name, query.GroupBy); ok {orderCol = alias}- sb.OrderBy(fmt.Sprintf("`%s` %s", orderCol, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderCol), orderBy.Direction.StringValue()))}}@@ -781,11 +782,11 @@ func aggOrderBy(k qbtypes.OrderBy, q qbtypes.QueryBuilderQuery[qbtypes.LogAggreg}func groupByColumnAlias(i int, name string) string {- return fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, name)+ return clickhousesql.Identifier(fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, name))}func selectColumnAlias(i int, name string) string {- return fmt.Sprintf("__SELECT_KEY_%d_%s", i, name)+ return clickhousesql.Identifier(fmt.Sprintf("__SELECT_KEY_%d_%s", i, name))}func groupByOrderAlias(orderKey string, groupBy []qbtypes.GroupByKey) (string, bool) {diff --git a/pkg/statementbuilder/meterstatementbuilder/statement_builder.go b/pkg/statementbuilder/meterstatementbuilder/statement_builder.goindex 14edeccba2..84ed893780 100644--- a/pkg/statementbuilder/meterstatementbuilder/statement_builder.go+++ b/pkg/statementbuilder/meterstatementbuilder/statement_builder.go@@ -155,7 +155,7 @@ func (b *meterQueryStatementBuilder) buildTemporalAggDeltaFastPath(if err != nil {return "", nil, err}- sb.SelectMore(fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(col), metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("%s AS %s", col, metricsstatementbuilder.GroupByColumnAlias(i, g.Name))))}tbl := metertelemetryschema.WhichSamplesTableToUse(start, end, query.Aggregations[0].Type, query.Aggregations[0].TimeAggregation, query.Aggregations[0].TableHints)@@ -244,7 +244,7 @@ func (b *meterQueryStatementBuilder) buildTemporalAggDelta(if err != nil {return "", nil, err}- sb.SelectMore(fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(col), metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("%s AS %s", col, metricsstatementbuilder.GroupByColumnAlias(i, g.Name))))}tbl := metertelemetryschema.WhichSamplesTableToUse(start, end, query.Aggregations[0].Type, query.Aggregations[0].TimeAggregation, query.Aggregations[0].TableHints)@@ -322,7 +322,7 @@ func (b *meterQueryStatementBuilder) buildTemporalAggCumulativeOrUnspecified(if err != nil {return "", nil, err}- baseSb.SelectMore(fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(col), metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))+ baseSb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("%s AS %s", col, metricsstatementbuilder.GroupByColumnAlias(i, g.Name))))}tbl := metertelemetryschema.WhichSamplesTableToUse(start, end, query.Aggregations[0].Type, query.Aggregations[0].TimeAggregation, query.Aggregations[0].TableHints)@@ -373,7 +373,7 @@ func (b *meterQueryStatementBuilder) buildTemporalAggCumulativeOrUnspecified(wrapped := sqlbuilder.NewSelectBuilder()wrapped.Select("ts")for i, g := range query.GroupBy {- wrapped.SelectMore(fmt.Sprintf("`%s`", metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))+ wrapped.SelectMore(sqlbuilder.Escape(metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))}wrapped.SelectMore(fmt.Sprintf("%s AS per_series_value", metricsstatementbuilder.RateTmpl))wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", innerQuery))@@ -384,7 +384,7 @@ func (b *meterQueryStatementBuilder) buildTemporalAggCumulativeOrUnspecified(wrapped := sqlbuilder.NewSelectBuilder()wrapped.Select("ts")for i, g := range query.GroupBy {- wrapped.SelectMore(fmt.Sprintf("`%s`", metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))+ wrapped.SelectMore(sqlbuilder.Escape(metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))}wrapped.SelectMore(fmt.Sprintf("%s AS per_series_value", metricsstatementbuilder.IncreaseTmpl))wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", innerQuery))@@ -414,7 +414,7 @@ func (b *meterQueryStatementBuilder) buildSpatialAggregationCTE(sb.Select("ts")for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(metricsstatementbuilder.GroupByColumnAlias(i, g.Name)))}sb.SelectMore(fmt.Sprintf("%s(per_series_value) AS value", query.Aggregations[0].SpaceAggregation.StringValue()))sb.From("__temporal_aggregation_cte")diff --git a/pkg/statementbuilder/metricsstatementbuilder/statement_builder.go b/pkg/statementbuilder/metricsstatementbuilder/statement_builder.goindex 3804302a49..88d3b06a44 100644--- a/pkg/statementbuilder/metricsstatementbuilder/statement_builder.go+++ b/pkg/statementbuilder/metricsstatementbuilder/statement_builder.go@@ -7,6 +7,7 @@ import ("slices""time"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/flagger""github.com/SigNoz/signoz/pkg/querybuilder"@@ -234,7 +235,7 @@ func (b *StatementBuilder) buildPipelineStatement(func unionStatements(main, reduced *qbtypes.Statement, query qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]) (*qbtypes.Statement, error) {orderBy := "ts"for i, g := range query.GroupBy {- orderBy = fmt.Sprintf("`%s`, ", GroupByColumnAlias(i, g.Name)) + orderBy+ orderBy = GroupByColumnAlias(i, g.Name) + ", " + orderBy}q := fmt.Sprintf("SELECT * FROM (%s) UNION ALL SELECT * FROM (%s) ORDER BY %s SETTINGS do_not_merge_across_partitions_select_final = 1, optimize_move_to_prewhere_if_final = 1",@@ -282,7 +283,7 @@ func (b *StatementBuilder) buildReducedTimeSeriesCTE(if err != nil {return "", nil, err}- sb.SelectMore(fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(col), GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("%s AS %s", col, GroupByColumnAlias(i, g.Name))))}sb.Where(sb.In("metric_name", query.Aggregations[0].MetricName),@@ -297,7 +298,8 @@ func (b *StatementBuilder) buildReducedTimeSeriesCTE(sb.GroupBy(GroupByAliases(query.GroupBy)...)q, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)- return fmt.Sprintf("(%s) AS filtered_time_series", q), args, nil+ // the caller joins this into another builder, which compiles it again+ return fmt.Sprintf("(%s) AS filtered_time_series", sqlbuilder.Escape(q)), args, nil}// buildReducedSpatialAggFastPath is the reduced analog of@@ -323,7 +325,7 @@ func (b *StatementBuilder) buildReducedSpatialAggFastPath(sb := sqlbuilder.NewSelectBuilder()sb.Select(fmt.Sprintf("toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), toIntervalSecond(%d)) AS ts", stepSec))for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}sb.SelectMore(fmt.Sprintf("%s AS value", metricstelemetryschema.ReducedTimeAggregationColumn(agg.TimeAggregation, stepSec, value)))sb.From(fmt.Sprintf("%s.%s AS points FINAL", metricstelemetryschema.DBName, metricstelemetryschema.WhichReducedSamplesTableToUse(agg.Type)))@@ -360,7 +362,7 @@ func (b *StatementBuilder) buildReducedTemporalAggregationCTE(sb.Select("points.reduced_fingerprint AS fingerprint")sb.SelectMore(fmt.Sprintf("toStartOfInterval(toDateTime(intDiv(unix_milli, 1000)), toIntervalSecond(%d)) AS ts", stepSec))for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}sb.SelectMore(fmt.Sprintf("%s AS per_series_value", metricstelemetryschema.ReducedTimeAggregationColumn(agg.TimeAggregation, stepSec, value)))if weight != "" {@@ -398,7 +400,7 @@ func (b *StatementBuilder) buildReducedSpatialAggregationCTE(sb := sqlbuilder.NewSelectBuilder()sb.Select("ts")for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}sb.SelectMore(spatial + " AS value")sb.From("__temporal_aggregation_cte")@@ -425,7 +427,7 @@ func (b *StatementBuilder) buildTemporalAggDeltaFastPath(stepSec,))for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}var aggCol string@@ -504,7 +506,7 @@ func (b *StatementBuilder) buildTimeSeriesCTE(if err != nil {return "", nil, nil, err}- sb.SelectMore(fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(col), GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("%s AS %s", col, GroupByColumnAlias(i, g.Name))))}sb.Where(@@ -531,7 +533,8 @@ func (b *StatementBuilder) buildTimeSeriesCTE(sb.GroupBy(GroupByAliases(query.GroupBy)...)q, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)- return fmt.Sprintf("(%s) AS filtered_time_series", q), args, preparedWhereClause.Warnings, nil+ // the caller joins this into another builder, which compiles it again+ return fmt.Sprintf("(%s) AS filtered_time_series", sqlbuilder.Escape(q)), args, preparedWhereClause.Warnings, nil}func (b *StatementBuilder) buildTemporalAggregationCTE(@@ -569,7 +572,7 @@ func (b *StatementBuilder) buildTemporalAggDelta(stepSec,))for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}aggCol, err := metricstelemetryschema.AggregationColumnForSamplesTable(samplesTable, query.Aggregations[0].Temporality, query.Aggregations[0].TimeAggregation)@@ -615,7 +618,7 @@ func (b *StatementBuilder) buildTemporalAggCumulativeOrUnspecified(stepSec,))for i, g := range query.GroupBy {- baseSb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ baseSb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}aggCol, err := metricstelemetryschema.AggregationColumnForSamplesTable(samplesTable, query.Aggregations[0].Temporality, query.Aggregations[0].TimeAggregation)@@ -642,10 +645,10 @@ func (b *StatementBuilder) buildTemporalAggCumulativeOrUnspecified(wrapped := sqlbuilder.NewSelectBuilder()wrapped.Select("ts")for i, g := range query.GroupBy {- wrapped.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ wrapped.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}wrapped.SelectMore(fmt.Sprintf("%s AS per_series_value", RateTmpl))- wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", innerQuery))+ wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", sqlbuilder.Escape(innerQuery)))q, args := wrapped.BuildWithFlavor(sqlbuilder.ClickHouse, innerArgs...)return fmt.Sprintf("__temporal_aggregation_cte AS (%s)", q), args, nil@@ -653,10 +656,10 @@ func (b *StatementBuilder) buildTemporalAggCumulativeOrUnspecified(wrapped := sqlbuilder.NewSelectBuilder()wrapped.Select("ts")for i, g := range query.GroupBy {- wrapped.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ wrapped.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}wrapped.SelectMore(fmt.Sprintf("%s AS per_series_value", IncreaseTmpl))- wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", innerQuery))+ wrapped.From(fmt.Sprintf("(%s) WINDOW rate_window AS (PARTITION BY fingerprint ORDER BY fingerprint, ts)", sqlbuilder.Escape(innerQuery)))q, args := wrapped.BuildWithFlavor(sqlbuilder.ClickHouse, innerArgs...)return fmt.Sprintf("__temporal_aggregation_cte AS (%s)", q), args, nildefault:@@ -680,7 +683,7 @@ func (b *StatementBuilder) buildTemporalAggForMultipleTemporalities(stepSec,))for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}aggForDeltaTemporality, err := metricstelemetryschema.AggregationColumnForSamplesTable(samplesTable, metrictypes.Delta, query.Aggregations[0].TimeAggregation)@@ -740,7 +743,7 @@ func (b *StatementBuilder) buildSpatialAggregationCTE(sb.Select("ts")for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}sb.SelectMore(fmt.Sprintf("%s(per_series_value) AS value", query.Aggregations[0].SpaceAggregation.StringValue()))sb.From("__temporal_aggregation_cte")@@ -776,7 +779,7 @@ func (b *StatementBuilder) BuildFinalSelect(quantile := query.Aggregations[0].SpaceAggregation.Percentile()sb.Select("ts")for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}sb.SelectMore(fmt.Sprintf("histogramQuantile(arrayMap(x -> toFloat64(x), groupArray(le)), groupArray(value), %.3f) AS value",@@ -797,7 +800,7 @@ func (b *StatementBuilder) BuildFinalSelect(sb.Select("ts")for i, g := range query.GroupBy {- sb.SelectMore(fmt.Sprintf("`%s`", GroupByColumnAlias(i, g.Name)))+ sb.SelectMore(sqlbuilder.Escape(GroupByColumnAlias(i, g.Name)))}aggQuery, err := metricstelemetryschema.AggregationQueryForHistogramCountWithParams(query.Aggregations[0].ComparisonSpaceAggregationParam)@@ -864,15 +867,15 @@ func histogramCTEQuery(query qbtypes.QueryBuilderQuery[qbtypes.MetricAggregationfunc GroupByColumnAlias(i int, name string) string {if name == histogramBucketKey {- return histogramBucketKey+ return clickhousesql.Identifier(histogramBucketKey)}- return fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, name)+ return clickhousesql.Identifier(fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, name))}func GroupByAliases(groupBy []qbtypes.GroupByKey) []string {aliases := make([]string, 0, len(groupBy))for i := range groupBy {- aliases = append(aliases, fmt.Sprintf("`%s`", GroupByColumnAlias(i, groupBy[i].Name)))+ aliases = append(aliases, sqlbuilder.Escape(GroupByColumnAlias(i, groupBy[i].Name)))}return aliases}diff --git a/pkg/statementbuilder/resourcefilter/condition_builder.go b/pkg/statementbuilder/resourcefilter/condition_builder.goindex 5529542111..ad506d8a8d 100644--- a/pkg/statementbuilder/resourcefilter/condition_builder.go+++ b/pkg/statementbuilder/resourcefilter/condition_builder.go@@ -4,6 +4,7 @@ import ("context""fmt"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/flagger""github.com/SigNoz/signoz/pkg/querybuilder"@@ -96,7 +97,7 @@ func valueIndexCondition(func memberPresenceCondition(sb *sqlbuilder.SelectBuilder, column string, members []*telemetrytypes.TelemetryFieldKey, exists bool) string {conditions := make([]string, 0, len(members))for _, member := range members {- field := fmt.Sprintf("simpleJSONHas(%s, '%s')", column, member.Name)+ field := fmt.Sprintf("simpleJSONHas(%s, %s)", column, clickhousesql.StringLiteral(member.Name))if exists {conditions = append(conditions, sb.E(field, true))} else {diff --git a/pkg/statementbuilder/resourcefilter/field_mapper.go b/pkg/statementbuilder/resourcefilter/field_mapper.goindex 0791a69be0..039ecd824b 100644--- a/pkg/statementbuilder/resourcefilter/field_mapper.go+++ b/pkg/statementbuilder/resourcefilter/field_mapper.go@@ -5,9 +5,11 @@ import ("fmt"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes""github.com/SigNoz/signoz/pkg/valuer"+ "github.com/huandu/go-sqlbuilder")var (@@ -66,7 +68,7 @@ func (m *defaultFieldMapper) FieldFor(return "", err}if key.FieldContext == telemetrytypes.FieldContextResource {- return fmt.Sprintf("simpleJSONExtractString(%s, '%s')", columns[0].Name, key.Name), nil+ return fmt.Sprintf("simpleJSONExtractString(%s, %s)", columns[0].Name, clickhousesql.StringLiteral(key.Name)), nil}return columns[0].Name, nil}@@ -91,7 +93,7 @@ func (m *defaultFieldMapper) ExistsFor(}return "false", nil}- pred := fmt.Sprintf("simpleJSONHas(%s, '%s')", columns[0].Name, key.Name)+ pred := fmt.Sprintf("simpleJSONHas(%s, %s)", columns[0].Name, clickhousesql.StringLiteral(key.Name))if exists {return pred, nil}@@ -110,5 +112,5 @@ func (m *defaultFieldMapper) ColumnExpressionFor(if err != nil {return "", err}- return fmt.Sprintf("%s AS `%s`", fieldExpression, key.Name), nil+ return sqlbuilder.Escape(fmt.Sprintf("%s AS %s", fieldExpression, clickhousesql.Identifier(key.Name))), nil}diff --git a/pkg/statementbuilder/scopedtracesstatementbuilder/statement_builder.go b/pkg/statementbuilder/scopedtracesstatementbuilder/statement_builder.goindex e88cc24124..9016908c37 100644--- a/pkg/statementbuilder/scopedtracesstatementbuilder/statement_builder.go+++ b/pkg/statementbuilder/scopedtracesstatementbuilder/statement_builder.go@@ -4,8 +4,10 @@ import ("context""fmt""log/slog"+ "regexp""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/flagger"@@ -522,7 +524,7 @@ func (b *scopedTraceStatementBuilder) buildMatchedCTE(sb *sqlbuilder.SelectBuildif _, ok := needed[rc.alias]; !ok {continue}- selects = append(selects, rc.expr+" AS "+quoteAlias(rc.alias))+ selects = append(selects, rc.expr+" AS "+sqlbuilder.Escape(quoteAlias(rc.alias)))}sb.Select(selects...)sb.From(fmt.Sprintf("%s.%s", tracestelemetryschema.DBName, tracestelemetryschema.SpanIndexV3TableName))@@ -595,7 +597,7 @@ func (b *scopedTraceStatementBuilder) buildRankedCTE(start, end uint64) (string,func (b *scopedTraceStatementBuilder) buildEnrichmentSelect(sb *sqlbuilder.SelectBuilder, resolved []resolvedColumn, orders []listOrder) (string, []any) {selects := []string{"trace_id"}for _, rc := range resolved {- selects = append(selects, rc.expr+" AS "+quoteAlias(rc.alias))+ selects = append(selects, rc.expr+" AS "+sqlbuilder.Escape(quoteAlias(rc.alias)))}sb.Select(selects...)sb.From(fmt.Sprintf("%s.%s", tracestelemetryschema.DBName, tracestelemetryschema.SpanIndexV3TableName))@@ -660,7 +662,7 @@ func validateAggregateFilter(havingExpr string, filterableSet map[string]struct{func orderClause(orders []listOrder) []string {out := make([]string, 0, len(orders)+1)for _, o := range orders {- out = append(out, fmt.Sprintf("%s %s", quoteAlias(o.alias), o.direction))+ out = append(out, fmt.Sprintf("%s %s", sqlbuilder.Escape(quoteAlias(o.alias)), o.direction))}return append(out, "trace_id DESC")}@@ -678,10 +680,12 @@ func spanFilterSelectors(expr string) []*telemetrytypes.FieldKeySelector {return selectors}-// quoteAlias backticks an alias containing characters special to the SQL builder.+var bareIdentifier = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)++// quoteAlias leaves an alias bare when ClickHouse accepts it unquoted.func quoteAlias(alias string) string {- if strings.ContainsAny(alias, ".$`") {- return "`" + alias + "`"+ if bareIdentifier.MatchString(alias) {+ return alias}- return alias+ return clickhousesql.Identifier(alias)}diff --git a/pkg/statementbuilder/scopedtracesstatementbuilder/trace_aggregation.go b/pkg/statementbuilder/scopedtracesstatementbuilder/trace_aggregation.goindex bdb7f125da..55281dfe5b 100644--- a/pkg/statementbuilder/scopedtracesstatementbuilder/trace_aggregation.go+++ b/pkg/statementbuilder/scopedtracesstatementbuilder/trace_aggregation.go@@ -7,6 +7,7 @@ import ("strings"chparser "github.com/AfterShip/clickhouse-sql-parser/parser"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetryschema/tracestelemetryschema"@@ -377,7 +378,7 @@ type groupColumn struct {// groupByColumnAlias prefixes the i-th group-by dimension so the alias cannot shadow the// span column its expression reads; the querier (stripKeyAlias) strips it back off.func groupByColumnAlias(i int, name string) string {- return fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, name)+ return clickhousesql.Identifier(fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, name))}// orderColumn is the SQL identifier a non-aggregation order key sorts by: the@@ -388,7 +389,7 @@ func orderColumn(orderKey string, groupBy []qbtypes.GroupByKey) string {return groupByColumnAlias(i, groupBy[i].Name)}}- return orderKey+ return clickhousesql.Identifier(orderKey)}// perTraceScanOpts parametrize one windowed, mask-pruned GROUP BY trace_id scan.@@ -413,13 +414,13 @@ func (b *scopedTraceStatementBuilder) buildPerTraceScan(sb *sqlbuilder.SelectBuiselects = append(selects, fmt.Sprintf("toStartOfInterval(timestamp, INTERVAL %d SECOND) AS ts", o.stepSeconds))}for _, gc := range o.groupCols {- selects = append(selects, fmt.Sprintf("toString(%s) AS `%s`", gc.expr, gc.alias))+ selects = append(selects, fmt.Sprintf("toString(%s) AS %s", gc.expr, sqlbuilder.Escape(gc.alias)))}for _, rc := range resolved {if _, ok := o.needed[rc.alias]; !ok {continue}- selects = append(selects, rc.expr+" AS "+quoteAlias(rc.alias))+ selects = append(selects, rc.expr+" AS "+sqlbuilder.Escape(quoteAlias(rc.alias)))}sb.Select(selects...)sb.From(fmt.Sprintf("%s.%s", tracestelemetryschema.DBName, tracestelemetryschema.SpanIndexV3TableName))@@ -450,7 +451,7 @@ func (b *scopedTraceStatementBuilder) buildPerTraceScan(sb *sqlbuilder.SelectBuigroupBy = append(groupBy, "ts")}for _, gc := range o.groupCols {- groupBy = append(groupBy, "`"+gc.alias+"`")+ groupBy = append(groupBy, sqlbuilder.Escape(gc.alias))}sb.GroupBy(groupBy...)if strings.TrimSpace(o.havingPred) != "" {@@ -602,7 +603,7 @@ func (b *scopedTraceStatementBuilder) buildTraceAggregationQuery(}groupNames := make([]string, 0, len(groupCols))for _, gc := range groupCols {- groupNames = append(groupNames, "`"+gc.alias+"`")+ groupNames = append(groupNames, sqlbuilder.Escape(gc.alias))}needed := make(map[string]struct{})@@ -701,7 +702,7 @@ func (b *scopedTraceStatementBuilder) buildTraceAggregationQuery(if len(query.Order) != 0 {for _, orderBy := range query.Order {if _, ok := traceAggOrderIndex(orderBy, query); !ok {- sb.OrderBy(fmt.Sprintf("`%s` %s", orderColumn(orderBy.Key.Name, query.GroupBy), orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderColumn(orderBy.Key.Name, query.GroupBy)), orderBy.Direction.StringValue()))}}sb.OrderBy("ts desc")@@ -711,7 +712,7 @@ func (b *scopedTraceStatementBuilder) buildTraceAggregationQuery(if idx, ok := traceAggOrderIndex(orderBy, query); ok {sb.OrderBy(fmt.Sprintf("__result_%d %s", idx, orderBy.Direction.StringValue()))} else {- sb.OrderBy(fmt.Sprintf("`%s` %s", orderColumn(orderBy.Key.Name, query.GroupBy), orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderColumn(orderBy.Key.Name, query.GroupBy)), orderBy.Direction.StringValue()))}}if len(query.Order) == 0 {@@ -759,7 +760,7 @@ func outerLimitSQL(query qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation], trif idx, ok := traceAggOrderIndex(orderBy, query); ok {sb.OrderBy(fmt.Sprintf("__result_%d %s", idx, orderBy.Direction.StringValue()))} else {- sb.OrderBy(fmt.Sprintf("`%s` %s", orderColumn(orderBy.Key.Name, query.GroupBy), orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderColumn(orderBy.Key.Name, query.GroupBy)), orderBy.Direction.StringValue()))}}if len(query.Order) == 0 {diff --git a/pkg/statementbuilder/tracesstatementbuilder/statement_builder.go b/pkg/statementbuilder/tracesstatementbuilder/statement_builder.goindex 413d73bf37..de2c99e3e9 100644--- a/pkg/statementbuilder/tracesstatementbuilder/statement_builder.go+++ b/pkg/statementbuilder/tracesstatementbuilder/statement_builder.go@@ -6,6 +6,7 @@ import ("log/slog""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/flagger"@@ -387,7 +388,7 @@ func (b *traceQueryStatementBuilder) buildListQuery(if err != nil {return nil, err}- sb.SelectMore(fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(expr), selectColumnAlias(i, field.Name)))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("%s AS %s", expr, selectColumnAlias(i, field.Name))))}if isSelectFieldsEmpty {@@ -601,8 +602,8 @@ func (b *traceQueryStatementBuilder) buildTimeSeriesQuery(return nil, err}fieldAlias := groupByColumnAlias(i, gb.Name)- sb.SelectMore(fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), fieldAlias))- fieldNames = append(fieldNames, fmt.Sprintf("`%s`", fieldAlias))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, fieldAlias)))+ fieldNames = append(fieldNames, sqlbuilder.Escape(fieldAlias))}// Aggregations@@ -660,11 +661,11 @@ func (b *traceQueryStatementBuilder) buildTimeSeriesQuery(for _, orderBy := range query.Order {_, ok := aggOrderBy(orderBy, query)if !ok {- orderCol := orderBy.Key.Name+ orderCol := clickhousesql.Identifier(orderBy.Key.Name)if alias, ok := groupByOrderAlias(orderBy.Key.Name, query.GroupBy); ok {orderCol = alias}- sb.OrderBy(fmt.Sprintf("`%s` %s", orderCol, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderCol), orderBy.Direction.StringValue()))}}sb.OrderBy("ts desc")@@ -693,11 +694,11 @@ func (b *traceQueryStatementBuilder) buildTimeSeriesQuery(for _, orderBy := range query.Order {_, ok := aggOrderBy(orderBy, query)if !ok {- orderCol := orderBy.Key.Name+ orderCol := clickhousesql.Identifier(orderBy.Key.Name)if alias, ok := groupByOrderAlias(orderBy.Key.Name, query.GroupBy); ok {orderCol = alias}- sb.OrderBy(fmt.Sprintf("`%s` %s", orderCol, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderCol), orderBy.Direction.StringValue()))}}sb.OrderBy("ts desc")@@ -764,8 +765,8 @@ func (b *traceQueryStatementBuilder) buildScalarQuery(return nil, err}fieldAlias := groupByColumnAlias(i, gb.Name)- sb.SelectMore(fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), fieldAlias))- fieldNames = append(fieldNames, fmt.Sprintf("`%s`", fieldAlias))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, fieldAlias)))+ fieldNames = append(fieldNames, sqlbuilder.Escape(fieldAlias))}// for scalar queries, the rate would be end-start@@ -816,11 +817,11 @@ func (b *traceQueryStatementBuilder) buildScalarQuery(if ok {sb.OrderBy(fmt.Sprintf("__result_%d %s", idx, orderBy.Direction.StringValue()))} else {- orderCol := orderBy.Key.Name+ orderCol := clickhousesql.Identifier(orderBy.Key.Name)if alias, ok := groupByOrderAlias(orderBy.Key.Name, query.GroupBy); ok {orderCol = alias}- sb.OrderBy(fmt.Sprintf("`%s` %s", orderCol, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(orderCol), orderBy.Direction.StringValue()))}}@@ -914,13 +915,13 @@ func aggOrderBy(k qbtypes.OrderBy, q qbtypes.QueryBuilderQuery[qbtypes.TraceAggr// groupByColumnAlias returns the positional SQL alias for the i-th group-by dimension;// the querier (consume.go stripKeyAlias) strips the prefix to recover the field name.func groupByColumnAlias(i int, name string) string {- return fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, name)+ return clickhousesql.Identifier(fmt.Sprintf("__GROUP_BY_KEY_%d_%s", i, name))}// selectColumnAlias returns the positional SQL alias for the i-th raw select field. Like// groupByColumnAlias, the prefix is stripped by the querier.func selectColumnAlias(i int, name string) string {- return fmt.Sprintf("__SELECT_KEY_%d_%s", i, name)+ return clickhousesql.Identifier(fmt.Sprintf("__SELECT_KEY_%d_%s", i, name))}// groupByOrderAlias returns the group-by column alias to order by when orderKey names adiff --git a/pkg/statementbuilder/tracesstatementbuilder/trace_operator_cte_builder.go b/pkg/statementbuilder/tracesstatementbuilder/trace_operator_cte_builder.goindex 737edfe1aa..6bddf91986 100644--- a/pkg/statementbuilder/tracesstatementbuilder/trace_operator_cte_builder.go+++ b/pkg/statementbuilder/tracesstatementbuilder/trace_operator_cte_builder.go@@ -8,6 +8,7 @@ import ("github.com/huandu/go-sqlbuilder"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetryschema/tracestelemetryschema"@@ -498,7 +499,7 @@ func (b *traceOperatorCTEBuilder) buildListQuery(ctx context.Context, selectFromslog.String("field", field.Name), errors.Attr(err))continue}- sb.SelectMore(fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(expr), selectColumnAlias(i, field.Name)))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("%s AS %s", expr, selectColumnAlias(i, field.Name))))selectedFields[field.Name] = true}@@ -641,7 +642,7 @@ func (b *traceOperatorCTEBuilder) buildTimeSeriesQuery(ctx context.Context, seleerr,)}- sb.SelectMore(fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), gb.Name))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, clickhousesql.Identifier(gb.Name))))}var allAggChArgs []any@@ -676,7 +677,7 @@ func (b *traceOperatorCTEBuilder) buildTimeSeriesQuery(ctx context.Context, seleif len(b.operator.GroupBy) > 0 {groupByKeys := make([]string, len(b.operator.GroupBy))for i, gb := range b.operator.GroupBy {- groupByKeys[i] = fmt.Sprintf("`%s`", gb.Name)+ groupByKeys[i] = sqlbuilder.Escape(clickhousesql.Identifier(gb.Name))}sb.GroupBy(groupByKeys...)}@@ -687,7 +688,7 @@ func (b *traceOperatorCTEBuilder) buildTimeSeriesQuery(ctx context.Context, seleif ok {sb.OrderBy(fmt.Sprintf("__result_%d %s", idx, orderBy.Direction.StringValue()))} else {- sb.OrderBy(fmt.Sprintf("`%s` %s", orderBy.Key.Name, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(clickhousesql.Identifier(orderBy.Key.Name)), orderBy.Direction.StringValue()))}}sb.OrderBy("ts desc")@@ -737,7 +738,7 @@ func (b *traceOperatorCTEBuilder) buildTraceQuery(ctx context.Context, selectFroerr,)}- sb.SelectMore(fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), gb.Name))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, clickhousesql.Identifier(gb.Name))))}rateInterval := (b.end - b.start) / querybuilder.NsToSeconds@@ -789,7 +790,7 @@ func (b *traceOperatorCTEBuilder) buildTraceQuery(ctx context.Context, selectFroif len(b.operator.GroupBy) > 0 {groupByKeys := make([]string, len(b.operator.GroupBy))for i, gb := range b.operator.GroupBy {- groupByKeys[i] = fmt.Sprintf("`%s`", gb.Name)+ groupByKeys[i] = sqlbuilder.Escape(clickhousesql.Identifier(gb.Name))}sb.GroupBy(groupByKeys...)}@@ -863,7 +864,7 @@ func (b *traceOperatorCTEBuilder) buildScalarQuery(ctx context.Context, selectFrerr,)}- sb.SelectMore(fmt.Sprintf("toString(%s) AS `%s`", sqlbuilder.Escape(expr), gb.Name))+ sb.SelectMore(sqlbuilder.Escape(fmt.Sprintf("toString(%s) AS %s", expr, clickhousesql.Identifier(gb.Name))))}var allAggChArgs []any@@ -897,7 +898,7 @@ func (b *traceOperatorCTEBuilder) buildScalarQuery(ctx context.Context, selectFrif len(b.operator.GroupBy) > 0 {groupByKeys := make([]string, len(b.operator.GroupBy))for i, gb := range b.operator.GroupBy {- groupByKeys[i] = fmt.Sprintf("`%s`", gb.Name)+ groupByKeys[i] = sqlbuilder.Escape(clickhousesql.Identifier(gb.Name))}sb.GroupBy(groupByKeys...)}@@ -908,7 +909,7 @@ func (b *traceOperatorCTEBuilder) buildScalarQuery(ctx context.Context, selectFrif ok {sb.OrderBy(fmt.Sprintf("__result_%d %s", idx, orderBy.Direction.StringValue()))} else {- sb.OrderBy(fmt.Sprintf("`%s` %s", orderBy.Key.Name, orderBy.Direction.StringValue()))+ sb.OrderBy(fmt.Sprintf("%s %s", sqlbuilder.Escape(clickhousesql.Identifier(orderBy.Key.Name)), orderBy.Direction.StringValue()))}}diff --git a/pkg/telemetrymetadata/condition_builder.go b/pkg/telemetrymetadata/condition_builder.goindex cf956bfbce..de5020a236 100644--- a/pkg/telemetrymetadata/condition_builder.go+++ b/pkg/telemetrymetadata/condition_builder.go@@ -5,6 +5,7 @@ import ("fmt"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/querybuilder"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes"@@ -131,9 +132,9 @@ func (c *conditionBuilder) conditionForKey(cond = sb.NotILike(fieldExpression, fmt.Sprintf("%%%s%%", value))case qbtypes.FilterOperatorRegexp:- cond = fmt.Sprintf(`match(%s, %s)`, fieldExpression, sb.Var(value))+ cond = fmt.Sprintf(`match(%s, %s)`, sqlbuilder.Escape(fieldExpression), sb.Var(value))case qbtypes.FilterOperatorNotRegexp:- cond = fmt.Sprintf(`NOT match(%s, %s)`, fieldExpression, sb.Var(value))+ cond = fmt.Sprintf(`NOT match(%s, %s)`, sqlbuilder.Escape(fieldExpression), sb.Var(value))// in and not incase qbtypes.FilterOperatorIn:@@ -168,7 +169,7 @@ func (c *conditionBuilder) conditionForKey(KeyType: schema.LowCardinalityColumnType{ElementType: schema.ColumnTypeString},ValueType: schema.ColumnTypeString,}:- leftOperand := fmt.Sprintf("mapContains(%s, '%s')", columns[0].Name, key.Name)+ leftOperand := fmt.Sprintf("mapContains(%s, %s)", columns[0].Name, clickhousesql.StringLiteral(key.Name))if operator == qbtypes.FilterOperatorExists {cond = sb.E(leftOperand, true)} else {diff --git a/pkg/telemetrymetadata/field_mapper.go b/pkg/telemetrymetadata/field_mapper.goindex 45cb3fdde4..0fa3da9a5e 100644--- a/pkg/telemetrymetadata/field_mapper.go+++ b/pkg/telemetrymetadata/field_mapper.go@@ -6,6 +6,7 @@ import ("strings"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes"@@ -64,7 +65,7 @@ func (m *fieldMapper) ExistsFor(ctx context.Context, _ valuer.UUID, tsStart, tsEif err != nil {return "", err}- pred := fmt.Sprintf("mapContains(%s, '%s')", columns[0].Name, key.Name)+ pred := fmt.Sprintf("mapContains(%s, %s)", columns[0].Name, clickhousesql.StringLiteral(key.Name))if exists {return pred, nil}@@ -82,7 +83,7 @@ func (m *fieldMapper) FieldFor(ctx context.Context, _ valuer.UUID, startNs, endNKeyType: schema.LowCardinalityColumnType{ElementType: schema.ColumnTypeString},ValueType: schema.ColumnTypeString,}:- return fmt.Sprintf("%s['%s']", columns[0].Name, key.Name), nil+ return fmt.Sprintf("%s[%s]", columns[0].Name, clickhousesql.StringLiteral(key.Name)), nil}return columns[0].Name, nil}@@ -130,5 +131,5 @@ func (m *fieldMapper) ColumnExpressionFor(}}- return fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(fieldExpression), field.Name), nil+ return sqlbuilder.Escape(fmt.Sprintf("%s AS %s", fieldExpression, clickhousesql.Identifier(field.Name))), nil}diff --git a/pkg/telemetrymetadata/metadata.go b/pkg/telemetrymetadata/metadata.goindex 3eb66763c2..35059fbab0 100644--- a/pkg/telemetrymetadata/metadata.go+++ b/pkg/telemetrymetadata/metadata.go@@ -10,6 +10,7 @@ import ("github.com/huandu/go-sqlbuilder""golang.org/x/exp/maps"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/flagger"@@ -71,10 +72,6 @@ type telemetryMetaStore struct {jsonColumnMetadata map[telemetrytypes.Signal]map[telemetrytypes.FieldContext]telemetrytypes.JSONColumnMetadata}-func escapeForLike(s string) string {- return strings.ReplaceAll(strings.ReplaceAll(s, `_`, `\_`), `%`, `\%`)-}-func NewTelemetryMetaStore(settings factory.ProviderSettings,telemetrystore telemetrystore.TelemetryStore,@@ -203,7 +200,7 @@ func (t *telemetryMetaStore) getTracesKeys(ctx context.Context, fieldKeySelectorif fieldKeySelector.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {fieldKeyConds = append(fieldKeyConds, sb.E("tagKey", fieldKeySelector.Name))} else {- fieldKeyConds = append(fieldKeyConds, sb.ILike("tagKey", "%"+escapeForLike(fieldKeySelector.Name)+"%"))+ fieldKeyConds = append(fieldKeyConds, sb.ILike("tagKey", "%"+clickhousesql.LikePattern(fieldKeySelector.Name)+"%"))}// now look at the field context@@ -438,7 +435,7 @@ func (t *telemetryMetaStore) getLogsKeys(ctx context.Context, orgID valuer.UUID,if sel.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {fieldKeyConds = append(fieldKeyConds, sb.E("name", sel.Name))} else {- fieldKeyConds = append(fieldKeyConds, sb.ILike("name", "%"+escapeForLike(sel.Name)+"%"))+ fieldKeyConds = append(fieldKeyConds, sb.ILike("name", "%"+clickhousesql.LikePattern(sel.Name)+"%"))}if sel.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {fieldKeyConds = append(fieldKeyConds, sb.E("datatype", sel.FieldDataType.TagDataType()))@@ -486,7 +483,7 @@ func (t *telemetryMetaStore) getLogsKeys(ctx context.Context, orgID valuer.UUID,if sel.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {fieldKeyConds = append(fieldKeyConds, sb.E("field_name", sel.Name))} else {- fieldKeyConds = append(fieldKeyConds, sb.ILike("field_name", "%"+escapeForLike(sel.Name)+"%"))+ fieldKeyConds = append(fieldKeyConds, sb.ILike("field_name", "%"+clickhousesql.LikePattern(sel.Name)+"%"))}if sel.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {fieldKeyConds = append(fieldKeyConds, sb.E("field_data_type", sel.FieldDataType.StringValue()))@@ -728,7 +725,7 @@ func (t *telemetryMetaStore) getAuditKeys(ctx context.Context, fieldKeySelectorsif fieldKeySelector.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {fieldKeyConds = append(fieldKeyConds, sb.E("name", fieldKeySelector.Name))} else {- fieldKeyConds = append(fieldKeyConds, sb.ILike("name", "%"+escapeForLike(fieldKeySelector.Name)+"%"))+ fieldKeyConds = append(fieldKeyConds, sb.ILike("name", "%"+clickhousesql.LikePattern(fieldKeySelector.Name)+"%"))}if fieldKeySelector.FieldDataType != telemetrytypes.FieldDataTypeUnspecified {@@ -879,7 +876,7 @@ func (t *telemetryMetaStore) getMetricsKeys(ctx context.Context, fieldKeySelectoif fieldKeySelector.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {fieldConds = append(fieldConds, sb.E("attr_name", fieldKeySelector.Name))} else {- fieldConds = append(fieldConds, sb.ILike("attr_name", "%"+escapeForLike(fieldKeySelector.Name)+"%"))+ fieldConds = append(fieldConds, sb.ILike("attr_name", "%"+clickhousesql.LikePattern(fieldKeySelector.Name)+"%"))}fieldConds = append(fieldConds, sb.NotLike("attr_name", "\\_\\_%"))@@ -898,7 +895,7 @@ func (t *telemetryMetaStore) getMetricsKeys(ctx context.Context, fieldKeySelectofieldConds = append(fieldConds, sb.E("metric_name", fieldKeySelector.MetricContext.MetricName))}if fieldKeySelector.MetricContext.MetricNamespace != "" {- fieldConds = append(fieldConds, sb.Like("metric_name", escapeForLike(fieldKeySelector.MetricContext.MetricNamespace)+"%"))+ fieldConds = append(fieldConds, sb.Like("metric_name", clickhousesql.LikePattern(fieldKeySelector.MetricContext.MetricNamespace)+"%"))}}@@ -991,7 +988,7 @@ func (t *telemetryMetaStore) getMeterSourceMetricKeys(ctx context.Context, fieldfieldConds = append(fieldConds, sb.E("metric_name", fieldKeySelector.MetricContext.MetricName))}if fieldKeySelector.MetricContext.MetricNamespace != "" {- fieldConds = append(fieldConds, sb.Like("metric_name", escapeForLike(fieldKeySelector.MetricContext.MetricNamespace)+"%"))+ fieldConds = append(fieldConds, sb.Like("metric_name", clickhousesql.LikePattern(fieldKeySelector.MetricContext.MetricNamespace)+"%"))}}@@ -1542,15 +1539,15 @@ func (t *telemetryMetaStore) getTagTableValues(ctx context.Context, table stringif fieldValueSelector.Value != "" {switch fieldValueSelector.FieldDataType {case telemetrytypes.FieldDataTypeString:- sb.Where(sb.ILike("string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"))+ sb.Where(sb.ILike("string_value", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))case telemetrytypes.FieldDataTypeNumber:sb.Where(sb.IsNotNull("number_value"))- sb.Where(sb.ILike("toString(number_value)", "%"+escapeForLike(fieldValueSelector.Value)+"%"))+ sb.Where(sb.ILike("toString(number_value)", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))case telemetrytypes.FieldDataTypeUnspecified:// or b/w string and numbersb.Where(sb.Or(- sb.ILike("string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"),- sb.ILike("toString(number_value)", "%"+escapeForLike(fieldValueSelector.Value)+"%"),+ sb.ILike("string_value", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"),+ sb.ILike("toString(number_value)", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"),))}}@@ -1629,14 +1626,14 @@ func (t *telemetryMetaStore) getAuditFieldValues(ctx context.Context, fieldValueif fieldValueSelector.Value != "" {switch fieldValueSelector.FieldDataType {case telemetrytypes.FieldDataTypeString:- sb.Where(sb.ILike("string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"))+ sb.Where(sb.ILike("string_value", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))case telemetrytypes.FieldDataTypeNumber:sb.Where(sb.IsNotNull("number_value"))- sb.Where(sb.ILike("toString(number_value)", "%"+escapeForLike(fieldValueSelector.Value)+"%"))+ sb.Where(sb.ILike("toString(number_value)", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))case telemetrytypes.FieldDataTypeUnspecified:sb.Where(sb.Or(- sb.ILike("string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"),- sb.ILike("toString(number_value)", "%"+escapeForLike(fieldValueSelector.Value)+"%"),+ sb.ILike("string_value", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"),+ sb.ILike("toString(number_value)", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"),))}}@@ -1740,7 +1737,7 @@ func (t *telemetryMetaStore) getMetricFieldValues(ctx context.Context, orgID valsb.Where(sb.E("metric_name", fieldValueSelector.MetricContext.MetricName))}if fieldValueSelector.MetricContext != nil && fieldValueSelector.MetricContext.MetricNamespace != "" {- sb.Where(sb.Like("metric_name", escapeForLike(fieldValueSelector.MetricContext.MetricNamespace)+"%"))+ sb.Where(sb.Like("metric_name", clickhousesql.LikePattern(fieldValueSelector.MetricContext.MetricNamespace)+"%"))}if fieldValueSelector.StartUnixMilli > 0 {@@ -1755,7 +1752,7 @@ func (t *telemetryMetaStore) getMetricFieldValues(ctx context.Context, orgID valif fieldValueSelector.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {sb.Where(sb.E("attr_string_value", fieldValueSelector.Value))} else {- sb.Where(sb.ILike("attr_string_value", "%"+escapeForLike(fieldValueSelector.Value)+"%"))+ sb.Where(sb.ILike("attr_string_value", "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))}}// query one extra to check if we hit the limit@@ -1874,7 +1871,7 @@ func (t *telemetryMetaStore) getIntrinsicMetricFieldValuesForTable(ctx context.Csb.Where(sb.E("metric_name", fieldValueSelector.MetricContext.MetricName))}if fieldValueSelector.MetricContext != nil && fieldValueSelector.MetricContext.MetricNamespace != "" {- sb.Where(sb.Like("metric_name", escapeForLike(fieldValueSelector.MetricContext.MetricNamespace)+"%"))+ sb.Where(sb.Like("metric_name", clickhousesql.LikePattern(fieldValueSelector.MetricContext.MetricNamespace)+"%"))}if fieldValueSelector.StartUnixMilli > 0 {@@ -1889,7 +1886,7 @@ func (t *telemetryMetaStore) getIntrinsicMetricFieldValuesForTable(ctx context.Cif fieldValueSelector.SelectorMatchType == telemetrytypes.FieldSelectorMatchTypeExact {sb.Where(sb.E(key.Name, fieldValueSelector.Value))} else {- sb.Where(sb.ILike(key.Name, "%"+escapeForLike(fieldValueSelector.Value)+"%"))+ sb.Where(sb.ILike(key.Name, "%"+clickhousesql.LikePattern(fieldValueSelector.Value)+"%"))}}@@ -1942,7 +1939,7 @@ func (t *telemetryMetaStore) getMeterSourceMetricFieldValues(ctx context.Contextsb.Where(sb.E("metric_name", fieldValueSelector.MetricContext.MetricName))}if fieldValueSelector.MetricContext != nil && fieldValueSelector.MetricContext.MetricNamespace != "" {- sb.Where(sb.Like("metric_name", escapeForLike(fieldValueSelector.MetricContext.MetricNamespace)+"%"))+ sb.Where(sb.Like("metric_name", clickhousesql.LikePattern(fieldValueSelector.MetricContext.MetricNamespace)+"%"))}if fieldValueSelector.Value != "" {diff --git a/pkg/telemetryschema/audittelemetryschema/field_mapper.go b/pkg/telemetryschema/audittelemetryschema/field_mapper.goindex 173696155c..40e410e122 100644--- a/pkg/telemetryschema/audittelemetryschema/field_mapper.go+++ b/pkg/telemetryschema/audittelemetryschema/field_mapper.go@@ -5,6 +5,7 @@ import ("fmt"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/querybuilder"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"@@ -68,7 +69,7 @@ func (m *fieldMapper) FieldFor(ctx context.Context, _ valuer.UUID, _, _ uint64,if key.FieldContext != telemetrytypes.FieldContextResource {return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "only resource context fields are supported for json columns in audit, got %s", key.FieldContext.String)}- return fmt.Sprintf("%s.`%s`::String", column.Name, key.Name), nil+ return fmt.Sprintf("%s.%s::String", column.Name, clickhousesql.Identifier(key.Name)), nilcase schema.ColumnTypeEnumLowCardinality:return column.Name, nilcase schema.ColumnTypeEnumString, schema.ColumnTypeEnumUInt64, schema.ColumnTypeEnumUInt32, schema.ColumnTypeEnumUInt8:@@ -84,7 +85,7 @@ func (m *fieldMapper) FieldFor(ctx context.Context, _ valuer.UUID, _, _ uint64,if key.Materialized {return telemetrytypes.FieldKeyToMaterializedColumnName(key), nil}- return fmt.Sprintf("%s['%s']", column.Name, key.Name), nil+ return fmt.Sprintf("%s[%s]", column.Name, clickhousesql.StringLiteral(key.Name)), nildefault:return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "unsupported map value type %s", valueType)}@@ -156,7 +157,7 @@ func (m *fieldMapper) ColumnExpressionFor(return fmt.Sprintf("multiIf(%s, %s, NULL)", guard, coerced), nil}- return fmt.Sprintf("%s AS `%s`", sqlbuilder.Escape(fieldExpression), field.Name), nil+ return sqlbuilder.Escape(fmt.Sprintf("%s AS %s", fieldExpression, clickhousesql.Identifier(field.Name))), nil}// CandidateKeys returns nil: audit has no synthesize-on-unknown-key fallback, so andiff --git a/pkg/telemetryschema/logstelemetryschema/condition_builder.go b/pkg/telemetryschema/logstelemetryschema/condition_builder.goindex 6406c2cf00..0b800e51ed 100644--- a/pkg/telemetryschema/logstelemetryschema/condition_builder.go+++ b/pkg/telemetryschema/logstelemetryschema/condition_builder.go@@ -137,7 +137,7 @@ func (c *conditionBuilder) conditionForArrayFunction(vals[i] = legacyCoerceNeedle(v, elemType)}// Pin the needle array type to the haystack; scalar fallback below coerces value-level.- arrayCond := fmt.Sprintf("%s(%s, %s)", operator.FunctionName(), arrayExpr, castNeedleArray(elemType, sb.Var(vals)))+ arrayCond := fmt.Sprintf("%s(%s, %s)", operator.FunctionName(), sqlbuilder.Escape(arrayExpr), castNeedleArray(elemType, sb.Var(vals)))if !hasScalar {return arrayCond, nil}@@ -151,14 +151,14 @@ func (c *conditionBuilder) conditionForArrayFunction(} else {membership = sb.In(scalarExpr, vals...)}- return fmt.Sprintf("(%s OR ifNull(%s, false))", arrayCond, sb.And(membership, scalarGuard)), nil+ return fmt.Sprintf("(%s OR ifNull(%s, false))", arrayCond, sb.And(membership, sqlbuilder.Escape(scalarGuard))), nil}typedNeedle := legacyCoerceNeedle(needle, elemType)- arrayCond := fmt.Sprintf("%s(%s, %s)", operator.FunctionName(), arrayExpr, sb.Var(typedNeedle))+ arrayCond := fmt.Sprintf("%s(%s, %s)", operator.FunctionName(), sqlbuilder.Escape(arrayExpr), sb.Var(typedNeedle))if !hasScalar {return arrayCond, nil}- return fmt.Sprintf("(%s OR ifNull(%s, false))", arrayCond, sb.And(sb.E(scalarExpr, typedNeedle), scalarGuard)), nil+ return fmt.Sprintf("(%s OR ifNull(%s, false))", arrayCond, sb.And(sb.E(scalarExpr, typedNeedle), sqlbuilder.Escape(scalarGuard))), nil}// castNeedleArray pins an Int64 needle array to Array(Int64) so it matches the Array(Nullable(Int64))@@ -358,9 +358,9 @@ func (c *conditionBuilder) conditionForResolvedKey(case qbtypes.FilterOperatorExists, qbtypes.FilterOperatorNotExists:if isBodyJSONSearch(key, columns) && !c.fl.BooleanOrEmpty(ctx, flagger.FeatureUseJSONBody, featuretypes.NewFlaggerEvaluationContext(orgID)) {if operator == qbtypes.FilterOperatorExists {- return GetBodyJSONKeyForExists(ctx, key, operator, value), nil+ return sqlbuilder.Escape(GetBodyJSONKeyForExists(ctx, key, operator, value)), nil}- return "NOT " + GetBodyJSONKeyForExists(ctx, key, operator, value), nil+ return "NOT " + sqlbuilder.Escape(GetBodyJSONKeyForExists(ctx, key, operator, value)), nil}pred, err := querybuilder.ExistsExpression(columns, key, startNs, endNs, fieldExpression, operator == qbtypes.FilterOperatorExists)if err != nil {diff --git a/pkg/telemetryschema/logstelemetryschema/field_mapper.go b/pkg/telemetryschema/logstelemetryschema/field_mapper.goindex 9e1f568f7d..5449c072f1 100644--- a/pkg/telemetryschema/logstelemetryschema/field_mapper.go+++ b/pkg/telemetryschema/logstelemetryschema/field_mapper.go@@ -7,6 +7,7 @@ import (schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator""github.com/SigNoz/signoz-otel-collector/utils"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/flagger""github.com/SigNoz/signoz/pkg/querybuilder"@@ -141,8 +142,8 @@ func (m *fieldMapper) FieldFor(ctx context.Context, orgID valuer.UUID, tsStart,case schema.ColumnTypeEnumJSON:switch key.FieldContext {case telemetrytypes.FieldContextResource:- exprs = append(exprs, fmt.Sprintf("%s.`%s`::String", columnName, key.Name))- existExpr = append(existExpr, fmt.Sprintf("%s.`%s` IS NOT NULL", columnName, key.Name))+ exprs = append(exprs, fmt.Sprintf("%s.%s::String", columnName, clickhousesql.Identifier(key.Name)))+ existExpr = append(existExpr, fmt.Sprintf("%s.%s IS NOT NULL", columnName, clickhousesql.Identifier(key.Name)))case telemetrytypes.FieldContextBody:if key.Name == messageSubField {exprs = append(exprs, messageSubColumn)@@ -186,8 +187,8 @@ func (m *fieldMapper) FieldFor(ctx context.Context, orgID valuer.UUID, tsStart,exprs = append(exprs, telemetrytypes.FieldKeyToMaterializedColumnName(key))existExpr = append(existExpr, telemetrytypes.FieldKeyToMaterializedColumnNameForExists(key))} else {- exprs = append(exprs, fmt.Sprintf("%s['%s']", columnName, key.Name))- existExpr = append(existExpr, fmt.Sprintf("mapContains(%s, '%s')", columnName, key.Name))+ exprs = append(exprs, fmt.Sprintf("%s[%s]", columnName, clickhousesql.StringLiteral(key.Name)))+ existExpr = append(existExpr, fmt.Sprintf("mapContains(%s, %s)", columnName, clickhousesql.StringLiteral(key.Name)))}default:return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "exists operator is not supported for map column type %s", valueType)@@ -415,7 +416,7 @@ func (m *fieldMapper) buildFieldForJSON(key *telemetrytypes.TelemetryFieldKey) (elemType = telemetrytypes.String}- fieldPath := fmt.Sprintf("%s.`%s`", LogsV2BodyV2Column, key.Name)+ fieldPath := fmt.Sprintf("%s.%s", LogsV2BodyV2Column, clickhousesql.Identifier(key.Name))return fmt.Sprintf("dynamicElement(%s, '%s')", fieldPath, elemType.StringValue()), nil}diff --git a/pkg/telemetryschema/logstelemetryschema/json_condition_builder.go b/pkg/telemetryschema/logstelemetryschema/json_condition_builder.goindex f388c4c635..4bfa162cf8 100644--- a/pkg/telemetryschema/logstelemetryschema/json_condition_builder.go+++ b/pkg/telemetryschema/logstelemetryschema/json_condition_builder.go@@ -6,6 +6,7 @@ import ("strings"schemamigrator "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/querybuilder"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"@@ -41,7 +42,7 @@ func (c *jsonConditionBuilder) buildJSONCondition(operator qbtypes.FilterOperato// path indexif operator.AddDefaultExistsFilter() {- pathIndex := fmt.Sprintf(`has(%s, '%s')`, schemamigrator.JSONPathsIndexExpr(LogsV2BodyV2Column), c.key.ArrayParentPaths()[0])+ pathIndex := sqlbuilder.Escape(fmt.Sprintf(`has(%s, %s)`, schemamigrator.JSONPathsIndexExpr(LogsV2BodyV2Column), clickhousesql.StringLiteral(c.key.ArrayParentPaths()[0])))return sb.And(baseCond, pathIndex), nil}@@ -123,7 +124,7 @@ func (c *jsonConditionBuilder) buildAccessNodeBranches(current *telemetrytypes.Jif err != nil {return "", err}- branches = append(branches, fmt.Sprintf("arrayExists(%s-> %s, %s)", currAlias, childGroup, c.branchArrayExpr(current, branch)))+ branches = append(branches, fmt.Sprintf("arrayExists(%s-> %s, %s)", sqlbuilder.Escape(currAlias), childGroup, sqlbuilder.Escape(c.branchArrayExpr(current, branch))))}if len(branches) == 1 {@@ -302,7 +303,7 @@ func (c *jsonConditionBuilder) buildArrayMembershipCondition(node *telemetrytypereturn "", err}- return fmt.Sprintf("arrayExists(%s -> %s, %s)", key, op, arrayExpr), nil+ return fmt.Sprintf("arrayExists(%s -> %s, %s)", key, op, sqlbuilder.Escape(arrayExpr)), nil}// buildArrayFunctionCondition builds a has/hasAny/hasAll condition over a body JSON path,@@ -386,7 +387,7 @@ func (c *jsonConditionBuilder) buildArrayExistsChain(node *telemetrytypes.JSONAcif err != nil {return "", err}- branches = append(branches, fmt.Sprintf("arrayExists(%s-> %s, %s)", node.Alias(), childCond, c.branchArrayExpr(node, branch)))+ branches = append(branches, fmt.Sprintf("arrayExists(%s-> %s, %s)", sqlbuilder.Escape(node.Alias()), childCond, sqlbuilder.Escape(c.branchArrayExpr(node, branch))))}if len(branches) == 1 {return branches[0], nil@@ -456,10 +457,10 @@ func (c *jsonConditionBuilder) tokenLeaf(node *telemetrytypes.JSONAccessNode, neswitch node.TerminalConfig.ElemType {case telemetrytypes.String:fieldExpr := fmt.Sprintf("dynamicElement(%s, 'String')", node.FieldPath())- return fmt.Sprintf("ifNull(hasToken(LOWER(%s), LOWER(%s)), false)", fieldExpr, sb.Var(needle)), nil+ return fmt.Sprintf("ifNull(hasToken(LOWER(%s), LOWER(%s)), false)", sqlbuilder.Escape(fieldExpr), sb.Var(needle)), nilcase telemetrytypes.ArrayString:arrayExpr := fmt.Sprintf("dynamicElement(%s, '%s')", node.FieldPath(), node.TerminalConfig.ElemType.StringValue())- return fmt.Sprintf("arrayExists(x -> hasToken(LOWER(x), LOWER(%s)), %s)", sb.Var(needle), arrayExpr), nil+ return fmt.Sprintf("arrayExists(x -> hasToken(LOWER(x), LOWER(%s)), %s)", sb.Var(needle), sqlbuilder.Escape(arrayExpr)), nildefault:return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "function `hasToken` only supports string fields; field `%s` is `%s`", c.key.Name, node.TerminalConfig.Key.FieldDataType.StringValue())}@@ -496,9 +497,9 @@ func (c *jsonConditionBuilder) applyOperator(sb *sqlbuilder.SelectBuilder, fieldcase qbtypes.FilterOperatorNotILike:return sb.NotILike(fieldExpr, value), nilcase qbtypes.FilterOperatorRegexp:- return fmt.Sprintf("match(%s, %s)", fieldExpr, sb.Var(value)), nil+ return fmt.Sprintf("match(%s, %s)", sqlbuilder.Escape(fieldExpr), sb.Var(value)), nilcase qbtypes.FilterOperatorNotRegexp:- return fmt.Sprintf("NOT match(%s, %s)", fieldExpr, sb.Var(value)), nil+ return fmt.Sprintf("NOT match(%s, %s)", sqlbuilder.Escape(fieldExpr), sb.Var(value)), nilcase qbtypes.FilterOperatorContains:return sb.ILike(fieldExpr, fmt.Sprintf("%%%v%%", value)), nilcase qbtypes.FilterOperatorNotContains:diff --git a/pkg/telemetryschema/logstelemetryschema/json_string.go b/pkg/telemetryschema/logstelemetryschema/json_string.goindex 458fb870b2..6ce3abdbbb 100644--- a/pkg/telemetryschema/logstelemetryschema/json_string.go+++ b/pkg/telemetryschema/logstelemetryschema/json_string.go@@ -7,6 +7,7 @@ import ("strconv""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes")@@ -92,19 +93,29 @@ func InferDataType(value any, operator qbtypes.FilterOperator, key *telemetrytypreturn closure(value, key)}-func getBodyJSONPath(key *telemetrytypes.TelemetryFieldKey) string {+// ClickHouse's JSONPath parser accepts only \\ and \" inside a quoted member.+func jsonPathMember(segment string) string {+ escaped := strings.ReplaceAll(segment, `\`, `\\`)+ escaped = strings.ReplaceAll(escaped, `"`, `\"`)+ return `"` + escaped + `"`+}++// bodyJSONPathLiteral escapes each segment for JSONPath, then the whole path as a+// ClickHouse literal; the fixed "$." root is kept out of the literal escaping.+func bodyJSONPathLiteral(key *telemetrytypes.TelemetryFieldKey) string {parts := strings.Split(key.Name, ".")- newParts := []string{}+ newParts := make([]string, 0, len(parts))for _, part := range parts {if strings.HasSuffix(part, "[*]") {- newParts = append(newParts, fmt.Sprintf(`"%s"[*]`, strings.TrimSuffix(part, "[*]")))+ newParts = append(newParts, jsonPathMember(strings.TrimSuffix(part, "[*]"))+"[*]")} else if strings.HasSuffix(part, "[]") {- newParts = append(newParts, fmt.Sprintf(`"%s"[*]`, strings.TrimSuffix(part, "[]")))+ newParts = append(newParts, jsonPathMember(strings.TrimSuffix(part, "[]"))+"[*]")} else {- newParts = append(newParts, fmt.Sprintf(`"%s"`, part))+ newParts = append(newParts, jsonPathMember(part))}}- return strings.Join(newParts, ".")+ members := clickhousesql.StringLiteral(strings.Join(newParts, "."))+ return "'$." + members[1:]}func GetBodyJSONKey(_ context.Context, key *telemetrytypes.TelemetryFieldKey, operator qbtypes.FilterOperator, value any) (string, any) {@@ -116,12 +127,12 @@ func GetBodyJSONKey(_ context.Context, key *telemetrytypes.TelemetryFieldKey, opdataType == telemetrytypes.FieldDataTypeArrayString ||dataType == telemetrytypes.FieldDataTypeArrayBool ||dataType == telemetrytypes.FieldDataTypeArrayNumber {- return fmt.Sprintf("JSONExtract(JSON_QUERY(body, '$.%s'), '%s')", getBodyJSONPath(key), dataType.CHDataType()), value+ return fmt.Sprintf("JSONExtract(JSON_QUERY(body, %s), '%s')", bodyJSONPathLiteral(key), dataType.CHDataType()), value}if dataType != telemetrytypes.FieldDataTypeString {// for all types except strings, we need to extract the value from the JSON_VALUE- return fmt.Sprintf("JSONExtract(JSON_VALUE(body, '$.%s'), '%s')", getBodyJSONPath(key), dataType.CHDataType()), value+ return fmt.Sprintf("JSONExtract(JSON_VALUE(body, %s), '%s')", bodyJSONPathLiteral(key), dataType.CHDataType()), value}// JSON_VALUE returns a String; stringify list operands so a numeric element in a mixed// set (e.g. IN ['alpha', 42]) doesn't hit a String-vs-number supertype error (CH 386).@@ -132,11 +143,11 @@ func GetBodyJSONKey(_ context.Context, key *telemetrytypes.TelemetryFieldKey, op}value = strs}- return fmt.Sprintf("JSON_VALUE(body, '$.%s')", getBodyJSONPath(key)), value+ return fmt.Sprintf("JSON_VALUE(body, %s)", bodyJSONPathLiteral(key)), value}func GetBodyJSONKeyForExists(_ context.Context, key *telemetrytypes.TelemetryFieldKey, _ qbtypes.FilterOperator, _ any) string {- return fmt.Sprintf("JSON_EXISTS(body, '$.%s')", getBodyJSONPath(key))+ return fmt.Sprintf("JSON_EXISTS(body, %s)", bodyJSONPathLiteral(key))}// legacyElemType infers the has-family element type from the needle (legacy has no schema). It@@ -211,7 +222,7 @@ func getBodyJSONArrayKey(key *telemetrytypes.TelemetryFieldKey, dt telemetrytypename += "[*]"}arrKey := telemetrytypes.NewTelemetryFieldKey(name, key.FieldContext, key.FieldDataType)- return fmt.Sprintf("JSONExtract(JSON_QUERY(body, '$.%s'), 'Array(Nullable(%s))')", getBodyJSONPath(arrKey), dt.CHDataType())+ return fmt.Sprintf("JSONExtract(JSON_QUERY(body, %s), 'Array(Nullable(%s))')", bodyJSONPathLiteral(arrKey), dt.CHDataType())}// getBodyJSONScalarKey builds the single-element-set fallback for a scalar body value: the leaf@@ -225,18 +236,18 @@ func getBodyJSONScalarKey(key *telemetrytypes.TelemetryFieldKey, dt telemetrytypreturn "", "", false}scalarKey := telemetrytypes.NewTelemetryFieldKey(name, key.FieldContext, key.FieldDataType)- path := getBodyJSONPath(scalarKey)+ path := bodyJSONPathLiteral(scalarKey)if dt == telemetrytypes.FieldDataTypeString {- expr = fmt.Sprintf("JSON_VALUE(body, '$.%s')", path)+ expr = fmt.Sprintf("JSON_VALUE(body, %s)", path)} else {// Nullable so a scalar of a different type (e.g. a bool/string where a number is// searched) extracts to NULL rather than the type's default (0/false), which would// otherwise zero-value match has(x, 0).- expr = fmt.Sprintf("JSONExtract(JSON_VALUE(body, '$.%s'), 'Nullable(%s)')", path, dt.CHDataType())+ expr = fmt.Sprintf("JSONExtract(JSON_VALUE(body, %s), 'Nullable(%s)')", path, dt.CHDataType())}keys := strings.Split(name, ".")for i, k := range keys {- keys[i] = "'" + k + "'"+ keys[i] = clickhousesql.StringLiteral(k)}guard = fmt.Sprintf("JSONType(body, %s) NOT IN ('Array', 'Object', 'Null')", strings.Join(keys, ", "))return expr, guard, truediff --git a/pkg/telemetryschema/logstelemetryschema/json_string_test.go b/pkg/telemetryschema/logstelemetryschema/json_string_test.gonew file mode 100644index 0000000000..1c4154b3ef--- /dev/null+++ b/pkg/telemetryschema/logstelemetryschema/json_string_test.go@@ -0,0 +1,31 @@+package logstelemetryschema++import (+ "testing"++ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/stretchr/testify/assert"+)++func TestBodyJSONPathLiteral(t *testing.T) {+ testCases := []struct {+ name string+ key string+ expected string+ }{+ {name: "Nested", key: "user.name", expected: `'$."user"."name"'`},+ {name: "ArrayWildcard", key: "items[*].sku", expected: `'$."items"[*]."sku"'`},+ {name: "DoubleQuote", key: `a"b`, expected: `'$."a\\"b"'`},+ {name: "Backslash", key: `a\b`, expected: `'$."a\\\\b"'`},+ {name: "SingleQuote", key: "a'b", expected: `'$."a\'b"'`},+ {name: "DollarDigit", key: "a$0b", expected: `'$."a\x240b"'`},+ {name: "Injection", key: `x"]) OR 1=1 --`, expected: `'$."x\\"]) OR 1=1 --"'`},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ key := &telemetrytypes.TelemetryFieldKey{Name: testCase.key, FieldContext: telemetrytypes.FieldContextBody}+ assert.Equal(t, testCase.expected, bodyJSONPathLiteral(key))+ })+ }+}diff --git a/pkg/telemetryschema/metricstelemetryschema/condition_builder.go b/pkg/telemetryschema/metricstelemetryschema/condition_builder.goindex 374bdb775f..e21acdb458 100644--- a/pkg/telemetryschema/metricstelemetryschema/condition_builder.go+++ b/pkg/telemetryschema/metricstelemetryschema/condition_builder.go@@ -6,6 +6,7 @@ import ("slices"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/querybuilder"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"@@ -163,9 +164,9 @@ func (c *conditionBuilder) conditionFor(}if operator == qbtypes.FilterOperatorExists {- return fmt.Sprintf("has(JSONExtractKeys(labels), '%s')", key.Name), nil+ return sqlbuilder.Escape(fmt.Sprintf("has(JSONExtractKeys(labels), %s)", clickhousesql.StringLiteral(key.Name))), nil}- return fmt.Sprintf("not has(JSONExtractKeys(labels), '%s')", key.Name), nil+ return sqlbuilder.Escape(fmt.Sprintf("not has(JSONExtractKeys(labels), %s)", clickhousesql.StringLiteral(key.Name))), nil}return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "unsupported operator: %v", operator)}diff --git a/pkg/telemetryschema/metricstelemetryschema/field_mapper.go b/pkg/telemetryschema/metricstelemetryschema/field_mapper.goindex a73a2ca7dc..cbcde87670 100644--- a/pkg/telemetryschema/metricstelemetryschema/field_mapper.go+++ b/pkg/telemetryschema/metricstelemetryschema/field_mapper.go@@ -6,6 +6,7 @@ import ("slices"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes""github.com/SigNoz/signoz/pkg/valuer"@@ -79,14 +80,14 @@ func (m *fieldMapper) FieldFor(ctx context.Context, _ valuer.UUID, startNs, endNswitch key.FieldContext {case telemetrytypes.FieldContextResource, telemetrytypes.FieldContextScope, telemetrytypes.FieldContextAttribute:- return fmt.Sprintf("JSONExtractString(%s, '%s')", columns[0].Name, key.Name), nil+ return fmt.Sprintf("JSONExtractString(%s, %s)", columns[0].Name, clickhousesql.StringLiteral(key.Name)), nilcase telemetrytypes.FieldContextMetric:return columns[0].Name, nilcase telemetrytypes.FieldContextUnspecified:if slices.Contains(IntrinsicFields, key.Name) {return columns[0].Name, nil}- return fmt.Sprintf("JSONExtractString(%s, '%s')", columns[0].Name, key.Name), nil+ return fmt.Sprintf("JSONExtractString(%s, %s)", columns[0].Name, clickhousesql.StringLiteral(key.Name)), nil}return columns[0].Name, nil@@ -103,9 +104,9 @@ func (m *fieldMapper) ExistsFor(_ context.Context, _ valuer.UUID, _, _ uint64, kreturn "true", nil}if exists {- return fmt.Sprintf("has(JSONExtractKeys(labels), '%s')", key.Name), nil+ return fmt.Sprintf("has(JSONExtractKeys(labels), %s)", clickhousesql.StringLiteral(key.Name)), nil}- return fmt.Sprintf("not has(JSONExtractKeys(labels), '%s')", key.Name), nil+ return fmt.Sprintf("not has(JSONExtractKeys(labels), %s)", clickhousesql.StringLiteral(key.Name)), nil}func (m *fieldMapper) ColumnExpressionFor(diff --git a/pkg/telemetryschema/tracestelemetryschema/field_mapper.go b/pkg/telemetryschema/tracestelemetryschema/field_mapper.goindex 72d3b84b0a..384fa494db 100644--- a/pkg/telemetryschema/tracestelemetryschema/field_mapper.go+++ b/pkg/telemetryschema/tracestelemetryschema/field_mapper.go@@ -6,6 +6,7 @@ import ("strings"schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/flagger""github.com/SigNoz/signoz/pkg/querybuilder"@@ -297,8 +298,8 @@ func (m *fieldMapper) resolveColumnExprs(// once clickHouse dependency is updated, we need to check if we can remove it.switch key.FieldContext {case telemetrytypes.FieldContextResource:- exprs = append(exprs, fmt.Sprintf("%s.`%s`::String", columnName, key.Name))- existExprs = append(existExprs, fmt.Sprintf("%s.`%s` IS NOT NULL", columnName, key.Name))+ exprs = append(exprs, fmt.Sprintf("%s.%s::String", columnName, clickhousesql.Identifier(key.Name)))+ existExprs = append(existExprs, fmt.Sprintf("%s.%s IS NOT NULL", columnName, clickhousesql.Identifier(key.Name)))case telemetrytypes.FieldContextScope:if f, ok := IntrinsicFields[key.Name]; ok && f.FieldContext == telemetrytypes.FieldContextScope {// declared String paths on the scope column read '' for the missing case@@ -306,8 +307,8 @@ func (m *fieldMapper) resolveColumnExprs(existExprs = append(existExprs, fmt.Sprintf("%s <> ''", key.Name))} else {attributeName := strings.TrimPrefix(key.Name, "attribute.") // literal "attribute" prefix in attribute keys needs double prefix- exprs = append(exprs, fmt.Sprintf("%s.attributes.%s::String", columnName, querybuilder.ClickHouseIdentifier(attributeName)))- existExprs = append(existExprs, fmt.Sprintf("%s.attributes.%s IS NOT NULL", columnName, querybuilder.ClickHouseIdentifier(attributeName)))+ exprs = append(exprs, fmt.Sprintf("%s.attributes.%s::String", columnName, clickhousesql.Identifier(attributeName)))+ existExprs = append(existExprs, fmt.Sprintf("%s.attributes.%s IS NOT NULL", columnName, clickhousesql.Identifier(attributeName)))}default:return nil, nil, nil, errors.NewInternalf(errors.CodeInternal, "only resource and scope context fields are supported for json columns, got %s", key.FieldContext.String)@@ -341,8 +342,8 @@ func (m *fieldMapper) resolveColumnExprs(exprs = append(exprs, telemetrytypes.FieldKeyToMaterializedColumnName(key))existExprs = append(existExprs, telemetrytypes.FieldKeyToMaterializedColumnNameForExists(key))} else {- exprs = append(exprs, fmt.Sprintf("%s['%s']", columnName, key.Name))- existExprs = append(existExprs, fmt.Sprintf("mapContains(%s, '%s')", columnName, key.Name))+ exprs = append(exprs, fmt.Sprintf("%s[%s]", columnName, clickhousesql.StringLiteral(key.Name)))+ existExprs = append(existExprs, fmt.Sprintf("mapContains(%s, %s)", columnName, clickhousesql.StringLiteral(key.Name)))}default:return nil, nil, nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "value type %s is not supported for map column type %s", valueType, column.Type)diff --git a/pkg/types/telemetrytypes/field.go b/pkg/types/telemetrytypes/field.goindex c46c24fc94..09449c2fd3 100644--- a/pkg/types/telemetrytypes/field.go+++ b/pkg/types/telemetrytypes/field.go@@ -4,6 +4,7 @@ import ("fmt""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/valuer")@@ -202,19 +203,19 @@ func TelemetryFieldKeyToText(key *TelemetryFieldKey) string {}func FieldKeyToMaterializedColumnName(key *TelemetryFieldKey) string {- return fmt.Sprintf("`%s_%s_%s`",+ return clickhousesql.Identifier(fmt.Sprintf("%s_%s_%s",key.FieldContext.String,fieldDataTypes[key.FieldDataType.StringValue()].StringValue(),strings.ReplaceAll(key.Name, ".", "$$"),- )+ ))}func FieldKeyToMaterializedColumnNameForExists(key *TelemetryFieldKey) string {- return fmt.Sprintf("`%s_%s_%s_exists`",+ return clickhousesql.Identifier(fmt.Sprintf("%s_%s_%s_exists",key.FieldContext.String,fieldDataTypes[key.FieldDataType.StringValue()].StringValue(),strings.ReplaceAll(key.Name, ".", "$$"),- )+ ))}type TelemetryFieldValues struct {diff --git a/pkg/types/telemetrytypes/json_access_plan.go b/pkg/types/telemetrytypes/json_access_plan.goindex 18dee950e5..f12fc65e2b 100644--- a/pkg/types/telemetrytypes/json_access_plan.go+++ b/pkg/types/telemetrytypes/json_access_plan.go@@ -1,11 +1,11 @@package telemetrytypesimport (- "fmt""maps""slices""strings"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/valuer")@@ -65,26 +65,26 @@ func NewRootJSONAccessNode(name string, maxDynamicTypes, maxDynamicPaths int) *J}}+// Alias is the bare column name for the root and the quoted logical path otherwise.func (n *JSONAccessNode) Alias() string {if n.isRoot {return n.Name- } else if n.Parent == nil {- return fmt.Sprintf("`%s`", n.Name)}+ return clickhousesql.Identifier(n.aliasName())+}- parentAlias := strings.TrimLeft(n.Parent.Alias(), "`")- parentAlias = strings.TrimRight(parentAlias, "`")-- sep := ArraySep- if n.Parent.isRoot {- sep = "."+func (n *JSONAccessNode) aliasName() string {+ if n.Parent == nil || n.Parent.isRoot {+ if n.Parent == nil {+ return n.Name+ }+ return n.Parent.Name + "." + n.Name}- return fmt.Sprintf("`%s%s%s`", parentAlias, sep, n.Name)+ return n.Parent.aliasName() + ArraySep + n.Name}func (n *JSONAccessNode) FieldPath() string {- key := "`" + n.Name + "`"- return n.Parent.Alias() + "." + key+ return n.Parent.Alias() + "." + clickhousesql.Identifier(n.Name)}// Returns true if the current node is a non-nested path.diff --git a/tests/integration/tests/querier_json_body/07_field_name_quoting.py b/tests/integration/tests/querier_json_body/07_field_name_quoting.pynew file mode 100644index 0000000000..006f935877--- /dev/null+++ b/tests/integration/tests/querier_json_body/07_field_name_quoting.py@@ -0,0 +1,110 @@+import json+from collections.abc import Callable+from datetime import UTC, datetime, timedelta+from http import HTTPStatus++import pytest++from fixtures import types+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD+from fixtures.logs import Logs+from fixtures.querier import build_aggregation, build_raw_query, build_scalar_query, get_rows, get_scalar_table_data, make_query_request++SERVICE = "quoting-json-svc"++NESTED_KEY = "us`er.na'me"+DOLLAR_KEY = "a$0b"+SLASH_KEY = "sl\\ash"+INJECT_KEY = "x` OR 1=1 --"++BODIES = {+ "alice": json.dumps({"us`er": {"na'me": "alice"}, DOLLAR_KEY: 7, SLASH_KEY: "alice-slash", INJECT_KEY: "alice-inject", "plain": "alice"}),+ "bob": json.dumps({"us`er": {"na'me": "bob"}, DOLLAR_KEY: 8, SLASH_KEY: "bob-slash", INJECT_KEY: "bob-inject", "plain": "bob"}),+ "carol": json.dumps({"plain": "carol"}),+}+++ "key,expected",+ [+ pytest.param(NESTED_KEY, {"alice": 1, "bob": 1}, id="backtick_parent_quote_leaf"),+ pytest.param(SLASH_KEY, {"alice-slash": 1, "bob-slash": 1}, id="backslash"),+ pytest.param(INJECT_KEY, {"alice-inject": 1, "bob-inject": 1}, id="injection"),+ ],+)+def test_body_json_group_by_and_select_hostile_key(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_logs: Callable[[list[Logs]], None],+ export_json_types: Callable[[list[Logs]], None],+ key: str,+ expected: dict[str, int],+) -> None:+ now = datetime.now(tz=UTC)+ logs = [Logs(timestamp=now - timedelta(seconds=3 - i), resources={"service.name": SERVICE}, body_v2=body, body_promoted="") for i, body in enumerate(BODIES.values())]+ export_json_types(logs)+ insert_logs(logs)+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ start_ms = int((now - timedelta(minutes=2)).timestamp() * 1000)+ end_ms = int((now + timedelta(seconds=1)).timestamp() * 1000)+ field = {"name": key, "fieldContext": "body", "fieldDataType": "string"}++ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_scalar_query("A", "logs", [build_aggregation("count()")], group_by=[field], order=[{"key": {"name": key}, "direction": "asc"}], filter_expression=f"service.name = '{SERVICE}'")],+ request_type="scalar",+ )+ assert response.status_code == HTTPStatus.OK, response.text+ rows = [row for row in get_scalar_table_data(response.json()) if len(row) >= 2 and row[0]]+ assert {str(row[0]): int(row[-1]) for row in rows} == expected, response.text+ assert [str(row[0]) for row in rows] == sorted(expected), response.text++ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_raw_query("A", "logs", limit=100, filter_expression=f"service.name = '{SERVICE}'", order=[{"key": {"name": "timestamp"}, "direction": "asc"}], select_fields=[field])],+ request_type="raw",+ )+ assert response.status_code == HTTPStatus.OK, response.text+ rows = get_rows(response)+ assert len(rows) == 3, response.text+ assert [row["data"].get(key) for row in rows][:2] == sorted(expected), response.text+++def test_body_json_filter_with_dollar_in_key(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_logs: Callable[[list[Logs]], None],+ export_json_types: Callable[[list[Logs]], None],+) -> None:+ now = datetime.now(tz=UTC)+ logs = [Logs(timestamp=now - timedelta(seconds=3 - i), resources={"service.name": SERVICE}, body_v2=body, body_promoted="") for i, body in enumerate(BODIES.values())]+ export_json_types(logs)+ insert_logs(logs)+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ start_ms = int((now - timedelta(minutes=2)).timestamp() * 1000)+ end_ms = int((now + timedelta(seconds=1)).timestamp() * 1000)++ for expression, expected in [+ (f"{DOLLAR_KEY} = 7", {"alice"}),+ (f"{DOLLAR_KEY} > 7", {"bob"}),+ (f"{DOLLAR_KEY} EXISTS", {"alice", "bob"}),+ (f"{DOLLAR_KEY} NOT EXISTS AND service.name = '{SERVICE}'", {"carol"}),+ ]:+ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_raw_query("A", "logs", limit=100, filter_expression=expression, order=[{"key": {"name": "timestamp"}, "direction": "asc"}])],+ request_type="raw",+ )+ assert response.status_code == HTTPStatus.OK, f"{expression}: {response.text}"+ assert {row["data"]["body"]["plain"] for row in get_rows(response)} == expected, f"{expression}: {response.text}"diff --git a/tests/integration/tests/queriercommon/08_field_name_quoting.py b/tests/integration/tests/queriercommon/08_field_name_quoting.pynew file mode 100644index 0000000000..89d4c1ce91--- /dev/null+++ b/tests/integration/tests/queriercommon/08_field_name_quoting.py@@ -0,0 +1,240 @@+from collections.abc import Callable+from datetime import UTC, datetime, timedelta+from http import HTTPStatus++import pytest++from fixtures import types+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD+from fixtures.logs import Logs+from fixtures.metrics import Metrics+from fixtures.querier import (+ build_aggregation,+ build_builder_query,+ build_raw_query,+ build_scalar_query,+ get_all_series,+ get_rows,+ get_scalar_table_data,+ make_query_request,+)+from fixtures.traces import Traces++SERVICE = "quoting-svc"++HOSTILE_KEYS = {+ "backtick": "at`tick",+ "quote": "at'quote",+ "double_quote": 'at"dq',+ "backslash": "at\\back",+ "trailing_backslash": "at\\",+ "dollar": "at$0dollar",+ "brace": "at${x}",+ "injection": "x` OR 1=1 --",+}+RESOURCE_KEYS = {+ "backtick": "rk`tick",+ "quote": "rk'quote",+ "dollar": "rk$0",+}++[email protected]("key_id", list(HOSTILE_KEYS), ids=list(HOSTILE_KEYS))+def test_logs_group_by_order_by_and_select_hostile_attribute(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_logs: Callable[[list[Logs]], None],+ key_id: str,+) -> None:+ now = datetime.now(tz=UTC)+ insert_logs(+ [+ Logs(timestamp=now - timedelta(seconds=3), resources={"service.name": SERVICE}, attributes={key: f"alpha-{k}" for k, key in HOSTILE_KEYS.items()}, body="alpha body"),+ Logs(timestamp=now - timedelta(seconds=2), resources={"service.name": SERVICE}, attributes={key: f"beta-{k}" for k, key in HOSTILE_KEYS.items()}, body="beta body"),+ Logs(timestamp=now - timedelta(seconds=1), resources={"service.name": SERVICE}, attributes={"plain": "gamma"}, body="gamma body"),+ ]+ )+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ start_ms = int((now - timedelta(minutes=2)).timestamp() * 1000)+ end_ms = int((now + timedelta(seconds=1)).timestamp() * 1000)+ key = HOSTILE_KEYS[key_id]+ field = {"name": key, "fieldContext": "attribute", "fieldDataType": "string"}++ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_scalar_query("A", "logs", [build_aggregation("count()")], group_by=[field], filter_expression=f"service.name = '{SERVICE}'")],+ request_type="scalar",+ )+ assert response.status_code == HTTPStatus.OK, response.text+ counts = {str(row[0]): int(row[-1]) for row in get_scalar_table_data(response.json()) if len(row) >= 2 and str(row[0]).startswith(("alpha-", "beta-"))}+ assert counts == {f"alpha-{key_id}": 1, f"beta-{key_id}": 1}, response.text++ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_scalar_query("A", "logs", [build_aggregation("count()")], group_by=[field], order=[{"key": {"name": key}, "direction": "asc"}], filter_expression=f"service.name = '{SERVICE}'")],+ request_type="scalar",+ )+ assert response.status_code == HTTPStatus.OK, response.text+ ordered = [str(row[0]) for row in get_scalar_table_data(response.json()) if row and str(row[0]).startswith(("alpha-", "beta-"))]+ assert ordered == [f"alpha-{key_id}", f"beta-{key_id}"], response.text++ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_raw_query("A", "logs", limit=100, filter_expression=f"service.name = '{SERVICE}'", order=[{"key": {"name": "timestamp"}, "direction": "asc"}], select_fields=[field])],+ request_type="raw",+ )+ assert response.status_code == HTTPStatus.OK, response.text+ rows = get_rows(response)+ assert len(rows) == 3, response.text+ assert [row["data"].get(key) for row in rows][:2] == [f"alpha-{key_id}", f"beta-{key_id}"], response.text+ assert not rows[2]["data"].get(key), response.text+++def test_logs_filter_expression_with_dollar_in_key(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_logs: Callable[[list[Logs]], None],+) -> None:+ now = datetime.now(tz=UTC)+ insert_logs(+ [+ Logs(timestamp=now - timedelta(seconds=3), resources={"service.name": SERVICE, "rk$0": "alpha-dollar"}, attributes={"at$0dollar": "alpha-dollar", "at${x}": "alpha-brace"}, body="alpha body"),+ Logs(timestamp=now - timedelta(seconds=2), resources={"service.name": SERVICE, "rk$0": "beta-dollar"}, attributes={"at$0dollar": "beta-dollar", "at${x}": "beta-brace"}, body="beta body"),+ Logs(timestamp=now - timedelta(seconds=1), resources={"service.name": SERVICE}, attributes={"plain": "gamma"}, body="gamma body"),+ ]+ )+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ start_ms = int((now - timedelta(minutes=2)).timestamp() * 1000)+ end_ms = int((now + timedelta(seconds=1)).timestamp() * 1000)++ for expression, expected_bodies in [+ ("at$0dollar = 'alpha-dollar'", {"alpha body"}),+ ("at$0dollar EXISTS", {"alpha body", "beta body"}),+ (f"at$0dollar NOT EXISTS AND service.name = '{SERVICE}'", {"gamma body"}),+ ("at${x} = 'beta-brace'", {"beta body"}),+ ("rk$0 = 'alpha-dollar'", {"alpha body"}),+ ]:+ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_raw_query("A", "logs", limit=100, filter_expression=expression, order=[{"key": {"name": "timestamp"}, "direction": "asc"}])],+ request_type="raw",+ )+ assert response.status_code == HTTPStatus.OK, f"{expression}: {response.text}"+ assert {row["data"]["body"] for row in get_rows(response)} == expected_bodies, f"{expression}: {response.text}"++[email protected]("key_id", list(RESOURCE_KEYS), ids=list(RESOURCE_KEYS))+def test_logs_group_by_hostile_resource_attribute(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_logs: Callable[[list[Logs]], None],+ key_id: str,+) -> None:+ now = datetime.now(tz=UTC)+ insert_logs(+ [+ Logs(timestamp=now - timedelta(seconds=3), resources={"service.name": SERVICE, **{key: f"alpha-{k}" for k, key in RESOURCE_KEYS.items()}}, body="alpha body"),+ Logs(timestamp=now - timedelta(seconds=2), resources={"service.name": SERVICE, **{key: f"beta-{k}" for k, key in RESOURCE_KEYS.items()}}, body="beta body"),+ Logs(timestamp=now - timedelta(seconds=1), resources={"service.name": SERVICE}, body="gamma body"),+ ]+ )+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ key = RESOURCE_KEYS[key_id]++ response = make_query_request(+ signoz,+ token,+ int((now - timedelta(minutes=2)).timestamp() * 1000),+ int((now + timedelta(seconds=1)).timestamp() * 1000),+ [build_scalar_query("A", "logs", [build_aggregation("count()")], group_by=[{"name": key, "fieldContext": "resource", "fieldDataType": "string"}], filter_expression=f"service.name = '{SERVICE}'")],+ request_type="scalar",+ )+ assert response.status_code == HTTPStatus.OK, response.text+ counts = {str(row[0]): int(row[-1]) for row in get_scalar_table_data(response.json()) if len(row) >= 2 and str(row[0]).startswith(("alpha-", "beta-"))}+ assert counts == {f"alpha-{key_id}": 1, f"beta-{key_id}": 1}, response.text++[email protected]("key_id", list(HOSTILE_KEYS), ids=list(HOSTILE_KEYS))+def test_traces_group_by_and_select_hostile_attribute(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+ key_id: str,+) -> None:+ now = datetime.now(tz=UTC)+ insert_traces(+ [+ Traces(timestamp=now - timedelta(seconds=3), name="alpha span", resources={"service.name": SERVICE}, attributes={key: f"alpha-{k}" for k, key in HOSTILE_KEYS.items()}),+ Traces(timestamp=now - timedelta(seconds=2), name="beta span", resources={"service.name": SERVICE}, attributes={key: f"beta-{k}" for k, key in HOSTILE_KEYS.items()}),+ Traces(timestamp=now - timedelta(seconds=1), name="gamma span", resources={"service.name": SERVICE}, attributes={"plain": "gamma"}),+ ]+ )+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ start_ms = int((now - timedelta(minutes=2)).timestamp() * 1000)+ end_ms = int((now + timedelta(seconds=1)).timestamp() * 1000)+ key = HOSTILE_KEYS[key_id]+ field = {"name": key, "fieldContext": "attribute", "fieldDataType": "string"}++ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_scalar_query("A", "traces", [build_aggregation("count()")], group_by=[field], filter_expression=f"service.name = '{SERVICE}'")],+ request_type="scalar",+ )+ assert response.status_code == HTTPStatus.OK, response.text+ counts = {str(row[0]): int(row[-1]) for row in get_scalar_table_data(response.json()) if len(row) >= 2 and str(row[0]).startswith(("alpha-", "beta-"))}+ assert counts == {f"alpha-{key_id}": 1, f"beta-{key_id}": 1}, response.text++ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_raw_query("A", "traces", limit=100, filter_expression=f"service.name = '{SERVICE}'", order=[{"key": {"name": "timestamp"}, "direction": "asc"}], select_fields=[field, {"name": "name"}])],+ request_type="raw",+ )+ assert response.status_code == HTTPStatus.OK, response.text+ assert [row["data"].get(key) for row in get_rows(response)][:2] == [f"alpha-{key_id}", f"beta-{key_id}"], response.text++[email protected]("label", ["lb`tick", "lb'quote", "lb$0", "lb\\slash", "x` OR 1=1 --"], ids=["backtick", "quote", "dollar", "backslash", "injection"])+def test_metrics_group_by_hostile_label(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_metrics: Callable[[list[Metrics]], None],+ label: str,+) -> None:+ now = datetime.now(tz=UTC).replace(second=0, microsecond=0)+ metric = "quoting_gauge"+ insert_metrics([Metrics(metric_name=metric, labels={label: value, "host": host}, timestamp=now - timedelta(minutes=minute), value=1.0, type_="Gauge", is_monotonic=False) for minute in range(3) for value, host in [("alpha", "h1"), ("beta", "h2")]])+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)++ response = make_query_request(+ signoz,+ token,+ int((now - timedelta(minutes=5)).timestamp() * 1000),+ int((now + timedelta(minutes=1)).timestamp() * 1000),+ [build_builder_query("A", metric, "avg", "avg", group_by=[label])],+ )+ assert response.status_code == HTTPStatus.OK, response.text+ labels = {tuple(sorted((entry["key"]["name"], entry["value"]) for entry in item.get("labels", []))) for item in get_all_series(response.json(), "A")}+ assert labels == {((label, "alpha"),), ((label, "beta"),)}, response.text