/
template_stitching_sql.go
77 lines (63 loc) · 1.58 KB
/
template_stitching_sql.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
package main
import (
"bytes"
"log"
"text/template"
)
const TemplateStitchingSQL = `// Code generated by "gml"; DO NOT EDIT.
package {{.Package}}
import(
"database/sql"
"errors"
{{if .IsAddImport}}"github.com/ganLuo960214/StitchingSQLGo"{{end}}
)
// --- basic sql method ---
var (
ErrorDBIsNil = errors.New("db is nil")
ErrorTxIsNil = errors.New("tx is nil")
)
func QueryRowScan(db *sql.DB, s {{if .IsAddImport}}StitchingSQLGo.{{end}}Query,scans ...interface{}) error {
if db == nil {
return ErrorDBIsNil
}
sql, args, err := s.Query()
if err != nil {
return err
}
if err := db.QueryRow(sql, args...).Scan(scans...); err != nil {
return err
}
return nil
}
func TxQueryRowScan(tx *sql.Tx, s {{if .IsAddImport}}StitchingSQLGo.{{end}}Query,scans ...interface{}) error {
if tx == nil {
return ErrorTxIsNil
}
sql, args, err := s.Query()
if err != nil {
return err
}
if err := tx.QueryRow(sql, args...).Scan(scans...); err != nil {
return err
}
return nil
}
`
type TemplateStitchingSQLContent struct {
Package string
IsAddImport bool
}
func (c TemplateStitchingSQLContent) generateContent() []byte {
templateStitchingSQLSourceContent := bytes.NewBuffer([]byte{})
templateStitchingSQLSource, err := template.New("").Parse(TemplateStitchingSQL)
if err != nil {
log.Fatal(err)
}
if err := templateStitchingSQLSource.Execute(templateStitchingSQLSourceContent, TemplateStitchingSQLContent{
Package: GOPACKAGE,
IsAddImport: flags.IsAddImport,
}); err != nil {
log.Fatal(err)
}
return templateStitchingSQLSourceContent.Bytes()
}