-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidentifier.go
49 lines (39 loc) · 1.33 KB
/
identifier.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
package pgidentifier
import (
"encoding/base64"
"fmt"
"regexp"
"strings"
"github.com/google/uuid"
)
var (
// SimpleIdentifierRegex matches identifiers in Postgres that require no quotes
SimpleIdentifierRegex = regexp.MustCompile("^[a-z_][a-z0-9_$]*$")
)
func IsSimpleIdentifier(val string) bool {
return SimpleIdentifierRegex.MatchString(val)
}
const encodePostgresIdentifier = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$_"
var postgresIdentifierEncoding = base64.NewEncoding(encodePostgresIdentifier).WithPadding(base64.NoPadding)
// RandomUUID builds a RandomUUID to be used in Postgres identifiers. This RandomUUID cannot be used directly as an identifier
// and must be prefixed with a letter
func RandomUUID() (string, error) {
uuid, err := uuid.NewRandom()
if err != nil {
return "", fmt.Errorf("generating RandomUUID: %w", err)
}
// Encode in base64 to make the RandomUUID smaller
binary, err := uuid.MarshalBinary()
if err != nil {
return "", fmt.Errorf("marshaling RandomUUID: %w", err)
}
var sb strings.Builder
encoder := base64.NewEncoder(postgresIdentifierEncoding, &sb)
if _, err := encoder.Write(binary); err != nil {
return "", fmt.Errorf("encoding RandomUUID: %w", err)
}
if err := encoder.Close(); err != nil {
return "", fmt.Errorf("closing encoder: %w", err)
}
return sb.String(), nil
}