~rbn/rom

ref: c19ccfd10eab36fba5538912e9b7255a1e62ca35 rom/output/templates/insert.tmpl -rw-r--r-- 2.0 KiB
c19ccfd1Ruben Schuller fix broken INSERT code generation 1 year, 9 months ago
                                                                                
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
{{- /*
rom, reads schema information from various DBMS and generates according code.
Copyright (C) 2021  Ruben Schuller <code@rbn.im>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, version 3 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/ -}}
const (
	// SQL to insert a row in {{.QualifiedName}}
	sqlInsert{{ .GoName }} = "INSERT INTO {{ .QualifiedName }} ({{ range $i, $c := .Columns }}{{ if $i }}, {{ end }}{{ $c.Name }}{{ end }}) VALUES ({{ range $i, $c := .Columns }}{{ if $i }}, {{end}}?{{end}});"

	)

func (x *{{ .GoName }}) prepareInsert(p Preparer) (*sql.Stmt, error) {
	return p.Prepare(sqlInsert{{ .GoName }})
}

func (x *{{ .GoName }}) prepareContextInsert(ctx context.Context, p ContextPreparer) (*sql.Stmt, error) {
	return p.PrepareContext(ctx, sqlInsert{{ .GoName }})
}

// Insert inserts {{.GoName}} into the table {{.QualifiedName}}.
func (x *{{ .GoName }}) Insert(p Preparer) (sql.Result, error) {
	stmt, err := x.prepareInsert(p)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	return stmt.Exec(
{{- range $i, $c := .Columns -}}
{{- if $i }}, {{ end }}x.{{ $c.GoName }}
{{- end -}}
)
}

// InsertContext inserts {{.GoName}} into the table {{.QualifiedName}}
func (x *{{ .GoName }}) InsertContext(ctx context.Context, p ContextPreparer) (sql.Result, error) {
	stmt, err := x.prepareContextInsert(ctx, p)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	return stmt.ExecContext(ctx,
{{- range $i, $c := .Columns -}}
{{- if $i }}, {{ end }}x.{{ $c.GoName }}
{{- end -}}
)
}