-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslate.go
More file actions
334 lines (303 loc) · 7.28 KB
/
Copy pathtranslate.go
File metadata and controls
334 lines (303 loc) · 7.28 KB
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
package postgres
import (
"github.com/tinywasm/ddl"
"github.com/tinywasm/fmt"
"github.com/tinywasm/model"
"github.com/tinywasm/storage"
)
func postgresType(t model.FieldType) string {
switch t {
case model.FieldInt:
return "BIGINT"
case model.FieldFloat:
return "DOUBLE PRECISION"
case model.FieldBool:
return "BOOLEAN"
case model.FieldBlob:
return "BYTEA"
default:
return "TEXT"
}
}
func postgresColumnType(f model.Field) string {
if f.Type.Storage() == model.FieldText && f.Permitted.Maximum > 0 {
return fmt.Sprintf("VARCHAR(%d)", f.Permitted.Maximum)
}
return postgresType(f.Type.Storage())
}
func onDeleteSQL(action string) string {
switch action {
case "restrict":
return "RESTRICT"
case "set_null":
return "SET NULL"
case "no_action":
return "NO ACTION"
default:
return "CASCADE"
}
}
// translate converts a storage.Query (DML only) into Postgres SQL.
func translate(q storage.Query, m model.Model) (string, []any, error) {
sb := fmt.Convert()
var args []any
argIndex := 1
switch q.Action {
case storage.ActionCreate:
sb.Write("INSERT INTO ")
sb.Write(q.Table)
sb.Write(" (")
sb.Write(fmt.Convert(q.Columns).Join(", ").String())
sb.Write(") VALUES (")
for i, v := range q.Values {
if i > 0 {
sb.Write(", ")
}
sb.Write(fmt.Sprintf("$%d", argIndex))
args = append(args, v)
argIndex++
}
sb.Write(")")
case storage.ActionReadOne, storage.ActionReadAll:
sb.Write("SELECT ")
if len(q.Columns) == 0 {
sb.Write("*")
} else {
sb.Write(fmt.Convert(q.Columns).Join(", ").String())
}
sb.Write(" FROM ")
sb.Write(q.Table)
if err := buildConditions(sb, q.Conditions, &args, &argIndex); err != nil {
return "", nil, err
}
if len(q.OrderBy) > 0 {
sb.Write(" ORDER BY ")
for i, o := range q.OrderBy {
if i > 0 {
sb.Write(", ")
}
sb.Write(o.Column())
sb.Write(" ")
sb.Write(o.Dir())
}
}
if q.Limit > 0 {
sb.Write(fmt.Sprintf(" LIMIT %d", q.Limit))
}
if q.Offset > 0 {
sb.Write(fmt.Sprintf(" OFFSET %d", q.Offset))
}
case storage.ActionUpdate:
sb.Write("UPDATE ")
sb.Write(q.Table)
sb.Write(" SET ")
isPKCol := make(map[string]bool)
if m != nil {
for _, f := range m.Schema() {
if f.IsPK() || f.IsAutoInc() {
isPKCol[f.Name] = true
}
}
}
added := 0
for i, c := range q.Columns {
if isPKCol[c] {
continue
}
if added > 0 {
sb.Write(", ")
}
sb.Write(c)
sb.Write(fmt.Sprintf(" = $%d", argIndex))
args = append(args, q.Values[i])
argIndex++
added++
}
// Fallback to original behavior if no columns are left (should not happen for valid updates)
if added == 0 {
for i, c := range q.Columns {
if i > 0 {
sb.Write(", ")
}
sb.Write(c)
sb.Write(fmt.Sprintf(" = $%d", argIndex))
args = append(args, q.Values[i])
argIndex++
}
}
if err := buildConditions(sb, q.Conditions, &args, &argIndex); err != nil {
return "", nil, err
}
case storage.ActionDelete:
sb.Write("DELETE FROM ")
sb.Write(q.Table)
if err := buildConditions(sb, q.Conditions, &args, &argIndex); err != nil {
return "", nil, err
}
default:
return "", nil, fmt.Errf("postgres: unknown DML action: %v", q.Action)
}
return sb.String(), args, nil
}
// translateDDL converts a ddl.Stmt into Postgres SQL.
func translateDDL(s ddl.Stmt, m model.Model) (string, []any, error) {
sb := fmt.Convert()
switch s.Op {
case ddl.OpCreateTable:
sb.Write("CREATE TABLE IF NOT EXISTS ")
sb.Write(s.Table)
sb.Write(" (")
fields := m.Schema()
var pkCols []string
for _, f := range fields {
if f.IsPK() {
pkCols = append(pkCols, f.Name)
}
}
compositePK := len(pkCols) > 1
for i, f := range fields {
if i > 0 {
sb.Write(", ")
}
sb.Write(f.Name)
sb.Write(" ")
isPK := f.IsPK()
isAuto := f.IsAutoInc()
if isPK && isAuto && !compositePK {
if f.Type.Storage() == model.FieldInt {
sb.Write("BIGSERIAL")
} else {
sb.Write("SERIAL")
}
} else if isAuto && f.Type.Storage() == model.FieldInt {
sb.Write("BIGSERIAL")
} else if isAuto {
sb.Write("SERIAL")
} else {
sb.Write(postgresColumnType(f))
}
if isPK {
if compositePK {
sb.Write(" NOT NULL")
} else {
sb.Write(" PRIMARY KEY")
}
}
if f.NotNull {
sb.Write(" NOT NULL")
}
if f.IsUnique() {
sb.Write(" UNIQUE")
}
}
if compositePK {
sb.Write(fmt.Sprintf(", PRIMARY KEY (%s)", fmt.Convert(pkCols).Join(", ").String()))
}
if ext, ok := m.(interface{ SchemaExt() []model.FieldExt }); ok {
for _, f := range ext.SchemaExt() {
if f.Ref != "" {
refCol := f.RefColumn
if refCol == "" {
refCol = "id"
}
sb.Write(fmt.Sprintf(", CONSTRAINT fk_%s_%s FOREIGN KEY (%s) REFERENCES %s(%s) ON DELETE %s",
s.Table, f.Name, f.Name, f.Ref, refCol, onDeleteSQL(f.OnDelete)))
}
}
}
sb.Write(")")
case ddl.OpDropTable:
sb.Write("DROP TABLE IF EXISTS ")
sb.Write(s.Table)
case ddl.OpAddColumn:
if s.Column == nil || s.Table == "" {
return "", nil, fmt.Err("table and column required for add column")
}
sb.Write("ALTER TABLE ")
sb.Write(s.Table)
sb.Write(" ADD COLUMN IF NOT EXISTS ")
sb.Write(s.Column.Name)
sb.Write(" ")
sb.Write(postgresType(s.Column.Type.Storage()))
case ddl.OpRenameColumn:
if s.Column == nil || s.OldName == "" || s.Table == "" {
return "", nil, fmt.Err("table, old name and column required for rename")
}
sb.Write("ALTER TABLE ")
sb.Write(s.Table)
sb.Write(" RENAME COLUMN ")
sb.Write(s.OldName)
sb.Write(" TO ")
sb.Write(s.Column.Name)
case ddl.OpDropColumn:
if s.Table == "" || s.ColumnName == "" {
return "", nil, fmt.Err("table and column name required for drop column")
}
sb.Write("ALTER TABLE ")
sb.Write(s.Table)
sb.Write(" DROP COLUMN IF EXISTS ")
sb.Write(s.ColumnName)
default:
return "", nil, fmt.Errf("postgres: unknown DDL op: %v", s.Op)
}
return sb.String(), nil, nil
}
// Translate is the public DML export.
func Translate(q storage.Query, m model.Model) (string, []any, error) {
return translate(q, m)
}
// TranslateDDL is the new DDL counterpart.
func TranslateDDL(s ddl.Stmt, m model.Model) (string, []any, error) {
return translateDDL(s, m)
}
func buildConditions(sb *fmt.Conv, conditions []storage.Condition, args *[]any, argIndex *int) error {
if len(conditions) == 0 {
return nil
}
sb.Write(" WHERE ")
for i, c := range conditions {
if i > 0 {
logic := c.Logic()
if logic == "" {
logic = "AND"
}
sb.Write(fmt.Sprintf(" %s ", logic))
}
op := c.Operator()
if op == "IS NULL" || op == "IS NOT NULL" {
sb.Write(c.Field())
sb.Write(" ")
sb.Write(op)
continue
}
if op == "IN" {
slice, ok := c.Value().([]any)
if !ok {
return fmt.Errf("IN operator requires []any value, got %T", c.Value())
}
if len(slice) == 0 {
return fmt.Err("IN operator slice cannot be empty")
}
sb.Write(c.Field())
sb.Write(" IN (")
for j, val := range slice {
if j > 0 {
sb.Write(", ")
}
sb.Write(fmt.Sprintf("$%d", *argIndex))
*args = append(*args, val)
(*argIndex)++
}
sb.Write(")")
} else {
sb.Write(c.Field())
sb.Write(" ")
sb.Write(c.Operator())
sb.Write(" ")
sb.Write(fmt.Sprintf("$%d", *argIndex))
*args = append(*args, c.Value())
(*argIndex)++
}
}
return nil
}