-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.go
166 lines (151 loc) · 5.61 KB
/
sql.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
// Package database - Content managed by Project Forge, see [projectforge.md] for details.
package database
import (
"fmt"
"strings"
"github.com/samber/lo"
)
const whereC, fromC, returningC, selectC = " where ", " from ", " returning ", "select "
func SQLSelect(columns string, tables string, where string, orderBy string, limit int, offset int, dbt *DBType) string {
return SQLSelectGrouped(columns, tables, where, "", orderBy, limit, offset, dbt)
}
func SQLSelectSimple(columns string, tables string, dbt *DBType, where ...string) string {
return SQLSelectGrouped(columns, tables, strings.Join(where, " and "), "", "", 0, 0, dbt)
}
func SQLSelectGrouped(columns string, tables string, where string, groupBy string, orderBy string, limit int, offset int, dbt *DBType) string {
if columns == "" {
columns = "*"
}
whereClause := ""
if where != "" {
whereClause = whereC + where
}
groupByClause := ""
if groupBy != "" {
groupByClause = " group by " + groupBy
}
orderByClause := ""
if orderBy != "" {
orderByClause = " order by " + orderBy
}
if dbt.Placeholder == "@" {
switch {
case limit == 0 && offset == 0:
return selectC + columns + fromC + tables + whereClause + groupByClause + orderByClause
case limit > 0 && offset == 0:
limitClause := fmt.Sprintf("top %d ", limit)
return selectC + limitClause + columns + fromC + tables + whereClause + groupByClause + orderByClause
case offset > 0:
if orderByClause == "" {
orderByClause = " order by (select null)"
}
offsetClause := fmt.Sprintf(" offset %d rows", offset)
limitClause := fmt.Sprintf(" fetch next %d rows only", limit)
return selectC + columns + fromC + tables + whereClause + groupByClause + orderByClause + offsetClause + limitClause
}
}
limitClause := ""
offsetClause := ""
if limit > 0 {
limitClause = fmt.Sprintf(" limit %d", limit)
}
if offset > 0 {
offsetClause = fmt.Sprintf(" offset %d", offset)
}
return selectC + columns + fromC + tables + whereClause + groupByClause + orderByClause + limitClause + offsetClause
}
func SQLInsert(table string, columns []string, rows int, dbt *DBType) string {
if rows <= 0 {
rows = 1
}
colString := strings.Join(columns, ", ")
var placeholders []string
lo.Times(rows, func(i int) struct{} {
ph := lo.Map(columns, func(_ string, idx int) string {
return dbt.PlaceholderFor((i * len(columns)) + idx + 1)
})
placeholders = append(placeholders, "("+strings.Join(ph, ", ")+")")
return struct{}{}
})
return fmt.Sprintf("insert into %s (%s) values %s", table, colString, strings.Join(placeholders, ", "))
}
func SQLInsertReturning(table string, columns []string, rows int, returning []string, dbt *DBType) string {
q := SQLInsert(table, columns, rows, dbt)
if len(returning) > 0 {
q += returningC + strings.Join(returning, ", ")
}
return q
}
func SQLUpdate(table string, columns []string, where string, dbt *DBType) string {
whereClause := ""
if where != "" {
whereClause = whereC + where
}
stmts := lo.FilterMap(columns, func(col string, i int) (string, bool) {
return fmt.Sprintf("%s = %s", col, dbt.PlaceholderFor(i+1)), true
})
return fmt.Sprintf("update %s set %s%s", table, strings.Join(stmts, ", "), whereClause)
}
func SQLUpdateReturning(table string, columns []string, where string, returned []string, dbt *DBType) string {
q := SQLUpdate(table, columns, where, dbt)
if len(returned) > 0 {
q += returningC + strings.Join(returned, ", ")
}
return q
}
func SQLUpsert(table string, columns []string, rows int, conflicts []string, updates []string, dbt *DBType) string {
if dbt.Placeholder == "@" {
return sqlServerUpsert(table, columns, rows, conflicts, updates, dbt)
}
q := SQLInsert(table, columns, rows, dbt)
q += " on conflict (" + strings.Join(conflicts, ", ") + ") do update set "
lo.ForEach(updates, func(x string, idx int) {
if idx > 0 {
q += ", "
}
q += fmt.Sprintf("%s = excluded.%s", x, x)
})
return q
}
func sqlServerUpsert(table string, columns []string, rows int, conflicts []string, updates []string, dbt *DBType) string {
colNames := strings.Join(columns, ", ")
params := make([]string, 0, rows)
for rowIdx := range lo.Range(rows) {
cols := make([]string, 0, len(columns))
for colIdx := range columns {
cols = append(cols, fmt.Sprintf("@p%d", (rowIdx*len(columns))+colIdx+1))
}
params = append(params, fmt.Sprintf("(%s)", strings.Join(cols, ", ")))
}
atSymbols := strings.Join(params, ", ")
sourceJoin := strings.Join(lo.Map(conflicts, func(pk string, _ int) string {
return fmt.Sprintf("%s.%s = source.%s", table, pk, pk)
}), " and ")
assignments := strings.Join(lo.Map(updates, func(c string, _ int) string {
return fmt.Sprintf("%s = \"source\".%s", c, c)
}), ", ")
vals := strings.Join(lo.Map(updates, func(c string, _ int) string {
return fmt.Sprintf("source.%s", c)
}), ", ")
sql := `merge into %s using (values %s) as source (%s) on %s when matched then update set %s when not matched then insert (%s) values (%s);`
return fmt.Sprintf(sql, table, atSymbols, colNames, sourceJoin, assignments, colNames, vals)
}
func SQLDelete(table string, where string, _ *DBType) string {
if strings.TrimSpace(where) == "" {
return fmt.Sprintf("attempt to delete from [%s] with empty where clause", table)
}
return "delete from " + table + whereC + where
}
func SQLInClause(column string, numParams int, offset int, dbt *DBType) string {
resBuilder := strings.Builder{}
for index := 0; index < numParams; index++ {
if index == 0 {
resBuilder.WriteString(column + " in (")
} else {
resBuilder.WriteString(", ")
}
resBuilder.WriteString(dbt.PlaceholderFor(index + offset + 1))
}
resBuilder.WriteString(")")
return resBuilder.String()
}