dbutil: RewriteTable, generalize table.RewriteRows to copy from source table to destination table with row transformation
This commit is contained in:
committed by
Michal Jan Matczuk
parent
13ef8ceaf1
commit
69f6f201f2
37
dbutil/rewrite.go
Normal file
37
dbutil/rewrite.go
Normal file
@@ -0,0 +1,37 @@
|
||||
// Copyright (C) 2017 ScyllaDB
|
||||
// Use of this source code is governed by a ALv2-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package dbutil
|
||||
|
||||
import (
|
||||
"github.com/scylladb/gocqlx/v2"
|
||||
"github.com/scylladb/gocqlx/v2/table"
|
||||
)
|
||||
|
||||
// RewriteTable rewrites src table to dst table.
|
||||
// Rows can be transformed using the transform function.
|
||||
// Additional options can be passed to modify the insert query.
|
||||
func RewriteTable(session gocqlx.Session, dst, src *table.Table, transform func(map[string]interface{}), options ...func(q *gocqlx.Queryx)) error {
|
||||
insert := dst.InsertQuery(session)
|
||||
defer insert.Release()
|
||||
|
||||
// Apply query options
|
||||
for _, o := range options {
|
||||
o(insert)
|
||||
}
|
||||
|
||||
// Iterate over all rows and reinsert them to dst table
|
||||
iter := session.Query(src.SelectAll()).Iter()
|
||||
m := make(map[string]interface{})
|
||||
for iter.MapScan(m) {
|
||||
if transform != nil {
|
||||
transform(m)
|
||||
}
|
||||
if err := insert.BindMap(m).Exec(); err != nil {
|
||||
return err
|
||||
}
|
||||
m = map[string]interface{}{}
|
||||
}
|
||||
return iter.Close()
|
||||
}
|
||||
Reference in New Issue
Block a user