formatExpression formats SQL expressions
(expr ast.Expression)
| 617 | |
| 618 | // formatExpression formats SQL expressions |
| 619 | func (f *SQLFormatter) formatExpression(expr ast.Expression) error { |
| 620 | switch e := expr.(type) { |
| 621 | case *ast.Identifier: |
| 622 | if e.Table != "" { |
| 623 | f.builder.WriteString(e.Table + ".") |
| 624 | } |
| 625 | f.builder.WriteString(e.Name) |
| 626 | case *ast.LiteralValue: |
| 627 | // Handle string literals with proper quoting |
| 628 | switch e.Type { |
| 629 | case "string", "STRING": |
| 630 | // Escape single quotes in the string value and wrap in quotes |
| 631 | // Use type assertion for efficiency instead of fmt.Sprintf |
| 632 | var strVal string |
| 633 | if str, ok := e.Value.(string); ok { |
| 634 | strVal = str |
| 635 | } else { |
| 636 | strVal = fmt.Sprintf("%v", e.Value) |
| 637 | } |
| 638 | escaped := strings.ReplaceAll(strVal, "'", "''") |
| 639 | f.builder.WriteString("'") |
| 640 | f.builder.WriteString(escaped) |
| 641 | f.builder.WriteString("'") |
| 642 | case "null", "NULL": |
| 643 | f.writeKeyword("NULL") |
| 644 | default: |
| 645 | // For non-string types, use type assertions for common types |
| 646 | switch v := e.Value.(type) { |
| 647 | case string: |
| 648 | f.builder.WriteString(v) |
| 649 | case int: |
| 650 | f.builder.WriteString(strconv.Itoa(v)) |
| 651 | case int64: |
| 652 | f.builder.WriteString(strconv.FormatInt(v, 10)) |
| 653 | case float64: |
| 654 | f.builder.WriteString(strconv.FormatFloat(v, 'f', -1, 64)) |
| 655 | case bool: |
| 656 | if v { |
| 657 | f.writeKeyword("TRUE") |
| 658 | } else { |
| 659 | f.writeKeyword("FALSE") |
| 660 | } |
| 661 | default: |
| 662 | f.builder.WriteString(fmt.Sprintf("%v", e.Value)) |
| 663 | } |
| 664 | } |
| 665 | case *ast.BinaryExpression: |
| 666 | // Handle IS NULL / IS NOT NULL specially |
| 667 | if e.Operator == "IS NULL" { |
| 668 | if err := f.formatExpression(e.Left); err != nil { |
| 669 | return err |
| 670 | } |
| 671 | if e.Not { |
| 672 | f.builder.WriteString(" IS NOT NULL") |
| 673 | } else { |
| 674 | f.builder.WriteString(" IS NULL") |
| 675 | } |
| 676 | return nil |
no test coverage detected