|
| 1 | +// Copyright 2026 GoSQLX Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + |
| 5 | +package parser_test |
| 6 | + |
| 7 | +import ( |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/ajitpratap0/GoSQLX/pkg/gosqlx" |
| 11 | + "github.com/ajitpratap0/GoSQLX/pkg/sql/ast" |
| 12 | + "github.com/ajitpratap0/GoSQLX/pkg/sql/keywords" |
| 13 | +) |
| 14 | + |
| 15 | +// TestMinusAsExceptSynonym verifies MINUS is accepted as a set operator |
| 16 | +// (synonym for EXCEPT) in Snowflake and Oracle dialects, and that it is |
| 17 | +// normalized to "EXCEPT" on the AST. Regression for #483. |
| 18 | +func TestMinusAsExceptSynonym(t *testing.T) { |
| 19 | + dialects := []keywords.SQLDialect{ |
| 20 | + keywords.DialectSnowflake, |
| 21 | + keywords.DialectOracle, |
| 22 | + } |
| 23 | + q := `SELECT id FROM a MINUS SELECT id FROM b` |
| 24 | + for _, d := range dialects { |
| 25 | + d := d |
| 26 | + t.Run(string(d), func(t *testing.T) { |
| 27 | + tree, err := gosqlx.ParseWithDialect(q, d) |
| 28 | + if err != nil { |
| 29 | + t.Fatalf("parse failed: %v", err) |
| 30 | + } |
| 31 | + if len(tree.Statements) != 1 { |
| 32 | + t.Fatalf("want 1 statement, got %d", len(tree.Statements)) |
| 33 | + } |
| 34 | + so, ok := tree.Statements[0].(*ast.SetOperation) |
| 35 | + if !ok { |
| 36 | + t.Fatalf("want *ast.SetOperation, got %T", tree.Statements[0]) |
| 37 | + } |
| 38 | + if so.Operator != "EXCEPT" { |
| 39 | + t.Fatalf("Operator: want %q, got %q", "EXCEPT", so.Operator) |
| 40 | + } |
| 41 | + }) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// TestMinusNotSetOpInOtherDialects verifies that MINUS is still treated as |
| 46 | +// a table alias (not a set operator) in dialects that do not support it. |
| 47 | +// This protects against accidental hijacking in e.g. MySQL/PostgreSQL. |
| 48 | +func TestMinusNotSetOpInOtherDialects(t *testing.T) { |
| 49 | + q := `SELECT id FROM a MINUS SELECT id FROM b` |
| 50 | + // In dialects without MINUS-as-EXCEPT, the MINUS identifier is consumed |
| 51 | + // as a table alias ("a AS MINUS") and "SELECT ..." starts a new statement. |
| 52 | + // We expect either success with 2 statements, or at minimum no panic. |
| 53 | + tree, err := gosqlx.ParseWithDialect(q, keywords.DialectPostgreSQL) |
| 54 | + if err != nil { |
| 55 | + return // error is acceptable; we only verify no hijacking |
| 56 | + } |
| 57 | + if len(tree.Statements) == 1 { |
| 58 | + if _, isSetOp := tree.Statements[0].(*ast.SetOperation); isSetOp { |
| 59 | + t.Fatal("PostgreSQL should not parse MINUS as a set operator") |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments