Review comments

This commit is contained in:
Evgeniy Bastrykov 2018-11-05 16:03:54 +04:00
parent 16d63e3a76
commit d2d449ad78
2 changed files with 25 additions and 15 deletions

View File

@ -1,21 +1,19 @@
package database package database
import ( import (
"bytes"
"fmt" "fmt"
"hash/crc32" "hash/crc32"
"strings"
) )
const advisoryLockIdSalt uint = 1486364155 const advisoryLockIdSalt uint = 1486364155
// GenerateAdvisoryLockId inspired by rails migrations, see https://goo.gl/8o9bCT // GenerateAdvisoryLockId inspired by rails migrations, see https://goo.gl/8o9bCT
func GenerateAdvisoryLockId(databaseName string, additionalNames ...string) (string, error) { func GenerateAdvisoryLockId(databaseName string, additionalNames ...string) (string, error) {
buf := bytes.NewBufferString(databaseName) if len(additionalNames) > 0 {
for _, name := range additionalNames { databaseName = strings.Join(append(additionalNames, databaseName), "\x00")
buf.WriteByte(0)
buf.WriteString(name)
} }
sum := crc32.ChecksumIEEE(buf.Bytes()) sum := crc32.ChecksumIEEE([]byte(databaseName))
sum = sum * uint32(advisoryLockIdSalt) sum = sum * uint32(advisoryLockIdSalt)
return fmt.Sprintf("%v", sum), nil return fmt.Sprintf("%v", sum), nil
} }

View File

@ -7,21 +7,33 @@ import (
func TestGenerateAdvisoryLockId(t *testing.T) { func TestGenerateAdvisoryLockId(t *testing.T) {
testcases := []struct { testcases := []struct {
dbname string dbname string
schema string additional []string
expectedID string // empty string signifies that an error is expected expectedID string // empty string signifies that an error is expected
}{ }{
{dbname: "database_name", expectedID: "1764327054"}, {
{dbname: "database_name", schema: "schema_name_1", expectedID: "3244152297"}, dbname: "database_name",
{dbname: "database_name", schema: "schema_name_2", expectedID: "810103531"}, expectedID: "1764327054",
},
{
dbname: "database_name",
additional: []string{"schema_name_1"},
expectedID: "2453313553",
},
{
dbname: "database_name",
additional: []string{"schema_name_2"},
expectedID: "235207038",
},
{
dbname: "database_name",
additional: []string{"schema_name_1", "schema_name_2"},
expectedID: "3743845847",
},
} }
for _, tc := range testcases { for _, tc := range testcases {
t.Run(tc.dbname, func(t *testing.T) { t.Run(tc.dbname, func(t *testing.T) {
names := []string{} if id, err := GenerateAdvisoryLockId(tc.dbname, tc.additional...); err == nil {
if len(tc.schema) > 0 {
names = append(names, tc.schema)
}
if id, err := GenerateAdvisoryLockId(tc.dbname, names...); err == nil {
if id != tc.expectedID { if id != tc.expectedID {
t.Error("Generated incorrect ID:", id, "!=", tc.expectedID) t.Error("Generated incorrect ID:", id, "!=", tc.expectedID)
} }