-
Notifications
You must be signed in to change notification settings - Fork 6
/
column.go
129 lines (107 loc) · 2.78 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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Copyright 2014 by caixw, All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package orm
import (
"reflect"
"strconv"
)
// Column 列结构
type Column struct {
model *Model
Name string // 数据库的字段名
Len1 int // 长度1,仅对部分类型启作用
Len2 int // 长度2,仅对部分类型启作用
Nullable bool // 是否可以为 NULL
GoType reflect.Type // Go 语言中的数据类型
zero interface{} // GoType 的零值
GoName string // 结构字段名
HasDefault bool
Default string // 默认值
}
// ForeignKey 外键
type ForeignKey struct {
Col *Column
RefTableName, RefColName string
UpdateRule, DeleteRule string
}
func (m *Model) newColumn(field reflect.StructField) *Column {
return &Column{
GoType: field.Type,
zero: reflect.Zero(field.Type).Interface(),
Name: field.Name,
model: m,
GoName: field.Name,
}
}
// IsZero 是否为零值
func (c *Column) IsZero(v reflect.Value) bool {
if !v.IsValid() {
return false
}
if c.GoType.Comparable() {
return c.zero == v.Interface()
}
if v.Kind() == reflect.Slice {
return v.Len() == 0
}
return false
}
// IsAI 当前列是否为自增列
func (c *Column) IsAI() bool {
return (c.model != nil) && (c.model.AI == c)
}
// 检测长试是否合法,必须要 Column 初始化已经完成。
func (c *Column) checkLen() error {
if c.GoType.Kind() == reflect.String {
if c.Len1 == 0 {
return propertyError(c.Name, "len", "字符类型,必须指定 len 属性")
}
if c.Len1 < -1 {
return propertyError(c.Name, "len", "必须大于 0 或是 -1")
}
} else {
if c.Len1 < 0 { // 不能为负数
return propertyError(c.Name, "len", "不能小于 0")
}
if c.Len2 < 0 { // 不能为负数
return propertyError(c.Name, "len", "不能小于 0")
}
}
return nil
}
// 从参数中获取 Column 的 len1 和 len2 变量。
// len(len1,len2)
func (c *Column) setLen(vals []string) (err error) {
switch len(vals) {
case 0:
case 1:
c.Len1, err = strconv.Atoi(vals[0])
case 2:
if c.Len1, err = strconv.Atoi(vals[0]); err != nil {
return err
}
c.Len2, err = strconv.Atoi(vals[1])
default:
return propertyError(c.Name, "len", "过多的参数")
}
return
}
// 从 vals 中分析,得出 Column.Nullable 的值。
// nullable; or nullable(true);
func (c *Column) setNullable(vals []string) (err error) {
if c.IsAI() {
return propertyError(c.Name, "nullable", "自增列不能设置此值")
}
switch len(vals) {
case 0:
c.Nullable = true
case 1:
if c.Nullable, err = strconv.ParseBool(vals[0]); err != nil {
return err
}
default:
return propertyError(c.Name, "nullable", "过多的参数值")
}
return nil
}