-
Notifications
You must be signed in to change notification settings - Fork 2
/
unique.go
59 lines (51 loc) · 1.48 KB
/
unique.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
50
51
52
53
54
55
56
57
58
59
package sol
import (
"fmt"
"strings"
"github.com/aodin/sol/dialect"
"github.com/aodin/sol/types"
)
// UniqueArray is a list of columns representing a table UNIQUE constraint.
type UniqueArray []string
var _ types.Type = UniqueArray{}
var _ Modifier = UniqueArray{}
// Create returns the proper syntax for CREATE TABLE commands.
func (unique UniqueArray) Create(d dialect.Dialect) (string, error) {
columns := make([]string, len(unique))
for i, col := range unique {
columns[i] = col
}
return fmt.Sprintf("UNIQUE (%s)", strings.Join(columns, ", ")), nil
}
// Has returns true if the UniqueArray contains the given column name.
func (unique UniqueArray) Has(name string) bool {
for _, col := range unique {
if col == name {
return true
}
}
return false
}
// Modify implements the TableModifier interface. It confirms that every column
// given exists in the parent table.
func (unique UniqueArray) Modify(tabular Tabular) error {
if tabular == nil || tabular.Table() == nil {
return fmt.Errorf("sol: unique constraints cannot modify a nil table")
}
table := tabular.Table() // Get the dialect neutral table
for _, col := range unique {
if !table.Has(col) {
return fmt.Errorf(
"sol: table '%s' does not have a column '%s'. Is it created after Unique()?",
table.name,
col,
)
}
}
table.uniques = append(table.uniques, unique)
table.creates = append(table.creates, unique)
return nil
}
func Unique(names ...string) UniqueArray {
return UniqueArray(names)
}