Selaa lähdekoodia

Merge pull request #239 from phillipCouto/nil_in_query

Added support for marshalling a nil value.
Ben Hood 11 vuotta sitten
vanhempi
commit
f09085c7ba
3 muutettua tiedostoa jossa 36 lisäystä ja 0 poistoa
  1. 22 0
      cassandra_test.go
  2. 4 0
      marshal.go
  3. 10 0
      marshal_test.go

+ 22 - 0
cassandra_test.go

@@ -1214,3 +1214,25 @@ func TestBatchStats(t *testing.T) {
 		}
 	}
 }
+
+//TestNilInQuery tests to see that a nil value passed to a query is handled by Cassandra
+//TODO validate the nil value by reading back the nil. Need to fix Unmarshalling.
+func TestNilInQuery(t *testing.T) {
+	session := createSession(t)
+	defer session.Close()
+
+	if err := createTable(session, "CREATE TABLE testNilInsert (id int, count int, PRIMARY KEY (id))"); err != nil {
+		t.Fatalf("failed to create table with error '%v'", err)
+	}
+	if err := session.Query("INSERT INTO testNilInsert (id,count) VALUES (?,?)", 1, nil).Exec(); err != nil {
+		t.Fatalf("failed to insert with err: %v", err)
+	}
+
+	var id int
+
+	if err := session.Query("SELECT id FROM testNilInsert").Scan(&id); err != nil {
+		t.Fatalf("failed to select with err: %v", err)
+	} else if id != 1 {
+		t.Fatalf("expected id to be 1, got %v", id)
+	}
+}

+ 4 - 0
marshal.go

@@ -35,6 +35,10 @@ type Unmarshaler interface {
 // Marshal returns the CQL encoding of the value for the Cassandra
 // internal type described by the info parameter.
 func Marshal(info *TypeInfo, value interface{}) ([]byte, error) {
+	if value == nil {
+		return nil, nil
+	}
+
 	if v, ok := value.(Marshaler); ok {
 		return v.MarshalCQL(info)
 	}

+ 10 - 0
marshal_test.go

@@ -297,6 +297,16 @@ func TestMarshal(t *testing.T) {
 	}
 }
 
+func TestMarshalNil(t *testing.T) {
+	data, err := Marshal(&TypeInfo{Type: TypeInt}, nil)
+	if err != nil {
+		t.Errorf("failed to marshal nil with err: %v", err)
+	}
+	if data != nil {
+		t.Errorf("expected nil, got %v", data)
+	}
+}
+
 func TestUnmarshal(t *testing.T) {
 	for i, test := range marshalTests {
 		v := reflect.New(reflect.TypeOf(test.Value))