-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute.go
More file actions
294 lines (256 loc) · 6.7 KB
/
Copy pathexecute.go
File metadata and controls
294 lines (256 loc) · 6.7 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
package main
import (
"bytes"
"fmt"
)
// QLEvalContext holds the current row of data being evaluated
type QLEvalContext struct {
env Record // input row values
out Value // output value
err error
}
// qlEval processes a single AST node and computes its result
func qlEval(ctx *QLEvalContext, node QLNode) {
if ctx.err != nil {
return
}
switch node.Type {
case QL_SYM:
// Look up a column from the current row
if v := ctx.env.Get(string(node.Str)); v != nil {
ctx.out = *v
} else {
ctx.err = fmt.Errorf("unknown column: %s", string(node.Str))
}
case QL_I64:
ctx.out = Value{Type: TYPE_INT64, I64: node.I64}
case QL_STR:
ctx.out = Value{Type: TYPE_BYTES, Str: node.Str}
case QL_ADD:
qlEval(ctx, node.Kids[0])
left := ctx.out
qlEval(ctx, node.Kids[1])
right := ctx.out
if left.Type == TYPE_INT64 && right.Type == TYPE_INT64 {
ctx.out = Value{Type: TYPE_INT64, I64: left.I64 + right.I64}
} else {
ctx.err = fmt.Errorf("QL_ADD type error")
}
case QL_CMP_GT:
qlEval(ctx, node.Kids[0])
left := ctx.out
qlEval(ctx, node.Kids[1])
right := ctx.out
if left.Type == TYPE_INT64 && right.Type == TYPE_INT64 {
if left.I64 > right.I64 {
ctx.out = Value{Type: TYPE_INT64, I64: 1} // 1 = True
} else {
ctx.out = Value{Type: TYPE_INT64, I64: 0} // 0 = False
}
} else if left.Type == TYPE_BYTES && right.Type == TYPE_BYTES {
if bytes.Compare(left.Str, right.Str) > 0 {
ctx.out = Value{Type: TYPE_INT64, I64: 1}
} else {
ctx.out = Value{Type: TYPE_INT64, I64: 0}
}
} else {
ctx.err = fmt.Errorf("QL_CMP_GT type mismatch")
}
}
}
// qlEvalMulti evaluates a list of expressions to generate a new output row
func qlEvalMulti(env Record, exprs []QLNode) ([]Value, error) {
ctx := &QLEvalContext{env: env}
vals := make([]Value, len(exprs))
for i, expr := range exprs {
qlEval(ctx, expr)
if ctx.err != nil {
return nil, ctx.err
}
vals[i] = ctx.out
}
return vals, nil
}
// RecordIter is the standard interface for our streaming pipeline
type RecordIter interface {
Valid() bool
Next()
Deref(*Record) error
}
// qlScanIter wraps the Scanner to provide LIMIT and FILTER logic
type qlScanIter struct {
req *QLScan
sc *Scanner
idx int64
end bool
rec Record
err error
}
func (iter *qlScanIter) Valid() bool {
if iter.end || iter.err != nil {
return false
}
if iter.idx >= iter.req.Limit { // Enforce LIMIT
return false
}
return iter.sc.Valid()
}
func (iter *qlScanIter) Next() {
if iter.end { return }
// scanning until we find a row that passes the filter (or hit the end)
for {
iter.sc.Next()
if !iter.sc.Valid() {
iter.end = true
return
}
iter.sc.Deref(&iter.rec)
// If no filter, we accept the row
if iter.req.Filter.Type == 0 {
iter.idx++
return
}
// Apply the FILTER expression
ctx := &QLEvalContext{env: iter.rec}
qlEval(ctx, iter.req.Filter)
if ctx.err != nil {
iter.err = ctx.err
iter.end = true
return
}
// If truthy (I64 > 0), we accept the row
if ctx.out.Type == TYPE_INT64 && ctx.out.I64 > 0 {
iter.idx++
return
}
}
}
func (iter *qlScanIter) Deref(rec *Record) error {
if iter.err != nil { return iter.err }
*rec = iter.rec
return nil
}
// qlSelectIter wraps the ScanIter to shape the final output columns
type qlSelectIter struct {
iter RecordIter
names []string
exprs []QLNode
}
func (iter *qlSelectIter) Valid() bool {
return iter.iter.Valid()
}
func (iter *qlSelectIter) Next() {
iter.iter.Next()
}
func (iter *qlSelectIter) Deref(rec *Record) error {
var inputRec Record
if err := iter.iter.Deref(&inputRec); err != nil {
return err
}
// Evaluate the SELECT expressions against the raw database row
vals, err := qlEvalMulti(inputRec, iter.exprs)
if err != nil {
return err
}
*rec = Record{Cols: iter.names, Vals: vals}
return nil
}
// ExecuteSelect sets up the iterator pipeline and returns all matching rows
func ExecuteSelect(tx *DBTX, query *QLSelect) ([]Record, error) {
// 1. Initialize the raw DB Scanner
sc := &Scanner{}
sc.Key1 = Record{} // A full parser would extract the INDEX BY values into Key1/Key2 here
sc.Key2 = Record{}
sc.Cmp1 = CMP_GE
sc.Cmp2 = CMP_LE
if err := tx.Scan(query.Table, sc); err != nil {
return nil, err
}
// 2. Wrap it in the Filter/Limit Iterator
scanIter := &qlScanIter{
req: &query.QLScan,
sc: sc,
}
// Initialize the first row
if scanIter.sc.Valid() {
scanIter.sc.Deref(&scanIter.rec)
}
// 3. Wrap it in the Select Iterator
selectIter := &qlSelectIter{
iter: scanIter,
names: query.Names,
exprs: query.Output,
}
// 4. Consume the pipeline!
var results []Record
for selectIter.Valid() {
var finalRec Record
if err := selectIter.Deref(&finalRec); err != nil {
return nil, err
}
results = append(results, finalRec)
selectIter.Next()
}
return results, nil
}
// ExecuteCreateTable translates an AST Create Table node into the internal TableDef and applies it
func ExecuteCreateTable(tx *DBTX, stmt *QLCreateTable) error {
return tx.TableNew(&stmt.Def)
}
// ExecuteInsert evaluates each value and inserts the rows
func ExecuteInsert(tx *DBTX, stmt *QLInsert) error {
tdef := getTableDef(tx, stmt.Table)
if tdef == nil {
return fmt.Errorf("table not found: %s", stmt.Table)
}
for _, row := range stmt.Values {
rec := Record{}
// Evaluate each expression to get the value
for i, expr := range row {
if i >= len(stmt.Names) {
return fmt.Errorf("too many values for columns specified")
}
colName := stmt.Names[i]
// Evaluate constant expression (like 'Alice' or 1+1)
ctx := &QLEvalContext{env: Record{}}
qlEval(ctx, expr)
if ctx.err != nil {
return fmt.Errorf("error evaluating value for %s: %v", colName, ctx.err)
}
rec.Cols = append(rec.Cols, colName)
rec.Vals = append(rec.Vals, ctx.out)
}
// Ensure all schema columns are present, fill with zero values if missing
for i, colName := range tdef.Cols {
if rec.Get(colName) == nil {
rec.Cols = append(rec.Cols, colName)
if tdef.Types[i] == TYPE_INT64 {
rec.Vals = append(rec.Vals, Value{Type: TYPE_INT64, I64: 0})
} else {
rec.Vals = append(rec.Vals, Value{Type: TYPE_BYTES, Str: []byte{}})
}
}
}
if _, err := tx.Insert(stmt.Table, rec); err != nil {
return err
}
}
return nil
}
// ExecuteQuery is a high-level wrapper to parse and execute raw SQL automatically
func ExecuteQuery(tx *DBTX, sql string) (interface{}, error) {
ast, err := ParseSQL(sql)
if err != nil {
return nil, err
}
switch stmt := ast.(type) {
case *QLSelect:
return ExecuteSelect(tx, stmt)
case *QLCreateTable:
return nil, ExecuteCreateTable(tx, stmt)
case *QLInsert:
return nil, ExecuteInsert(tx, stmt)
default:
return nil, fmt.Errorf("unsupported AST node type")
}
}