-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathmain.go
126 lines (105 loc) · 2.52 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"context"
"fmt"
"os"
"github.com/davecgh/go-spew/spew"
"go.ytsaurus.tech/yt/go/guid"
"go.ytsaurus.tech/yt/go/schema"
"go.ytsaurus.tech/yt/go/ypath"
"go.ytsaurus.tech/yt/go/yt"
"go.ytsaurus.tech/yt/go/yt/ythttp"
)
const (
numberOfRows int = 100
cluster string = "freud"
)
type Contact struct {
Name string `yson:"name"`
Email string `yson:"email"`
Phone string `yson:"phone"`
Age int `yson:"age"`
}
func (c *Contact) Init() {
c.Name = "Gopher"
c.Email = "gopher@ytsaurus.tech"
c.Phone = "+70000000000"
c.Age = 27
}
func Example() error {
yc, err := ythttp.NewClient(&yt.Config{
Proxy: cluster,
ReadTokenFromFile: true,
})
if err != nil {
return err
}
fakeContacts := make([]Contact, numberOfRows)
for i := range fakeContacts {
fakeContacts[i].Init()
}
fmt.Println("Generated contacts:")
spew.Fdump(os.Stdout, fakeContacts)
tableSchema, err := schema.Infer(Contact{})
if err != nil {
return err
}
fmt.Println("Inferred struct schema:")
spew.Fdump(os.Stdout, tableSchema)
ctx := context.Background()
tablePath := ypath.Path("//tmp/go-table-example-" + guid.New().String())
_, err = yt.CreateTable(ctx, yc, tablePath, yt.WithSchema(tableSchema))
if err != nil {
return err
}
fmt.Printf("Created table at https://yt.yandex-team.ru/%s/navigation?path=%s\n", cluster, tablePath.String())
writer, err := yc.WriteTable(ctx, tablePath, nil)
if err != nil {
return err
}
fmt.Println("Writing rows to table...")
for _, v := range fakeContacts {
if err = writer.Write(v); err != nil {
return err
}
}
if err = writer.Commit(); err != nil {
return err
}
fmt.Printf("Written and committed %v rows\n", len(fakeContacts))
type Attrs struct {
Rows int `yson:"row_count"`
}
var attrs Attrs
if err = yc.GetNode(ctx, tablePath.Attrs(), &attrs, nil); err != nil {
return err
}
fmt.Printf("YT table contains %v rows\n", attrs.Rows)
reader, err := yc.ReadTable(ctx, tablePath, nil)
if err != nil {
return err
}
defer func() { _ = reader.Close() }()
fmt.Println("Reading rows from table...")
readContacts := make([]Contact, 0, attrs.Rows)
for reader.Next() {
var c Contact
err = reader.Scan(&c)
if err != nil {
return err
}
readContacts = append(readContacts, c)
}
if reader.Err() != nil {
return reader.Err()
}
fmt.Printf("Read %v rows:\n", len(readContacts))
spew.Fdump(os.Stdout, readContacts)
return nil
}
func main() {
if err := Example(); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "error: %+v\n", err)
os.Exit(1)
}
}