-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhas.go
75 lines (61 loc) · 2.15 KB
/
has.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
package bob
import (
"errors"
"strings"
"github.com/lann/builder"
)
type HasBuilder builder.Builder
type hasData struct {
Name string
Column string
Schema string
Placeholder string
}
func init() {
builder.Register(HasBuilder{}, hasData{})
}
// HasTable checks for a table's existence by tableName,
// resolving with a boolean to signal if the table exists.
func (h HasBuilder) HasTable(table string) HasBuilder {
return builder.Set(h, "Name", table).(HasBuilder)
}
// HasColumn checks if a column exists in the current table,
// resolves the promise with a boolean, true if the column exists, false otherwise.
func (h HasBuilder) HasColumn(column string) HasBuilder {
return builder.Set(h, "Column", column).(HasBuilder)
}
// WithSchema specifies the schema to be used when using the schema-building commands.
func (h HasBuilder) WithSchema(schema string) HasBuilder {
return builder.Set(h, "Schema", schema).(HasBuilder)
}
// PlaceholderFormat changes the default placeholder (?) to desired placeholder.
func (h HasBuilder) PlaceholderFormat(f string) HasBuilder {
return builder.Set(h, "Placeholder", f).(HasBuilder)
}
// ToSql returns 3 variables filled out with the correct values based on bindings, etc.
func (h HasBuilder) ToSql() (string, []interface{}, error) {
data := builder.GetStruct(h).(hasData)
return data.ToSql()
}
// ToSql returns 3 variables filled out with the correct values based on bindings, etc.
func (d *hasData) ToSql() (sqlStr string, args []interface{}, err error) {
var sql strings.Builder
if d.Name == "" {
err = errors.New("has statement should have a table name")
return
}
if d.Column != "" && d.Name != "" {
// search for column
sql.WriteString("SELECT * FROM information_schema.columns WHERE table_name = ? AND column_name = ?")
} else if d.Name != "" && d.Column == "" {
sql.WriteString("SELECT * FROM information_schema.tables WHERE table_name = ?")
}
if d.Schema != "" {
sql.WriteString(" AND table_schema = ?;")
} else {
sql.WriteString(" AND table_schema = current_schema();")
}
sqlStr = ReplacePlaceholder(sql.String(), d.Placeholder)
args = createArgs(d.Name, d.Column, d.Schema)
return
}