/
table.go
105 lines (89 loc) · 2.49 KB
/
table.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
package create
import (
"database/sql"
"fmt"
"strings"
"github.com/Snehal1112/QueryBuilder/query"
)
type field struct {
fieldName string
fieldType string
constrain string
}
type foreignKeyConstrain struct {
constrain string
foreignKey string
fkTable string
}
type Table struct {
db *sql.DB
table string
fields []field
primaryKey string
foreignKey string
foreignKeyConstrain *foreignKeyConstrain
}
func NewTable(name string, db *sql.DB) TableService {
return &Table{db: db, table: name}
}
func (t *Table) Field(name string, dataType *query.DataType, constrain *query.Constrain) *Table {
t.fields = append(t.fields, field{
fieldName: name,
fieldType: dataType.AsString(),
constrain: constrain.AsString(),
})
return t
}
// SetPrimaryKey function used to set the PK to multiple columns.
func (t *Table) SetPrimaryKey(fields []string) *Table {
t.primaryKey = fmt.Sprintf("%s (%s)", query.GetConstrain(query.PK), strings.Join(fields, ", "))
return t
}
func (t *Table) NewForeignKeyConstrain(constrain, foreignKey, fkTable string) *Table {
t.foreignKeyConstrain = &foreignKeyConstrain{
constrain: constrain,
foreignKey: foreignKey,
fkTable: fkTable,
}
return t
}
func (f *foreignKeyConstrain) onUpdate(referenceOpt int) string {
return fmt.Sprintf(" ON UPDATE %s", query.GetReferenceOpt(referenceOpt))
}
func (f *foreignKeyConstrain) onDelete(referenceOpt int) string {
return fmt.Sprintf(" ON DELETE %s", query.GetReferenceOpt(referenceOpt))
}
// SetForeignKey set the foreign key on the table.
func (t *Table) SetForeignKey(onUpdate, onDelete interface{}) *Table {
fk := t.foreignKeyConstrain
t.foreignKey = fmt.Sprintf(", CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s)", fk.constrain, fk.foreignKey, fk.fkTable, fk.foreignKey)
if onUpdate != nil {
t.foreignKey += fk.onUpdate(onUpdate.(int))
}
if onDelete != nil {
t.foreignKey += fk.onDelete(onDelete.(int))
}
return t
}
func (t *Table) prepareQuery() string {
var fields []string
for _, v := range t.fields {
fields = append(fields, strings.Trim(v.fieldName+" "+v.fieldType+" "+v.constrain, " "))
}
columns := strings.Join(fields, ", ")
if len(t.primaryKey) != 0 {
columns += t.primaryKey
}
if len(t.foreignKey) != 0 {
columns += t.foreignKey
}
return fmt.Sprintf("CREATE Table IF NOT EXISTS %s ( %s );", t.table, columns)
}
func (t *Table) Execute() (sql.Result, error) {
stmt, err := t.db.Prepare(t.prepareQuery())
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.Exec()
}