forked from mattatcha/scaneo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tmpl.go
78 lines (70 loc) · 2.13 KB
/
tmpl.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
package main
const (
scansText = `{{define "scans"}}// DON'T EDIT *** generated by scaneo *** DON'T EDIT //
package {{.PackageName}}
import (
"database/sql"{{ if .ImportPkg }}
"{{.ImportPkg}}"{{end}}
)
{{range .Tokens}}
func {{$.Visibility}}can{{title .Name}}(r *sql.Row) (*{{pkg .Name}}, error) {
s := &{{pkg .Name}}{}
if err := r.Scan({{range .Fields}}
&s.{{.Name}},{{end}}
); err != nil {
return &{{pkg .Name}}{}, err
}
return s, nil
}
func {{$.Visibility}}can{{title .Name}}s(rs *sql.Rows) ([]*{{pkg .Name}}, error) {
structs := make([]*{{pkg .Name}}, 0, 16)
var err error
for rs.Next() {
s := &{{pkg .Name}}{}
if err = rs.Scan({{range .Fields}}
&s.{{.Name}},{{end}}
); err != nil {
return nil, err
}
structs = append(structs, s)
}
if err = rs.Err(); err != nil {
return nil, err
}
return structs, nil
}
{{if $.Funcs}}
// Select{{title .Name}} selects a single {{title .Name}} row from the database
func Select{{title .Name}}(db *sql.DB, query string, args ...interface{}) (*{{pkg .Name}}, error) {
row := db.QueryRow(query, args...)
return {{$.Visibility}}can{{title .Name}}(row)
}
// Select{{title .Name}}s selects multiple {{title .Name}} rows from the database
func Select{{title .Name}}s(db *sql.DB, query string, args ...interface{}) ([]*{{pkg .Name}}, error) {
rows, err := db.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
return {{$.Visibility}}can{{title .Name}}s(rows)
}
// slice{{title .Name}} returns a slice of arguments from {{title .Name}} struct values
func slice{{title .Name}}(v *{{pkg .Name}}) []interface{} {
return []interface{}{ {{range .Fields}}
&v.{{.Name}},{{end}}
}
}
// Insert{{title .Name}} inserts a single {{title .Name}} row
func Insert{{title .Name}}(db *sql.DB, query string, v *{{pkg .Name}}) error {
_, err := db.Exec(query, slice{{title .Name}}(v)[1:]...)
return err
}
// Update{{title .Name}} updates a single {{title .Name}} row
func Update{{title .Name}}(db *sql.DB, query string, v *{{pkg .Name}}) error {
args := slice{{title .Name}}(v)[1:]
args = append(args, v.ID)
_, err := db.Exec(query, args...)
return err
}
{{end}}{{end}}{{end}}`
)