forked from cjfinnell/pgverify
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcolumn.go
41 lines (36 loc) · 1.15 KB
/
column.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
package pgverify
import (
"fmt"
"strings"
)
// column represents a column in a table.
type column struct {
name string
dataType string
constraints []string
}
// IsPrimaryKey attempts to parse the constraint string to determine if the
// column is a primary key.
func (c column) IsPrimaryKey() bool {
for _, constraintType := range c.constraints {
if constraintType == "PRIMARY KEY" {
return true
}
}
return false
}
// CastToText generates PSQL expression to cast the column to the TEXT type in
// a way that is consistent between supported databases.
func (c column) CastToText(precision string) string {
switch strings.ToLower(c.dataType) {
case "timestamp with time zone":
// Truncating the epoch means that timestamps will be compared "to the second"; timestamps with ms/ns differences will be considered equal.
return fmt.Sprintf(`(extract(epoch from date_trunc('%s', "%s"))::DECIMAL * 1000000)::BIGINT::TEXT`, precision, c.name)
case "json":
return fmt.Sprintf(`length("%s"::JSONB::TEXT)::TEXT`, c.name)
case "jsonb":
return fmt.Sprintf(`length("%s"::TEXT)::TEXT`, c.name)
default:
return fmt.Sprintf(`"%s"::TEXT`, c.name)
}
}