forked from longbridge/gorm-sharding
-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
primary_key.go
68 lines (57 loc) · 1.79 KB
/
primary_key.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
package sharding
import "fmt"
const (
// Use Snowflake primary key generator
PKSnowflake = iota
// Use PostgreSQL sequence primary key generator
PKPGSequence
// Use MySQL sequence primary key generator
PKMySQLSequence
// Use custom primary key generator
PKCustom
)
func (s *Sharding) genSnowflakeKey(index int64) int64 {
return s.snowflakeNodes[index].Generate().Int64()
}
// PostgreSQL sequence
func (s *Sharding) genPostgreSQLSequenceKey(tableName string, index int64) int64 {
var id int64
err := s.DB.Raw("SELECT nextval('" + pgSeqName(tableName) + "')").Scan(&id).Error
if err != nil {
panic(err)
}
return id
}
func (s *Sharding) createPostgreSQLSequenceKeyIfNotExist(tableName string) error {
return s.DB.Exec(`CREATE SEQUENCE IF NOT EXISTS "` + pgSeqName(tableName) + `" START 1`).Error
}
func pgSeqName(table string) string {
return fmt.Sprintf("gorm_sharding_%s_id_seq", table)
}
// MySQL Sequence
func (s *Sharding) genMySQLSequenceKey(tableName string, index int64) int64 {
var id int64
err := s.DB.Exec("UPDATE `" + mySQLSeqName(tableName) + "` SET id = LAST_INSERT_ID(id + 1)").Error
if err != nil {
panic(err)
}
err = s.DB.Raw("SELECT LAST_INSERT_ID()").Scan(&id).Error
if err != nil {
panic(err)
}
return id
}
func (s *Sharding) createMySQLSequenceKeyIfNotExist(tableName string) error {
stmt := s.DB.Exec("CREATE TABLE IF NOT EXISTS `" + mySQLSeqName(tableName) + "` (id INT NOT NULL)")
if stmt.Error != nil {
return fmt.Errorf("failed to create sequence table: %w", stmt.Error)
}
stmt = s.DB.Exec("INSERT INTO `" + mySQLSeqName(tableName) + "` VALUES (0)")
if stmt.Error != nil {
return fmt.Errorf("failed to insert into sequence table: %w", stmt.Error)
}
return nil
}
func mySQLSeqName(table string) string {
return fmt.Sprintf("gorm_sharding_%s_id_seq", table)
}