-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuperbasic.go
307 lines (232 loc) · 6.16 KB
/
superbasic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//nolint:exhaustivestruct,exhaustruct,ireturn,wrapcheck
package superbasic
import (
"fmt"
"strings"
)
// ExpressionError is returned by the Compile Expression, if an expression is nil.
type ExpressionError struct {
Position int
}
func (e ExpressionError) Error() string {
return fmt.Sprintf("wroge/superbasic error: expression at position '%d' is nil", e.Position)
}
// NumberOfArgumentsError is returned if arguments doesn't match the number of placeholders.
type NumberOfArgumentsError struct {
SQL string
Placeholders, Arguments int
}
func (e NumberOfArgumentsError) Error() string {
argument := "argument"
if e.Arguments > 1 {
argument += "s"
}
placeholder := "placeholder"
if e.Placeholders > 1 {
placeholder += "s"
}
return fmt.Sprintf("wroge/superbasic error: %d %s and %d %s in '%s'",
e.Placeholders, placeholder, e.Arguments, argument, e.SQL)
}
type Expression interface {
ToSQL() (string, []any, error)
}
func Value(a any) Raw {
return Raw{SQL: "?", Args: []any{a}}
}
type Values []any
func (v Values) ToSQL() (string, []any, error) {
return fmt.Sprintf("(%s)", strings.Repeat(", ?", len(v))[2:]), v, nil
}
// Compile takes a template with placeholders into which expressions can be compiled.
// Escape '?' by using '??'.
func Compile(template string, expressions ...Expression) Compiler {
return Compiler{Template: template, Expressions: expressions}
}
type Compiler struct {
Template string
Expressions []Expression
}
func (c Compiler) ToSQL() (string, []any, error) {
builder := &strings.Builder{}
arguments := make([]any, 0, len(c.Expressions))
exprIndex := -1
for {
index := strings.IndexRune(c.Template, '?')
if index < 0 {
builder.WriteString(c.Template)
break
}
if index < len(c.Template)-1 && c.Template[index+1] == '?' {
builder.WriteString(c.Template[:index+2])
c.Template = c.Template[index+2:]
continue
}
exprIndex++
if exprIndex >= len(c.Expressions) {
return "", nil, NumberOfArgumentsError{
SQL: builder.String(),
Placeholders: exprIndex,
Arguments: len(c.Expressions),
}
}
if c.Expressions[exprIndex] == nil {
return "", nil, ExpressionError{Position: exprIndex}
}
builder.WriteString(c.Template[:index])
c.Template = c.Template[index+1:]
sql, args, err := c.Expressions[exprIndex].ToSQL()
if err != nil {
return "", nil, err
}
builder.WriteString(sql)
arguments = append(arguments, args...)
}
if exprIndex != len(c.Expressions)-1 {
return "", nil, NumberOfArgumentsError{
SQL: builder.String(),
Placeholders: exprIndex,
Arguments: len(c.Expressions),
}
}
return builder.String(), arguments, nil
}
func Append(expressions ...Expression) Joiner {
return Joiner{Expressions: expressions}
}
func Join(sep string, expressions ...Expression) Joiner {
return Joiner{Sep: sep, Expressions: expressions}
}
type Joiner struct {
Sep string
Expressions []Expression
}
func (j Joiner) ToSQL() (string, []any, error) {
builder := &strings.Builder{}
arguments := make([]any, 0, len(j.Expressions))
isFirst := true
for _, expr := range j.Expressions {
if expr == nil {
return "", nil, ExpressionError{}
}
sql, args, err := expr.ToSQL()
if err != nil {
return "", nil, err
}
if sql == "" {
continue
}
if isFirst {
builder.WriteString(sql)
isFirst = false
} else {
builder.WriteString(j.Sep + sql)
}
arguments = append(arguments, args...)
}
return builder.String(), arguments, nil
}
// Switch returns a Expression of a Case matching a value.
func Switch[T comparable](value T, cases ...Caser[T]) Expression {
for _, cas := range cases {
if value == cas.Value {
return cas.Then
}
}
return Raw{}
}
// Case returns a Caser that can be used inside the Switch statement.
func Case[T any](value T, then Expression) Caser[T] {
return Caser[T]{
Value: value,
Then: then,
}
}
type Caser[T any] struct {
Value T
Then Expression
}
func If(condition bool, then Expression) Expression {
if condition {
return then
}
return Raw{}
}
func IfElse(condition bool, then, els Expression) Expression {
if condition {
return then
}
return els
}
func SQL(sql string, args ...any) Raw {
return Raw{SQL: sql, Args: args}
}
type Raw struct {
SQL string
Args []any
Err error
}
func (r Raw) ToSQL() (string, []any, error) {
return r.SQL, r.Args, r.Err
}
// Finalize takes a static placeholder like '?' or a positional placeholder containing '%d'.
// Escaped placeholders ('??') are replaced to '?' when placeholder argument is not '?'.
func Finalize(placeholder string, expression Expression) (string, []any, error) {
if expression == nil {
return "", nil, ExpressionError{}
}
sql, args, err := expression.ToSQL()
if err != nil {
return "", nil, err
}
var count int
sql, count = Replace(placeholder, sql)
if count != len(args) {
return "", nil, NumberOfArgumentsError{SQL: sql, Placeholders: count, Arguments: len(args)}
}
return sql, args, nil
}
// Replace takes a static placeholder like '?' or a positional placeholder containing '%d'.
// Escaped placeholders ('??') are replaced to '?' when placeholder argument is not '?'.
func Replace(placeholder string, sql string) (string, int) {
build := &strings.Builder{}
count := 0
question := "?"
positional := false
if placeholder == "?" {
question = "??"
}
if strings.Contains(placeholder, "%d") {
positional = true
}
for {
index := strings.IndexRune(sql, '?')
if index < 0 {
build.WriteString(sql)
break
}
if index < len(sql)-1 && sql[index+1] == '?' {
build.WriteString(sql[:index] + question)
sql = sql[index+2:]
continue
}
count++
build.WriteString(sql[:index])
if positional {
build.WriteString(fmt.Sprintf(placeholder, count))
} else {
build.WriteString(placeholder)
}
sql = sql[index+1:]
}
return build.String(), count
}
// Map is a generic function for mapping one slice to another slice.
// It is useful for creating a slice of expressions as input to the join function.
func Map[From any, To any](from []From, mapper func(int, From) To) []To {
toSlice := make([]To, len(from))
for i, f := range from {
toSlice[i] = mapper(i, f)
}
return toSlice
}