-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.go
93 lines (79 loc) · 1.94 KB
/
generate.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
package main
import (
"fmt"
"github.com/lqr471814/sqlc-joins-gen/lib/inputs"
"github.com/lqr471814/sqlc-joins-gen/lib/outputs"
"github.com/lqr471814/sqlc-joins-gen/lib/transform"
"github.com/lqr471814/sqlc-joins-gen/lib/types"
"github.com/titanous/json5"
)
func generate(
task inputs.SqlcCodegenTask,
sqlgen outputs.SqlGenerator,
plgen outputs.PlGenerator,
) error {
schema, err := inputs.ParseSqliteSchema(task.Schema)
if err != nil {
return err
}
var cfg []types.MethodCfg
err = json5.Unmarshal(task.Joins, &cfg)
if err != nil {
return err
}
methods := make([]types.Method, len(cfg))
for i, m := range cfg {
methods[i], err = m.ToMethod(schema)
if err != nil {
return err
}
}
fromSchema := transform.FromSchema{Schema: schema}
script := outputs.PlScript{}
for _, method := range methods {
selectStmt, err := fromSchema.GetSelect(method)
if err != nil {
return err
}
out, err := fromSchema.GetMethodDef(method)
if err != nil {
return err
}
out.Sql = sqlgen.Select(selectStmt)
for _, selectField := range selectStmt.Select {
defIdx := -1
for i, row := range out.RowDefs {
if row.TableName == selectField.Table {
defIdx = i
break
}
}
if defIdx < 0 {
return fmt.Errorf(
"could not find table '%s' in RowDefs for '%s'",
selectField.Table, method.Name,
)
}
fieldIdx := -1
for i, field := range out.RowDefs[defIdx].Fields {
if field.TableFieldName == selectField.Attr {
fieldIdx = i
break
}
}
if fieldIdx < 0 {
return fmt.Errorf(
"could not find field '%s' in RowDef '%s' for '%s'",
selectField.Table, out.RowDefs[defIdx].DefName, method.Name,
)
}
out.ScanOrder = append(out.ScanOrder, outputs.PlScanEntry{
RowDef: out.RowDefs[defIdx],
Field: out.RowDefs[defIdx].Fields[fieldIdx],
})
}
out.RootDef = out.RowDefs[0]
script.Methods = append(script.Methods, &out)
}
return plgen.Generate(script)
}