Skip to content

Commit a774e44

Browse files
committed
impl.InsertStructs with transaction
1 parent 2259044 commit a774e44

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

impl/insert.go

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -143,17 +143,23 @@ func insertStructValues(table string, rowStruct any, namer sqldb.StructFieldMapp
143143
return columns, vals, nil
144144
}
145145

146+
// InsertStructs is a helper that calls InsertStruct for every
147+
// struct in the rowStructs slice or array.
148+
// The inserts are performed within a new transaction
149+
// if the passed conn is not already a transaction.
146150
func InsertStructs(conn sqldb.Connection, table string, rowStructs any, ignoreColumns ...sqldb.ColumnFilter) error {
147151
v := reflect.ValueOf(rowStructs)
148152
if k := v.Type().Kind(); k != reflect.Slice && k != reflect.Array {
149-
return fmt.Errorf("InsertStructs needs slice or array, got %T", rowStructs)
153+
return fmt.Errorf("InsertStructs expects a slice or array as rowStructs, got %T", rowStructs)
150154
}
151-
l := v.Len()
152-
for i := 0; i < l; i++ {
153-
err := conn.InsertStruct(table, v.Index(i).Interface(), ignoreColumns...)
154-
if err != nil {
155-
return err
155+
numRows := v.Len()
156+
return sqldb.Transaction(conn, nil, func(tx sqldb.Connection) error {
157+
for i := 0; i < numRows; i++ {
158+
err := tx.InsertStruct(table, v.Index(i).Interface(), ignoreColumns...)
159+
if err != nil {
160+
return err
161+
}
156162
}
157-
}
158-
return nil
163+
return nil
164+
})
159165
}

0 commit comments

Comments
 (0)