-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample_test.go
99 lines (81 loc) · 1.8 KB
/
example_test.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
package ydb_test
import (
"context"
"fmt"
environ "github.com/ydb-platform/ydb-go-sdk-auth-environ"
"gorm.io/gorm"
ydb "github.com/ydb-platform/gorm-driver"
)
//nolint:funlen
func Example_query() {
type Product struct {
ID uint `gorm:"primarykey;not null;autoIncrement:false"`
Code string
Price uint `gorm:"index"`
}
db, err := gorm.Open(
ydb.Open("grpc://localhost:2136/local",
ydb.With(environ.WithEnvironCredentials()),
),
)
if err != nil {
panic(err)
}
db = db.Debug()
// Migrate the schema
err = db.AutoMigrate(&Product{})
if err != nil {
panic(err)
}
// Create
err = db.Create(&Product{ID: 1, Code: "D42", Price: 100}).Error
if err != nil {
panic(err)
}
// Scan query
var products []Product
err = db.
WithContext(ydb.WithQueryMode(context.Background(), ydb.ScanQueryMode)).
Model(&Product{}).
Scan(&products).
Error
if err != nil {
panic(err)
}
// Read
var product Product
err = db.First(&product, 1).Error // find product with integer primary key
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", product)
err = db.First(&product, "code = ?", "D42").Error // find product with code D42
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", product)
// Update - update product's price to 200
err = db.Model(&product).Update("Price", 200).Error
if err != nil {
panic(err)
}
// Update - update multiple fields
err = db.Model(&product).Updates(Product{Price: 200, Code: "F42"}).Error // non-zero fields
if err != nil {
panic(err)
}
err = db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}).Error
if err != nil {
panic(err)
}
// Delete - delete product
err = db.Delete(&product, 1).Error
if err != nil {
panic(err)
}
// Drop table
err = db.Migrator().DropTable(&Product{})
if err != nil {
panic(err)
}
}