-
Notifications
You must be signed in to change notification settings - Fork 75
/
sharding_test.go
230 lines (194 loc) · 6.89 KB
/
sharding_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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package sharding
import (
"fmt"
"os"
"strconv"
"testing"
"github.com/longbridgeapp/assert"
"github.com/longbridgeapp/gorm-sharding/keygen"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/hints"
)
type Order struct {
ID int64 `gorm:"primarykey"`
UserID int64
Product string
}
type Category struct {
ID int64 `gorm:"primarykey"`
Name string
}
func databaseURL() string {
databaseURL := os.Getenv("DATABASE_URL")
if len(databaseURL) == 0 {
databaseURL = "postgres://localhost:5432/sharding-test?sslmode=disable"
}
return databaseURL
}
var (
dbConfig = postgres.Config{
DSN: databaseURL(),
PreferSimpleProtocol: true,
}
db, _ = gorm.Open(postgres.New(dbConfig), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
})
sharding = Register(map[string]Resolver{
"orders": {
EnableFullTable: true,
ShardingColumn: "user_id",
ShardingAlgorithm: func(value interface{}) (suffix string, err error) {
userId := 0
switch value := value.(type) {
case int:
userId = value
case int64:
userId = int(value)
case string:
userId, err = strconv.Atoi(value)
if err != nil {
return "", err
}
default:
return "", err
}
return fmt.Sprintf("_%02d", userId%4), nil
},
ShardingAlgorithmByPrimaryKey: func(id int64) (suffix string) {
return fmt.Sprintf("_%02d", keygen.TableIdx(id))
},
PrimaryKeyGenerate: func(tableIdx int64) int64 {
return keygen.Next(tableIdx)
},
},
})
)
func init() {
dropTables()
err := db.AutoMigrate(&Order{}, &Category{})
if err != nil {
panic(err)
}
stables := []string{"orders_00", "orders_01", "orders_02", "orders_03"}
for _, table := range stables {
db.Exec(`CREATE TABLE ` + table + ` (
id BIGSERIAL PRIMARY KEY,
user_id bigint,
product text
)`)
}
db.Use(&sharding)
}
func dropTables() {
tables := []string{"orders", "orders_00", "orders_01", "orders_02", "orders_03", "categories"}
for _, table := range tables {
db.Exec("DROP TABLE IF EXISTS " + table)
}
}
func TestInsert(t *testing.T) {
tx := db.Create(&Order{ID: 100, UserID: 100, Product: "iPhone"})
assertQueryResult(t, `INSERT INTO "orders_00" ("user_id", "product", "id") VALUES ($1, $2, $3) RETURNING "id"`, tx)
}
func TestFillID(t *testing.T) {
db.Create(&Order{UserID: 100, Product: "iPhone"})
lastQuery := sharding.LastQuery()
assert.Equal(t, `INSERT INTO "orders_00" ("user_id", "product", "id") VALUES`, lastQuery[0:59])
}
func TestSelect1(t *testing.T) {
tx := db.Model(&Order{}).Where("user_id", 101).Where("id", keygen.Next(1)).Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_01" WHERE "user_id" = $1 AND "id" = $2`, tx)
}
func TestSelect2(t *testing.T) {
tx := db.Model(&Order{}).Where("id", keygen.Next(1)).Where("user_id", 101).Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_01" WHERE "id" = $1 AND "user_id" = $2`, tx)
}
func TestSelect3(t *testing.T) {
tx := db.Model(&Order{}).Where("id", keygen.Next(1)).Where("user_id = 101").Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_01" WHERE "id" = $1 AND "user_id" = 101`, tx)
}
func TestSelect4(t *testing.T) {
tx := db.Model(&Order{}).Where("product", "iPad").Where("user_id", 100).Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_00" WHERE "product" = $1 AND "user_id" = $2`, tx)
}
func TestSelect5(t *testing.T) {
tx := db.Model(&Order{}).Where("user_id = 101").Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_01" WHERE "user_id" = 101`, tx)
}
func TestSelect6(t *testing.T) {
tx := db.Model(&Order{}).Where("id", keygen.Next(2)).Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_02" WHERE "id" = $1`, tx)
}
func TestSelect7(t *testing.T) {
tx := db.Model(&Order{}).Where("user_id", 101).Where("id > ?", keygen.Next(1)).Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_01" WHERE "user_id" = $1 AND "id" > $2`, tx)
}
func TestSelect8(t *testing.T) {
tx := db.Model(&Order{}).Where("id > ?", keygen.Next(1)).Where("user_id", 101).Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_01" WHERE "id" > $1 AND "user_id" = $2`, tx)
}
func TestSelect9(t *testing.T) {
tx := db.Model(&Order{}).Where("user_id = 101").First(&[]Order{})
assertQueryResult(t, `SELECT * FROM "orders_01" WHERE "user_id" = 101 ORDER BY "orders_01"."id" LIMIT 1`, tx)
}
func TestSelect10(t *testing.T) {
tx := db.Clauses(hints.Comment("select", "nosharding")).Model(&Order{}).Find(&[]Order{})
assertQueryResult(t, `SELECT /* nosharding */ * FROM "orders"`, tx)
}
func TestSelect11(t *testing.T) {
tx := db.Clauses(hints.Comment("select", "nosharding")).Model(&Order{}).Where("user_id", 101).Find(&[]Order{})
assertQueryResult(t, `SELECT /* nosharding */ * FROM "orders" WHERE "user_id" = $1`, tx)
}
func TestSelect12(t *testing.T) {
tx := db.Raw(`SELECT * FROM "public"."orders" WHERE "user_id" = 101`).Find(&[]Order{})
assertQueryResult(t, `SELECT * FROM "public"."orders" WHERE "user_id" = 101`, tx)
}
func TestSelect13(t *testing.T) {
tx := db.Raw("SELECT 1").Find(&[]Order{})
assertQueryResult(t, `SELECT 1`, tx)
}
func TestUpdate(t *testing.T) {
tx := db.Model(&Order{}).Where("user_id = ?", 100).Update("product", "new title")
assertQueryResult(t, `UPDATE "orders_00" SET "product" = $1 WHERE "user_id" = $2`, tx)
}
func TestDelete(t *testing.T) {
tx := db.Where("user_id = ?", 100).Delete(&Order{})
assertQueryResult(t, `DELETE FROM "orders_00" WHERE "user_id" = $1`, tx)
}
func TestInsertMissingShardingKey(t *testing.T) {
err := db.Exec(`INSERT INTO "orders" ("id", "product") VALUES(1, 'iPad')`).Error
assert.Equal(t, ErrMissingShardingKey, err)
}
func TestSelectMissingShardingKey(t *testing.T) {
err := db.Exec(`SELECT * FROM "orders" WHERE "product" = 'iPad'`).Error
assert.Equal(t, ErrMissingShardingKey, err)
}
func TestSelectNoSharding(t *testing.T) {
err := db.Exec(`SELECT /* nosharding */ * FROM "orders" WHERE "product" = 'iPad'`).Error
assert.Equal(t, nil, err)
}
func TestNoEq(t *testing.T) {
err := db.Model(&Order{}).Where("user_id <> ?", 101).Find([]Order{}).Error
assert.Equal(t, ErrMissingShardingKey, err)
}
func TestShardingKeyOK(t *testing.T) {
err := db.Model(&Order{}).Where("user_id = ? and id > ?", 101, int64(100)).Find(&[]Order{}).Error
assert.Equal(t, nil, err)
}
func TestShardingKeyNotOK(t *testing.T) {
err := db.Model(&Order{}).Where("user_id > ? and id > ?", 101, int64(100)).Find(&[]Order{}).Error
assert.Equal(t, ErrMissingShardingKey, err)
}
func TestShardingIdOK(t *testing.T) {
err := db.Model(&Order{}).Where("id = ? and user_id > ?", int64(101), 100).Find(&[]Order{}).Error
assert.Equal(t, nil, err)
}
func TestNoSharding(t *testing.T) {
categories := []Category{}
tx := db.Model(&Category{}).Where("id = ?", 1).Find(&categories)
assertQueryResult(t, `SELECT * FROM "categories" WHERE id = $1`, tx)
}
func assertQueryResult(t *testing.T, query string, tx *gorm.DB) {
t.Helper()
assert.Equal(t, query, sharding.LastQuery())
}