-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
512 lines (426 loc) · 14 KB
/
database.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package hey
import (
"encoding/hex"
"fmt"
"strconv"
"strings"
)
/**
* database helper.
**/
type Identifier interface {
Identify() string
AddIdentify(names []string) []string
DelIdentify(names []string) []string
}
type identifier struct {
identify string
}
func (s *identifier) Identify() string {
return s.identify
}
func (s *identifier) AddIdentify(names []string) []string {
length := len(names)
identify := s.identify
if length == 0 || identify == EmptyString {
return names
}
result := make([]string, 0, length)
for i := 0; i < length; i++ {
if names[i] == EmptyString {
continue
}
if strings.Contains(names[i], identify) {
result = append(result, names[i])
continue
}
value := fmt.Sprintf("%s%s%s", identify, names[i], identify)
if strings.Contains(value, SqlPoint) {
value = strings.ReplaceAll(names[i], SqlPoint, fmt.Sprintf("%s%s%s", identify, SqlPoint, identify))
}
result = append(result, value)
}
return result
}
func (s *identifier) DelIdentify(names []string) []string {
length := len(names)
identify := s.identify
if length == 0 || identify == EmptyString {
return names
}
result := make([]string, length)
for i := 0; i < length; i++ {
result[i] = strings.ReplaceAll(names[i], identify, EmptyString)
}
return result
}
func NewIdentifier(identify string) Identifier {
return &identifier{
identify: identify,
}
}
type Helper interface {
// DriverName Get the driver name.
DriverName() []byte
// DataSourceName Get the data source name.
DataSourceName() []byte
Identifier
SetIdentify(identifier Identifier) Helper
// Prepare Before executing preprocessing, adjust the preprocessing SQL format.
Prepare(prepare string) string
// IfNull Set a default value when the query field value is NULL.
IfNull(columnName string, columnDefaultValue string) string
// BinaryDataToHexString Convert binary data to hexadecimal string.
BinaryDataToHexString(binaryData []byte) string
}
// MysqlHelper helper for mysql.
type MysqlHelper struct {
driverName []byte
dataSourceName []byte
Identifier
}
func (s *MysqlHelper) DriverName() []byte {
return s.driverName
}
func (s *MysqlHelper) DataSourceName() []byte {
return s.dataSourceName
}
func (s *MysqlHelper) SetIdentify(identifier Identifier) Helper {
s.Identifier = identifier
return s
}
func (s *MysqlHelper) Prepare(prepare string) string {
return prepare
}
func (s *MysqlHelper) IfNull(columnName string, columnDefaultValue string) string {
return fmt.Sprintf("IFNULL(%s,%s)", columnName, columnDefaultValue)
}
func (s *MysqlHelper) BinaryDataToHexString(binaryData []byte) string {
return fmt.Sprintf("UNHEX('%s')", hex.EncodeToString(binaryData))
}
func NewMysqlHelper() *MysqlHelper {
return &MysqlHelper{
Identifier: NewIdentifier("`"),
}
}
// PostgresHelper helper for postgresql.
type PostgresHelper struct {
driverName []byte
dataSourceName []byte
Identifier
}
func (s *PostgresHelper) DriverName() []byte {
return s.driverName
}
func (s *PostgresHelper) DataSourceName() []byte {
return s.dataSourceName
}
func (s *PostgresHelper) SetIdentify(identifier Identifier) Helper {
s.Identifier = identifier
return s
}
func (s *PostgresHelper) Prepare(prepare string) string {
var index int64
latest := getStringBuilder()
defer putStringBuilder(latest)
origin := []byte(prepare)
length := len(origin)
dollar := byte('$') // $
questionMark := byte('?') // ?
for i := 0; i < length; i++ {
if origin[i] == questionMark {
index++
latest.WriteByte(dollar)
latest.WriteString(strconv.FormatInt(index, 10))
} else {
latest.WriteByte(origin[i])
}
}
return latest.String()
}
func (s *PostgresHelper) IfNull(columnName string, columnDefaultValue string) string {
return fmt.Sprintf("COALESCE(%s,%s)", columnName, columnDefaultValue)
}
func (s *PostgresHelper) BinaryDataToHexString(binaryData []byte) string {
return fmt.Sprintf(`E'\\x%s'`, hex.EncodeToString(binaryData))
}
func NewPostgresHelper() *PostgresHelper {
return &PostgresHelper{
Identifier: NewIdentifier(`"`),
}
}
// Sqlite3Helper helper for sqlite3.
type Sqlite3Helper struct {
driverName []byte
dataSourceName []byte
Identifier
}
func (s *Sqlite3Helper) DriverName() []byte {
return s.driverName
}
func (s *Sqlite3Helper) DataSourceName() []byte {
return s.dataSourceName
}
func (s *Sqlite3Helper) SetIdentify(identifier Identifier) Helper {
s.Identifier = identifier
return s
}
func (s *Sqlite3Helper) Prepare(prepare string) string {
return prepare
}
func (s *Sqlite3Helper) IfNull(columnName string, columnDefaultValue string) string {
return fmt.Sprintf("COALESCE(%s,%s)", columnName, columnDefaultValue)
}
func (s *Sqlite3Helper) BinaryDataToHexString(binaryData []byte) string {
return fmt.Sprintf(`X'%s'`, hex.EncodeToString(binaryData))
}
func NewSqlite3Helper() *Sqlite3Helper {
return &Sqlite3Helper{
Identifier: NewIdentifier("`"),
}
}
/**
* sql identifier.
**/
type AdjustColumn struct {
alias string
way *Way
}
// Alias Get the alias name value.
func (s *AdjustColumn) Alias() string {
return s.alias
}
// SetAlias Set the alias name value.
func (s *AdjustColumn) SetAlias(alias string) *AdjustColumn {
s.alias = alias
return s
}
// Adjust Batch adjust columns.
func (s *AdjustColumn) Adjust(adjust func(column string) string, columns ...string) []string {
if adjust != nil {
for index, column := range columns {
columns[index] = adjust(column)
}
}
return columns
}
// ColumnAll Add table name prefix to column names in batches.
func (s *AdjustColumn) ColumnAll(columns ...string) []string {
if s.alias == EmptyString {
return columns
}
prefix := fmt.Sprintf("%s%s", s.alias, SqlPoint)
for index, column := range columns {
if !strings.HasPrefix(column, prefix) {
columns[index] = fmt.Sprintf("%s%s", prefix, column)
}
}
return columns
}
// Column Add table name prefix to single column name, allowing column alias to be set.
func (s *AdjustColumn) Column(column string, aliases ...string) string {
return SqlAlias(s.ColumnAll(column)[0], LastNotEmptyString(aliases))
}
// Sum SUM(column[, alias])
func (s *AdjustColumn) Sum(column string, aliases ...string) string {
return SqlAlias(fmt.Sprintf("SUM(%s)", s.Column(column)), LastNotEmptyString(aliases))
}
// Max MAX(column[, alias])
func (s *AdjustColumn) Max(column string, aliases ...string) string {
return SqlAlias(fmt.Sprintf("MAX(%s)", s.Column(column)), LastNotEmptyString(aliases))
}
// Min MIN(column[, alias])
func (s *AdjustColumn) Min(column string, aliases ...string) string {
return SqlAlias(fmt.Sprintf("MIN(%s)", s.Column(column)), LastNotEmptyString(aliases))
}
// Avg AVG(column[, alias])
func (s *AdjustColumn) Avg(column string, aliases ...string) string {
return SqlAlias(fmt.Sprintf("AVG(%s)", s.Column(column)), LastNotEmptyString(aliases))
}
// Count Example
// Count(): `COUNT(*) AS counts`
// Count("total"): `COUNT(*) AS total`
// Count("1", "total"): `COUNT(1) AS total`
// Count("id", "counts"): `COUNT(id) AS counts`
func (s *AdjustColumn) Count(counts ...string) string {
count := "COUNT(*)"
length := len(counts)
if length == 0 {
// using default expression: `COUNT(*) AS counts`
return SqlAlias(count, s.way.cfg.Helper.AddIdentify([]string{DefaultAliasNameCount})[0])
}
if length == 1 && counts[0] != EmptyString {
// only set alias name
return SqlAlias(count, counts[0])
}
// set COUNT function parameters and alias name
countAlias := s.way.cfg.Helper.AddIdentify([]string{DefaultAliasNameCount})[0]
field := false
for i := 0; i < length; i++ {
if counts[i] == EmptyString {
continue
}
if field {
countAlias = counts[i]
break
}
count, field = fmt.Sprintf("COUNT(%s)", counts[i]), true
}
return SqlAlias(count, countAlias)
}
// IfNull If the value is NULL, set the default value.
func (s *AdjustColumn) IfNull(column string, defaultValue string, aliases ...string) string {
return SqlAlias(s.way.cfg.Helper.IfNull(s.Column(column), defaultValue), LastNotEmptyString(aliases))
}
// IfNullSum IF_NULL(SUM(column),0)[ AS column_name]
func (s *AdjustColumn) IfNullSum(column string, aliases ...string) string {
return SqlAlias(s.IfNull(s.Sum(column), "0"), LastNotEmptyString(aliases))
}
// IfNullMax IF_NULL(MAX(column),0)[ AS column_name]
func (s *AdjustColumn) IfNullMax(column string, aliases ...string) string {
return SqlAlias(s.IfNull(s.Max(column), "0"), LastNotEmptyString(aliases))
}
// IfNullMin IF_NULL(MIN(column),0)[ AS column_name]
func (s *AdjustColumn) IfNullMin(column string, aliases ...string) string {
return SqlAlias(s.IfNull(s.Min(column), "0"), LastNotEmptyString(aliases))
}
// IfNullAvg IF_NULL(AVG(column),0)[ AS column_name]
func (s *AdjustColumn) IfNullAvg(column string, aliases ...string) string {
return SqlAlias(s.IfNull(s.Avg(column), "0"), LastNotEmptyString(aliases))
}
func NewAdjustColumn(way *Way, aliases ...string) *AdjustColumn {
return &AdjustColumn{
alias: LastNotEmptyString(aliases),
way: way,
}
}
/**
* sql window functions.
**/
// WindowFunc sql window function.
type WindowFunc struct {
// Helper Database helper.
Helper Helper
// withFunc The window function used.
withFunc string
// partition Setting up window partitions.
partition []string
// order Sorting data within a group.
order []string
// windowFrame Window frame clause. `ROWS` or `RANGE`.
windowFrame string
// alias Serial number column alias.
alias string
}
// WithFunc Using custom function. for example: CUME_DIST(), PERCENT_RANK(), PERCENTILE_CONT(), PERCENTILE_DISC()...
func (s *WindowFunc) WithFunc(withFunc string) *WindowFunc {
s.withFunc = withFunc
return s
}
// RowNumber ROW_NUMBER() Assign a unique serial number to each row, in the order specified, starting with 1.
func (s *WindowFunc) RowNumber() *WindowFunc {
return s.WithFunc("ROW_NUMBER()")
}
// Rank RANK() Assign a rank to each row, if there are duplicate values, the rank is skipped.
func (s *WindowFunc) Rank() *WindowFunc {
return s.WithFunc("RANK()")
}
// DenseRank DENSE_RANK() Similar to RANK(), but does not skip rankings.
func (s *WindowFunc) DenseRank() *WindowFunc {
return s.WithFunc("DENSE_RANK()")
}
// Ntile NTILE() Divide the rows in the window into n buckets and assign a bucket number to each row.
func (s *WindowFunc) Ntile(buckets int64) *WindowFunc {
return s.WithFunc(fmt.Sprintf("NTILE(%d)", buckets))
}
// Sum SUM() Returns the sum of all rows in the window.
func (s *WindowFunc) Sum(column string) *WindowFunc {
return s.WithFunc(fmt.Sprintf("SUM(%s)", column))
}
// Max MAX() Returns the maximum value within the window.
func (s *WindowFunc) Max(column string) *WindowFunc {
return s.WithFunc(fmt.Sprintf("MAX(%s)", column))
}
// Min MIN() Returns the minimum value within the window.
func (s *WindowFunc) Min(column string) *WindowFunc {
return s.WithFunc(fmt.Sprintf("MIN(%s)", column))
}
// Avg AVG() Returns the average of all rows in the window.
func (s *WindowFunc) Avg(column string) *WindowFunc {
return s.WithFunc(fmt.Sprintf("AVG(%s)", column))
}
// Count COUNT() Returns the number of rows in the window.
func (s *WindowFunc) Count(column string) *WindowFunc {
return s.WithFunc(fmt.Sprintf("COUNT(%s)", column))
}
// Lag LAG() Returns the value of the row before the current row.
func (s *WindowFunc) Lag(column string, offset int64, defaultValue any) *WindowFunc {
return s.WithFunc(fmt.Sprintf("LAG(%s, %d, %s)", column, offset, ArgString(s.Helper, defaultValue)))
}
// Lead LEAD() Returns the value of a row after the current row.
func (s *WindowFunc) Lead(column string, offset int64, defaultValue any) *WindowFunc {
return s.WithFunc(fmt.Sprintf("LEAD(%s, %d, %s)", column, offset, ArgString(s.Helper, defaultValue)))
}
// NthValue NTH_VALUE() The Nth value can be returned according to the specified order. This is very useful when you need to get data at a specific position.
func (s *WindowFunc) NthValue(column string, LineNumber int64) *WindowFunc {
return s.WithFunc(fmt.Sprintf("NTH_VALUE(%s, %d)", column, LineNumber))
}
// FirstValue FIRST_VALUE() Returns the value of the first row in the window.
func (s *WindowFunc) FirstValue(column string) *WindowFunc {
return s.WithFunc(fmt.Sprintf("FIRST_VALUE(%s)", column))
}
// LastValue LAST_VALUE() Returns the value of the last row in the window.
func (s *WindowFunc) LastValue(column string) *WindowFunc {
return s.WithFunc(fmt.Sprintf("LAST_VALUE(%s)", column))
}
// Partition The OVER clause defines window partitions so that the window function is calculated independently in each partition.
func (s *WindowFunc) Partition(column ...string) *WindowFunc {
s.partition = append(s.partition, column...)
return s
}
// Asc Define the sorting within the partition so that the window function is calculated in order.
func (s *WindowFunc) Asc(column string) *WindowFunc {
s.order = append(s.order, fmt.Sprintf("%s %s", column, SqlAsc))
return s
}
// Desc Define the sorting within the partition so that the window function is calculated in descending order.
func (s *WindowFunc) Desc(column string) *WindowFunc {
s.order = append(s.order, fmt.Sprintf("%s %s", column, SqlDesc))
return s
}
// WindowFrame Set custom window frame clause.
func (s *WindowFunc) WindowFrame(windowFrame string) *WindowFunc {
s.windowFrame = windowFrame
return s
}
// Alias Set the alias of the field that uses the window function.
func (s *WindowFunc) Alias(alias string) *WindowFunc {
s.alias = alias
return s
}
// Result Query column expressions.
func (s *WindowFunc) Result() string {
if s.withFunc == EmptyString || s.partition == nil || s.order == nil || s.alias == EmptyString {
panic("hey: the SQL window function parameters are incomplete.")
}
b := getStringBuilder()
defer putStringBuilder(b)
b.WriteString(s.withFunc)
b.WriteString(" OVER ( PARTITION BY ")
b.WriteString(strings.Join(s.partition, ", "))
b.WriteString(" ORDER BY ")
b.WriteString(strings.Join(s.order, ", "))
if s.windowFrame != "" {
b.WriteString(" ")
b.WriteString(s.windowFrame)
}
b.WriteString(" ) AS ")
b.WriteString(s.alias)
return b.String()
}
func NewWindowFunc(way *Way, aliases ...string) *WindowFunc {
return &WindowFunc{
Helper: way.cfg.Helper,
alias: LastNotEmptyString(aliases),
}
}