bob/has.go

76 lines
2.1 KiB
Go
Raw Normal View History

2021-06-24 07:43:28 +00:00
package bob
2021-06-25 17:04:41 +00:00
import (
"errors"
"strings"
2021-06-25 17:04:41 +00:00
"github.com/lann/builder"
)
2021-06-24 07:43:28 +00:00
type HasBuilder builder.Builder
type hasData struct {
Name string
2021-06-25 17:04:41 +00:00
Column string
Schema string
Placeholder string
2021-06-24 07:43:28 +00:00
}
func init() {
builder.Register(HasBuilder{}, hasData{})
}
2021-11-05 05:06:47 +00:00
// HasTable checks for a table's existence by tableName,
// resolving with a boolean to signal if the table exists.
2021-06-24 07:43:28 +00:00
func (h HasBuilder) HasTable(table string) HasBuilder {
return builder.Set(h, "Name", table).(HasBuilder)
}
2021-11-05 05:06:47 +00:00
// HasColumn checks if a column exists in the current table,
// resolves the promise with a boolean, true if the column exists, false otherwise.
2021-06-25 17:04:41 +00:00
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.
2021-06-25 17:04:41 +00:00
func (h HasBuilder) WithSchema(schema string) HasBuilder {
return builder.Set(h, "Schema", schema).(HasBuilder)
}
// PlaceholderFormat changes the default placeholder (?) to desired placeholder.
2021-06-25 17:04:41 +00:00
func (h HasBuilder) PlaceholderFormat(f string) HasBuilder {
2021-06-24 07:43:28 +00:00
return builder.Set(h, "Placeholder", f).(HasBuilder)
}
2021-06-25 17:04:41 +00:00
// ToSql returns 3 variables filled out with the correct values based on bindings, etc.
func (h HasBuilder) ToSql() (string, []interface{}, error) {
2021-06-25 17:04:41 +00:00
data := builder.GetStruct(h).(hasData)
return data.ToSql()
2021-06-25 17:04:41 +00:00
}
// 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
2021-06-25 17:04:41 +00:00
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)
2021-11-05 05:06:47 +00:00
args = createArgs(d.Name, d.Column, d.Schema)
2021-06-25 17:04:41 +00:00
return
}