format_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package parser
  2. import (
  3. "testing"
  4. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  5. )
  6. // FormatExpr output is persisted in the schema and re-parsed on every later
  7. // evaluation, so an identifier that lexes as a keyword has to stay quoted or the
  8. // stored text would no longer name a column.
  9. func TestFormatExprQuotesKeywordIdentifiers(t *testing.T) {
  10. tests := []struct {
  11. name string
  12. expr Expr
  13. want string
  14. }{
  15. {"keyword column", &ColumnRef{Column: "order"}, `"order"`},
  16. {"plain column", &ColumnRef{Column: "age"}, "age"},
  17. {"keyword in expression", &BinaryExpr{
  18. Left: &ColumnRef{Column: "order"},
  19. Op: lexer.TokenGt,
  20. Right: &LiteralExpr{Type: lexer.TokenNumber, Value: "0"},
  21. }, `("order" > 0)`},
  22. {"qualified keyword column", &ColumnRef{Table: "select", Column: "from"}, `"select"."from"`},
  23. {"underscored column", &ColumnRef{Column: "user_id"}, "user_id"},
  24. }
  25. for _, tt := range tests {
  26. t.Run(tt.name, func(t *testing.T) {
  27. formatted := FormatExpr(tt.expr)
  28. if formatted != tt.want {
  29. t.Fatalf("FormatExpr = %q, want %q", formatted, tt.want)
  30. }
  31. if _, err := ParseExpr(formatted); err != nil {
  32. t.Fatalf("formatted expression %q does not re-parse: %v", formatted, err)
  33. }
  34. })
  35. }
  36. }