diff --git a/ast/ast.go b/ast/ast.go index 489881fbd4..ff7d21f7e0 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -82,6 +82,7 @@ type SelectQuery struct { Window []*WindowDefinition `json:"window,omitempty"` OrderBy []*OrderByElement `json:"order_by,omitempty"` Interpolate []*InterpolateElement `json:"interpolate,omitempty"` + HasInterpolate bool `json:"has_interpolate,omitempty"` // INTERPOLATE clause present, possibly empty Limit Expression `json:"limit,omitempty"` LimitBy []Expression `json:"limit_by,omitempty"` LimitByLimit Expression `json:"limit_by_limit,omitempty"` // LIMIT value before BY (e.g., LIMIT 1 BY x LIMIT 3) @@ -341,7 +342,7 @@ type CreateQuery struct { AlterUser bool `json:"alter_user,omitempty"` HasAuthenticationData bool `json:"has_authentication_data,omitempty"` AuthenticationValues []string `json:"authentication_values,omitempty"` // Password/hash values from IDENTIFIED BY - AuthValidUntil map[int]Expression `json:"auth_valid_until,omitempty"` // VALID UNTIL per AuthenticationValues index + AuthValidUntil map[int]Expression `json:"auth_valid_until,omitempty"` // VALID UNTIL per AuthenticationValues index UserValidUntil Expression `json:"user_valid_until,omitempty"` // VALID UNTIL not attached to an auth method SSHKeyCount int `json:"ssh_key_count,omitempty"` // Number of SSH keys for ssh_key auth CreateDictionary bool `json:"create_dictionary,omitempty"` @@ -371,7 +372,7 @@ type ColumnDeclaration struct { TTL Expression `json:"ttl,omitempty"` PrimaryKey bool `json:"primary_key,omitempty"` // PRIMARY KEY constraint Comment string `json:"comment,omitempty"` - Settings []*SettingExpr `json:"settings,omitempty"` // Column-level SETTINGS + Settings []*SettingExpr `json:"settings,omitempty"` // Column-level SETTINGS Collation string `json:"collation,omitempty"` // COLLATE name } @@ -974,6 +975,7 @@ const ( ExplainPipeline ExplainType = "PIPELINE" ExplainEstimate ExplainType = "ESTIMATE" ExplainAnalyze ExplainType = "ANALYZE" + ExplainWhatIf ExplainType = "WHATIF" ExplainQueryTree ExplainType = "QUERY TREE" ExplainCurrentTransaction ExplainType = "CURRENT TRANSACTION" ) @@ -1919,7 +1921,7 @@ func (e *ExecuteAsQuery) statementNode() {} // ShowAccessEntitiesQuery represents SHOW USERS, SHOW ROLES, SHOW [ROW] POLICIES, etc. type ShowAccessEntitiesQuery struct { - Position token.Position `json:"-"` + Position token.Position `json:"-"` Keyword string `json:"keyword"` // e.g. "USERS", "ROW POLICIES" Format string `json:"format,omitempty"` OutFile string `json:"out_file,omitempty"` diff --git a/internal/explain/explain.go b/internal/explain/explain.go index a875609113..b12ea07efc 100644 --- a/internal/explain/explain.go +++ b/internal/explain/explain.go @@ -55,56 +55,9 @@ func ExplainStatements(stmts []ast.Statement) string { setParamSubstitution(stmts[0]) var sb strings.Builder Node(&sb, stmts[0], 0) - - // If the first statement is an INSERT and there are subsequent SELECT statements - // with simple literals, append those literal values (matching ClickHouse's behavior) - if _, isInsert := stmts[0].(*ast.InsertQuery); isInsert { - for i := 1; i < len(stmts); i++ { - if result := getSimpleSelectResult(stmts[i]); result != "" { - sb.WriteString(result) - sb.WriteString("\n") - } - } - } - return sb.String() } -// getSimpleSelectResult extracts the literal value from a simple SELECT statement -// like "SELECT 11111" and returns it as a string. Returns empty string if not a simple SELECT. -func getSimpleSelectResult(stmt ast.Statement) string { - // Check if it's a SelectWithUnionQuery - selectUnion, ok := stmt.(*ast.SelectWithUnionQuery) - if !ok { - return "" - } - - // Must have exactly one select query - if len(selectUnion.Selects) != 1 { - return "" - } - - // Get the inner select query - selectQuery, ok := selectUnion.Selects[0].(*ast.SelectQuery) - if !ok { - return "" - } - - // Must have exactly one expression in the select list - if len(selectQuery.Columns) != 1 { - return "" - } - - // Must be a literal - literal, ok := selectQuery.Columns[0].(*ast.Literal) - if !ok { - return "" - } - - // Format the literal value - return formatLiteralValue(literal) -} - // formatLiteralValue formats a literal value as it would appear in query results func formatLiteralValue(lit *ast.Literal) string { switch v := lit.Value.(type) { @@ -528,7 +481,7 @@ func Column(sb *strings.Builder, col *ast.ColumnDeclaration, depth int) { children++ } if children > 0 { - fmt.Fprintf(sb, "%sColumnDeclaration %s (children %d)\n", indent, sanitizeUTF8(col.Name), children) + fmt.Fprintf(sb, "%sColumnDeclaration %s (children %d)\n", indent, strings.ReplaceAll(sanitizeUTF8(col.Name), "'", "\\'"), children) } else { fmt.Fprintf(sb, "%sColumnDeclaration %s\n", indent, sanitizeUTF8(col.Name)) } @@ -632,7 +585,7 @@ func Index(sb *strings.Builder, idx *ast.IndexDefinition, depth int) { if idx.Expression != nil { // Expression is typically an identifier if ident, ok := idx.Expression.(*ast.Identifier); ok { - fmt.Fprintf(sb, "%s Identifier %s\n", indent, ident.Name()) + fmt.Fprintf(sb, "%s Identifier %s\n", indent, formatIdentifierName(ident)) } else { Node(sb, idx.Expression, depth+1) } diff --git a/internal/explain/expressions.go b/internal/explain/expressions.go index bc83507129..824dcd3772 100644 --- a/internal/explain/expressions.go +++ b/internal/explain/expressions.go @@ -31,8 +31,8 @@ func sanitizeUTF8(s string) string { for i := 0; i < len(s); { r, size := utf8.DecodeRuneInString(s[i:]) if r == utf8.RuneError && size == 1 { - // Invalid byte - write replacement character - result.WriteRune('\uFFFD') + // Invalid bytes are written as they are + result.WriteByte(s[i]) i++ } else if r == 0 { // Null byte - write as escape sequence \0 @@ -66,10 +66,9 @@ func explainIdentifier(sb *strings.Builder, n *ast.Identifier, indent string) { // escapeIdentifierPart escapes backslashes and single quotes in an identifier part // and sanitizes invalid UTF-8 bytes func escapeIdentifierPart(s string) string { - s = sanitizeUTF8(s) s = strings.ReplaceAll(s, "\\", "\\\\") s = strings.ReplaceAll(s, "'", "\\'") - return s + return sanitizeUTF8(s) } // formatIdentifierName formats an identifier name, handling JSON path notation, @@ -83,12 +82,8 @@ func formatIdentifierName(n *ast.Identifier) string { } result := escapeIdentifierPart(n.Parts[0]) for _, p := range n.Parts[1:] { - // JSON path notation: ^fieldname should be formatted as ^`fieldname` - if strings.HasPrefix(p, "^") { - result += ".^`" + escapeIdentifierPart(p[1:]) + "`" - } else { - result += "." + escapeIdentifierPart(p) - } + // JSON path parts (^`a`) are stored formatted by the parser + result += "." + escapeIdentifierPart(p) } return result } @@ -114,7 +109,7 @@ func explainLiteral(sb *strings.Builder, n *ast.Literal, indent string, depth in // ClickHouse 26 folds parenthesized literals into the tuple literal // Nested tuples that contain only primitive literals are OK if lit.Type == ast.LiteralTuple { - if !containsOnlyPrimitiveLiteralsWithUnary(lit) { + if inner, ok := lit.Value.([]ast.Expression); (ok && len(inner) == 1) || !containsOnlyPrimitiveLiteralsWithUnary(lit) { hasComplexExpr = true break } @@ -537,6 +532,11 @@ func explainUnaryExpr(sb *strings.Builder, n *ast.UnaryExpr, indent string, dept } func explainSubquery(sb *strings.Builder, n *ast.Subquery, indent string, depth int) { + // A scalar (EXPLAIN ...) subquery becomes SELECT * FROM viewExplain(...) + if explainQ, ok := n.Query.(*ast.ExplainQuery); ok { + explainViewExplain(sb, explainQ, n.Alias, indent, depth) + return + } children := 1 if n.Alias != "" { fmt.Fprintf(sb, "%sSubquery (alias %s) (children %d)\n", indent, escapeAlias(n.Alias), children) @@ -557,121 +557,7 @@ func explainAliasedExpr(sb *strings.Builder, n *ast.AliasedExpr, depth int) { switch e := n.Expr.(type) { case *ast.Literal: - // Check if this is a tuple with complex expressions that should be rendered as Function tuple - if e.Type == ast.LiteralTuple { - if exprs, ok := e.Value.([]ast.Expression); ok { - needsFunctionFormat := false - // Empty tuples always use Function tuple format - if len(exprs) == 0 { - needsFunctionFormat = true - } - for _, expr := range exprs { - if _, isLit := expr.(*ast.Literal); !isLit { - needsFunctionFormat = true - break - } - // Check if tuple contains array literals - these need Function tuple format - if lit, ok := expr.(*ast.Literal); ok { - if lit.Type == ast.LiteralArray { - needsFunctionFormat = true - break - } - // Also check if nested arrays/tuples contain non-literal elements - if containsNonLiteralInNested(lit) { - needsFunctionFormat = true - break - } - } - } - if needsFunctionFormat { - // Render as Function tuple with alias - fmt.Fprintf(sb, "%sFunction tuple (alias %s) (children %d)\n", indent, escapeAlias(n.Alias), 1) - // For empty ExpressionList, don't include children count - if len(exprs) > 0 { - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(exprs)) - } else { - fmt.Fprintf(sb, "%s ExpressionList\n", indent) - } - for _, expr := range exprs { - Node(sb, expr, depth+2) - } - return - } - } - } - // Check if this is an array containing specific expressions that need Function array format - if e.Type == ast.LiteralArray { - if exprs, ok := e.Value.([]ast.Expression); ok { - needsFunctionFormat := false - hasNestedArrays := false - for _, expr := range exprs { - // Check for tuples - use Function array - if lit, ok := expr.(*ast.Literal); ok && lit.Type == ast.LiteralTuple { - needsFunctionFormat = true - break - } - // Check for nested arrays - if lit, ok := expr.(*ast.Literal); ok && lit.Type == ast.LiteralArray { - hasNestedArrays = true - } - // Check for identifiers - use Function array - if _, ok := expr.(*ast.Identifier); ok { - needsFunctionFormat = true - break - } - // Check for function calls - use Function array - if _, ok := expr.(*ast.FunctionCall); ok { - needsFunctionFormat = true - break - } - // Check for CAST expressions - use Function array - if _, ok := expr.(*ast.CastExpr); ok { - needsFunctionFormat = true - break - } - // Check for binary expressions - use Function array - if _, ok := expr.(*ast.BinaryExpr); ok { - needsFunctionFormat = true - break - } - // Check for other non-literal expressions (skip arrays/tuples which are handled separately) - if lit, ok := expr.(*ast.Literal); !ok { - // Not a literal - check if it's a unary negation of a number (which is OK) - if unary, ok := expr.(*ast.UnaryExpr); ok && unary.Op == "-" { - if innerLit, ok := unary.Operand.(*ast.Literal); ok { - if innerLit.Type == ast.LiteralInteger || innerLit.Type == ast.LiteralFloat { - continue // Negated number is OK - } - } - } - needsFunctionFormat = true - break - } else if lit.Type != ast.LiteralArray && lit.Type != ast.LiteralTuple { - // Simple literal (not array/tuple) - OK - continue - } - // Arrays and tuples are handled by the earlier checks for nested arrays - } - // Also check for tuples at any depth within nested arrays - if hasNestedArrays && containsTuplesRecursive(exprs) { - needsFunctionFormat = true - } - if needsFunctionFormat { - // Render as Function array with alias - fmt.Fprintf(sb, "%sFunction array (alias %s) (children %d)\n", indent, escapeAlias(n.Alias), 1) - if len(exprs) > 0 { - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(exprs)) - } else { - fmt.Fprintf(sb, "%s ExpressionList\n", indent) - } - for _, expr := range exprs { - Node(sb, expr, depth+2) - } - return - } - } - } - fmt.Fprintf(sb, "%sLiteral %s (alias %s)\n", indent, FormatLiteral(e), escapeAlias(n.Alias)) + explainLiteralWithAlias(sb, e, n.Alias, indent, depth) case *ast.BinaryExpr: // Binary expressions become functions with alias fnName := OperatorToFunction(e.Op) @@ -779,6 +665,8 @@ func explainAliasedExpr(sb *strings.Builder, n *ast.AliasedExpr, depth int) { case *ast.IsNullExpr: // IS NULL expressions with alias explainIsNullExprWithAlias(sb, e, n.Alias, indent, depth) + case *ast.BetweenExpr: + explainBetweenExprWithAlias(sb, e, n.Alias, indent, depth) case *ast.Parameter: // QueryParameter with alias if e.Name != "" { @@ -1012,75 +900,7 @@ func explainWithElement(sb *strings.Builder, n *ast.WithElement, indent string, // When name is empty, don't show the alias part switch e := n.Query.(type) { case *ast.Literal: - // Tuples containing complex expressions (subqueries, function calls, etc) should be rendered as Function tuple - // But tuples of simple literals (including nested tuples of literals) stay as Literal - if e.Type == ast.LiteralTuple { - if exprs, ok := e.Value.([]ast.Expression); ok { - needsFunctionFormat := false - // Empty tuples always use Function tuple format - if len(exprs) == 0 { - needsFunctionFormat = true - } else { - for _, expr := range exprs { - // Check if any element is a truly complex expression (not just a literal) - if !isSimpleLiteralOrNestedLiteral(expr) { - needsFunctionFormat = true - break - } - } - } - if needsFunctionFormat { - if n.Name != "" { - fmt.Fprintf(sb, "%sFunction tuple (alias %s) (children %d)\n", indent, n.Name, 1) - } else { - fmt.Fprintf(sb, "%sFunction tuple (children %d)\n", indent, 1) - } - if len(exprs) > 0 { - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(exprs)) - } else { - fmt.Fprintf(sb, "%s ExpressionList\n", indent) - } - for _, expr := range exprs { - Node(sb, expr, depth+2) - } - return - } - } - } - // Arrays containing non-literal expressions should be rendered as Function array - if e.Type == ast.LiteralArray { - if exprs, ok := e.Value.([]ast.Expression); ok { - needsFunctionFormat := false - for _, elem := range exprs { - if !isSimpleLiteralOrNegation(elem) { - needsFunctionFormat = true - break - } - } - if needsFunctionFormat { - // Render as Function array with alias - if n.Name != "" { - fmt.Fprintf(sb, "%sFunction array (alias %s) (children %d)\n", indent, n.Name, 1) - } else { - fmt.Fprintf(sb, "%sFunction array (children %d)\n", indent, 1) - } - if len(exprs) > 0 { - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(exprs)) - } else { - fmt.Fprintf(sb, "%s ExpressionList\n", indent) - } - for _, elem := range exprs { - Node(sb, elem, depth+2) - } - return - } - } - } - if n.Name != "" { - fmt.Fprintf(sb, "%sLiteral %s (alias %s)\n", indent, FormatLiteral(e), n.Name) - } else { - fmt.Fprintf(sb, "%sLiteral %s\n", indent, FormatLiteral(e)) - } + explainLiteralWithAlias(sb, e, n.Name, indent, depth) case *ast.Identifier: if n.Name != "" { fmt.Fprintf(sb, "%sIdentifier %s (alias %s)\n", indent, e.Name(), n.Name) @@ -1204,3 +1024,28 @@ func explainWithElement(sb *strings.Builder, n *ast.WithElement, indent string, Node(sb, n.Query, depth) } } + +// explainLiteralWithAlias prints a literal the way explainLiteral does, with +// the alias added to its first line. +func explainLiteralWithAlias(sb *strings.Builder, lit *ast.Literal, alias string, indent string, depth int) { + if alias == "" { + explainLiteral(sb, lit, indent, depth) + return + } + var tmp strings.Builder + explainLiteral(&tmp, lit, indent, depth) + out := tmp.String() + nl := strings.IndexByte(out, '\n') + if nl < 0 { + nl = len(out) + } + first := out[:nl] + suffix := " (alias " + escapeAlias(alias) + ")" + if i := strings.Index(first, " (children "); i >= 0 { + first = first[:i] + suffix + first[i:] + } else { + first += suffix + } + sb.WriteString(first) + sb.WriteString(out[nl:]) +} diff --git a/internal/explain/format.go b/internal/explain/format.go index b469a6a6c0..9099bf8dbd 100644 --- a/internal/explain/format.go +++ b/internal/explain/format.go @@ -293,6 +293,14 @@ func needsBacktickQuoting(name string) bool { if name == "" { return false } + // backQuoteIfNeed also quotes the words that parse as literals + switch strings.ToLower(name) { + case "null", "true", "false", "nan", "inf": + return true + } + if name[0] >= '0' && name[0] <= '9' { + return true + } // Check each character - backticks needed if name contains non-alphanumeric/underscore chars for _, c := range name { if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') { @@ -329,7 +337,8 @@ func FormatDataType(dt *ast.DataType) string { // Named tuple field: "name Type" // Wrap name in backticks if it contains special characters name := ntp.Name - if needsBacktickQuoting(name) { + _, isObject := dt.Parameters[0].(*ast.ObjectTypeArgument) + if needsBacktickQuoting(name) || (isObject && strings.EqualFold(name, "skip")) { name = "`" + name + "`" } params = append(params, name+" "+FormatDataType(ntp.Type)) diff --git a/internal/explain/format_setting_names.go b/internal/explain/format_setting_names.go new file mode 100644 index 0000000000..8c660a7842 --- /dev/null +++ b/internal/explain/format_setting_names.go @@ -0,0 +1,179 @@ +package explain + +import "strings" + +// Generated from ClickHouse 26.8: query-level settings that an S3, Azure, +// HDFS or Kafka table keeps in its SETTINGS clause (format settings). +var formatSettingNames = func() map[string]bool { + m := map[string]bool{} + for _, n := range strings.Fields(formatSettingNamesText) { + m[n] = true + } + return m +}() + +const formatSettingNamesText = ` +allow_special_bool_values_inside_variant bool_false_representation bool_true_representation +check_conversion_from_numbers_to_enum column_names_for_schema_inference +date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands date_time_input_format +date_time_output_format date_time_overflow_behavior errors_output_format +format_avro_schema_registry_connection_timeout format_avro_schema_registry_max_retries +format_avro_schema_registry_receive_timeout format_avro_schema_registry_retry_initial_backoff_ms +format_avro_schema_registry_send_timeout format_avro_schema_registry_url +format_binary_max_array_size format_binary_max_object_size format_binary_max_string_size +format_capn_proto_enum_comparising_mode format_capn_proto_max_message_size +format_capn_proto_use_autogenerated_schema format_csv_allow_double_quotes +format_csv_allow_single_quotes format_csv_delimiter format_csv_null_representation +format_custom_escaping_rule format_custom_field_delimiter format_custom_result_after_delimiter +format_custom_result_before_delimiter format_custom_row_after_delimiter +format_custom_row_before_delimiter format_custom_row_between_delimiter +format_display_secrets_in_show_and_select format_geojson_validate_geometry +format_hive_text_rows_delimiter format_json_object_each_row_column_for_object_name +format_protobuf_use_autogenerated_schema format_regexp format_regexp_escaping_rule +format_regexp_skip_unmatched format_schema format_schema_message_name format_schema_source +format_template_resultset format_template_resultset_format format_template_row +format_template_row_format format_template_rows_between_delimiter format_tsv_null_representation +input_format_allow_errors_num input_format_allow_errors_ratio input_format_allow_seeks +input_format_arrow_allow_missing_columns input_format_arrow_case_insensitive_column_matching +input_format_arrow_import_nested +input_format_arrow_skip_columns_with_unsupported_types_in_schema_inference +input_format_arrow_use_native_reader input_format_avro_allow_missing_fields +input_format_avro_null_as_default input_format_binary_decode_types_in_binary_format +input_format_binary_max_type_complexity input_format_binary_read_json_as_string +input_format_bson_skip_fields_with_unsupported_types_in_schema_inference +input_format_capn_proto_skip_fields_with_unsupported_types_in_schema_inference +input_format_column_name_matching_mode input_format_connection_handling +input_format_csv_allow_cr_end_of_line input_format_csv_allow_variable_number_of_columns +input_format_csv_allow_whitespace_or_tab_as_delimiter input_format_csv_arrays_as_nested_csv +input_format_csv_deserialize_separate_columns_into_tuple input_format_csv_detect_header +input_format_csv_empty_as_default input_format_csv_enum_as_number +input_format_csv_missing_nullable_as_empty_string input_format_csv_skip_first_lines +input_format_csv_skip_trailing_empty_lines input_format_csv_trim_whitespaces +input_format_csv_try_infer_numbers_from_strings +input_format_csv_try_infer_strings_from_quoted_tuples +input_format_csv_use_best_effort_in_schema_inference input_format_csv_use_default_on_bad_values +input_format_custom_allow_variable_number_of_columns input_format_custom_detect_header +input_format_custom_skip_trailing_empty_lines input_format_defaults_for_omitted_fields +input_format_force_null_for_omitted_fields input_format_geojson_unsupported_geometry_handling +input_format_hive_text_allow_variable_number_of_columns +input_format_hive_text_collection_items_delimiter input_format_hive_text_fields_delimiter +input_format_hive_text_map_keys_delimiter input_format_import_nested_json +input_format_ipv4_default_on_conversion_error input_format_ipv6_default_on_conversion_error +input_format_json_compact_allow_variable_number_of_columns +input_format_json_defaults_for_missing_elements_in_named_tuple input_format_json_empty_as_default +input_format_json_ignore_unknown_keys_in_named_tuple input_format_json_ignore_unnecessary_fields +input_format_json_infer_array_of_dynamic_from_array_of_different_types +input_format_json_infer_incomplete_types_as_strings input_format_json_map_as_array_of_tuples +input_format_json_max_depth input_format_json_max_object_size +input_format_json_max_string_column_growth_step input_format_json_named_tuples_as_objects +input_format_json_read_arrays_as_strings input_format_json_read_bools_as_numbers +input_format_json_read_bools_as_strings input_format_json_read_numbers_as_strings +input_format_json_read_objects_as_strings input_format_json_throw_on_bad_escape_sequence +input_format_json_try_infer_named_tuples_from_objects +input_format_json_try_infer_numbers_from_strings +input_format_json_use_string_type_for_ambiguous_paths_in_named_tuples_inference_from_objects +input_format_json_validate_types_from_metadata input_format_max_block_size_bytes +input_format_max_block_wait_ms input_format_max_bytes_to_read_for_schema_inference +input_format_max_rows_to_read_for_schema_inference input_format_msgpack_number_of_columns +input_format_mysql_dump_map_column_names input_format_mysql_dump_table_name +input_format_native_allow_types_conversion input_format_native_decode_types_in_binary_format +input_format_null_as_default input_format_orc_allow_missing_columns +input_format_orc_case_insensitive_column_matching input_format_orc_dictionary_as_low_cardinality +input_format_orc_filter_push_down input_format_orc_import_nested +input_format_orc_reader_time_zone_name input_format_orc_row_batch_size +input_format_orc_skip_columns_with_unsupported_types_in_schema_inference +input_format_orc_use_fast_decoder input_format_parallel_parsing +input_format_parquet_allow_geoparquet_parser input_format_parquet_allow_missing_columns +input_format_parquet_bloom_filter_push_down input_format_parquet_case_insensitive_column_matching +input_format_parquet_dictionary_filter_push_down input_format_parquet_enable_json_parsing +input_format_parquet_enable_row_group_prefetch input_format_parquet_filter_push_down +input_format_parquet_import_nested input_format_parquet_local_file_min_bytes_for_seek +input_format_parquet_local_time_as_utc input_format_parquet_max_block_size +input_format_parquet_memory_high_watermark input_format_parquet_memory_low_watermark +input_format_parquet_page_filter_push_down input_format_parquet_prefer_block_bytes +input_format_parquet_preserve_order +input_format_parquet_skip_columns_with_unsupported_types_in_schema_inference +input_format_parquet_spatial_filter_push_down input_format_parquet_use_native_reader +input_format_parquet_use_native_reader_v3 input_format_parquet_use_offset_index +input_format_parquet_verify_checksums input_format_protobuf_flatten_google_wrappers +input_format_protobuf_oneof_presence +input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference +input_format_read_datetime_number_as_raw_value input_format_record_errors_file_path +input_format_skip_unknown_fields input_format_try_infer_dates input_format_try_infer_datetimes +input_format_try_infer_datetimes_only_datetime64 input_format_try_infer_exponent_floats +input_format_try_infer_integers input_format_try_infer_variants +input_format_tsv_allow_variable_number_of_columns input_format_tsv_crlf_end_of_line +input_format_tsv_detect_header input_format_tsv_empty_as_default input_format_tsv_enum_as_number +input_format_tsv_skip_first_lines input_format_tsv_skip_trailing_empty_lines +input_format_tsv_use_best_effort_in_schema_inference input_format_values_accurate_types_of_literals +input_format_values_deduce_templates_of_expressions input_format_values_interpret_expressions +input_format_with_names_use_header input_format_with_types_use_header +insert_distributed_one_random_shard interval_output_format into_outfile_create_parent_directories +json_type_escape_dots_in_keys max_dynamic_subcolumns_in_json_type_parsing +output_format_always_write_decimal_point_in_float_and_decimal output_format_arrow_compression_method +output_format_arrow_date_as_uint16 output_format_arrow_fixed_string_as_fixed_byte_array +output_format_arrow_low_cardinality_as_dictionary output_format_arrow_max_record_batch_size_bytes +output_format_arrow_record_batch_size output_format_arrow_record_batch_size_bytes +output_format_arrow_string_as_string output_format_arrow_unsupported_types_as_binary +output_format_arrow_use_64_bit_indexes_for_dictionary output_format_arrow_use_native_writer +output_format_arrow_use_signed_indexes_for_dictionary output_format_avro_codec +output_format_avro_confluent_subject output_format_avro_rows_in_file +output_format_avro_string_column_pattern output_format_avro_sync_interval +output_format_binary_encode_types_in_binary_format output_format_binary_write_json_as_string +output_format_bson_string_as_string output_format_compression_level +output_format_compression_zstd_window_log output_format_csv_crlf_end_of_line +output_format_csv_header_serialize_tuple_into_separate_columns +output_format_csv_serialize_tuple_into_separate_columns output_format_decimal_trailing_zeros +output_format_enable_streaming output_format_float_precision output_format_image_height +output_format_image_streaming_animation output_format_image_terminal_mode +output_format_image_time_divisor_seconds output_format_image_time_multiplier_seconds +output_format_image_width output_format_json_array_of_rows output_format_json_escape_forward_slashes +output_format_json_map_as_array_of_tuples output_format_json_named_tuples_as_objects +output_format_json_pretty_print output_format_json_quote_64bit_floats +output_format_json_quote_64bit_integers output_format_json_quote_decimals +output_format_json_quote_denormals output_format_json_skip_null_value_in_named_tuples +output_format_json_validate_utf8 output_format_markdown_escape_special_characters +output_format_msgpack_uuid_representation output_format_native_encode_types_in_binary_format +output_format_native_use_flattened_dynamic_and_json_serialization +output_format_native_write_json_as_string output_format_orc_compression_block_size +output_format_orc_compression_method output_format_orc_dictionary_key_size_threshold +output_format_orc_row_index_stride output_format_orc_string_as_string +output_format_orc_writer_time_zone_name output_format_parallel_formatting +output_format_parquet_batch_size output_format_parquet_bloom_filter_bits_per_value +output_format_parquet_bloom_filter_flush_threshold_bytes +output_format_parquet_compliant_nested_types output_format_parquet_compression_method +output_format_parquet_data_page_size output_format_parquet_date_as_uint16 +output_format_parquet_datetime_as_uint32 output_format_parquet_enum_as_byte_array +output_format_parquet_fixed_string_as_fixed_byte_array output_format_parquet_geometadata +output_format_parquet_max_dictionary_size output_format_parquet_parallel_encoding +output_format_parquet_row_group_size output_format_parquet_row_group_size_bytes +output_format_parquet_string_as_string output_format_parquet_unsupported_types_as_binary +output_format_parquet_use_custom_encoder output_format_parquet_version +output_format_parquet_wide_integer_as_decimal output_format_parquet_write_bloom_filter +output_format_parquet_write_checksums output_format_parquet_write_page_index +output_format_pretty_color output_format_pretty_display_footer_column_names +output_format_pretty_display_footer_column_names_min_rows output_format_pretty_fallback_to_vertical +output_format_pretty_fallback_to_vertical_max_rows_per_chunk +output_format_pretty_fallback_to_vertical_min_columns +output_format_pretty_fallback_to_vertical_min_table_width output_format_pretty_glue_chunks +output_format_pretty_grid_charset output_format_pretty_highlight_digit_groups +output_format_pretty_highlight_trailing_spaces output_format_pretty_max_column_name_width_cut_to +output_format_pretty_max_column_name_width_min_chars_to_cut +output_format_pretty_max_column_pad_width output_format_pretty_max_rows +output_format_pretty_max_value_width output_format_pretty_max_value_width_apply_for_single_value +output_format_pretty_multiline_fields output_format_pretty_named_tuples_as_json +output_format_pretty_row_numbers output_format_pretty_single_large_number_tip_threshold +output_format_pretty_squash_consecutive_ms output_format_pretty_squash_max_wait_ms +output_format_pretty_use_nbsp_for_padding output_format_protobuf_nullables_with_google_wrappers +output_format_schema output_format_sql_insert_include_column_names +output_format_sql_insert_max_batch_size output_format_sql_insert_quote_names +output_format_sql_insert_table_name output_format_sql_insert_use_replace +output_format_trim_fixed_string output_format_tsv_crlf_end_of_line +output_format_values_escape_quote_with_quote output_format_write_statistics precise_float_parsing +schema_inference_hints schema_inference_make_columns_nullable +schema_inference_make_json_columns_nullable schema_inference_mode +show_create_query_identifier_quoting_rule show_create_query_identifier_quoting_style +type_json_allow_duplicated_key_with_literal_and_nested_object type_json_skip_duplicated_paths +type_json_skip_invalid_typed_paths type_json_use_partial_match_to_skip_paths_by_regexp +validate_experimental_and_suspicious_types_inside_nested_types +` diff --git a/internal/explain/functions.go b/internal/explain/functions.go index f9a1683ae8..309eedab2f 100644 --- a/internal/explain/functions.go +++ b/internal/explain/functions.go @@ -227,17 +227,12 @@ func handleSpecialFunction(sb *strings.Builder, n *ast.FunctionCall, alias strin fnName := strings.ToUpper(n.Name) // date_part('unit', expr) is parsed like EXTRACT(unit FROM expr) - if fnName == "DATE_PART" { + if fnName == "DATE_PART" || fnName == "DATEPART" { if explainDatePart(sb, n, alias, indent, depth) { return true } } - // Handle kql() function - transforms KQL (Kusto Query Language) to SQL - if fnName == "KQL" { - return handleKQLFunction(sb, n, alias, indent, depth) - } - // Handle quantified comparison operators (ANY/ALL with comparison operators) if handled := handleQuantifiedComparison(sb, n, alias, indent, depth); handled { return true @@ -598,7 +593,10 @@ func explainCastExprWithAlias(sb *strings.Builder, n *ast.CastExpr, alias string // For arrays/tuples of simple primitives, use FormatLiteral (Array_[...] format) // For strings and other types, use string format if lit.Type == ast.LiteralArray || lit.Type == ast.LiteralTuple { - if useArrayFormat { + if !castOperandIsPlainText(lit) { + // Not parseable as a plain-text literal: ClickHouse parses it as an expression + Node(sb, n.Expr, depth+2) + } else if useArrayFormat { fmt.Fprintf(sb, "%s Literal %s\n", indent, FormatLiteral(lit)) } else if containsCastExpressions(lit) || !containsOnlyLiterals(lit) || !castOperandIsPlainText(lit) { // Array contains CastExpr or non-literal elements - output as Function array with children @@ -1886,208 +1884,6 @@ func explainWindowSpec(sb *strings.Builder, n *ast.WindowSpec, indent string, de } } -// handleKQLFunction handles the kql() table function. -// kql() transforms Kusto Query Language (KQL) into SQL and wraps it in a view() function. -// Example: kql($$Customers|project FirstName$$) -> view(SELECT FirstName FROM Customers) -func handleKQLFunction(sb *strings.Builder, n *ast.FunctionCall, alias string, indent string, depth int) bool { - if len(n.Arguments) != 1 { - return false - } - - // Get the KQL string from the argument - lit, ok := n.Arguments[0].(*ast.Literal) - if !ok || lit.Type != ast.LiteralString { - return false - } - - kqlStr, ok := lit.Value.(string) - if !ok { - return false - } - - // Parse the KQL string - parsed := parseKQL(kqlStr) - if parsed == nil { - return false - } - - // Output as Function view - fmt.Fprintf(sb, "%sFunction view (children %d)\n", indent, 1) - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1) - fmt.Fprintf(sb, "%s SelectWithUnionQuery (children %d)\n", indent, 1) - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 1) - - // Calculate children count for SelectQuery - // Always have: TablesInSelectQuery, ExpressionList (columns) - // Optionally: WHERE clause (Function equals/etc) - selectChildren := 2 - if parsed.filter != nil { - selectChildren = 3 - } - - fmt.Fprintf(sb, "%s SelectQuery (children %d)\n", indent, selectChildren) - - // Output TablesInSelectQuery first - fmt.Fprintf(sb, "%s TablesInSelectQuery (children %d)\n", indent, 1) - fmt.Fprintf(sb, "%s TablesInSelectQueryElement (children %d)\n", indent, 1) - fmt.Fprintf(sb, "%s TableExpression (children %d)\n", indent, 1) - fmt.Fprintf(sb, "%s TableIdentifier %s\n", indent, parsed.tableName) - - // Output WHERE clause if present (before columns in the order shown in expected output) - if parsed.filter != nil { - explainKQLFilter(sb, parsed.filter, indent+" ", depth+5) - } - - // Output columns (ExpressionList) - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(parsed.columns)) - for _, col := range parsed.columns { - fmt.Fprintf(sb, "%s Identifier %s\n", indent, col) - } - - return true -} - -// kqlParsed represents a parsed KQL query -type kqlParsed struct { - tableName string - columns []string - filter *kqlFilter -} - -// kqlFilter represents a KQL filter condition -type kqlFilter struct { - left string - operator string - right string -} - -// parseKQL parses a KQL string into its components -// Supports: TableName | project col1, col2, ... | filter condition -func parseKQL(kql string) *kqlParsed { - // Split by pipe operator - parts := splitKQLPipes(kql) - if len(parts) == 0 { - return nil - } - - result := &kqlParsed{} - - // First part is always the table name - result.tableName = strings.TrimSpace(parts[0]) - - // Process remaining operators - for i := 1; i < len(parts); i++ { - part := strings.TrimSpace(parts[i]) - - if strings.HasPrefix(strings.ToLower(part), "project ") { - // project col1, col2, ... - columnsStr := strings.TrimPrefix(part, "project ") - columnsStr = strings.TrimPrefix(columnsStr, "PROJECT ") - cols := strings.Split(columnsStr, ",") - for _, col := range cols { - result.columns = append(result.columns, strings.TrimSpace(col)) - } - } else if strings.HasPrefix(strings.ToLower(part), "filter ") { - // filter condition - conditionStr := strings.TrimPrefix(part, "filter ") - conditionStr = strings.TrimPrefix(conditionStr, "FILTER ") - result.filter = parseKQLCondition(conditionStr) - } - } - - return result -} - -// splitKQLPipes splits a KQL string by pipe operators -func splitKQLPipes(kql string) []string { - var parts []string - var current strings.Builder - inQuote := false - quoteChar := byte(0) - - for i := 0; i < len(kql); i++ { - c := kql[i] - - if !inQuote && (c == '\'' || c == '"') { - inQuote = true - quoteChar = c - current.WriteByte(c) - } else if inQuote && c == quoteChar { - inQuote = false - current.WriteByte(c) - } else if !inQuote && c == '|' { - parts = append(parts, current.String()) - current.Reset() - } else { - current.WriteByte(c) - } - } - - if current.Len() > 0 { - parts = append(parts, current.String()) - } - - return parts -} - -// parseKQLCondition parses a KQL condition like "LastName=='Diaz'" -func parseKQLCondition(cond string) *kqlFilter { - cond = strings.TrimSpace(cond) - - // Try to match comparison operators - // KQL uses == for equality - operators := []string{"==", "!=", ">=", "<=", ">", "<"} - for _, op := range operators { - if idx := strings.Index(cond, op); idx > 0 { - left := strings.TrimSpace(cond[:idx]) - right := strings.TrimSpace(cond[idx+len(op):]) - return &kqlFilter{ - left: left, - operator: op, - right: right, - } - } - } - - return nil -} - -// explainKQLFilter outputs the EXPLAIN AST for a KQL filter condition -func explainKQLFilter(sb *strings.Builder, filter *kqlFilter, indent string, depth int) { - // Map KQL operators to ClickHouse function names - fnName := "equals" - switch filter.operator { - case "==": - fnName = "equals" - case "!=": - fnName = "notEquals" - case ">": - fnName = "greater" - case "<": - fnName = "less" - case ">=": - fnName = "greaterOrEquals" - case "<=": - fnName = "lessOrEquals" - } - - fmt.Fprintf(sb, "%sFunction %s (children %d)\n", indent, fnName, 1) - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, 2) - fmt.Fprintf(sb, "%s Identifier %s\n", indent, filter.left) - - // Output the right side - could be a string literal or identifier - rightVal := filter.right - if (strings.HasPrefix(rightVal, "'") && strings.HasSuffix(rightVal, "'")) || - (strings.HasPrefix(rightVal, "\"") && strings.HasSuffix(rightVal, "\"")) { - // String literal - remove quotes and escape for output - rightVal = rightVal[1 : len(rightVal)-1] - fmt.Fprintf(sb, "%s Literal \\'%s\\'\n", indent, rightVal) - } else { - // Identifier - fmt.Fprintf(sb, "%s Identifier %s\n", indent, rightVal) - } -} - // explainInListHeader prints the ExpressionList of an IN list; an empty list // (x IN ()) prints without a children count. func explainInListHeader(sb *strings.Builder, indent string, n int) { diff --git a/internal/explain/secrets.go b/internal/explain/secrets.go index ba863b648c..09bf736748 100644 --- a/internal/explain/secrets.go +++ b/internal/explain/secrets.go @@ -1145,10 +1145,57 @@ func hideLiteralsInSubtree(e ast.Expression) ast.Expression { } } return &c + case *ast.Subquery: + if q := hideLiteralsInQuery(n.Query); q != nil { + c := *n + c.Query = q + return &c + } } return e } +// hideLiteralsInQuery hides the literals of a subquery's expressions. +func hideLiteralsInQuery(stmt ast.Statement) ast.Statement { + hideAll := func(exprs []ast.Expression) []ast.Expression { + if exprs == nil { + return nil + } + out := make([]ast.Expression, len(exprs)) + for i, x := range exprs { + out[i] = hideLiteralsInSubtree(x) + } + return out + } + hide := func(x ast.Expression) ast.Expression { + if x == nil { + return nil + } + return hideLiteralsInSubtree(x) + } + switch q := stmt.(type) { + case *ast.SelectWithUnionQuery: + c := *q + c.Selects = make([]ast.Statement, len(q.Selects)) + for i, sel := range q.Selects { + if h := hideLiteralsInQuery(sel); h != nil { + c.Selects[i] = h + } else { + c.Selects[i] = sel + } + } + return &c + case *ast.SelectQuery: + c := *q + c.Columns = hideAll(q.Columns) + c.Where = hide(q.Where) + c.PreWhere = hide(q.PreWhere) + c.Having = hide(q.Having) + return &c + } + return nil +} + // maskFunctionSecrets returns fn, or a copy of it with secret arguments hidden. func maskFunctionSecrets(fn *ast.FunctionCall) *ast.FunctionCall { if len(fn.Arguments) == 0 && len(fn.Settings) == 0 { diff --git a/internal/explain/select.go b/internal/explain/select.go index 41849d7e94..182b35429c 100644 --- a/internal/explain/select.go +++ b/internal/explain/select.go @@ -69,6 +69,10 @@ func extractWithClause(stmt ast.Statement) []ast.Expression { if len(s.Selects) > 0 { return extractWithClause(s.Selects[0]) } + case *ast.SelectIntersectExceptQuery: + if len(s.Selects) > 0 { + return extractWithClause(s.Selects[0]) + } } return nil } @@ -165,17 +169,6 @@ func explainSelectQueryWithInheritedWith(sb *strings.Builder, stmt ast.Statement Node(sb, o, depth+2) } } - // SETTINGS (when INTERPOLATE is present, SETTINGS comes before INTERPOLATE) - if len(sq.Settings) > 0 && len(sq.Interpolate) > 0 && !sq.SettingsAfterFormat { - fmt.Fprintf(sb, "%s Set\n", indent) - } - // INTERPOLATE - if len(sq.Interpolate) > 0 { - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(sq.Interpolate)) - for _, i := range sq.Interpolate { - Node(sb, i, depth+2) - } - } // LIMIT BY handling - order: LimitByOffset, LimitByLimit, LimitBy expressions, Offset, Limit if sq.LimitByLimit != nil { // Output LIMIT BY offset first (if present) @@ -223,10 +216,16 @@ func explainSelectQueryWithInheritedWith(sb *strings.Builder, stmt ast.Statement Node(sb, sq.Limit, depth+1) } } - // SETTINGS (when no INTERPOLATE - the case with INTERPOLATE is handled above) - if len(sq.Settings) > 0 && len(sq.Interpolate) == 0 && !sq.SettingsAfterFormat { + if len(sq.Settings) > 0 && !sq.SettingsAfterFormat { fmt.Fprintf(sb, "%s Set\n", indent) } + // INTERPOLATE comes after LIMIT and SETTINGS + if sq.HasInterpolate || len(sq.Interpolate) > 0 { + explainInListHeader(sb, indent+" ", len(sq.Interpolate)) + for _, i := range sq.Interpolate { + Node(sb, i, depth+2) + } + } // TOP clause if sq.Top != nil { Node(sb, sq.Top, depth+1) @@ -290,11 +289,8 @@ func explainSelectWithUnionQueryWithInheritedWith(sb *strings.Builder, n *ast.Se fmt.Fprintf(sb, "%s Set\n", indent) } // FORMAT clause - check individual SelectQuery nodes - for _, sel := range n.Selects { - if sq, ok := sel.(*ast.SelectQuery); ok && sq.Format != nil { - Node(sb, sq.Format, depth+1) - break - } + if f := unionFormat(n); f != nil { + Node(sb, f, depth+1) } } @@ -372,8 +368,31 @@ func explainSelectWithUnionQuery(sb *strings.Builder, n *ast.SelectWithUnionQuer inheritedWith = extractWithClause(selects[0]) } + // Operands of a flattened nested union inherit that union's own WITH + nestedWith := map[ast.Statement][]ast.Expression{} + var collectNestedWith func(stmts []ast.Statement) + collectNestedWith = func(stmts []ast.Statement) { + for _, st := range stmts { + nested, ok := st.(*ast.SelectWithUnionQuery) + if !ok || len(nested.Selects) == 0 { + continue + } + if w := extractWithClause(nested.Selects[0]); len(w) > 0 { + for _, inner := range nested.Selects[1:] { + if _, seen := nestedWith[inner]; !seen { + nestedWith[inner] = w + } + } + } + collectNestedWith(nested.Selects) + } + } + collectNestedWith(selects) + for i, sel := range groupedSelects { - if i > 0 && len(inheritedWith) > 0 { + if w, ok := nestedWith[sel]; ok && i > 0 { + explainSelectQueryWithInheritedWith(sb, sel, w, depth+2, true) + } else if i > 0 && len(inheritedWith) > 0 { // Subsequent operands inherit the WITH clause from the first operand explainSelectQueryWithInheritedWith(sb, sel, inheritedWith, depth+2, true) } else { @@ -394,11 +413,8 @@ func explainSelectWithUnionQuery(sb *strings.Builder, n *ast.SelectWithUnionQuer // FORMAT clause - check if any SelectQuery has Format set // Skip this when inside CreateQuery context, as Format is output at CreateQuery level if !inCreateQueryContext { - for _, sel := range n.Selects { - if sq, ok := sel.(*ast.SelectQuery); ok && sq.Format != nil { - Node(sb, sq.Format, depth+1) - break - } + if f := unionFormat(n); f != nil { + Node(sb, f, depth+1) } } } @@ -504,15 +520,12 @@ func explainSelectQuery(sb *strings.Builder, n *ast.SelectQuery, indent string, Node(sb, o, depth+2) } } - // SETTINGS (when INTERPOLATE is present, SETTINGS comes before INTERPOLATE) - if len(n.Settings) > 0 && len(n.Interpolate) > 0 && !n.SettingsAfterFormat { - fmt.Fprintf(sb, "%s Set\n", indent) - } - // INTERPOLATE - if len(n.Interpolate) > 0 { - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Interpolate)) - for _, i := range n.Interpolate { - Node(sb, i, depth+2) + // DISTINCT ON columns become LIMIT 1 BY + if len(n.DistinctOn) > 0 { + fmt.Fprintf(sb, "%s Literal UInt64_1\n", indent) + fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.DistinctOn)) + for _, col := range n.DistinctOn { + Node(sb, col, depth+2) } } // LIMIT BY handling - order: LimitByOffset, LimitByLimit, LimitBy expressions, Offset, Limit @@ -572,21 +585,20 @@ func explainSelectQuery(sb *strings.Builder, n *ast.SelectQuery, indent string, // SETTINGS is output at SelectQuery level only when NOT after FORMAT // When SettingsAfterFormat is true, it's output at SelectWithUnionQuery level instead // When INTERPOLATE is present, SETTINGS was already output above - if len(n.Settings) > 0 && len(n.Interpolate) == 0 && !n.SettingsAfterFormat { + if len(n.Settings) > 0 && !n.SettingsAfterFormat { fmt.Fprintf(sb, "%s Set\n", indent) } + // INTERPOLATE comes after LIMIT and SETTINGS + if n.HasInterpolate || len(n.Interpolate) > 0 { + explainInListHeader(sb, indent+" ", len(n.Interpolate)) + for _, i := range n.Interpolate { + Node(sb, i, depth+2) + } + } // TOP clause is output at the end if n.Top != nil { Node(sb, n.Top, depth+1) } - // DISTINCT ON columns - if len(n.DistinctOn) > 0 { - fmt.Fprintf(sb, "%s Literal UInt64_1\n", indent) - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.DistinctOn)) - for _, col := range n.DistinctOn { - Node(sb, col, depth+2) - } - } } func explainOrderByElement(sb *strings.Builder, n *ast.OrderByElement, indent string, depth int) { @@ -677,11 +689,8 @@ func countSelectUnionChildren(n *ast.SelectWithUnionQuery) int { // Check if any SelectQuery has Format set // Skip this when inside CreateQuery context, as Format is output at CreateQuery level if !inCreateQueryContext { - for _, sel := range n.Selects { - if sq, ok := sel.(*ast.SelectQuery); ok && sq.Format != nil { - count++ - break - } + if f := unionFormat(n); f != nil { + count++ } } // Count union-level SETTINGS (either before or after FORMAT) @@ -890,7 +899,7 @@ func countSelectQueryChildren(n *ast.SelectQuery) int { if len(n.OrderBy) > 0 { count++ } - if len(n.Interpolate) > 0 { + if n.HasInterpolate || len(n.Interpolate) > 0 { count++ } if n.LimitByOffset != nil { @@ -944,3 +953,31 @@ func cteAliases(n *ast.SelectQuery) []string { } return aliases } + +// unionFormat returns the FORMAT of the query, which the parser keeps on the +// last SELECT (possibly inside an INTERSECT/EXCEPT chain). +func unionFormat(n *ast.SelectWithUnionQuery) ast.Expression { + for _, sel := range n.Selects { + if sq, ok := sel.(*ast.SelectQuery); ok && sq.Format != nil { + return sq.Format + } + } + if len(n.Selects) > 0 { + if ie, ok := n.Selects[len(n.Selects)-1].(*ast.SelectIntersectExceptQuery); ok { + for ie != nil && len(ie.Selects) > 0 { + switch last := ie.Selects[len(ie.Selects)-1].(type) { + case *ast.SelectQuery: + if last.Format != nil { + return last.Format + } + return nil + case *ast.SelectIntersectExceptQuery: + ie = last + default: + return nil + } + } + } + } + return nil +} diff --git a/internal/explain/statements.go b/internal/explain/statements.go index cfd87167a1..05734be1c8 100644 --- a/internal/explain/statements.go +++ b/internal/explain/statements.go @@ -2,6 +2,7 @@ package explain import ( "fmt" + "math" "strings" "github.com/sqlc-dev/doubleclick/ast" @@ -127,10 +128,13 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string, return } // A table engine's SETTINGS clause drops query-level settings. - if n.Table != "" && n.Engine != nil && len(n.Settings) > 0 && (n.Comment == "" || n.SettingsBeforeComment) && engineDropsQuerySettings(n.Engine.Name) { + // Without an ENGINE the default engine (a MergeTree) applies. A storage + // clause left with no settings still prints an empty Storage definition. + storageSettingsDropped := false + if n.Table != "" && len(n.Settings) > 0 && (n.Comment == "" || n.SettingsBeforeComment) && (n.Engine == nil || engineDropsQuerySettings(n.Engine.Name)) { var kept []*ast.SettingExpr for _, st := range n.Settings { - if !querySettingNames[st.Name] { + if !querySettingNames[st.Name] || (n.Engine != nil && engineKeepsSetting(n.Engine.Name, st.Name)) { kept = append(kept, st) } } @@ -138,6 +142,7 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string, cp := *n cp.Settings = kept n = &cp + storageSettingsDropped = len(kept) == 0 } } // A view definition keeps its query-construction settings as written. @@ -240,7 +245,7 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string, settingsInStorage := len(n.Settings) > 0 && (n.Comment == "" || n.SettingsBeforeComment) // For WINDOW VIEW with INNER ENGINE, ORDER BY goes inside ViewTargets, not in regular Storage definition orderByInRegularStorage := len(n.OrderBy) > 0 && !(n.WindowView && n.InnerEngine != nil) - hasStorageChild := n.Engine != nil || orderByInRegularStorage || len(n.PrimaryKey) > 0 || len(n.UniqueKey) > 0 || n.PartitionBy != nil || n.SampleBy != nil || n.TTL != nil || settingsInStorage || len(n.ColumnsPrimaryKey) > 0 || hasColumnPrimaryKey + hasStorageChild := storageSettingsDropped || n.Engine != nil || orderByInRegularStorage || len(n.PrimaryKey) > 0 || len(n.UniqueKey) > 0 || n.PartitionBy != nil || n.SampleBy != nil || n.TTL != nil || settingsInStorage || len(n.ColumnsPrimaryKey) > 0 || hasColumnPrimaryKey if hasStorageChild { children++ } @@ -348,12 +353,6 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string, Index(sb, idx, depth+3) } } - if len(n.Projections) > 0 { - fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Projections)) - for _, proj := range n.Projections { - explainProjection(sb, proj, indent+" ", depth+3) - } - } // Output constraints wrapped in Constraint nodes if len(n.Constraints) > 0 { fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Constraints)) @@ -362,6 +361,12 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string, Node(sb, constraint.Expression, depth+4) } } + if len(n.Projections) > 0 { + fmt.Fprintf(sb, "%s ExpressionList (children %d)\n", indent, len(n.Projections)) + for _, proj := range n.Projections { + explainProjection(sb, proj, indent+" ", depth+3) + } + } // Output PRIMARY KEY columns as Function tuple if len(primaryKeyColumns) > 0 { fmt.Fprintf(sb, "%s Function tuple (children %d)\n", indent, 1) @@ -436,7 +441,7 @@ func explainCreateQuery(sb *strings.Builder, n *ast.CreateQuery, indent string, } // For WINDOW VIEW with INNER ENGINE, ORDER BY goes inside ViewTargets hasOrderByInStorage := len(n.OrderBy) > 0 && !(n.WindowView && n.InnerEngine != nil) - hasStorage := n.Engine != nil || hasOrderByInStorage || len(n.PrimaryKey) > 0 || len(n.UniqueKey) > 0 || n.PartitionBy != nil || n.SampleBy != nil || n.TTL != nil || settingsInStorage || len(n.ColumnsPrimaryKey) > 0 || hasColumnPrimaryKey + hasStorage := storageSettingsDropped || n.Engine != nil || hasOrderByInStorage || len(n.PrimaryKey) > 0 || len(n.UniqueKey) > 0 || n.PartitionBy != nil || n.SampleBy != nil || n.TTL != nil || settingsInStorage || len(n.ColumnsPrimaryKey) > 0 || hasColumnPrimaryKey if hasStorage { storageChildren := 0 if n.Engine != nil { @@ -1142,37 +1147,35 @@ func explainShowQuery(sb *strings.Builder, n *ast.ShowQuery, indent string) { // SHOW CREATE VIEW has special output format if n.ShowType == ast.ShowCreateView && (n.Database != "" || n.From != "") { - if n.Database != "" && n.From != "" { - children := 2 - if n.HasSettings { - children++ - } - fmt.Fprintf(sb, "%sShowCreateViewQuery %s %s (children %d)\n", indent, n.Database, n.From, children) - fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database) - fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.From) - if n.HasSettings { - fmt.Fprintf(sb, "%s Set\n", indent) - } - } else if n.From != "" { - children := 1 - if n.HasSettings { - children++ - } - fmt.Fprintf(sb, "%sShowCreateViewQuery %s (children %d)\n", indent, n.From, children) - fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.From) - if n.HasSettings { - fmt.Fprintf(sb, "%s Set\n", indent) - } - } else if n.Database != "" { - children := 1 - if n.HasSettings { - children++ - } - fmt.Fprintf(sb, "%sShowCreateViewQuery %s (children %d)\n", indent, n.Database, children) - fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Database) - if n.HasSettings { - fmt.Fprintf(sb, "%s Set\n", indent) - } + var idents []string + header := "" + switch { + case n.Database != "" && n.From != "": + idents = []string{n.Database, n.From} + header = n.Database + " " + n.From + case n.From != "": + idents = []string{n.From} + header = " " + n.From + default: + idents = []string{n.Database} + header = " " + n.Database + } + children := len(idents) + if n.Format != "" { + children++ + } + if n.HasSettings { + children++ + } + fmt.Fprintf(sb, "%sShowCreateViewQuery %s (children %d)\n", indent, header, children) + for _, id := range idents { + fmt.Fprintf(sb, "%s Identifier %s\n", indent, id) + } + if n.Format != "" { + fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format) + } + if n.HasSettings { + fmt.Fprintf(sb, "%s Set\n", indent) } return } @@ -1317,7 +1320,7 @@ func explainDescribeQuery(sb *strings.Builder, n *ast.DescribeQuery, indent stri } fmt.Fprintf(sb, "%sDescribeQuery (children %d)\n", indent, children) fmt.Fprintf(sb, "%s TableExpression (children 1)\n", indent) - explainFunctionCall(sb, n.TableFunction, indent+" ", 2) + explainFunctionCall(sb, n.TableFunction, indent+" ", depth+2) if n.Format != "" { fmt.Fprintf(sb, "%s Identifier %s\n", indent, n.Format) } @@ -1446,6 +1449,16 @@ func isEnumWithValues(n *ast.DataType) bool { if lit, ok := b.Left.(*ast.Literal); !ok || lit.Type != ast.LiteralString { return false } + // A value that does not fit Int64 is left to the generic type parser + right := b.Right + if u, ok := right.(*ast.UnaryExpr); ok && u.Op == "-" { + right = u.Operand + } + if lit, ok := right.(*ast.Literal); ok { + if v, ok := lit.Value.(uint64); ok && v > math.MaxInt64 { + return false + } + } } return true } @@ -2856,7 +2869,17 @@ func getParallelWithName(stmt ast.Statement) string { case *ast.InsertQuery: return "InsertQuery__" default: - return "Statement" + // getID('_') matches the EXPLAIN header with spaces as separators + var tmp strings.Builder + Node(&tmp, stmt, 0) + line, _, _ := strings.Cut(tmp.String(), "\n") + if i := strings.Index(line, " (children "); i >= 0 { + line = line[:i] + } + if line == "" { + return "Statement" + } + return strings.ReplaceAll(line, " ", "_") } } @@ -3104,12 +3127,25 @@ func engineDropsQuerySettings(engine string) bool { return true } switch engine { - case "Log", "TinyLog", "StripeLog", "Memory", "Null", "Kafka": + case "Log", "TinyLog", "StripeLog", "Memory", "Null", "Kafka", + "S3", "COSN", "OSS", "GCS", "AzureBlobStorage", "HDFS", "S3Queue", "AzureQueue": return true } return false } +// engineKeepsSetting reports whether an engine's own settings include a name +// that is also a query-level setting. +func engineKeepsSetting(engine, name string) bool { + switch engine { + case "S3Queue", "AzureQueue": + return name == "use_hive_partitioning" || formatSettingNames[name] + case "S3", "COSN", "OSS", "GCS", "AzureBlobStorage", "HDFS", "Kafka": + return formatSettingNames[name] + } + return false +} + // viewColumnAliases reports whether a view's column list only names columns. func viewColumnAliases(n *ast.CreateQuery) bool { if n.View == "" || len(n.Columns) == 0 || len(n.Indexes) > 0 || len(n.Projections) > 0 || len(n.Constraints) > 0 { diff --git a/lexer/lexer.go b/lexer/lexer.go index 3234b933eb..3186769d20 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -191,10 +191,10 @@ func (l *Lexer) NextToken() Item { if l.ch == '/' && l.peekChar() == '*' { return l.readBlockComment() } - // Unicode minus (U+2212) is treated as starting a line comment - // ClickHouse doesn't recognize it as an operator + // Unicode minus (U+2212) is a minus operator in ClickHouse 26 if l.ch == '\u2212' { - return l.readUnicodeMinusComment() + l.readChar() + return Item{Token: token.MINUS, Value: "-", Pos: pos} } switch l.ch { @@ -559,27 +559,22 @@ func (l *Lexer) readHexString() Item { var sb strings.Builder l.readChar() // skip opening quote + var digits []rune for !l.eof { if l.ch == '\'' { l.readChar() // skip closing quote break } - // Read two hex digits and convert to byte - hex1 := l.ch - l.readChar() - if l.eof || l.ch == '\'' { - // Odd number of hex digits - write single value - sb.WriteByte(byte(hexValue(hex1))) - if l.ch == '\'' { - l.readChar() // skip closing quote - } - break - } - hex2 := l.ch - val := hexValue(hex1)*16 + hexValue(hex2) - sb.WriteByte(byte(val)) + digits = append(digits, l.ch) l.readChar() } + // An odd number of digits is padded on the left + if len(digits)%2 == 1 { + digits = append([]rune{'0'}, digits...) + } + for i := 0; i+1 < len(digits); i += 2 { + sb.WriteByte(byte(hexValue(digits[i])*16 + hexValue(digits[i+1]))) + } return Item{Token: token.STRING, Value: sb.String(), Pos: pos} } @@ -614,6 +609,19 @@ func (l *Lexer) readBinaryString() Item { bits = paddedBits } + // A leading partial byte that is zero is dropped (binStringDecode) + if remainder != 0 && len(bits) > 8 { + zero := true + for _, b := range bits[:8] { + if b != 0 { + zero = false + } + } + if zero { + bits = bits[8:] + } + } + // Convert each group of 8 bits to a byte for i := 0; i < len(bits); i += 8 { var byteVal byte diff --git a/parser/expression.go b/parser/expression.go index a337361796..ad57224e9a 100644 --- a/parser/expression.go +++ b/parser/expression.go @@ -149,7 +149,8 @@ func (p *Parser) parseExpressionList() []ast.Expression { for p.currentIs(token.COMMA) { p.nextToken() // Handle trailing commas by checking if next token is a clause keyword - if p.isClauseKeyword() { + // (a column named from is followed by the FROM clause) + if p.isClauseKeyword() && !(p.currentIs(token.FROM) && p.peekIs(token.FROM)) { break } expr := p.parseExpression(LOWEST) @@ -351,12 +352,12 @@ func mergeMultiParamLambdas(exprs []ast.Expression) []ast.Expression { } // Only check at position 0 - the pattern must start at the beginning - if ident, ok := exprs[0].(*ast.Identifier); ok && len(ident.Parts) == 1 { + if ident, ok := exprs[0].(*ast.Identifier); ok && ident.Alias == "" { // Count consecutive simple identifiers at the start j := 0 var params []string for j < len(exprs) { - if id, ok := exprs[j].(*ast.Identifier); ok && len(id.Parts) == 1 { + if id, ok := exprs[j].(*ast.Identifier); ok && id.Alias == "" { params = append(params, id.Name()) j++ } else { @@ -397,7 +398,7 @@ func (p *Parser) parseImplicitAlias(expr ast.Expression) ast.Expression { if !canBeAlias { // Some keywords can be used as implicit aliases in ClickHouse switch p.current.Token { - case token.KEY, token.INDEX, token.VIEW, token.DATABASE, token.TABLE, token.SYNC: + case token.KEY, token.INDEX, token.VIEW, token.DATABASE, token.TABLE, token.SYNC, token.CLUSTER, token.ALIAS: canBeAlias = true case token.COMMENT: // "SELECT 1 comment" uses comment as an alias, but COMMENT 'text' @@ -849,7 +850,7 @@ func (p *Parser) parseFunctionCall(name string, pos token.Position) *ast.Functio // Handle view() and similar functions that take a subquery as argument // view(SELECT ...) should parse SELECT as a subquery - if (strings.EqualFold(name, "view") || strings.EqualFold(name, "eval")) && (p.isQueryStart()) { + if (strings.EqualFold(name, "view") || strings.EqualFold(name, "eval")) && (p.isQueryStart() || (p.currentIs(token.LPAREN) && (p.peekIs(token.SELECT) || p.peekIs(token.WITH) || p.peekIs(token.LPAREN)))) { subquery := p.parseSelectWithUnion() fn.Arguments = []ast.Expression{&ast.Subquery{Position: pos, Query: subquery}} } else if strings.EqualFold(name, "viewIfPermitted") && p.isQueryStart() { @@ -1488,16 +1489,6 @@ func (p *Parser) parseCase() ast.Expression { p.expect(token.END) - // Handle alias - if p.currentIs(token.AS) { - p.nextToken() - if p.currentIs(token.IDENT) { - expr.Alias = p.current.Value - expr.QuotedAlias = p.current.Quoted - p.nextToken() - } - } - return expr } @@ -2062,7 +2053,7 @@ func (p *Parser) parseSubstring() ast.Expression { return &ast.FunctionCall{ Position: pos, Name: name, - Arguments: args, + Arguments: mergeMultiParamLambdas(args), } } @@ -2520,8 +2511,15 @@ func (p *Parser) parseArrayAccess(left ast.Expression) ast.Expression { p.nextToken() // skip ] if ident, ok := left.(*ast.Identifier); ok { - // Append the JSON array type notation to the identifier - ident.Parts = append(ident.Parts, ":`Array(JSON)`") + // Append the JSON array type notation to the identifier; a[][] + // nests the array types + arrayType := "Array(JSON)" + for p.currentIs(token.LBRACKET) && p.peekIs(token.RBRACKET) { + p.nextToken() + p.nextToken() + arrayType = "Array(" + arrayType + ")" + } + ident.Parts = append(ident.Parts, ":`"+arrayType+"`") // Continue parsing any dot accesses that follow for p.currentIs(token.DOT) { @@ -3054,7 +3052,7 @@ func (p *Parser) parseKeywordAsFunction() ast.Expression { } // Handle view() and similar functions that take a subquery as argument - if (name == "view" || name == "eval") && (p.isQueryStart()) { + if (name == "view" || name == "eval") && (p.isQueryStart() || (p.currentIs(token.LPAREN) && (p.peekIs(token.SELECT) || p.peekIs(token.WITH) || p.peekIs(token.LPAREN)))) { subquery := p.parseSelectWithUnion() fn.Arguments = []ast.Expression{&ast.Subquery{Position: pos, Query: subquery}} } else if !p.currentIs(token.RPAREN) { @@ -3271,8 +3269,8 @@ func (p *Parser) parseAsteriskApply(asterisk *ast.Asterisk) ast.Expression { p.nextToken() // skip ( } - // Check for lambda expression: x -> expr - if p.currentIs(token.IDENT) && p.peekIs(token.ARROW) { + // Check for lambda expression: x -> expr or (x) -> expr + if (p.currentIs(token.IDENT) && p.peekIs(token.ARROW)) || p.currentIs(token.LPAREN) { // Parse lambda expression lambda := p.parseExpression(LOWEST) asterisk.Transformers = append(asterisk.Transformers, &ast.ColumnTransformer{ @@ -3329,8 +3327,8 @@ func (p *Parser) parseColumnsApply(matcher *ast.ColumnsMatcher) ast.Expression { p.nextToken() // skip ( } - // Check for lambda expression: x -> expr - if p.currentIs(token.IDENT) && p.peekIs(token.ARROW) { + // Check for lambda expression: x -> expr or (x) -> expr + if (p.currentIs(token.IDENT) && p.peekIs(token.ARROW)) || p.currentIs(token.LPAREN) { // Parse lambda expression lambda := p.parseExpression(LOWEST) matcher.Transformers = append(matcher.Transformers, &ast.ColumnTransformer{ @@ -3505,10 +3503,7 @@ func (p *Parser) isJSONPathPrefix() bool { // keep the prefix and are quoted when explained; @ parts are stored quoted, // as ClickHouse names the subcolumn json.@`a`. func jsonPathPart(prefix, name string) string { - if prefix == "@" { - return "@`" + name + "`" - } - return prefix + name + return prefix + "`" + name + "`" } // compoundIntervalFields lists the fields of the SQL-standard compound diff --git a/parser/parser.go b/parser/parser.go index 56a8cbd7a1..9859100e93 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -118,7 +118,7 @@ func (p *Parser) isExplainFollowedByStatement() bool { // Check if it's an EXPLAIN type or option upperValue := strings.ToUpper(p.peek.Value) switch upperValue { - case "QUERY", "AST", "SYNTAX", "PLAN", "PIPELINE", "ESTIMATE", "TABLE", "CURRENT": + case "QUERY", "AST", "SYNTAX", "PLAN", "PIPELINE", "ESTIMATE", "TABLE", "CURRENT", "WHATIF": return true case "HEADER", "ACTIONS", "DESCRIPTION", "JSON", "GRAPH", "COMPACT", "INDEXES", "SORTING", "AGGREGATION": // These are explain options @@ -1059,10 +1059,13 @@ func buildIntersectExceptTree(stmts []ast.Statement, ops []string) ast.Statement // Single statement, no grouping needed groupStmt = groupStmts[0] } else { - // Multiple statements connected by INTERSECT - groupStmt = &ast.SelectIntersectExceptQuery{ - Selects: groupStmts, - Operators: groupOps, + // Multiple statements connected by INTERSECT: left-associative binary tree + groupStmt = groupStmts[0] + for k, op := range groupOps { + groupStmt = &ast.SelectIntersectExceptQuery{ + Selects: []ast.Statement{groupStmt, groupStmts[k+1]}, + Operators: []string{op}, + } } } groups = append(groups, groupStmt) @@ -1242,6 +1245,15 @@ func (p *Parser) parseSelectInternal(preParsedWith []ast.Expression) *ast.Select p.nextToken() sel.WithTotals = true } + } else if p.currentIs(token.WITH) && (p.peekIs(token.ROLLUP) || p.peekIs(token.CUBE)) { + // WITH ROLLUP/CUBE without GROUP BY + p.nextToken() + if p.currentIs(token.ROLLUP) { + sel.WithRollup = true + } else { + sel.WithCube = true + } + p.nextToken() } // Parse HAVING clause @@ -1274,6 +1286,7 @@ func (p *Parser) parseSelectInternal(preParsedWith []ast.Expression) *ast.Select // Parse INTERPOLATE clause (comes after ORDER BY ... WITH FILL) if p.currentIs(token.INTERPOLATE) { p.nextToken() + sel.HasInterpolate = true sel.Interpolate = p.parseInterpolateList() } @@ -1371,6 +1384,11 @@ func (p *Parser) parseSelectInternal(preParsedWith []ast.Expression) *ast.Select } } } + // LIMIT n OFFSET m WITH TIES + if p.currentIs(token.WITH) && p.peekIs(token.TIES) { + p.nextToken() // skip WITH + p.nextToken() // skip TIES + } } // Parse FETCH FIRST ... ROW ONLY (SQL standard syntax) @@ -1920,6 +1938,10 @@ func (p *Parser) parseTableExpression() *ast.TableExpression { expr.Alias = p.current.Value p.nextToken() } + } else if p.currentIs(token.SELECT) && (p.peekIs(token.ON) || p.peekIs(token.USING)) { + // JOIN (...) select ON ...: SELECT can only be an alias here + expr.Alias = p.current.Value + p.nextToken() } else if (p.currentIs(token.IDENT) || p.current.Token.IsKeyword()) && !p.isKeywordForClause() && !p.currentIs(token.FINAL) && !p.currentIs(token.SAMPLE) && !p.isStreamClause() { // Don't consume PARALLEL as alias if followed by WITH (parallel query syntax) if p.currentIs(token.PARALLEL) && p.peekIs(token.WITH) { @@ -2083,10 +2105,10 @@ func (p *Parser) parseOrderByList() []*ast.OrderByElement { id.Parts[0] = "all" } - // Handle ASC/DESC - if p.currentIs(token.ASC) { + // Handle ASC/DESC (also spelled ASCENDING/DESCENDING) + if p.currentIs(token.ASC) || (p.currentIs(token.IDENT) && !p.current.Backquoted && !p.current.Quoted && strings.EqualFold(p.current.Value, "ASCENDING")) { p.nextToken() - } else if p.currentIs(token.DESC) { + } else if p.currentIs(token.DESC) || (p.currentIs(token.IDENT) && !p.current.Backquoted && !p.current.Quoted && strings.EqualFold(p.current.Value, "DESCENDING")) { elem.Descending = true p.nextToken() } @@ -2879,6 +2901,13 @@ func (p *Parser) parseCreateTable(create *ast.CreateQuery) { if p.isQueryStart() || p.currentIs(token.LPAREN) { // AS SELECT... or AS (SELECT...) INTERSECT ... create.AsSelect = p.parseSelectWithUnion() + // SETTINGS after a parenthesized query belong to the CREATE query + if swu, ok := create.AsSelect.(*ast.SelectWithUnionQuery); ok && swu != nil && len(swu.Settings) > 0 && len(create.QuerySettings) == 0 { + create.QuerySettings = swu.Settings + swu.Settings = nil + swu.SettingsBeforeFormat = false + swu.SettingsAfterFormat = false + } } else if p.currentIs(token.IDENT) || p.current.Token.IsKeyword() { // AS table_function(...) or AS database.table name := p.parseIdentifierName() @@ -3466,6 +3495,12 @@ func (p *Parser) parseCreateView(create *ast.CreateQuery) { p.nextToken() if p.isQueryStart() || p.currentIs(token.LPAREN) { create.AsSelect = p.parseSelectWithUnion() + if swu, ok := create.AsSelect.(*ast.SelectWithUnionQuery); ok && swu != nil && len(swu.Settings) > 0 && len(create.QuerySettings) == 0 { + create.QuerySettings = swu.Settings + swu.Settings = nil + swu.SettingsBeforeFormat = false + swu.SettingsAfterFormat = false + } // Extract FORMAT from inner SelectQuery and move it to CreateQuery // For CREATE VIEW/MATERIALIZED VIEW, FORMAT should be at CreateQuery level if swu, ok := create.AsSelect.(*ast.SelectWithUnionQuery); ok && swu != nil { @@ -5397,7 +5432,7 @@ func (p *Parser) parseDataType() *ast.DataType { var param ast.Expression // Special handling for SKIP in JSON/OBJECT types: SKIP path or SKIP REGEXP 'pattern' - if isObjectType && (p.currentIs(token.IDENT) || p.current.Token.IsKeyword()) && strings.ToUpper(p.current.Value) == "SKIP" { + if isObjectType && (p.currentIs(token.IDENT) || p.current.Token.IsKeyword()) && strings.ToUpper(p.current.Value) == "SKIP" && !p.current.Quoted && !p.current.Backquoted { pos := p.current.Pos p.nextToken() // consume SKIP @@ -5554,7 +5589,10 @@ func (p *Parser) isDataTypeName(name string) bool { "NOTHING", "INTERVAL", "JSON", "OBJECT", "VARIANT", "AGGREGATEFUNCTION", "SIMPLEAGGREGATEFUNCTION", - "POINT", "RING", "POLYGON", "MULTIPOLYGON", + "POINT", "RING", "POLYGON", "MULTIPOLYGON", "LINESTRING", "MULTILINESTRING", "GEOMETRY", + "INTERVALNANOSECOND", "INTERVALMICROSECOND", "INTERVALMILLISECOND", "INTERVALSECOND", + "INTERVALMINUTE", "INTERVALHOUR", "INTERVALDAY", "INTERVALWEEK", "INTERVALMONTH", + "INTERVALQUARTER", "INTERVALYEAR", "TIME64", "TIME", "DYNAMIC", "QBIT", @@ -7695,6 +7733,10 @@ func (p *Parser) parseExplain() *ast.ExplainQuery { explain.ExplainType = ast.ExplainEstimate explain.ExplicitType = true p.nextToken() + case "WHATIF": + explain.ExplainType = ast.ExplainWhatIf + explain.ExplicitType = true + p.nextToken() case "ANALYZE": explain.ExplainType = ast.ExplainAnalyze explain.ExplicitType = true @@ -8097,7 +8139,9 @@ func (p *Parser) parseSystem() *ast.SystemQuery { } } else if strings.Contains(upperCmd, "STOP DISTRIBUTED SENDS") || strings.Contains(upperCmd, "START DISTRIBUTED SENDS") || - strings.Contains(upperCmd, "LOAD DICTIONARY") { + strings.Contains(upperCmd, "LOAD DICTIONARY") || + strings.Contains(upperCmd, "RESTORE REPLICA") || + strings.Contains(upperCmd, "LOAD PRIMARY KEY") { // Only set duplicate if database and table are different (qualified name) if sys.Database != sys.Table { sys.DuplicateTableOutput = true @@ -8865,29 +8909,17 @@ func (p *Parser) parseFromSelectSyntaxNoPipe(with []ast.Expression) *ast.SelectW query.Selects = append(query.Selects, sel) return query } - p.nextToken() // skip SELECT - - // Handle DISTINCT - if p.currentIs(token.DISTINCT) { - sel.Distinct = true - p.nextToken() - // Check for DISTINCT ON (col1, col2, ...) - if p.currentIs(token.ON) { - p.nextToken() // skip ON - if p.expect(token.LPAREN) { - sel.DistinctOn = p.parseExpressionList() - p.expect(token.RPAREN) - } - } + // The SELECT part is an ordinary SELECT whose FROM was written first + full := p.parseSelectInternal(with) + if full == nil { + return nil } - - // Parse column list - sel.Columns = p.parseExpressionList() - - // Continue parsing the rest of SELECT (WHERE, GROUP BY, etc.) - p.parseSelectRemainder(sel) - - query.Selects = append(query.Selects, sel) + full.Position = sel.Position + if full.From == nil { + full.From = sel.From + } + full.ColumnAliases = sel.ColumnAliases + query.Selects = append(query.Selects, full) return query } @@ -9980,6 +10012,32 @@ func (p *Parser) parsePipeOperators(query *ast.SelectWithUnionQuery) *ast.Select p.nextToken() } query = res + case p.currentIs(token.INTERSECT) || p.currentIs(token.EXCEPT): + op := strings.ToUpper(p.current.Value) + p.nextToken() + if p.currentIs(token.ALL) || p.currentIs(token.DISTINCT) { + op += " " + strings.ToUpper(p.current.Value) + p.nextToken() + } + if pendingAlias != "" { + query = pipeUnion(pipeWrap(query, &pendingAlias, nil)) + } + var left ast.Statement = query + if len(query.Selects) == 1 { + left = query.Selects[0] + } + for { + elem := p.parsePipeUnionElement() + if elem == nil { + break + } + left = &ast.SelectIntersectExceptQuery{Selects: []ast.Statement{left, elem}, Operators: []string{op}} + if !p.currentIs(token.COMMA) { + break + } + p.nextToken() + } + query = &ast.SelectWithUnionQuery{Position: query.Position, Selects: []ast.Statement{left}} case p.isJoinKeyword() || p.currentIs(token.COMMA): // |> [LEFT ...] JOIN t ON ..., |> ARRAY JOIN expr, |> , t sel := pipeWrap(query, &pendingAlias, nil) diff --git a/parser/parser_test.go b/parser/parser_test.go index 6c18a0ad55..1ad1d7ccd7 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "strings" "testing" "time" @@ -34,10 +35,13 @@ type testMetadata struct { // statementInfo holds a parsed statement and its metadata type statementInfo struct { - stmt string - hasClientErr bool + stmt string + hasClientErr bool } +// errorHintRe matches the "-- { error CODE }" test hint. +var errorHintRe = regexp.MustCompile(`\{\s*error\s`) + // splitStatements splits SQL content into individual statements. func splitStatements(content string) []statementInfo { var statements []statementInfo @@ -55,7 +59,8 @@ func splitStatements(content string) []statementInfo { // Check for clientError annotation before stripping comment // Handles both "-- { clientError" and "--{clientError" formats - if strings.Contains(trimmed, "clientError") { + // "{ error CODE }" covers client-side (syntax) errors too + if strings.Contains(trimmed, "clientError") || errorHintRe.MatchString(trimmed) { currentHasClientErr = true } @@ -133,6 +138,7 @@ func findCommentStart(line string) int { // - skip: true to skip the test entirely (e.g., causes infinite loop) // - parse_error: true if the query is intentionally invalid SQL (expected to fail parsing) // - explain_todo: map of stmtN -> true to skip specific statements (e.g., {"stmt2": true, "stmt5": true}) +// // - explain.txt: Expected EXPLAIN AST output for first statement // - explain_N.txt: Expected EXPLAIN AST output for Nth statement (N >= 2) func TestParser(t *testing.T) { @@ -238,10 +244,8 @@ func TestParser(t *testing.T) { // For statements beyond the first, check if explain file exists explainFileExists := true - if stmtIndex > 1 { - if _, err := os.Stat(explainPath); os.IsNotExist(err) { - explainFileExists = false - } + if _, err := os.Stat(explainPath); os.IsNotExist(err) { + explainFileExists = false } // If no explain file and statement has clientError annotation, skip (no expected output for runtime errors) diff --git a/parser/testdata/00306_insert_values_and_expressions/metadata.json b/parser/testdata/00306_insert_values_and_expressions/metadata.json index b563327205..0967ef424b 100644 --- a/parser/testdata/00306_insert_values_and_expressions/metadata.json +++ b/parser/testdata/00306_insert_values_and_expressions/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt7": true - } -} +{} diff --git a/parser/testdata/02184_default_table_engine/metadata.json b/parser/testdata/02184_default_table_engine/metadata.json index ec15f27e12..0967ef424b 100644 --- a/parser/testdata/02184_default_table_engine/metadata.json +++ b/parser/testdata/02184_default_table_engine/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt106": true - } -} +{} diff --git a/parser/testdata/02346_text_index_bug90609/metadata.json b/parser/testdata/02346_text_index_bug90609/metadata.json index 3a06a4a1ac..0967ef424b 100644 --- a/parser/testdata/02346_text_index_bug90609/metadata.json +++ b/parser/testdata/02346_text_index_bug90609/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt5": true - } -} +{} diff --git a/parser/testdata/02366_kql_create_table/metadata.json b/parser/testdata/02366_kql_create_table/metadata.json index 2021dee830..0967ef424b 100644 --- a/parser/testdata/02366_kql_create_table/metadata.json +++ b/parser/testdata/02366_kql_create_table/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt11": true, - "stmt5": true, - "stmt7": true - } -} +{} diff --git a/parser/testdata/02677_analyzer_compound_expressions/metadata.json b/parser/testdata/02677_analyzer_compound_expressions/metadata.json index f4c74e32be..0967ef424b 100644 --- a/parser/testdata/02677_analyzer_compound_expressions/metadata.json +++ b/parser/testdata/02677_analyzer_compound_expressions/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt10": true - } -} +{} diff --git a/parser/testdata/02869_unicode_minus/metadata.json b/parser/testdata/02869_unicode_minus/metadata.json index 682bda1cbc..0967ef424b 100644 --- a/parser/testdata/02869_unicode_minus/metadata.json +++ b/parser/testdata/02869_unicode_minus/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt1": true, - "stmt2": true - } -} +{} diff --git a/parser/testdata/02998_analyzer_secret_args_tree_node/metadata.json b/parser/testdata/02998_analyzer_secret_args_tree_node/metadata.json index 9a8cc69c0b..0967ef424b 100644 --- a/parser/testdata/02998_analyzer_secret_args_tree_node/metadata.json +++ b/parser/testdata/02998_analyzer_secret_args_tree_node/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt2": true, - "stmt4": true - } -} +{} diff --git a/parser/testdata/03363_hive_style_partition/metadata.json b/parser/testdata/03363_hive_style_partition/metadata.json index 7cce0369ae..0967ef424b 100644 --- a/parser/testdata/03363_hive_style_partition/metadata.json +++ b/parser/testdata/03363_hive_style_partition/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt22": true, - "stmt25": true, - "stmt27": true - } -} +{} diff --git a/parser/testdata/03622_distributed_index_analysis_all_replicas/metadata.json b/parser/testdata/03622_distributed_index_analysis_all_replicas/metadata.json index ca584b3e28..0967ef424b 100644 --- a/parser/testdata/03622_distributed_index_analysis_all_replicas/metadata.json +++ b/parser/testdata/03622_distributed_index_analysis_all_replicas/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt17": true - } -} +{} diff --git a/parser/testdata/03709_tuple_inside_nullable_basic/metadata.json b/parser/testdata/03709_tuple_inside_nullable_basic/metadata.json index 20427253d3..0967ef424b 100644 --- a/parser/testdata/03709_tuple_inside_nullable_basic/metadata.json +++ b/parser/testdata/03709_tuple_inside_nullable_basic/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt134": true - } -} +{} diff --git a/parser/testdata/03773_json_with_typed_path_skip/metadata.json b/parser/testdata/03773_json_with_typed_path_skip/metadata.json index e9d6e46171..0967ef424b 100644 --- a/parser/testdata/03773_json_with_typed_path_skip/metadata.json +++ b/parser/testdata/03773_json_with_typed_path_skip/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt1": true - } -} +{} diff --git a/parser/testdata/03789_skip_index_bad_utf8/metadata.json b/parser/testdata/03789_skip_index_bad_utf8/metadata.json index f33d7d9f5a..0967ef424b 100644 --- a/parser/testdata/03789_skip_index_bad_utf8/metadata.json +++ b/parser/testdata/03789_skip_index_bad_utf8/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt10": true, - "stmt2": true, - "stmt6": true - } -} +{} diff --git a/parser/testdata/03812_truncate_optimize_in_transaction/metadata.json b/parser/testdata/03812_truncate_optimize_in_transaction/metadata.json index 342b3ff5b4..0967ef424b 100644 --- a/parser/testdata/03812_truncate_optimize_in_transaction/metadata.json +++ b/parser/testdata/03812_truncate_optimize_in_transaction/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt8": true - } -} +{} diff --git a/parser/testdata/03815_array_of_json_in_tuple_element/metadata.json b/parser/testdata/03815_array_of_json_in_tuple_element/metadata.json index e9d6e46171..0967ef424b 100644 --- a/parser/testdata/03815_array_of_json_in_tuple_element/metadata.json +++ b/parser/testdata/03815_array_of_json_in_tuple_element/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt1": true - } -} +{} diff --git a/parser/testdata/04029_json_typed_path_type_hint_subcolumn/metadata.json b/parser/testdata/04029_json_typed_path_type_hint_subcolumn/metadata.json index ae8c1054ab..0967ef424b 100644 --- a/parser/testdata/04029_json_typed_path_type_hint_subcolumn/metadata.json +++ b/parser/testdata/04029_json_typed_path_type_hint_subcolumn/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt53": true, - "stmt64": true, - "stmt65": true - } -} +{} diff --git a/parser/testdata/04035_create_as_select_intersect_settings/metadata.json b/parser/testdata/04035_create_as_select_intersect_settings/metadata.json index 8797b870e2..0967ef424b 100644 --- a/parser/testdata/04035_create_as_select_intersect_settings/metadata.json +++ b/parser/testdata/04035_create_as_select_intersect_settings/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt2": true, - "stmt4": true, - "stmt6": true - } -} +{} diff --git a/parser/testdata/04049_remote_subquery_in_unresolved_table_function_argument/metadata.json b/parser/testdata/04049_remote_subquery_in_unresolved_table_function_argument/metadata.json index 3a06a4a1ac..0967ef424b 100644 --- a/parser/testdata/04049_remote_subquery_in_unresolved_table_function_argument/metadata.json +++ b/parser/testdata/04049_remote_subquery_in_unresolved_table_function_argument/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt5": true - } -} +{} diff --git a/parser/testdata/04053_fuzz_issues_from_obsolete_version/metadata.json b/parser/testdata/04053_fuzz_issues_from_obsolete_version/metadata.json index 62b81668c3..0967ef424b 100644 --- a/parser/testdata/04053_fuzz_issues_from_obsolete_version/metadata.json +++ b/parser/testdata/04053_fuzz_issues_from_obsolete_version/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt13": true - } -} +{} diff --git a/parser/testdata/04054_sample_offset_formatting_ambiguity/metadata.json b/parser/testdata/04054_sample_offset_formatting_ambiguity/metadata.json index e9d6e46171..0967ef424b 100644 --- a/parser/testdata/04054_sample_offset_formatting_ambiguity/metadata.json +++ b/parser/testdata/04054_sample_offset_formatting_ambiguity/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt1": true - } -} +{} diff --git a/parser/testdata/04056_tuple_inside_nullable_casting/metadata.json b/parser/testdata/04056_tuple_inside_nullable_casting/metadata.json index 5550b23ed3..0967ef424b 100644 --- a/parser/testdata/04056_tuple_inside_nullable_casting/metadata.json +++ b/parser/testdata/04056_tuple_inside_nullable_casting/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt52": true, - "stmt53": true - } -} +{} diff --git a/parser/testdata/04064_describe_show_create_temporary_table/metadata.json b/parser/testdata/04064_describe_show_create_temporary_table/metadata.json index a08759fb21..0967ef424b 100644 --- a/parser/testdata/04064_describe_show_create_temporary_table/metadata.json +++ b/parser/testdata/04064_describe_show_create_temporary_table/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt21": true - } -} +{} diff --git a/parser/testdata/04064_join_use_nulls_apply_lambda_multiple_joins/metadata.json b/parser/testdata/04064_join_use_nulls_apply_lambda_multiple_joins/metadata.json index f4c74e32be..0967ef424b 100644 --- a/parser/testdata/04064_join_use_nulls_apply_lambda_multiple_joins/metadata.json +++ b/parser/testdata/04064_join_use_nulls_apply_lambda_multiple_joins/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt10": true - } -} +{} diff --git a/parser/testdata/04065_negative_limit_fractional_limit_explain_pipeline/metadata.json b/parser/testdata/04065_negative_limit_fractional_limit_explain_pipeline/metadata.json index c45b7602ba..0967ef424b 100644 --- a/parser/testdata/04065_negative_limit_fractional_limit_explain_pipeline/metadata.json +++ b/parser/testdata/04065_negative_limit_fractional_limit_explain_pipeline/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt12": true - } -} +{} diff --git a/parser/testdata/04078_error_hint_parsing_exception/metadata.json b/parser/testdata/04078_error_hint_parsing_exception/metadata.json index e9d6e46171..0967ef424b 100644 --- a/parser/testdata/04078_error_hint_parsing_exception/metadata.json +++ b/parser/testdata/04078_error_hint_parsing_exception/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt1": true - } -} +{} diff --git a/parser/testdata/04104_qbit_writeslice_structure_equals/metadata.json b/parser/testdata/04104_qbit_writeslice_structure_equals/metadata.json index b563327205..0967ef424b 100644 --- a/parser/testdata/04104_qbit_writeslice_structure_equals/metadata.json +++ b/parser/testdata/04104_qbit_writeslice_structure_equals/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt7": true - } -} +{} diff --git a/parser/testdata/04117_parser_system_query_variants/metadata.json b/parser/testdata/04117_parser_system_query_variants/metadata.json index bb4d0eb4fe..0967ef424b 100644 --- a/parser/testdata/04117_parser_system_query_variants/metadata.json +++ b/parser/testdata/04117_parser_system_query_variants/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt66": true, - "stmt94": true, - "stmt95": true - } -} +{} diff --git a/parser/testdata/04209_statistics_retry_load/metadata.json b/parser/testdata/04209_statistics_retry_load/metadata.json index 9be7220609..0967ef424b 100644 --- a/parser/testdata/04209_statistics_retry_load/metadata.json +++ b/parser/testdata/04209_statistics_retry_load/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt22": true - } -} +{} diff --git a/parser/testdata/04227_inconsistent_ast_function_lambda_after_comma_104605/metadata.json b/parser/testdata/04227_inconsistent_ast_function_lambda_after_comma_104605/metadata.json index 682bda1cbc..0967ef424b 100644 --- a/parser/testdata/04227_inconsistent_ast_function_lambda_after_comma_104605/metadata.json +++ b/parser/testdata/04227_inconsistent_ast_function_lambda_after_comma_104605/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt1": true, - "stmt2": true - } -} +{} diff --git a/parser/testdata/04241_date_part_as_extract/metadata.json b/parser/testdata/04241_date_part_as_extract/metadata.json index 8c6a18d871..0967ef424b 100644 --- a/parser/testdata/04241_date_part_as_extract/metadata.json +++ b/parser/testdata/04241_date_part_as_extract/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt19": true - } -} +{} diff --git a/parser/testdata/04247_attach_table_storage_clauses_without_engine_error/metadata.json b/parser/testdata/04247_attach_table_storage_clauses_without_engine_error/metadata.json index f4c74e32be..0967ef424b 100644 --- a/parser/testdata/04247_attach_table_storage_clauses_without_engine_error/metadata.json +++ b/parser/testdata/04247_attach_table_storage_clauses_without_engine_error/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt10": true - } -} +{} diff --git a/parser/testdata/04259_interpolate_with_fill_limit_by/metadata.json b/parser/testdata/04259_interpolate_with_fill_limit_by/metadata.json index 19830977ac..0967ef424b 100644 --- a/parser/testdata/04259_interpolate_with_fill_limit_by/metadata.json +++ b/parser/testdata/04259_interpolate_with_fill_limit_by/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt4": true, - "stmt5": true, - "stmt6": true - } -} +{} diff --git a/parser/testdata/04269_nullable_json_null_subcolumn/metadata.json b/parser/testdata/04269_nullable_json_null_subcolumn/metadata.json index b65b07d7a6..0967ef424b 100644 --- a/parser/testdata/04269_nullable_json_null_subcolumn/metadata.json +++ b/parser/testdata/04269_nullable_json_null_subcolumn/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt4": true - } -} +{} diff --git a/parser/testdata/04278_interpolate_empty_with_sorting_prefix/metadata.json b/parser/testdata/04278_interpolate_empty_with_sorting_prefix/metadata.json index b65b07d7a6..0967ef424b 100644 --- a/parser/testdata/04278_interpolate_empty_with_sorting_prefix/metadata.json +++ b/parser/testdata/04278_interpolate_empty_with_sorting_prefix/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt4": true - } -} +{} diff --git a/parser/testdata/04319_distributed_plan_set_operation_const_columns/metadata.json b/parser/testdata/04319_distributed_plan_set_operation_const_columns/metadata.json index ec09c7e10e..0967ef424b 100644 --- a/parser/testdata/04319_distributed_plan_set_operation_const_columns/metadata.json +++ b/parser/testdata/04319_distributed_plan_set_operation_const_columns/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt11": true, - "stmt12": true - } -} +{} diff --git a/parser/testdata/04327_enum_value_out_of_range/metadata.json b/parser/testdata/04327_enum_value_out_of_range/metadata.json index c45b7602ba..0967ef424b 100644 --- a/parser/testdata/04327_enum_value_out_of_range/metadata.json +++ b/parser/testdata/04327_enum_value_out_of_range/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt12": true - } -} +{} diff --git a/parser/testdata/04338_04305_values_non_column_argument_logical_error/metadata.json b/parser/testdata/04338_04305_values_non_column_argument_logical_error/metadata.json index 682bda1cbc..0967ef424b 100644 --- a/parser/testdata/04338_04305_values_non_column_argument_logical_error/metadata.json +++ b/parser/testdata/04338_04305_values_non_column_argument_logical_error/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt1": true, - "stmt2": true - } -} +{} diff --git a/parser/testdata/04408_hypothetical_index_partial_read/metadata.json b/parser/testdata/04408_hypothetical_index_partial_read/metadata.json index 3a06a4a1ac..0967ef424b 100644 --- a/parser/testdata/04408_hypothetical_index_partial_read/metadata.json +++ b/parser/testdata/04408_hypothetical_index_partial_read/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt5": true - } -} +{} diff --git a/parser/testdata/04489_create_table_as_inherit_engine_and_settings/metadata.json b/parser/testdata/04489_create_table_as_inherit_engine_and_settings/metadata.json index fbf54d36f1..0967ef424b 100644 --- a/parser/testdata/04489_create_table_as_inherit_engine_and_settings/metadata.json +++ b/parser/testdata/04489_create_table_as_inherit_engine_and_settings/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt28": true, - "stmt30": true - } -} +{} diff --git a/parser/testdata/04507_materialized_cte_union_merge/metadata.json b/parser/testdata/04507_materialized_cte_union_merge/metadata.json index f6d9f2395b..0967ef424b 100644 --- a/parser/testdata/04507_materialized_cte_union_merge/metadata.json +++ b/parser/testdata/04507_materialized_cte_union_merge/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt7": true, - "stmt8": true - } -} +{} diff --git a/parser/testdata/04507_mvt_encode_state_serialize/metadata.json b/parser/testdata/04507_mvt_encode_state_serialize/metadata.json index 0de7c95587..0967ef424b 100644 --- a/parser/testdata/04507_mvt_encode_state_serialize/metadata.json +++ b/parser/testdata/04507_mvt_encode_state_serialize/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt2": true, - "stmt7": true - } -} +{} diff --git a/parser/testdata/04516_join_reorder_duplicate_names_merge_expression/metadata.json b/parser/testdata/04516_join_reorder_duplicate_names_merge_expression/metadata.json index dbdbb76d4f..0967ef424b 100644 --- a/parser/testdata/04516_join_reorder_duplicate_names_merge_expression/metadata.json +++ b/parser/testdata/04516_join_reorder_duplicate_names_merge_expression/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt6": true - } -} +{} diff --git a/parser/testdata/04613_pipe_operators/metadata.json b/parser/testdata/04613_pipe_operators/metadata.json index aff5679158..0967ef424b 100644 --- a/parser/testdata/04613_pipe_operators/metadata.json +++ b/parser/testdata/04613_pipe_operators/metadata.json @@ -1,9 +1 @@ -{ - "explain_todo": { - "stmt104": true, - "stmt28": true, - "stmt29": true, - "stmt70": true, - "stmt71": true - } -} +{} diff --git a/parser/testdata/04648_replicate_generic_no_quadratic_realloc/metadata.json b/parser/testdata/04648_replicate_generic_no_quadratic_realloc/metadata.json index 379653fd26..0967ef424b 100644 --- a/parser/testdata/04648_replicate_generic_no_quadratic_realloc/metadata.json +++ b/parser/testdata/04648_replicate_generic_no_quadratic_realloc/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt26": true, - "stmt6": true, - "stmt7": true - } -} +{} diff --git a/parser/testdata/04713_materialized_cte_extremes_union/metadata.json b/parser/testdata/04713_materialized_cte_extremes_union/metadata.json index 7b61becc83..0967ef424b 100644 --- a/parser/testdata/04713_materialized_cte_extremes_union/metadata.json +++ b/parser/testdata/04713_materialized_cte_extremes_union/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt15": true, - "stmt16": true - } -} +{} diff --git a/parser/testdata/04811_aggregate_functions_timeseries_topk_bottomk_limitk/metadata.json b/parser/testdata/04811_aggregate_functions_timeseries_topk_bottomk_limitk/metadata.json index 55e0e23b2a..0967ef424b 100644 --- a/parser/testdata/04811_aggregate_functions_timeseries_topk_bottomk_limitk/metadata.json +++ b/parser/testdata/04811_aggregate_functions_timeseries_topk_bottomk_limitk/metadata.json @@ -1,9 +1 @@ -{ - "explain_todo": { - "stmt21": true, - "stmt22": true, - "stmt23": true, - "stmt25": true, - "stmt26": true - } -} +{} diff --git a/parser/testdata/04817_time_series_selector_bare_pk_conditions/metadata.json b/parser/testdata/04817_time_series_selector_bare_pk_conditions/metadata.json index 1cffc7878a..0967ef424b 100644 --- a/parser/testdata/04817_time_series_selector_bare_pk_conditions/metadata.json +++ b/parser/testdata/04817_time_series_selector_bare_pk_conditions/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt16": true, - "stmt21": true - } -} +{} diff --git a/parser/testdata/04837_parenthesized_definitions_replicated_metadata/metadata.json b/parser/testdata/04837_parenthesized_definitions_replicated_metadata/metadata.json index 7b4ddafa53..0967ef424b 100644 --- a/parser/testdata/04837_parenthesized_definitions_replicated_metadata/metadata.json +++ b/parser/testdata/04837_parenthesized_definitions_replicated_metadata/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt3": true, - "stmt4": true - } -} +{} diff --git a/parser/testdata/04840_json_skip_index_combined_subcolumn/metadata.json b/parser/testdata/04840_json_skip_index_combined_subcolumn/metadata.json index 2e9590304d..0967ef424b 100644 --- a/parser/testdata/04840_json_skip_index_combined_subcolumn/metadata.json +++ b/parser/testdata/04840_json_skip_index_combined_subcolumn/metadata.json @@ -1,7 +1 @@ -{ - "explain_todo": { - "stmt44": true, - "stmt45": true, - "stmt49": true - } -} +{} diff --git a/parser/testdata/04870_distinct_merge_over_distributed/metadata.json b/parser/testdata/04870_distinct_merge_over_distributed/metadata.json index 7ad5569408..0967ef424b 100644 --- a/parser/testdata/04870_distinct_merge_over_distributed/metadata.json +++ b/parser/testdata/04870_distinct_merge_over_distributed/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt9": true - } -} +{} diff --git a/parser/testdata/04896_inconsistent_ast_view_subquery_paren_round_trip_1941_1bfa/metadata.json b/parser/testdata/04896_inconsistent_ast_view_subquery_paren_round_trip_1941_1bfa/metadata.json index 1295a45747..0967ef424b 100644 --- a/parser/testdata/04896_inconsistent_ast_view_subquery_paren_round_trip_1941_1bfa/metadata.json +++ b/parser/testdata/04896_inconsistent_ast_view_subquery_paren_round_trip_1941_1bfa/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt3": true - } -} +{} diff --git a/parser/testdata/05024_binary_string_literal_uninitialized_byte/metadata.json b/parser/testdata/05024_binary_string_literal_uninitialized_byte/metadata.json index 682bda1cbc..0967ef424b 100644 --- a/parser/testdata/05024_binary_string_literal_uninitialized_byte/metadata.json +++ b/parser/testdata/05024_binary_string_literal_uninitialized_byte/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt1": true, - "stmt2": true - } -} +{} diff --git a/parser/testdata/05229_column_named_from_in_parenthesized_expression/metadata.json b/parser/testdata/05229_column_named_from_in_parenthesized_expression/metadata.json index d4d1d99f95..0967ef424b 100644 --- a/parser/testdata/05229_column_named_from_in_parenthesized_expression/metadata.json +++ b/parser/testdata/05229_column_named_from_in_parenthesized_expression/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt14": true - } -} +{} diff --git a/parser/testdata/05361_top_k_dynamic_filter_interval/metadata.json b/parser/testdata/05361_top_k_dynamic_filter_interval/metadata.json index 458f479051..0967ef424b 100644 --- a/parser/testdata/05361_top_k_dynamic_filter_interval/metadata.json +++ b/parser/testdata/05361_top_k_dynamic_filter_interval/metadata.json @@ -1,6 +1 @@ -{ - "explain_todo": { - "stmt52": true, - "stmt6": true - } -} +{} diff --git a/parser/testdata/05620_bloom_filter_index_map_keys_column_name/metadata.json b/parser/testdata/05620_bloom_filter_index_map_keys_column_name/metadata.json index 8d8c3756f7..0967ef424b 100644 --- a/parser/testdata/05620_bloom_filter_index_map_keys_column_name/metadata.json +++ b/parser/testdata/05620_bloom_filter_index_map_keys_column_name/metadata.json @@ -1,5 +1 @@ -{ - "explain_todo": { - "stmt45": true - } -} +{}