Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cmd/gosqlx/cmd/sql_formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,12 @@ func (f *SQLFormatter) formatExpression(expr ast.Expression) error {
}
}
case *ast.BinaryExpression:
// NOT EXISTS (subquery) is parsed as a NOT with the EXISTS on the left and no right operand.
if e.Operator == "NOT" && e.Right == nil {
f.writeKeyword("NOT")
f.builder.WriteString(" ")
return f.formatExpression(e.Left)
}
// Handle IS NULL / IS NOT NULL specially
if e.Operator == "IS NULL" {
if err := f.formatExpression(e.Left); err != nil {
Expand Down
30 changes: 30 additions & 0 deletions cmd/gosqlx/cmd/sql_formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -600,3 +600,33 @@ func TestSQLFormatter_ParenthesizedExpression(t *testing.T) {
}
}
}

// TestSQLFormatter_NotExistsDoesNotPanic covers NOT EXISTS (subquery), which the parser
// represents as a NOT with the EXISTS on the left and no right operand.
func TestSQLFormatter_NotExistsDoesNotPanic(t *testing.T) {
sql := "SELECT a FROM t WHERE NOT EXISTS (SELECT 1 FROM u WHERE u.id = t.id)"
tkz := tokenizer.GetTokenizer()
defer tokenizer.PutTokenizer(tkz)
tokens, err := tkz.Tokenize([]byte(sql))
if err != nil {
t.Fatalf("Tokenization failed: %v", err)
}

p := parser.NewParser()
astObj := ast.NewAST()
defer ast.ReleaseAST(astObj)
result, err := p.ParseFromModelTokens(tokens)
if err != nil {
t.Fatalf("Parsing failed: %v", err)
}
astObj.Statements = result.Statements

formatter := NewSQLFormatter(FormatterOptions{Indent: " ", UppercaseKw: true})
output, err := formatter.Format(astObj)
if err != nil {
t.Fatalf("Formatting failed: %v", err)
}
if !strings.Contains(output, "NOT EXISTS (") {
t.Errorf("expected NOT EXISTS in output, got:\n%s", output)
}
}
Loading