Skip to content

Commit

Permalink
Pass a map with refs to store columns to MapScan()
Browse files Browse the repository at this point in the history
  • Loading branch information
matope committed Sep 22, 2014
1 parent f68d4c0 commit b2e835d
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
58 changes: 58 additions & 0 deletions cassandra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,64 @@ func TestCreateSessionTimeout(t *testing.T) {
}
}

type FullName struct {
FirstName string
LastName string
}

func (n FullName) MarshalCQL(info *TypeInfo) ([]byte, error) {
return []byte(n.FirstName + " " + n.LastName), nil
}
func (n *FullName) UnmarshalCQL(info *TypeInfo, data []byte) error {
t := strings.SplitN(string(data), " ", 2)
n.FirstName, n.LastName = t[0], t[1]
return nil
}

func TestMapScanWithRefMap(t *testing.T) {
session := createSession(t)
defer session.Close()
if err := createTable(session, `CREATE TABLE scan_map_ref_table (
testtext text PRIMARY KEY,
testfullname text,
testint int,
)`); err != nil {
t.Fatal("create table:", err)
}
m := make(map[string]interface{})
m["testtext"] = "testtext"
m["testfullname"] = FullName{"John", "Doe"}
m["testint"] = 100

if err := session.Query(`INSERT INTO scan_map_ref_table (testtext, testfullname, testint) values (?,?,?)`, m["testtext"], m["testfullname"], m["testint"]).Exec(); err != nil {
t.Fatal("insert:", err)
}

var testText string
var testFullName FullName
ret := map[string]interface{}{
"testtext": &testText,
"testfullname": &testFullName,
// testint is not set here.
}
iter := session.Query(`SELECT * FROM scan_map_ref_table`).Iter()
if ok := iter.MapScan(ret); !ok {
t.Fatal("select:", iter.Close())
} else {
if ret["testtext"] != "testtext" {
t.Fatal("returned testtext did not match")
}
f := ret["testfullname"].(FullName)
if f.FirstName != "John" || f.LastName != "Doe" {
t.Fatal("returned testfullname did not match")
}
if ret["testint"] != 100 {
t.Fatal("returned testinit did not match")
}
}

}

func TestSliceMap(t *testing.T) {
session := createSession(t)
defer session.Close()
Expand Down
6 changes: 6 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,12 @@ func (iter *Iter) MapScan(m map[string]interface{}) bool {
// Not checking for the error because we just did
rowData, _ := iter.RowData()

for i, col := range rowData.Columns {
if dest, ok := m[col]; ok {
rowData.Values[i] = dest
}
}

if iter.Scan(rowData.Values...) {
rowData.rowMap(m)
return true
Expand Down

0 comments on commit b2e835d

Please sign in to comment.