gorm/statement.go

221 lines
4.7 KiB
Go
Raw Normal View History

2020-01-29 14:22:44 +03:00
package gorm
import (
"context"
"database/sql"
2020-01-29 22:03:06 +03:00
"database/sql/driver"
2020-01-29 14:22:44 +03:00
"fmt"
2020-01-29 22:03:06 +03:00
"strconv"
2020-01-29 14:22:44 +03:00
"strings"
"sync"
"github.com/jinzhu/gorm/clause"
2020-02-02 09:40:44 +03:00
"github.com/jinzhu/gorm/schema"
2020-01-29 14:22:44 +03:00
)
2020-01-30 10:14:48 +03:00
// Instance db instance
type Instance struct {
Error error
RowsAffected int64
Context context.Context
Statement *Statement
}
// AddError add error to instance
func (inst Instance) AddError(err error) {
if inst.Error == nil {
inst.Error = err
} else {
inst.Error = fmt.Errorf("%v; %w", inst.Error, err)
}
}
2020-01-29 14:22:44 +03:00
// Statement statement
type Statement struct {
2020-01-30 10:14:48 +03:00
Table string
2020-01-29 22:03:06 +03:00
Model interface{}
2020-01-29 14:22:44 +03:00
Dest interface{}
2020-01-30 10:14:48 +03:00
Clauses map[string]clause.Clause
2020-01-29 14:22:44 +03:00
Settings sync.Map
DB *DB
2020-02-02 09:40:44 +03:00
Schema *schema.Schema
2020-01-29 14:22:44 +03:00
2020-01-30 10:14:48 +03:00
// SQL Builder
SQL strings.Builder
2020-01-29 14:22:44 +03:00
Vars []interface{}
NamedVars []sql.NamedArg
}
2020-01-30 10:14:48 +03:00
// StatementOptimizer statement optimizer interface
type StatementOptimizer interface {
OptimizeStatement(Statement)
}
2020-01-29 14:22:44 +03:00
// Write write string
func (stmt Statement) Write(sql ...string) (err error) {
for _, s := range sql {
_, err = stmt.SQL.WriteString(s)
}
return
}
2020-01-30 10:14:48 +03:00
// Write write string
func (stmt Statement) WriteByte(c byte) (err error) {
return stmt.SQL.WriteByte(c)
}
2020-01-29 14:22:44 +03:00
// WriteQuoted write quoted field
func (stmt Statement) WriteQuoted(field interface{}) (err error) {
_, err = stmt.SQL.WriteString(stmt.Quote(field))
return
}
2020-01-30 10:14:48 +03:00
// Quote returns quoted value
2020-02-02 09:40:44 +03:00
func (stmt Statement) Quote(field interface{}) string {
var str strings.Builder
switch v := field.(type) {
case clause.Table:
str.WriteString(v.Table)
if v.Alias != "" {
str.WriteString(" AS ")
str.WriteString(v.Alias)
}
case clause.Column:
if v.Table != "" {
str.WriteString(v.Table)
str.WriteByte('.')
}
str.WriteString(v.Name)
if v.Alias != "" {
str.WriteString(" AS ")
str.WriteString(v.Alias)
}
default:
fmt.Sprint(field)
}
return str.String()
2020-01-30 10:14:48 +03:00
}
2020-01-29 14:22:44 +03:00
// Write write string
func (stmt Statement) AddVar(vars ...interface{}) string {
2020-01-29 22:03:06 +03:00
var placeholders strings.Builder
for idx, v := range vars {
if idx > 0 {
placeholders.WriteByte(',')
}
2020-01-29 14:22:44 +03:00
if namedArg, ok := v.(sql.NamedArg); ok && len(namedArg.Name) > 0 {
stmt.NamedVars = append(stmt.NamedVars, namedArg)
2020-01-29 22:03:06 +03:00
placeholders.WriteByte('@')
placeholders.WriteString(namedArg.Name)
} else if arrs, ok := v.([]interface{}); ok {
placeholders.WriteByte('(')
if len(arrs) > 0 {
placeholders.WriteString(stmt.AddVar(arrs...))
} else {
placeholders.WriteString("NULL")
}
placeholders.WriteByte(')')
2020-01-29 14:22:44 +03:00
} else {
2020-01-29 22:03:06 +03:00
placeholders.WriteString(stmt.DB.Dialector.BindVar(stmt, v))
2020-01-29 14:22:44 +03:00
}
}
2020-01-29 22:03:06 +03:00
return placeholders.String()
2020-01-29 14:22:44 +03:00
}
// AddClause add clause
2020-01-30 10:14:48 +03:00
func (stmt Statement) AddClause(v clause.Interface) {
if optimizer, ok := v.(StatementOptimizer); ok {
optimizer.OptimizeStatement(stmt)
}
c, _ := stmt.Clauses[v.Name()]
if namer, ok := v.(clause.OverrideNameInterface); ok {
c.Name = namer.OverrideName()
} else {
c.Name = v.Name()
}
if c.Expression != nil {
v.MergeExpression(c.Expression)
}
c.Expression = v
stmt.Clauses[v.Name()] = c
2020-01-29 14:22:44 +03:00
}
2020-01-29 22:03:06 +03:00
2020-01-30 10:14:48 +03:00
// BuildCondtion build condition
func (stmt Statement) BuildCondtion(query interface{}, args ...interface{}) (conditions []clause.Expression) {
2020-01-29 22:03:06 +03:00
if sql, ok := query.(string); ok {
if i, err := strconv.Atoi(sql); err != nil {
query = i
} else if len(args) == 0 || (len(args) > 0 && strings.Contains(sql, "?")) || strings.Contains(sql, "@") {
2020-01-30 10:14:48 +03:00
return []clause.Expression{clause.String{SQL: sql, Values: args}}
2020-01-29 22:03:06 +03:00
}
}
args = append([]interface{}{query}, args...)
for _, arg := range args {
if valuer, ok := arg.(driver.Valuer); ok {
arg, _ = valuer.Value()
}
switch v := arg.(type) {
2020-01-30 10:14:48 +03:00
case clause.Expression:
2020-01-29 22:03:06 +03:00
conditions = append(conditions, v)
case *DB:
if v.Statement == nil {
if cs, ok := v.Statement.Clauses["WHERE"]; ok {
2020-01-30 10:14:48 +03:00
conditions = append(conditions, cs.Expression)
2020-01-29 22:03:06 +03:00
}
}
case map[interface{}]interface{}:
var clauseMap = clause.Map{}
for i, j := range v {
clauseMap[i] = j
}
conditions = append(conditions, clauseMap)
case map[string]string:
var clauseMap = clause.Map{}
for i, j := range v {
clauseMap[i] = j
}
conditions = append(conditions, clauseMap)
case map[string]interface{}:
var clauseMap = clause.Map{}
for i, j := range v {
clauseMap[i] = j
}
conditions = append(conditions, clauseMap)
default:
// TODO check is struct
// struct, slice -> ids
}
}
if len(conditions) == 0 {
conditions = append(conditions, clause.ID{Value: args})
}
2020-01-30 10:14:48 +03:00
2020-01-29 22:03:06 +03:00
return conditions
}
2020-01-30 10:14:48 +03:00
// Build build sql with clauses names
func (stmt Statement) Build(clauses ...string) {
var includeSpace bool
for _, name := range clauses {
if c, ok := stmt.Clauses[name]; ok {
if includeSpace {
stmt.WriteByte(' ')
}
includeSpace = true
c.Build(stmt)
}
}
2020-01-29 22:03:06 +03:00
}