lukasz-antoniak commented on code in PR #1828:
URL: 
https://github.com/apache/cassandra-gocql-driver/pull/1828#discussion_r1824196570


##########
marshal.go:
##########
@@ -1709,6 +1719,169 @@ func unmarshalList(info TypeInfo, data []byte, value 
interface{}) error {
        return unmarshalErrorf("can not unmarshal %s into %T", info, value)
 }
 
+func marshalVector(info VectorType, value interface{}) ([]byte, error) {
+       if value == nil {
+               return nil, nil
+       } else if _, ok := value.(unsetColumn); ok {
+               return nil, nil
+       }
+
+       rv := reflect.ValueOf(value)
+       t := rv.Type()
+       k := t.Kind()
+       if k == reflect.Slice && rv.IsNil() {
+               return nil, nil
+       }
+
+       switch k {
+       case reflect.Slice, reflect.Array:
+               buf := &bytes.Buffer{}
+               n := rv.Len()
+               if n != info.Dimensions {
+                       return nil, marshalErrorf("expected vector with %d 
dimensions, received %d", info.Dimensions, n)
+               }
+
+               for i := 0; i < n; i++ {
+                       item, err := Marshal(info.SubType, 
rv.Index(i).Interface())
+                       if err != nil {
+                               return nil, err
+                       }
+                       if isVectorVariableLengthType(info.SubType) {
+                               writeUnsignedVInt(buf, uint64(len(item)))
+                       }
+                       buf.Write(item)
+               }
+               return buf.Bytes(), nil
+       }
+       return nil, marshalErrorf("can not marshal %T into %s", value, info)
+}
+
+func unmarshalVector(info VectorType, data []byte, value interface{}) error {
+       rv := reflect.ValueOf(value)
+       if rv.Kind() != reflect.Ptr {
+               return unmarshalErrorf("can not unmarshal into non-pointer %T", 
value)
+       }
+       rv = rv.Elem()
+       t := rv.Type()
+       k := t.Kind()
+       switch k {
+       case reflect.Slice, reflect.Array:
+               if data == nil {
+                       if k == reflect.Array {
+                               return unmarshalErrorf("unmarshal vector: can 
not store nil in array value")
+                       }
+                       if rv.IsNil() {
+                               return nil
+                       }
+                       rv.Set(reflect.Zero(t))
+                       return nil
+               }
+               if k == reflect.Array {
+                       if rv.Len() != info.Dimensions {
+                               return unmarshalErrorf("unmarshal vector: array 
with wrong size")

Review Comment:
   👍



##########
vector_test.go:
##########
@@ -0,0 +1,403 @@
+//go:build all || cassandra
+// +build all cassandra
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * Content before git sha 34fdeebefcbf183ed7f916f931aa0586fdaa1b40
+ * Copyright (c) 2016, The Gocql authors,
+ * provided under the BSD-3-Clause License.
+ * See the NOTICE file distributed with this work for additional information.
+ */
+
+package gocql
+
+import (
+       "fmt"
+       "github.com/stretchr/testify/require"
+       "gopkg.in/inf.v0"
+       "net"
+       "reflect"
+       "testing"
+       "time"
+)
+
+type person struct {
+       FirstName string `cql:"first_name"`
+       LastName  string `cql:"last_name"`
+       Age       int    `cql:"age"`
+}
+
+func (p person) String() string {
+       return fmt.Sprintf("Person{firstName: %s, lastName: %s, Age: %d}", 
p.FirstName, p.LastName, p.Age)
+}
+
+func TestVector_Marshaler(t *testing.T) {
+       session := createSession(t)
+       defer session.Close()
+
+       if flagCassVersion.Before(5, 0, 0) {
+               t.Skip("Vector types have been introduced in Cassandra 5.0")
+       }
+
+       err := createTable(session, `CREATE TABLE IF NOT EXISTS 
gocql_test.vector_fixed(id int primary key, vec vector<float, 3>);`)
+       if err != nil {
+               t.Fatal(err)
+       }
+
+       err = createTable(session, `CREATE TABLE IF NOT EXISTS 
gocql_test.vector_variable(id int primary key, vec vector<text, 4>);`)
+       if err != nil {
+               t.Fatal(err)
+       }
+
+       insertFixVec := []float32{8, 2.5, -5.0}
+       err = session.Query("INSERT INTO vector_fixed(id, vec) VALUES(?, ?)", 
1, insertFixVec).Exec()
+       if err != nil {
+               t.Fatal(err)
+       }
+       var selectFixVec []float32
+       err = session.Query("SELECT vec FROM vector_fixed WHERE id = ?", 
1).Scan(&selectFixVec)
+       if err != nil {
+               t.Fatal(err)
+       }
+       assertDeepEqual(t, "fixed size element vector", insertFixVec, 
selectFixVec)
+
+       longText := randomText(500)
+       insertVarVec := []string{"apache", "cassandra", longText, "gocql"}
+       err = session.Query("INSERT INTO vector_variable(id, vec) VALUES(?, 
?)", 1, insertVarVec).Exec()
+       if err != nil {
+               t.Fatal(err)
+       }
+       var selectVarVec []string
+       err = session.Query("SELECT vec FROM vector_variable WHERE id = ?", 
1).Scan(&selectVarVec)
+       if err != nil {
+               t.Fatal(err)
+       }
+       assertDeepEqual(t, "variable size element vector", insertVarVec, 
selectVarVec)
+}
+
+func TestVector_Types(t *testing.T) {
+       session := createSession(t)
+       defer session.Close()
+
+       if flagCassVersion.Before(5, 0, 0) {
+               t.Skip("Vector types have been introduced in Cassandra 5.0")
+       }
+
+       timestamp1, _ := time.Parse("2006-01-02", "2000-01-01")
+       timestamp2, _ := time.Parse("2006-01-02 15:04:05", "2024-01-01 
10:31:45")
+       timestamp3, _ := time.Parse("2006-01-02 15:04:05.000", "2024-05-01 
10:31:45.987")
+
+       date1, _ := time.Parse("2006-01-02", "2000-01-01")
+       date2, _ := time.Parse("2006-01-02", "2022-03-14")
+       date3, _ := time.Parse("2006-01-02", "2024-12-31")
+
+       time1, _ := time.Parse("15:04:05", "01:00:00")
+       time2, _ := time.Parse("15:04:05", "15:23:59")
+       time3, _ := time.Parse("15:04:05.000", "10:31:45.987")
+
+       duration1 := Duration{0, 1, 1920000000000}
+       duration2 := Duration{1, 1, 1920000000000}
+       duration3 := Duration{31, 0, 60000000000}
+
+       map1 := make(map[string]int)
+       map1["a"] = 1
+       map1["b"] = 2
+       map1["c"] = 3
+       map2 := make(map[string]int)
+       map2["abc"] = 123
+       map3 := make(map[string]int)
+
+       tests := []struct {
+               name       string
+               cqlType    string
+               value      interface{}
+               comparator func(interface{}, interface{})
+       }{
+               {name: "ascii", cqlType: TypeAscii.String(), value: 
[]string{"a", "1", "Z"}},
+               {name: "bigint", cqlType: TypeBigInt.String(), value: 
[]int64{1, 2, 3}},
+               {name: "blob", cqlType: TypeBlob.String(), value: 
[][]byte{[]byte{1, 2, 3}, []byte{4, 5, 6, 7}, []byte{8, 9}}},
+               {name: "boolean", cqlType: TypeBoolean.String(), value: 
[]bool{true, false, true}},
+               {name: "counter", cqlType: TypeCounter.String(), value: 
[]int64{5, 6, 7}},
+               {name: "decimal", cqlType: TypeDecimal.String(), value: 
[]inf.Dec{*inf.NewDec(1, 0), *inf.NewDec(2, 1), *inf.NewDec(-3, 2)}},
+               {name: "double", cqlType: TypeDouble.String(), value: 
[]float64{0.1, -1.2, 3}},
+               {name: "float", cqlType: TypeFloat.String(), value: 
[]float32{0.1, -1.2, 3}},
+               {name: "int", cqlType: TypeInt.String(), value: []int32{1, 2, 
3}},
+               {name: "text", cqlType: TypeText.String(), value: []string{"a", 
"b", "c"}},
+               {name: "timestamp", cqlType: TypeTimestamp.String(), value: 
[]time.Time{timestamp1, timestamp2, timestamp3}},
+               {name: "uuid", cqlType: TypeUUID.String(), value: 
[]UUID{MustRandomUUID(), MustRandomUUID(), MustRandomUUID()}},
+               {name: "varchar", cqlType: TypeVarchar.String(), value: 
[]string{"abc", "def", "ghi"}},
+               {name: "varint", cqlType: TypeVarint.String(), value: 
[]uint64{uint64(1234), uint64(123498765), uint64(18446744073709551615)}},
+               {name: "timeuuid", cqlType: TypeTimeUUID.String(), value: 
[]UUID{TimeUUID(), TimeUUID(), TimeUUID()}},
+               {
+                       name:    "inet",
+                       cqlType: TypeInet.String(),
+                       value:   []net.IP{net.IPv4(127, 0, 0, 1), net.IPv4(192, 
168, 1, 1), net.IPv4(8, 8, 8, 8)},
+                       comparator: func(e interface{}, a interface{}) {
+                               expected := e.([]net.IP)
+                               actual := a.([]net.IP)
+                               assertEqual(t, "vector size", len(expected), 
len(actual))
+                               for i, _ := range expected {
+                                       // TODO(lantoniak): Find a better way 
to compare IP addresses
+                                       assertEqual(t, "vector", 
expected[i].String(), actual[i].String())
+                               }
+                       },
+               },
+               {name: "date", cqlType: TypeDate.String(), value: 
[]time.Time{date1, date2, date3}},
+               {name: "time", cqlType: TypeTimestamp.String(), value: 
[]time.Time{time1, time2, time3}},
+               {name: "smallint", cqlType: TypeSmallInt.String(), value: 
[]int16{127, 256, -1234}},
+               {name: "tinyint", cqlType: TypeTinyInt.String(), value: 
[]int8{127, 9, -123}},
+               {name: "duration", cqlType: TypeDuration.String(), value: 
[]Duration{duration1, duration2, duration3}},
+               // TODO(lantonia): Test vector of custom types

Review Comment:
   👍



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to