Skip to content

Commit d2d449a

Browse files
committed
Review comments
1 parent 16d63e3 commit d2d449a

File tree

2 files changed

+25
-15
lines changed

2 files changed

+25
-15
lines changed

database/util.go

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
11
package database
22

33
import (
4-
"bytes"
54
"fmt"
65
"hash/crc32"
6+
"strings"
77
)
88

99
const advisoryLockIdSalt uint = 1486364155
1010

1111
// GenerateAdvisoryLockId inspired by rails migrations, see https://goo.gl/8o9bCT
1212
func GenerateAdvisoryLockId(databaseName string, additionalNames ...string) (string, error) {
13-
buf := bytes.NewBufferString(databaseName)
14-
for _, name := range additionalNames {
15-
buf.WriteByte(0)
16-
buf.WriteString(name)
13+
if len(additionalNames) > 0 {
14+
databaseName = strings.Join(append(additionalNames, databaseName), "\x00")
1715
}
18-
sum := crc32.ChecksumIEEE(buf.Bytes())
16+
sum := crc32.ChecksumIEEE([]byte(databaseName))
1917
sum = sum * uint32(advisoryLockIdSalt)
2018
return fmt.Sprintf("%v", sum), nil
2119
}

database/util_test.go

+21-9
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,33 @@ import (
77
func TestGenerateAdvisoryLockId(t *testing.T) {
88
testcases := []struct {
99
dbname string
10-
schema string
10+
additional []string
1111
expectedID string // empty string signifies that an error is expected
1212
}{
13-
{dbname: "database_name", expectedID: "1764327054"},
14-
{dbname: "database_name", schema: "schema_name_1", expectedID: "3244152297"},
15-
{dbname: "database_name", schema: "schema_name_2", expectedID: "810103531"},
13+
{
14+
dbname: "database_name",
15+
expectedID: "1764327054",
16+
},
17+
{
18+
dbname: "database_name",
19+
additional: []string{"schema_name_1"},
20+
expectedID: "2453313553",
21+
},
22+
{
23+
dbname: "database_name",
24+
additional: []string{"schema_name_2"},
25+
expectedID: "235207038",
26+
},
27+
{
28+
dbname: "database_name",
29+
additional: []string{"schema_name_1", "schema_name_2"},
30+
expectedID: "3743845847",
31+
},
1632
}
1733

1834
for _, tc := range testcases {
1935
t.Run(tc.dbname, func(t *testing.T) {
20-
names := []string{}
21-
if len(tc.schema) > 0 {
22-
names = append(names, tc.schema)
23-
}
24-
if id, err := GenerateAdvisoryLockId(tc.dbname, names...); err == nil {
36+
if id, err := GenerateAdvisoryLockId(tc.dbname, tc.additional...); err == nil {
2537
if id != tc.expectedID {
2638
t.Error("Generated incorrect ID:", id, "!=", tc.expectedID)
2739
}

0 commit comments

Comments
 (0)