forked from proullon/ramsql
/
attribute.go
90 lines (75 loc) · 2.31 KB
/
attribute.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package engine
import (
"fmt"
"strings"
"time"
"github.com/IllidanTwister/ramsql/engine/log"
"github.com/IllidanTwister/ramsql/engine/parser"
)
// Domain is the set of allowable values for an Attribute.
type Domain struct {
}
// Attribute is a named column of a relation
// AKA Field
// AKA Column
type Attribute struct {
name string
typeName string
typeInstance interface{}
defaultValue interface{}
domain Domain
autoIncrement bool
unique bool
}
func parseAttribute(decl *parser.Decl) (Attribute, error) {
attr := Attribute{}
// Attribute name
if decl.Token != parser.StringToken {
return attr, fmt.Errorf("engine: expected attribute name, got %v", decl.Token)
}
attr.name = decl.Lexeme
// Attribute type
if len(decl.Decl) < 1 {
return attr, fmt.Errorf("Attribute %s has no type", decl.Lexeme)
}
if decl.Decl[0].Token != parser.StringToken {
return attr, fmt.Errorf("engine: expected attribute type, got %v:%v", decl.Decl[0].Token, decl.Decl[0].Lexeme)
}
attr.typeName = decl.Decl[0].Lexeme
// Maybe domain and special thing like primary key
typeDecl := decl.Decl[1:]
for i := range typeDecl {
log.Debug("Got %v for %s %s", typeDecl[i], attr.name, attr.typeName)
if typeDecl[i].Token == parser.AutoincrementToken {
attr.autoIncrement = true
}
if typeDecl[i].Token == parser.DefaultToken {
log.Debug("we get a default value for %s: %s!\n", attr.name, typeDecl[i].Decl[0].Lexeme)
switch typeDecl[i].Decl[0].Token {
case parser.LocalTimestampToken, parser.NowToken:
log.Debug("Setting default value to NOW() func !\n")
attr.defaultValue = func() interface{} { return time.Now().Format(parser.DateLongFormat) }
default:
log.Debug("Setting default value to '%v'\n", typeDecl[i].Decl[0].Lexeme)
attr.defaultValue = typeDecl[i].Decl[0].Lexeme
}
}
// Check if attribute is unique
if typeDecl[i].Token == parser.UniqueToken {
attr.unique = true
}
}
if strings.ToLower(attr.typeName) == "bigserial" || strings.ToLower(attr.typeName) == "serial" {
attr.autoIncrement = true
}
return attr, nil
}
// NewAttribute initialize a new Attribute struct
func NewAttribute(name string, typeName string, autoIncrement bool) Attribute {
a := Attribute{
name: name,
typeName: typeName,
autoIncrement: autoIncrement,
}
return a
}