Skip to content
This repository has been archived by the owner on Sep 9, 2024. It is now read-only.

Commit

Permalink
Add an implementation of an INSERT statement
Browse files Browse the repository at this point in the history
  • Loading branch information
suhailpatel committed Nov 17, 2020
1 parent db83574 commit 0cad9fd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
36 changes: 36 additions & 0 deletions statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,42 @@ type InsertStatement struct {
ttl time.Duration // ttl of the row
}

// Query provides the CQL query string for an UPDATE query
func (s InsertStatement) Query() string {
query, _ := s.queryAndValues()
return query
}

// Values provide the binding values for an UPDATE query
func (s InsertStatement) Values() []interface{} {
_, values := s.queryAndValues()
return values
}

func (s InsertStatement) queryAndValues() (string, []interface{}) {
query := []string{"INSERT INTO", fmt.Sprintf("%s.%s", s.keyspace, s.table)}

fieldNames := make([]string, 0, len(s.fieldMap))
placeholders := make([]string, 0, len(s.fieldMap))
values := make([]interface{}, 0, len(s.fieldMap))
for _, field := range sortedKeys(s.fieldMap) {
fieldNames = append(fieldNames, strings.ToLower(field))
placeholders = append(placeholders, "?")
values = append(values, s.fieldMap[field])
}

query = append(query, "("+strings.Join(fieldNames, ", ")+")")
query = append(query, "VALUES ("+strings.Join(placeholders, ", ")+")")

// Determine if we need to set a TTL
if s.ttl > 0 {
query = append(query, "USING TTL ?")
values = append(values, int(s.ttl.Seconds()))
}

return strings.Join(query, " "), values
}

// UpdateStatement represents an UPDATE query to update some data in C*
// It satisfies the Statement interface
type UpdateStatement struct {
Expand Down
15 changes: 15 additions & 0 deletions statement_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ func TestStatement(t *testing.T) {
}
}

func TestInsertStatement(t *testing.T) {
stmt := InsertStatement{keyspace: "ks1", table: "tbl1"}
stmt.fieldMap = map[string]interface{}{"a": "b"}
assert.Equal(t, "INSERT INTO ks1.tbl1 (a) VALUES (?)", stmt.Query())
assert.Equal(t, []interface{}{"b"}, stmt.Values())

stmt.fieldMap = map[string]interface{}{"a": "b", "c": "d"}
assert.Equal(t, "INSERT INTO ks1.tbl1 (a, c) VALUES (?, ?)", stmt.Query())
assert.Equal(t, []interface{}{"b", "d"}, stmt.Values())

stmt.ttl = 1 * time.Hour
assert.Equal(t, "INSERT INTO ks1.tbl1 (a, c) VALUES (?, ?) USING TTL ?", stmt.Query())
assert.Equal(t, []interface{}{"b", "d", 3600}, stmt.Values())
}

func TestUpdateStatement(t *testing.T) {
stmt := UpdateStatement{keyspace: "ks1", table: "tbl1"}
stmt.fieldMap = map[string]interface{}{"a": "b"}
Expand Down

0 comments on commit 0cad9fd

Please sign in to comment.