Skip to content

Commit

Permalink
table: Add RewriteRows
Browse files Browse the repository at this point in the history
  • Loading branch information
mmatczuk committed Oct 30, 2020
1 parent bc762eb commit 13ef8ce
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
31 changes: 31 additions & 0 deletions table/rewrite.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 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 table

import (
"github.com/scylladb/gocqlx/v2"
)

// RewriteRows performs a sequential rewrite of all rows in a table.
func RewriteRows(session gocqlx.Session, t *Table, options ...func(q *gocqlx.Queryx)) error {
insert := t.InsertQuery(session)
defer insert.Release()

// Apply query options
for _, o := range options {
o(insert)
}

// Iterate over all rows and reinsert them
iter := session.Query(t.SelectAll()).Iter()
m := make(map[string]interface{})
for iter.MapScan(m) {
if err := insert.BindMap(m).Exec(); err != nil {
return err
}
m = make(map[string]interface{})
}
return iter.Close()
}
59 changes: 59 additions & 0 deletions table/rewrite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright (C) 2017 ScyllaDB
// Use of this source code is governed by a ALv2-style
// license that can be found in the LICENSE file.

// +build all integration

package table_test

import (
"testing"
"time"

. "github.com/scylladb/gocqlx/v2/gocqlxtest"
"github.com/scylladb/gocqlx/v2/qb"
"github.com/scylladb/gocqlx/v2/table"
)

func TestRewriteRows(t *testing.T) {
session := CreateSession(t)
defer session.Close()

if err := session.ExecStmt(`CREATE TABLE gocqlx_test.rewrite_table (testtext text PRIMARY KEY)`); err != nil {
t.Fatal("create table:", err)
}

tbl := table.New(table.Metadata{
Name: "gocqlx_test.rewrite_table",
Columns: []string{"testtext"},
PartKey: []string{"testtext"},
})

// Insert data with 500ms TTL
q := tbl.InsertBuilder().TTL(500 * time.Millisecond).Query(session)
if err := q.Bind("a").Exec(); err != nil {
t.Fatal("insert:", err)
}
if err := q.Bind("b").Exec(); err != nil {
t.Fatal("insert:", err)
}
if err := q.Bind("c").Exec(); err != nil {
t.Fatal("insert:", err)
}

// Rewrite data without TTL
if err := table.RewriteRows(session, tbl); err != nil {
t.Fatal("rewrite:", err)
}

// Wait and check if data persisted
time.Sleep(time.Second)

var n int
if err := qb.Select(tbl.Name()).CountAll().Query(session).Scan(&n); err != nil {
t.Fatal("scan:", err)
}
if n != 3 {
t.Fatal("expected 3 entries")
}
}

0 comments on commit 13ef8ce

Please sign in to comment.