-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshalerUnmarshaler.go
81 lines (70 loc) · 1.72 KB
/
marshalerUnmarshaler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
"strconv"
"strings"
"github.com/gocql/gocql"
)
type MyMarshaler struct {
major int
minor int
patch int
}
func (m MyMarshaler) MarshalCQL(typeInfo gocql.TypeInfo) ([]byte, error) {
return gocql.Marshal(typeInfo, fmt.Sprintf("%d.%d.%d", m.major, m.minor, m.patch))
}
func (m MyMarshaler) UnmarshalCQL(typeInfo gocql.TypeInfo, data []byte) error {
var s string
err := gocql.Unmarshal(typeInfo, data, &s)
if err != nil {
return err
}
parts := strings.SplitN(s, ".", 3)
if len(parts) != 3 {
return fmt.Errorf("parse version %q: %d parts instead of 3", s, len(parts))
}
major, err := strconv.Atoi(parts[0])
if err != nil {
return fmt.Errorf("parse version %q major number: %v", s, err)
}
minor, err := strconv.Atoi(parts[1])
if err != nil {
return fmt.Errorf("parse version %q minor number: %v", s, err)
}
patch, err := strconv.Atoi(parts[2])
if err != nil {
return fmt.Errorf("parse version %q patch number: %v", s, err)
}
m.major = major
m.minor = minor
m.patch = patch
return nil
}
func main() {
/*
create table example.my_marshaler_table(pk int, value text, PRIMARY KEY(pk));
*/
cluster := gocql.NewCluster("127.0.0.1", "127.0.0.2", "127.0.0.3")
cluster.Keyspace = "example"
cluster.ProtoVersion = 4
session, err := cluster.CreateSession()
if err != nil {
panic(err)
}
defer session.Close()
value := MyMarshaler{
major: 1,
minor: 2,
patch: 3,
}
err = session.Query(`INSERT INTO example.my_marshaler_table(pk, value) VALUES(?, ?)`, 1, value).Exec()
if err != nil {
panic(err)
}
var stringValue string
err = session.Query(`SELECT value FROM example.my_marshaler_table WHERE pk=1`).Scan(&stringValue)
if err != nil {
panic(err)
}
fmt.Println(stringValue)
}