Skip to content

Commit 08d7ffc

Browse files
committed
refs huandu#18. add CreateTableBuilder
1 parent 934d5c1 commit 08d7ffc

File tree

4 files changed

+169
-0
lines changed

4 files changed

+169
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ fmt.Println(args)
3838
Following builders are implemented right now. API document and examples are provided in the `godoc` document.
3939

4040
* [Struct](https://godoc.org/github.com/huandu/go-sqlbuilder#Struct): Builder factory for a struct.
41+
* [CreateTableBuilder](https://godoc.org/github.com/huandu/go-sqlbuilder#CreateTableBuilder): Builder for CREATE TABLE.
4142
* [SelectBuilder](https://godoc.org/github.com/huandu/go-sqlbuilder#SelectBuilder): Builder for SELECT.
4243
* [InsertBuilder](https://godoc.org/github.com/huandu/go-sqlbuilder#InsertBuilder): Builder for INSERT.
4344
* [UpdateBuilder](https://godoc.org/github.com/huandu/go-sqlbuilder#UpdateBuilder): Builder for UPDATE.

createtable.go

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
// Copyright 2018 Huan Du. All rights reserved.
2+
// Licensed under the MIT license that can be found in the LICENSE file.
3+
4+
package sqlbuilder
5+
6+
import (
7+
"bytes"
8+
"strings"
9+
)
10+
11+
// NewCreateTableBuilder creates a new CREATE TABLE builder.
12+
func NewCreateTableBuilder() *CreateTableBuilder {
13+
return DefaultFlavor.NewCreateTableBuilder()
14+
}
15+
16+
func newCreateTableBuilder() *CreateTableBuilder {
17+
args := &Args{}
18+
return &CreateTableBuilder{
19+
verb: "CREATE TABLE",
20+
args: args,
21+
}
22+
}
23+
24+
// CreateTableBuilder is a builder to build CREATE TABLE.
25+
type CreateTableBuilder struct {
26+
verb string
27+
ifNotExists bool
28+
table string
29+
defs [][]string
30+
options [][]string
31+
32+
args *Args
33+
}
34+
35+
// CreateTable sets the table name in CREATE TABLE.
36+
func (ctb *CreateTableBuilder) CreateTable(table string) *CreateTableBuilder {
37+
ctb.table = Escape(table)
38+
return ctb
39+
}
40+
41+
// CreateTempTable sets the table name and changes the verb of ctb to CREATE TEMPORARY TABLE.
42+
func (ctb *CreateTableBuilder) CreateTempTable(table string) *CreateTableBuilder {
43+
ctb.verb = "CREATE TEMPORARY TABLE"
44+
ctb.table = Escape(table)
45+
return ctb
46+
}
47+
48+
// IfNotExists adds IF NOT EXISTS before table name in CREATE TABLE.
49+
func (ctb *CreateTableBuilder) IfNotExists() *CreateTableBuilder {
50+
ctb.ifNotExists = true
51+
return ctb
52+
}
53+
54+
// Define adds definition of a column or index in CREATE TABLE.
55+
func (ctb *CreateTableBuilder) Define(def ...string) *CreateTableBuilder {
56+
ctb.defs = append(ctb.defs, def)
57+
return ctb
58+
}
59+
60+
// Option adds a table option in CREATE TABLE.
61+
func (ctb *CreateTableBuilder) Option(opt ...string) *CreateTableBuilder {
62+
ctb.options = append(ctb.options, opt)
63+
return ctb
64+
}
65+
66+
// String returns the compiled INSERT string.
67+
func (ctb *CreateTableBuilder) String() string {
68+
s, _ := ctb.Build()
69+
return s
70+
}
71+
72+
// Build returns compiled CREATE TABLE string and args.
73+
// They can be used in `DB#Query` of package `database/sql` directly.
74+
func (ctb *CreateTableBuilder) Build() (sql string, args []interface{}) {
75+
return ctb.BuildWithFlavor(ctb.args.Flavor)
76+
}
77+
78+
// BuildWithFlavor returns compiled CREATE TABLE string and args with flavor and initial args.
79+
// They can be used in `DB#Query` of package `database/sql` directly.
80+
func (ctb *CreateTableBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{}) (sql string, args []interface{}) {
81+
buf := &bytes.Buffer{}
82+
buf.WriteString(ctb.verb)
83+
84+
if ctb.ifNotExists {
85+
buf.WriteString(" IF NOT EXISTS")
86+
}
87+
88+
buf.WriteRune(' ')
89+
buf.WriteString(ctb.table)
90+
buf.WriteString(" (")
91+
92+
defs := make([]string, 0, len(ctb.defs))
93+
94+
for _, def := range ctb.defs {
95+
defs = append(defs, strings.Join(def, " "))
96+
}
97+
98+
buf.WriteString(strings.Join(defs, ", "))
99+
buf.WriteRune(')')
100+
101+
if len(ctb.options) > 0 {
102+
buf.WriteRune(' ')
103+
104+
opts := make([]string, 0, len(ctb.options))
105+
106+
for _, opt := range ctb.options {
107+
opts = append(opts, strings.Join(opt, " "))
108+
}
109+
110+
buf.WriteString(strings.Join(opts, ", "))
111+
}
112+
113+
return ctb.args.CompileWithFlavor(buf.String(), flavor, initialArg...)
114+
}
115+
116+
// SetFlavor sets the flavor of compiled sql.
117+
func (ctb *CreateTableBuilder) SetFlavor(flavor Flavor) (old Flavor) {
118+
old = ctb.args.Flavor
119+
ctb.args.Flavor = flavor
120+
return
121+
}

createtable_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Copyright 2018 Huan Du. All rights reserved.
2+
// Licensed under the MIT license that can be found in the LICENSE file.
3+
4+
package sqlbuilder
5+
6+
import (
7+
"fmt"
8+
)
9+
10+
func ExampleCreateTableBuilder() {
11+
ctb := NewCreateTableBuilder()
12+
ctb.CreateTable("demo.user").IfNotExists()
13+
ctb.Define("id", "BIGINT(20)", "NOT NULL", "AUTO_INCREMENT", "PRIMARY KEY", `COMMENT "user id"`)
14+
ctb.Define("name", "VARCHAR(255)", "NOT NULL", `COMMENT "user name"`)
15+
ctb.Define("created_at", "DATETIME", "NOT NULL", `COMMENT "user create time"`)
16+
ctb.Define("modified_at", "DATETIME", "NOT NULL", `COMMENT "user modify time"`)
17+
ctb.Define("KEY", "idx_name_modified_at", "name, modified_at")
18+
ctb.Option("DEFAULT CHARACTER SET", "utf8mb4")
19+
20+
fmt.Println(ctb)
21+
22+
// Output:
23+
// CREATE TABLE IF NOT EXISTS demo.user (id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT "user id", name VARCHAR(255) NOT NULL COMMENT "user name", created_at DATETIME NOT NULL COMMENT "user create time", modified_at DATETIME NOT NULL COMMENT "user modify time", KEY idx_name_modified_at name, modified_at) DEFAULT CHARACTER SET utf8mb4
24+
}
25+
26+
func ExampleCreateTableBuilder_tempTable() {
27+
ctb := NewCreateTableBuilder()
28+
ctb.CreateTempTable("demo.user").IfNotExists()
29+
ctb.Define("id", "BIGINT(20)", "NOT NULL", "AUTO_INCREMENT", "PRIMARY KEY", `COMMENT "user id"`)
30+
ctb.Define("name", "VARCHAR(255)", "NOT NULL", `COMMENT "user name"`)
31+
ctb.Define("created_at", "DATETIME", "NOT NULL", `COMMENT "user create time"`)
32+
ctb.Define("modified_at", "DATETIME", "NOT NULL", `COMMENT "user modify time"`)
33+
ctb.Define("KEY", "idx_name_modified_at", "name, modified_at")
34+
ctb.Option("DEFAULT CHARACTER SET", "utf8mb4")
35+
36+
fmt.Println(ctb)
37+
38+
// Output:
39+
// CREATE TEMPORARY TABLE IF NOT EXISTS demo.user (id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT "user id", name VARCHAR(255) NOT NULL COMMENT "user name", created_at DATETIME NOT NULL COMMENT "user create time", modified_at DATETIME NOT NULL COMMENT "user modify time", KEY idx_name_modified_at name, modified_at) DEFAULT CHARACTER SET utf8mb4
40+
}

flavor.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ func (f Flavor) String() string {
3333
return "<invalid>"
3434
}
3535

36+
// NewCreateTableBuilder creates a new CREATE TABLE builder with flavor.
37+
func (f Flavor) NewCreateTableBuilder() *CreateTableBuilder {
38+
b := newCreateTableBuilder()
39+
b.SetFlavor(f)
40+
return b
41+
}
42+
3643
// NewDeleteBuilder creates a new DELETE builder with flavor.
3744
func (f Flavor) NewDeleteBuilder() *DeleteBuilder {
3845
b := newDeleteBuilder()

0 commit comments

Comments
 (0)