|
| 1 | +package expr |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "io" |
| 7 | + |
| 8 | + "github.com/stephenafamo/bob" |
| 9 | +) |
| 10 | + |
| 11 | +type ( |
| 12 | + caseExpr struct { |
| 13 | + whens []when |
| 14 | + elseExpr bob.Expression |
| 15 | + } |
| 16 | + when struct { |
| 17 | + condition bob.Expression |
| 18 | + then bob.Expression |
| 19 | + } |
| 20 | +) |
| 21 | + |
| 22 | +func (c caseExpr) WriteSQL(ctx context.Context, w io.Writer, d bob.Dialect, start int) ([]any, error) { |
| 23 | + var args []any |
| 24 | + |
| 25 | + if len(c.whens) == 0 { |
| 26 | + return nil, errors.New("case must have at least one when expression") |
| 27 | + } |
| 28 | + |
| 29 | + w.Write([]byte("CASE")) |
| 30 | + for _, when := range c.whens { |
| 31 | + w.Write([]byte(" WHEN ")) |
| 32 | + whenArgs, err := when.condition.WriteSQL(ctx, w, d, start+len(args)) |
| 33 | + if err != nil { |
| 34 | + return nil, err |
| 35 | + } |
| 36 | + args = append(args, whenArgs...) |
| 37 | + |
| 38 | + w.Write([]byte(" THEN ")) |
| 39 | + thenArgs, err := when.then.WriteSQL(ctx, w, d, start+len(args)) |
| 40 | + if err != nil { |
| 41 | + return nil, err |
| 42 | + } |
| 43 | + args = append(args, thenArgs...) |
| 44 | + } |
| 45 | + |
| 46 | + if c.elseExpr != nil { |
| 47 | + w.Write([]byte(" ELSE ")) |
| 48 | + elseArgs, err := c.elseExpr.WriteSQL(ctx, w, d, start+len(args)) |
| 49 | + if err != nil { |
| 50 | + return nil, err |
| 51 | + } |
| 52 | + args = append(args, elseArgs...) |
| 53 | + } |
| 54 | + w.Write([]byte(" END")) |
| 55 | + |
| 56 | + return args, nil |
| 57 | +} |
| 58 | + |
| 59 | +type CaseChain[T bob.Expression, B builder[T]] func() caseExpr |
| 60 | + |
| 61 | +func NewCase[T bob.Expression, B builder[T]]() CaseChain[T, B] { |
| 62 | + return CaseChain[T, B](func() caseExpr { return caseExpr{} }) |
| 63 | +} |
| 64 | + |
| 65 | +func (cc CaseChain[T, B]) WriteSQL(ctx context.Context, w io.Writer, d bob.Dialect, start int) ([]any, error) { |
| 66 | + return cc().WriteSQL(ctx, w, d, start) |
| 67 | +} |
| 68 | + |
| 69 | +func (cc CaseChain[T, B]) When(condition, then bob.Expression) CaseChain[T, B] { |
| 70 | + c := cc() |
| 71 | + c.whens = append(c.whens, when{condition: condition, then: then}) |
| 72 | + return CaseChain[T, B](func() caseExpr { return c }) |
| 73 | +} |
| 74 | + |
| 75 | +func (cc CaseChain[T, B]) Else(then bob.Expression) T { |
| 76 | + c := cc() |
| 77 | + c.elseExpr = then |
| 78 | + return X[T, B](c) |
| 79 | +} |
| 80 | + |
| 81 | +func (cc CaseChain[T, B]) End() T { |
| 82 | + return X[T, B](cc()) |
| 83 | +} |
0 commit comments