Skip to content

Commit

Permalink
support custom sql dialects
Browse files Browse the repository at this point in the history
  • Loading branch information
oussama4 committed Nov 21, 2021
1 parent c40d5e8 commit 51ab1b8
Showing 1 changed file with 52 additions and 1 deletion.
53 changes: 52 additions & 1 deletion builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,20 @@ import (
"strings"
)

// Dialect names
const (
Postgres = "postgres"
Sqlite = "sqlite"
Mysql = "mysql"
)

type BuildFunc func(*Builder)

// Builder is where we put our built sql query
type Builder struct {
*strings.Builder
args []interface{}
dialect string
paramsCount int
}

Expand All @@ -19,6 +27,7 @@ func NewBuilder() *Builder {
b := &Builder{
Builder: &strings.Builder{},
args: []interface{}{},
dialect: Postgres,
paramsCount: 0,
}
return b
Expand All @@ -38,7 +47,49 @@ func Expr(expr string, args ...interface{}) BuildFunc {
// WriteArg adds an input argument to builder
func (b *Builder) WriteArg(arg interface{}) {
b.paramsCount++
param := fmt.Sprintf("$%d", b.paramsCount)
param := "?"
if b.dialect == Postgres {
param = fmt.Sprintf("$%d", b.paramsCount)
}
b.WriteString(param)
b.args = append(b.args, arg)
}

// DialectBuilder is for building queries for a custom sql dialect
type DialectBuilder struct {
dialect string
}

// Dialect creates a custom builder for the given sql dialect
func Dialect(dialect string) DialectBuilder {
db := DialectBuilder{dialect: dialect}
return db
}

// Select creates a SelectBuilder for the configured dialect
func (db DialectBuilder) Select(columns ...string) *SelectBuilder {
sb := Select(columns...)
sb.dialect = db.dialect
return sb
}

// Insert creates an InsertBuilder for the configured dialect
func (db DialectBuilder) Insert(table string) *InsertBuilder {
ib := Insert(table)
ib.dialect = db.dialect
return ib
}

// Update creates an UpdateBuilder for the configured dialect
func (db DialectBuilder) Update(table string) *UpdateBuilder {
ub := Update(table)
ub.dialect = db.dialect
return ub
}

// DeleteFrom creates a DeleteBuilder for the configured dialect
func (db DialectBuilder) DeleteFrom(table string) *DeleteBuilder {
dlb := DeleteFrom(table)
dlb.dialect = db.dialect
return dlb
}

0 comments on commit 51ab1b8

Please sign in to comment.