This repository has been archived by the owner on Nov 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert.go
59 lines (48 loc) · 1.5 KB
/
insert.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
package dbutil
import (
"fmt"
"strings"
)
func (dbu *DBUtil[E]) Insert(entity E, additionalStmts ...string) error {
cols := entity.Columns(InsertAction)
placeholders := make([]string, len(cols))
for i := range cols {
placeholders[i] = dbu.BindParam(i + 1)
}
_, err := dbu.db.Exec(fmt.Sprintf(
"insert into %s(%s) values(%s) %s",
entity.Table(), strings.Join(cols, ","), strings.Join(placeholders, ","), strings.Join(additionalStmts, " ")),
entity.Values(InsertAction)...,
)
return err
}
func (dbu *DBUtil[E]) InsertOrReplace(entity E, additionalStmts ...string) error {
cols := entity.Columns(InsertAction)
placeholders := make([]string, len(cols))
for i := range cols {
placeholders[i] = dbu.BindParam(i + 1)
}
_, err := dbu.db.Exec(fmt.Sprintf(
"insert or replace into %s(%s) values(%s) %s",
entity.Table(), strings.Join(cols, ","), strings.Join(placeholders, ","), strings.Join(additionalStmts, " ")),
entity.Values(InsertAction)...,
)
return err
}
func (dbu *DBUtil[E]) InsertReturning(entity E, retField string, retValue any) error {
cols := entity.Columns(InsertAction)
placeholders := make([]string, len(cols))
for i := range cols {
placeholders[i] = dbu.BindParam(i + 1)
}
stmt, err := dbu.db.Prepare(fmt.Sprintf(
"insert into %s(%s) values(%s) returning %s",
entity.Table(), strings.Join(cols, ","), strings.Join(placeholders, ","), retField),
)
if err != nil {
return err
}
row := stmt.QueryRow(entity.Values(InsertAction)...)
err = row.Scan(retValue)
return err
}