Skip to content

Commit 71c293d

Browse files
committed
feat: treat a = b and b = a as same
1 parent f34cdc9 commit 71c293d

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

reshape.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,30 @@ func sortBoolTree(n *pg_query.Node) {
927927
case *pg_query.Node_AExpr:
928928
sortBoolTree(v.AExpr.Lexpr)
929929
sortBoolTree(v.AExpr.Rexpr)
930+
orderCommutativeOperands(v.AExpr)
931+
}
932+
}
933+
934+
// commutativeOps: operands swappable without changing the plan
935+
var commutativeOps = map[string]bool{
936+
"=": true,
937+
"<>": true,
938+
}
939+
940+
// orderCommutativeOperands sorts operands so `a = b` ≡ `b = a`
941+
func orderCommutativeOperands(e *pg_query.A_Expr) {
942+
if e == nil || e.Kind != pg_query.A_Expr_Kind_AEXPR_OP {
943+
return
944+
}
945+
if e.Lexpr == nil || e.Rexpr == nil || len(e.Name) != 1 {
946+
return
947+
}
948+
op, ok := e.Name[0].Node.(*pg_query.Node_String_)
949+
if !ok || !commutativeOps[op.String_.Sval] {
950+
return
951+
}
952+
if argSortKey(e.Lexpr) > argSortKey(e.Rexpr) {
953+
e.Lexpr, e.Rexpr = e.Rexpr, e.Lexpr
930954
}
931955
}
932956

reshape_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ func TestReshapeUpdateWithFromCanonicalisesAliases(t *testing.T) {
208208
if err != nil {
209209
t.Fatal(err)
210210
}
211-
want := "UPDATE users SET name = $1 FROM orders WHERE orders.user_id = users.id"
211+
want := "UPDATE users SET name = $1 FROM orders WHERE users.id = orders.user_id"
212212
if got != want {
213213
t.Errorf("got: %q\nwant: %q", got, want)
214214
}

0 commit comments

Comments
 (0)