forked from drone/sqlgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtmpl.go
120 lines (99 loc) · 1.83 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
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
package main
// template to create a constant variable.
var sConst = `
const %s = %s
`
// template to wrap a string in multi-line quotes.
var sQuote = "`\n%s\n`"
// template to declare the package name.
var sPackage = `
package %s
// THIS FILE WAS AUTO-GENERATED. DO NOT MODIFY.
`
// template to delcare the package imports.
var sImport = `
import (
%s
)
`
// function template to scan a single row.
const sScanRow = `
func Scan%s(row *sql.Row) (*%s, error) {
%s
err := row.Scan(
%s
)
if err != nil {
return nil, err
}
v := &%s{}
%s
return v, nil
}
`
// function template to scan multiple rows.
const sScanRows = `
func Scan%s(rows *sql.Rows) ([]*%s, error) {
var err error
var vv []*%s
%s
for rows.Next() {
err = rows.Scan(
%s
)
if err != nil {
return vv, err
}
v := &%s{}
%s
vv = append(vv, v)
}
return vv, rows.Err()
}
`
const sSliceRow = `
func Slice%s(v *%s) []interface{} {
%s
%s
return []interface{}{
%s
}
}
`
const sSelectRow = `
func Select%s(db *sql.DB, query string, args ...interface{}) (*%s, error) {
row := db.QueryRow(query, args...)
return Scan%s(row)
}
`
// function template to select multiple rows.
const sSelectRows = `
func Select%s(db *sql.DB, query string, args ...interface{}) ([]*%s, error) {
rows, err := db.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
return Scan%s(rows)
}
`
// function template to insert a single row.
const sInsert = `
func Insert%s(db *sql.DB, query string, v *%s) error {
res, err := db.Exec(query, Slice%s(v)[1:]...)
if err != nil {
return err
}
v.ID, err = res.LastInsertId()
return err
}
`
// function template to update a single row.
const sUpdate = `
func Update%s(db *sql.DB, query string, v *%s) error {
args := Slice%s(v)[1:]
args = append(args, v.ID)
_, err := db.Exec(query, args...)
return err
}
`