-
Notifications
You must be signed in to change notification settings - Fork 1
/
create_rows.go
87 lines (66 loc) · 1.77 KB
/
create_rows.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
package sqlite
import (
"context"
"fmt"
"strings"
"github.com/Jumpaku/api-regression-detector/lib/cmd"
"github.com/Jumpaku/api-regression-detector/lib/db"
"github.com/Jumpaku/api-regression-detector/lib/db/impl"
"github.com/Jumpaku/api-regression-detector/lib/errors"
"github.com/Jumpaku/api-regression-detector/lib/jsonio/tables"
)
type insertOperation struct{}
func Insert() insertOperation {
return insertOperation{}
}
var _ cmd.RowCreator = insertOperation{}
func (o insertOperation) CreateRows(
ctx context.Context,
tx db.Tx,
tableName string,
schema db.Schema,
rows []tables.Row,
) error {
columnTypes := schema.ColumnTypes
if len(columnTypes) == 0 {
return nil
}
if len(rows) == 0 {
return nil
}
columnNames := columnTypes.GetColumnNames()
stmt := fmt.Sprintf("INSERT INTO %s (%s) VALUES", tableName, strings.Join(columnNames, ", "))
params := []any{}
for i, row := range rows {
if i > 0 {
stmt += ","
}
stmt += "("
for j, columnName := range columnNames {
if j > 0 {
stmt += ","
}
stmt += "?"
errInfo := errors.Info{"tableName": tableName, "columnName": columnName}
dbType, exists := columnTypes[columnName]
if !exists {
return errors.BadKeyAccess.New(errInfo.AppendTo("column not found in table"))
}
errInfo = errInfo.With("dbType", dbType)
param, err := impl.ExtractColumnValueAsDB(row, columnName, dbType)
if err != nil {
return errors.BadConversion.New(
errInfo.AppendTo("fail to parse column value to DB type"))
}
params = append(params, param)
}
stmt += ")"
}
if err := tx.Write(ctx, stmt, params); err != nil {
errInfo := errors.Info{"stmt": stmt, "params": params}
return errors.Wrap(
errors.DBFailure.Err(err),
errInfo.AppendTo("fail to insert rows"))
}
return nil
}