forked from longbridgeapp/gorm-sharding
-
-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Split primary_key gen as single file
- Loading branch information
Showing
3 changed files
with
42 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package sharding | ||
|
||
import "fmt" | ||
|
||
const ( | ||
// Use Snowflake primary key generator | ||
PKSnowflake = iota | ||
// Use PostgreSQL sequence primary key generator | ||
PKPGSequence | ||
// Use custom primary key generator | ||
PKCustom | ||
) | ||
|
||
func (s *Sharding) genSnowflakeKey(index int64) int64 { | ||
return s.snowflakeNodes[index].Generate().Int64() | ||
} | ||
|
||
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 pgSeqName(table string) string { | ||
return fmt.Sprintf("gorm_sharding_%s_id_seq", table) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package sharding | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/longbridgeapp/assert" | ||
) | ||
|
||
func Test_pgSeqName(t *testing.T) { | ||
assert.Equal(t, "gorm_sharding_users_id_seq", pgSeqName("users")) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters