forked from huandu/go-sqlbuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
createtable.go
249 lines (198 loc) · 6.66 KB
/
createtable.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// Copyright 2018 Huan Du. All rights reserved.
// Licensed under the MIT license that can be found in the LICENSE file.
package sqlbuilder
import (
"bytes"
"fmt"
"github.com/MatteoMiotello/go-sqlbuilder/types"
"strings"
)
const (
createTableMarkerInit injectionMarker = iota
createTableMarkerAfterCreate
createTableMarkerAfterDefine
createTableMarkerAfterOption
createTableMarkerAfterFinalize
)
// NewCreateTableBuilder creates a new CREATE TABLE builder.
func NewCreateTableBuilder() *CreateTableBuilder {
return DefaultFlavor.NewCreateTableBuilder()
}
func newCreateTableBuilder() *CreateTableBuilder {
args := &Args{}
return &CreateTableBuilder{
verb: "CREATE TABLE",
args: args,
injection: newInjection(),
marker: createTableMarkerInit,
}
}
// CreateTableBuilder is a builder to build CREATE TABLE.
type CreateTableBuilder struct {
verb string
ifNotExists bool
table string
defs [][]string
options [][]string
finalizers [][]string
args *Args
injection *injection
marker injectionMarker
}
var _ Builder = new(CreateTableBuilder)
// CreateTable sets the table name in CREATE TABLE.
func CreateTable(table string) *CreateTableBuilder {
return DefaultFlavor.NewCreateTableBuilder().CreateTable(table)
}
// CreateTable sets the table name in CREATE TABLE.
func (ctb *CreateTableBuilder) CreateTable(table string) *CreateTableBuilder {
ctb.table = Escape(table)
ctb.marker = createTableMarkerAfterCreate
return ctb
}
// CreateTempTable sets the table name and changes the verb of ctb to CREATE TEMPORARY TABLE.
func (ctb *CreateTableBuilder) CreateTempTable(table string) *CreateTableBuilder {
ctb.verb = "CREATE TEMPORARY TABLE"
ctb.table = Escape(table)
ctb.marker = createTableMarkerAfterCreate
return ctb
}
// IfNotExists adds IF NOT EXISTS before table name in CREATE TABLE.
func (ctb *CreateTableBuilder) IfNotExists() *CreateTableBuilder {
ctb.ifNotExists = true
return ctb
}
// Define adds definition of a column or index in CREATE TABLE.
func (ctb *CreateTableBuilder) Define(def ...string) *CreateTableBuilder {
ctb.defs = append(ctb.defs, def)
ctb.marker = createTableMarkerAfterDefine
return ctb
}
// Option adds a table option in CREATE TABLE.
func (ctb *CreateTableBuilder) Option(opt ...string) *CreateTableBuilder {
ctb.options = append(ctb.options, opt)
ctb.marker = createTableMarkerAfterOption
return ctb
}
func (ctb *CreateTableBuilder) Finalizer(finalizer ...string) *CreateTableBuilder {
ctb.finalizers = append(ctb.finalizers, finalizer)
ctb.marker = createTableMarkerAfterFinalize
return ctb
}
// String returns the compiled INSERT string.
func (ctb *CreateTableBuilder) String() string {
s, _ := ctb.Build()
return s
}
// Build returns compiled CREATE TABLE string and args.
// They can be used in `DB#Query` of package `database/sql` directly.
func (ctb *CreateTableBuilder) Build() (sql string, args []interface{}) {
return ctb.BuildWithFlavor(ctb.args.Flavor)
}
// BuildWithFlavor returns compiled CREATE TABLE string and args with flavor and initial args.
// They can be used in `DB#Query` of package `database/sql` directly.
func (ctb *CreateTableBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{}) (sql string, args []interface{}) {
buf := &bytes.Buffer{}
ctb.injection.WriteTo(buf, createTableMarkerInit)
buf.WriteString(ctb.verb)
if ctb.ifNotExists {
buf.WriteString(" IF NOT EXISTS")
}
buf.WriteRune(' ')
buf.WriteString(ctb.table)
ctb.injection.WriteTo(buf, createTableMarkerAfterCreate)
if len(ctb.defs) > 0 {
buf.WriteString(" (")
defs := make([]string, 0, len(ctb.defs))
for _, def := range ctb.defs {
defs = append(defs, strings.Join(def, " "))
}
buf.WriteString(strings.Join(defs, ", "))
buf.WriteRune(')')
ctb.injection.WriteTo(buf, createTableMarkerAfterDefine)
}
if len(ctb.options) > 0 {
buf.WriteRune(' ')
opts := make([]string, 0, len(ctb.options))
for _, opt := range ctb.options {
opts = append(opts, strings.Join(opt, " "))
}
buf.WriteString(strings.Join(opts, ", "))
ctb.injection.WriteTo(buf, createTableMarkerAfterOption)
}
if len(ctb.finalizers) > 0 {
buf.WriteString("; ")
finalizers := make([]string, 0, len(ctb.finalizers))
for _, fin := range ctb.finalizers {
finalizers = append(finalizers, strings.Join(fin, "; "))
}
buf.WriteString(strings.Join(finalizers, "; "))
ctb.injection.WriteTo(buf, createTableMarkerAfterFinalize)
}
return ctb.args.CompileWithFlavor(buf.String(), flavor, initialArg...)
}
// SetFlavor sets the flavor of compiled sql.
func (ctb *CreateTableBuilder) SetFlavor(flavor Flavor) (old Flavor) {
old = ctb.args.Flavor
ctb.args.Flavor = flavor
return
}
// Var returns a placeholder for value.
func (ctb *CreateTableBuilder) Var(arg interface{}) string {
return ctb.args.Add(arg)
}
// SQL adds an arbitrary sql to current position.
func (ctb *CreateTableBuilder) SQL(sql string) *CreateTableBuilder {
ctb.injection.SQL(ctb.marker, sql)
return ctb
}
func (ctb *CreateTableBuilder) PKColumn() *CreateTableBuilder {
colName := "id"
return ctb.Define(colName, string(types.Bigserial), "PRIMARY KEY")
}
func singleTableName(s string) string {
if strings.HasSuffix(s, "s") {
s = s[:len(s)-len("s")]
}
return s
}
func (ctb *CreateTableBuilder) FKColumn(completeTableName string, colName string, nullable bool) *CreateTableBuilder {
tableName := strings.Split(completeTableName, ".")[1]
curTableName := singleTableName(strings.Split(ctb.table, ".")[1])
tableName = singleTableName(tableName)
props := []string{
colName,
string(types.Bigint),
}
if nullable == false {
props = append(props, "NOT NULL")
} else {
props = append(props, "NULL")
}
ctb.Define(props...)
return ctb.Finalizer(
fmt.Sprintf("ALTER TABLE %s ADD CONSTRAINT fk_%s FOREIGN KEY (%s) REFERENCES %s (id) ON UPDATE CASCADE", ctb.table, tableName, colName, completeTableName),
fmt.Sprintf("CREATE INDEX idx_%s_%s ON %s (%s)", curTableName, colName, ctb.table, colName),
)
}
func (ctb *CreateTableBuilder) CreatedColumn() *CreateTableBuilder {
return ctb.Define("created_at", string(types.Timestamptz), "NOT NULL", "DEFAULT NOW()")
}
func (ctb *CreateTableBuilder) UpdatedColumn() *CreateTableBuilder {
return ctb.Define("updated_at", string(types.Timestamptz), "NOT NULL", "DEFAULT NOW()")
}
func (ctb *CreateTableBuilder) DeletedColumn() *CreateTableBuilder {
return ctb.Define("deleted_at", string(types.Timestamptz), "NULL")
}
func (ctb *CreateTableBuilder) Column(colName string, colType types.ColType, nullable bool) *CreateTableBuilder {
props := []string{
colName,
string(colType),
}
if nullable {
props = append(props, "NULL")
} else {
props = append(props, "NOT NULL")
}
return ctb.Define(props...)
}