-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslate.go
More file actions
285 lines (262 loc) · 7.05 KB
/
Copy pathtranslate.go
File metadata and controls
285 lines (262 loc) · 7.05 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
package postgres
import (
"github.com/tinywasm/fmt"
"github.com/tinywasm/orm"
)
// translate converts an ORM query to a PostgreSQL query and arguments.
func postgresType(t fmt.FieldType) string {
switch t {
case fmt.FieldInt:
return "BIGINT"
case fmt.FieldFloat:
return "DOUBLE PRECISION"
case fmt.FieldBool:
return "BOOLEAN"
case fmt.FieldBlob:
return "BYTEA"
default:
return "TEXT"
}
}
func translate(q orm.Query, m fmt.Model) (string, []any, error) {
sb := fmt.Convert()
var args []any
argIndex := 1
switch q.Action {
case orm.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(")")
// Append RETURNING id if it's likely expected, although not strictly in generic ORM spec.
// However, many ORMs rely on LastInsertId which Postgres doesn't support via Result.
// So we often need `RETURNING id`.
// Let's assume the user model has an 'id' column for now or handle it via Execute scan.
// If we don't add it here, `Execute` won't get it back.
// But generic `translate` shouldn't assume column names unless specified.
// The `orm` might handle ID assignment via UUIDs generated in Go, in which case RETURNING isn't needed.
// If the DB generates IDs (SERIAL/IDENTITY), we need it.
// Let's stick to standard INSERT for now. If tests fail on ID retrieval, we'll revisit.
case orm.ActionReadOne, orm.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()) // Changed from o.Field to o.Column()
sb.Write(" ")
sb.Write(o.Dir()) // Changed from checking o.Desc to o.Dir() which returns "ASC" or "DESC"
}
}
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 orm.ActionUpdate:
sb.Write("UPDATE ")
sb.Write(q.Table)
sb.Write(" SET ")
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 orm.ActionDelete:
sb.Write("DELETE FROM ")
sb.Write(q.Table)
if err := buildConditions(sb, q.Conditions, &args, &argIndex); err != nil {
return "", nil, err
}
case orm.ActionCreateTable:
sb.Write("CREATE TABLE IF NOT EXISTS ")
sb.Write(q.Table)
sb.Write(" (")
fields := m.Schema()
// Count composite PK fields upfront to decide between inline and table-level PK.
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 == fmt.FieldInt {
sb.Write("BIGSERIAL")
} else {
sb.Write("SERIAL")
}
} else if isAuto && f.Type == fmt.FieldInt {
sb.Write("BIGSERIAL")
} else if isAuto {
sb.Write("SERIAL")
} else {
sb.Write(postgresType(f.Type))
}
if isPK {
if compositePK {
// Composite PK: columns must be NOT NULL; constraint emitted as table-level below.
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()))
}
// orm.FieldExt is used for FKs. Since m.Schema() returns []fmt.Field,
// we need to check if the implementation provided FieldExt.
// In tinywasm/orm, models that have FKs can optionally implement an extended schema.
if ext, ok := m.(interface{ SchemaExt() []orm.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)",
q.Table, f.Name, f.Name, f.Ref, refCol))
}
}
}
sb.Write(")")
case orm.ActionDropTable:
sb.Write("DROP TABLE IF EXISTS ")
sb.Write(q.Table)
case orm.ActionAddColumn:
if q.Column == nil || q.Table == "" {
return "", nil, fmt.Err("table and column required for add column")
}
sb.Write("ALTER TABLE ")
sb.Write(q.Table)
sb.Write(" ADD COLUMN IF NOT EXISTS ")
sb.Write(q.Column.Name)
sb.Write(" ")
sb.Write(postgresType(q.Column.Type))
case orm.ActionRenameColumn:
if q.Column == nil || q.OldName == "" || q.Table == "" {
return "", nil, fmt.Err("table, old name and column required for rename")
}
sb.Write("ALTER TABLE ")
sb.Write(q.Table)
sb.Write(" RENAME COLUMN ")
sb.Write(q.OldName)
sb.Write(" TO ")
sb.Write(q.Column.Name)
case orm.ActionDropColumn:
if q.Table == "" || len(q.Columns) == 0 {
return "", nil, fmt.Err("table and column required for drop column")
}
sb.Write("ALTER TABLE ")
sb.Write(q.Table)
sb.Write(" DROP COLUMN IF EXISTS ")
sb.Write(q.Columns[0])
case orm.ActionCreateDatabase:
sb.Write("CREATE DATABASE ")
sb.Write(q.Database)
default:
return "", nil, fmt.Errf("unsupported action: %d", q.Action)
}
return sb.String(), args, nil
}
// Translate exposes translate for external testing packages.
func Translate(q orm.Query, m fmt.Model) (string, []any, error) {
return translate(q, m)
}
func buildConditions(sb *fmt.Conv, conditions []orm.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
}