| 1 |
package gorm |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"database/sql" |
| 6 |
"database/sql/driver" |
| 7 |
"fmt" |
| 8 |
"reflect" |
| 9 |
"regexp" |
| 10 |
"sort" |
| 11 |
"strconv" |
| 12 |
"strings" |
| 13 |
"sync" |
| 14 |
|
| 15 |
"gorm.io/gorm/clause" |
| 16 |
"gorm.io/gorm/logger" |
| 17 |
"gorm.io/gorm/schema" |
| 18 |
"gorm.io/gorm/utils" |
| 19 |
) |
| 20 |
|
| 21 |
// Statement statement |
| 22 |
type Statement struct { |
| 23 |
*DB |
| 24 |
TableExpr *clause.Expr |
| 25 |
Table string |
| 26 |
Model interface{} |
| 27 |
Unscoped bool |
| 28 |
Dest interface{} |
| 29 |
ReflectValue reflect.Value |
| 30 |
Clauses map[string]clause.Clause |
| 31 |
BuildClauses []string |
| 32 |
Distinct bool |
| 33 |
Selects []string // selected columns |
| 34 |
Omits []string // omit columns |
| 35 |
ColumnMapping map[string]string // map columns |
| 36 |
Joins []join |
| 37 |
Preloads map[string][]interface{} |
| 38 |
Settings sync.Map |
| 39 |
ConnPool ConnPool |
| 40 |
Schema *schema.Schema |
| 41 |
Context context.Context |
| 42 |
RaiseErrorOnNotFound bool |
| 43 |
SkipHooks bool |
| 44 |
SQL strings.Builder |
| 45 |
Vars []interface{} |
| 46 |
CurDestIndex int |
| 47 |
attrs []interface{} |
| 48 |
assigns []interface{} |
| 49 |
scopes []func(*DB) *DB |
| 50 |
Result *result |
| 51 |
} |
| 52 |
|
| 53 |
type join struct { |
| 54 |
Name string |
| 55 |
Alias string |
| 56 |
Conds []interface{} |
| 57 |
On *clause.Where |
| 58 |
Selects []string |
| 59 |
Omits []string |
| 60 |
Expression clause.Expression |
| 61 |
JoinType clause.JoinType |
| 62 |
} |
| 63 |
|
| 64 |
// StatementModifier statement modifier interface |
| 65 |
type StatementModifier interface { |
| 66 |
ModifyStatement(*Statement) |
| 67 |
} |
| 68 |
|
| 69 |
// WriteString write string |
| 70 |
func (stmt *Statement) WriteString(str string) (int, error) { |
| 71 |
return stmt.SQL.WriteString(str) |
| 72 |
} |
| 73 |
|
| 74 |
// WriteByte write byte |
| 75 |
func (stmt *Statement) WriteByte(c byte) error { |
| 76 |
return stmt.SQL.WriteByte(c) |
| 77 |
} |
| 78 |
|
| 79 |
// WriteQuoted write quoted value |
| 80 |
func (stmt *Statement) WriteQuoted(value interface{}) { |
| 81 |
stmt.QuoteTo(&stmt.SQL, value) |
| 82 |
} |
| 83 |
|
| 84 |
// QuoteTo write quoted value to writer |
| 85 |
func (stmt *Statement) QuoteTo(writer clause.Writer, field interface{}) { |
| 86 |
write := func(raw bool, str string) { |
| 87 |
if raw { |
| 88 |
writer.WriteString(str) |
| 89 |
} else { |
| 90 |
stmt.DB.Dialector.QuoteTo(writer, str) |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
switch v := field.(type) { |
| 95 |
case clause.Table: |
| 96 |
if v.Name == clause.CurrentTable { |
| 97 |
if stmt.TableExpr != nil { |
| 98 |
stmt.TableExpr.Build(stmt) |
| 99 |
} else if stmt.Table != "" { |
| 100 |
write(v.Raw, stmt.Table) |
| 101 |
} else if stmt.AddError(stmt.Parse(stmt.Model)) == nil { |
| 102 |
write(v.Raw, stmt.Table) |
| 103 |
} |
| 104 |
} else { |
| 105 |
write(v.Raw, v.Name) |
| 106 |
} |
| 107 |
|
| 108 |
if v.Alias != "" { |
| 109 |
writer.WriteByte(' ') |
| 110 |
write(v.Raw, v.Alias) |
| 111 |
} |
| 112 |
case clause.Column: |
| 113 |
if v.Table != "" { |
| 114 |
if v.Table == clause.CurrentTable { |
| 115 |
write(v.Raw, stmt.Table) |
| 116 |
} else { |
| 117 |
write(v.Raw, v.Table) |
| 118 |
} |
| 119 |
writer.WriteByte('.') |
| 120 |
} |
| 121 |
|
| 122 |
if v.Name == clause.PrimaryKey { |
| 123 |
if stmt.Schema == nil { |
| 124 |
stmt.DB.AddError(ErrModelValueRequired) |
| 125 |
} else if stmt.Schema.PrioritizedPrimaryField != nil { |
| 126 |
write(v.Raw, stmt.Schema.PrioritizedPrimaryField.DBName) |
| 127 |
} else if len(stmt.Schema.DBNames) > 0 { |
| 128 |
write(v.Raw, stmt.Schema.DBNames[0]) |
| 129 |
} else { |
| 130 |
stmt.DB.AddError(ErrModelAccessibleFieldsRequired) //nolint:typecheck,errcheck |
| 131 |
} |
| 132 |
} else { |
| 133 |
write(v.Raw, v.Name) |
| 134 |
} |
| 135 |
|
| 136 |
if v.Alias != "" { |
| 137 |
writer.WriteString(" AS ") |
| 138 |
write(v.Raw, v.Alias) |
| 139 |
} |
| 140 |
case []clause.Column: |
| 141 |
writer.WriteByte('(') |
| 142 |
for idx, d := range v { |
| 143 |
if idx > 0 { |
| 144 |
writer.WriteByte(',') |
| 145 |
} |
| 146 |
stmt.QuoteTo(writer, d) |
| 147 |
} |
| 148 |
writer.WriteByte(')') |
| 149 |
case clause.Expr: |
| 150 |
v.Build(stmt) |
| 151 |
case string: |
| 152 |
stmt.DB.Dialector.QuoteTo(writer, v) |
| 153 |
case []string: |
| 154 |
writer.WriteByte('(') |
| 155 |
for idx, d := range v { |
| 156 |
if idx > 0 { |
| 157 |
writer.WriteByte(',') |
| 158 |
} |
| 159 |
stmt.DB.Dialector.QuoteTo(writer, d) |
| 160 |
} |
| 161 |
writer.WriteByte(')') |
| 162 |
default: |
| 163 |
stmt.DB.Dialector.QuoteTo(writer, fmt.Sprint(field)) |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
// Quote returns quoted value |
| 168 |
func (stmt *Statement) Quote(field interface{}) string { |
| 169 |
var builder strings.Builder |
| 170 |
stmt.QuoteTo(&builder, field) |
| 171 |
return builder.String() |
| 172 |
} |
| 173 |
|
| 174 |
// AddVar add var |
| 175 |
func (stmt *Statement) AddVar(writer clause.Writer, vars ...interface{}) { |
| 176 |
for idx, v := range vars { |
| 177 |
if idx > 0 { |
| 178 |
writer.WriteByte(',') |
| 179 |
} |
| 180 |
|
| 181 |
switch v := v.(type) { |
| 182 |
case sql.NamedArg: |
| 183 |
stmt.Vars = append(stmt.Vars, v.Value) |
| 184 |
case clause.Column, clause.Table: |
| 185 |
stmt.QuoteTo(writer, v) |
| 186 |
case Valuer: |
| 187 |
reflectValue := reflect.ValueOf(v) |
| 188 |
if reflectValue.Kind() == reflect.Ptr && reflectValue.IsNil() { |
| 189 |
stmt.AddVar(writer, nil) |
| 190 |
} else { |
| 191 |
stmt.AddVar(writer, v.GormValue(stmt.Context, stmt.DB)) |
| 192 |
} |
| 193 |
case clause.Interface: |
| 194 |
c := clause.Clause{Name: v.Name()} |
| 195 |
v.MergeClause(&c) |
| 196 |
c.Build(stmt) |
| 197 |
case clause.Expression: |
| 198 |
v.Build(stmt) |
| 199 |
case driver.Valuer: |
| 200 |
stmt.Vars = append(stmt.Vars, v) |
| 201 |
stmt.DB.Dialector.BindVarTo(writer, stmt, v) |
| 202 |
case []byte: |
| 203 |
stmt.Vars = append(stmt.Vars, v) |
| 204 |
stmt.DB.Dialector.BindVarTo(writer, stmt, v) |
| 205 |
case []interface{}: |
| 206 |
if len(v) > 0 { |
| 207 |
writer.WriteByte('(') |
| 208 |
stmt.AddVar(writer, v...) |
| 209 |
writer.WriteByte(')') |
| 210 |
} else { |
| 211 |
writer.WriteString("(NULL)") |
| 212 |
} |
| 213 |
case interface{ getInstance() *DB }: |
| 214 |
cv := v.getInstance() |
| 215 |
|
| 216 |
subdb := cv.Session(&Session{Logger: logger.Discard, DryRun: true}).getInstance() |
| 217 |
if cv.Statement.SQL.Len() > 0 { |
| 218 |
var ( |
| 219 |
vars = subdb.Statement.Vars |
| 220 |
sql = cv.Statement.SQL.String() |
| 221 |
) |
| 222 |
|
| 223 |
subdb.Statement.Vars = make([]interface{}, 0, len(vars)) |
| 224 |
for _, vv := range vars { |
| 225 |
subdb.Statement.Vars = append(subdb.Statement.Vars, vv) |
| 226 |
bindvar := strings.Builder{} |
| 227 |
cv.BindVarTo(&bindvar, subdb.Statement, vv) |
| 228 |
sql = strings.Replace(sql, bindvar.String(), "?", 1) |
| 229 |
} |
| 230 |
|
| 231 |
subdb.Statement.SQL.Reset() |
| 232 |
subdb.Statement.Vars = stmt.Vars |
| 233 |
if strings.Contains(sql, "@") { |
| 234 |
clause.NamedExpr{SQL: sql, Vars: vars}.Build(subdb.Statement) |
| 235 |
} else { |
| 236 |
clause.Expr{SQL: sql, Vars: vars}.Build(subdb.Statement) |
| 237 |
} |
| 238 |
} else { |
| 239 |
subdb.Statement.Vars = append(stmt.Vars, subdb.Statement.Vars...) |
| 240 |
subdb.callbacks.Query().Execute(subdb) |
| 241 |
} |
| 242 |
|
| 243 |
writer.WriteString(subdb.Statement.SQL.String()) |
| 244 |
stmt.Vars = subdb.Statement.Vars |
| 245 |
default: |
| 246 |
switch rv := reflect.ValueOf(v); rv.Kind() { |
| 247 |
case reflect.Slice, reflect.Array: |
| 248 |
if rv.Len() == 0 { |
| 249 |
writer.WriteString("(NULL)") |
| 250 |
} else if rv.Type().Elem() == reflect.TypeOf(uint8(0)) { |
| 251 |
stmt.Vars = append(stmt.Vars, v) |
| 252 |
stmt.DB.Dialector.BindVarTo(writer, stmt, v) |
| 253 |
} else { |
| 254 |
writer.WriteByte('(') |
| 255 |
for i := 0; i < rv.Len(); i++ { |
| 256 |
if i > 0 { |
| 257 |
writer.WriteByte(',') |
| 258 |
} |
| 259 |
stmt.AddVar(writer, rv.Index(i).Interface()) |
| 260 |
} |
| 261 |
writer.WriteByte(')') |
| 262 |
} |
| 263 |
default: |
| 264 |
stmt.Vars = append(stmt.Vars, v) |
| 265 |
stmt.DB.Dialector.BindVarTo(writer, stmt, v) |
| 266 |
} |
| 267 |
} |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
// AddClause add clause |
| 272 |
func (stmt *Statement) AddClause(v clause.Interface) { |
| 273 |
if optimizer, ok := v.(StatementModifier); ok { |
| 274 |
optimizer.ModifyStatement(stmt) |
| 275 |
} else { |
| 276 |
name := v.Name() |
| 277 |
c := stmt.Clauses[name] |
| 278 |
c.Name = name |
| 279 |
v.MergeClause(&c) |
| 280 |
stmt.Clauses[name] = c |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
// AddClauseIfNotExists add clause if not exists |
| 285 |
func (stmt *Statement) AddClauseIfNotExists(v clause.Interface) { |
| 286 |
if c, ok := stmt.Clauses[v.Name()]; !ok || c.Expression == nil { |
| 287 |
stmt.AddClause(v) |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
// BuildCondition build condition |
| 292 |
func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) []clause.Expression { |
| 293 |
if s, ok := query.(string); ok { |
| 294 |
// if it is a number, then treats it as primary key |
| 295 |
if _, err := strconv.Atoi(s); err != nil { |
| 296 |
if s == "" && len(args) == 0 { |
| 297 |
return nil |
| 298 |
} |
| 299 |
|
| 300 |
if len(args) == 0 || (len(args) > 0 && strings.Contains(s, "?")) { |
| 301 |
// looks like a where condition |
| 302 |
return []clause.Expression{clause.Expr{SQL: s, Vars: args}} |
| 303 |
} |
| 304 |
|
| 305 |
if len(args) > 0 && strings.Contains(s, "@") { |
| 306 |
// looks like a named query |
| 307 |
return []clause.Expression{clause.NamedExpr{SQL: s, Vars: args}} |
| 308 |
} |
| 309 |
|
| 310 |
if strings.Contains(strings.TrimSpace(s), " ") { |
| 311 |
// looks like a where condition |
| 312 |
return []clause.Expression{clause.Expr{SQL: s, Vars: args}} |
| 313 |
} |
| 314 |
|
| 315 |
if len(args) == 1 { |
| 316 |
return []clause.Expression{clause.Eq{Column: s, Value: args[0]}} |
| 317 |
} |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
conds := make([]clause.Expression, 0, 4) |
| 322 |
args = append([]interface{}{query}, args...) |
| 323 |
for idx, arg := range args { |
| 324 |
if arg == nil { |
| 325 |
continue |
| 326 |
} |
| 327 |
if valuer, ok := arg.(driver.Valuer); ok { |
| 328 |
arg, _ = valuer.Value() |
| 329 |
} |
| 330 |
|
| 331 |
curTable := stmt.Table |
| 332 |
if curTable == "" { |
| 333 |
curTable = clause.CurrentTable |
| 334 |
} |
| 335 |
|
| 336 |
switch v := arg.(type) { |
| 337 |
case clause.Expression: |
| 338 |
conds = append(conds, v) |
| 339 |
case []clause.Expression: |
| 340 |
conds = append(conds, v...) |
| 341 |
case *DB: |
| 342 |
v.executeScopes() |
| 343 |
|
| 344 |
if cs, ok := v.Statement.Clauses["WHERE"]; ok { |
| 345 |
if where, ok := cs.Expression.(clause.Where); ok { |
| 346 |
if len(where.Exprs) == 1 { |
| 347 |
if orConds, ok := where.Exprs[0].(clause.OrConditions); ok { |
| 348 |
if len(orConds.Exprs) == 1 { |
| 349 |
where.Exprs[0] = clause.AndConditions(orConds) |
| 350 |
} |
| 351 |
} |
| 352 |
} |
| 353 |
conds = append(conds, clause.And(where.Exprs...)) |
| 354 |
} else if cs.Expression != nil { |
| 355 |
conds = append(conds, cs.Expression) |
| 356 |
} |
| 357 |
} |
| 358 |
case map[interface{}]interface{}: |
| 359 |
for i, j := range v { |
| 360 |
conds = append(conds, clause.Eq{Column: i, Value: j}) |
| 361 |
} |
| 362 |
case map[string]string: |
| 363 |
keys := make([]string, 0, len(v)) |
| 364 |
for i := range v { |
| 365 |
keys = append(keys, i) |
| 366 |
} |
| 367 |
sort.Strings(keys) |
| 368 |
|
| 369 |
for _, key := range keys { |
| 370 |
column := clause.Column{Name: key, Table: curTable} |
| 371 |
if strings.Contains(key, ".") { |
| 372 |
column = clause.Column{Name: key} |
| 373 |
} |
| 374 |
conds = append(conds, clause.Eq{Column: column, Value: v[key]}) |
| 375 |
} |
| 376 |
case map[string]interface{}: |
| 377 |
keys := make([]string, 0, len(v)) |
| 378 |
for i := range v { |
| 379 |
keys = append(keys, i) |
| 380 |
} |
| 381 |
sort.Strings(keys) |
| 382 |
|
| 383 |
for _, key := range keys { |
| 384 |
reflectValue := reflect.Indirect(reflect.ValueOf(v[key])) |
| 385 |
column := clause.Column{Name: key, Table: curTable} |
| 386 |
if strings.Contains(key, ".") { |
| 387 |
column = clause.Column{Name: key} |
| 388 |
} |
| 389 |
switch reflectValue.Kind() { |
| 390 |
case reflect.Slice, reflect.Array: |
| 391 |
if _, ok := v[key].(driver.Valuer); ok { |
| 392 |
conds = append(conds, clause.Eq{Column: column, Value: v[key]}) |
| 393 |
} else if _, ok := v[key].(Valuer); ok { |
| 394 |
conds = append(conds, clause.Eq{Column: column, Value: v[key]}) |
| 395 |
} else { |
| 396 |
// optimize reflect value length |
| 397 |
valueLen := reflectValue.Len() |
| 398 |
values := make([]interface{}, valueLen) |
| 399 |
for i := 0; i < valueLen; i++ { |
| 400 |
values[i] = reflectValue.Index(i).Interface() |
| 401 |
} |
| 402 |
|
| 403 |
conds = append(conds, clause.IN{Column: column, Values: values}) |
| 404 |
} |
| 405 |
default: |
| 406 |
conds = append(conds, clause.Eq{Column: column, Value: v[key]}) |
| 407 |
} |
| 408 |
} |
| 409 |
default: |
| 410 |
reflectValue := reflect.Indirect(reflect.ValueOf(arg)) |
| 411 |
for reflectValue.Kind() == reflect.Ptr { |
| 412 |
reflectValue = reflectValue.Elem() |
| 413 |
} |
| 414 |
|
| 415 |
if s, err := schema.Parse(arg, stmt.DB.cacheStore, stmt.DB.NamingStrategy); err == nil { |
| 416 |
selectedColumns := map[string]bool{} |
| 417 |
if idx == 0 { |
| 418 |
for _, v := range args[1:] { |
| 419 |
if vs, ok := v.(string); ok { |
| 420 |
selectedColumns[vs] = true |
| 421 |
} |
| 422 |
} |
| 423 |
} |
| 424 |
restricted := len(selectedColumns) != 0 |
| 425 |
|
| 426 |
switch reflectValue.Kind() { |
| 427 |
case reflect.Struct: |
| 428 |
for _, field := range s.Fields { |
| 429 |
selected := selectedColumns[field.DBName] || selectedColumns[field.Name] |
| 430 |
if selected || (!restricted && field.Readable) { |
| 431 |
if v, isZero := field.ValueOf(stmt.Context, reflectValue); !isZero || selected { |
| 432 |
if field.DBName != "" { |
| 433 |
conds = append(conds, clause.Eq{Column: clause.Column{Table: curTable, Name: field.DBName}, Value: v}) |
| 434 |
} else if field.DataType != "" { |
| 435 |
conds = append(conds, clause.Eq{Column: clause.Column{Table: curTable, Name: field.Name}, Value: v}) |
| 436 |
} |
| 437 |
} |
| 438 |
} |
| 439 |
} |
| 440 |
case reflect.Slice, reflect.Array: |
| 441 |
for i := 0; i < reflectValue.Len(); i++ { |
| 442 |
for _, field := range s.Fields { |
| 443 |
selected := selectedColumns[field.DBName] || selectedColumns[field.Name] |
| 444 |
if selected || (!restricted && field.Readable) { |
| 445 |
if v, isZero := field.ValueOf(stmt.Context, reflectValue.Index(i)); !isZero || selected { |
| 446 |
if field.DBName != "" { |
| 447 |
conds = append(conds, clause.Eq{Column: clause.Column{Table: curTable, Name: field.DBName}, Value: v}) |
| 448 |
} else if field.DataType != "" { |
| 449 |
conds = append(conds, clause.Eq{Column: clause.Column{Table: curTable, Name: field.Name}, Value: v}) |
| 450 |
} |
| 451 |
} |
| 452 |
} |
| 453 |
} |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
if restricted { |
| 458 |
break |
| 459 |
} |
| 460 |
} else if !reflectValue.IsValid() { |
| 461 |
stmt.AddError(ErrInvalidData) |
| 462 |
} else if len(conds) == 0 { |
| 463 |
if len(args) == 1 { |
| 464 |
switch reflectValue.Kind() { |
| 465 |
case reflect.Slice, reflect.Array: |
| 466 |
// optimize reflect value length |
| 467 |
valueLen := reflectValue.Len() |
| 468 |
values := make([]interface{}, valueLen) |
| 469 |
for i := 0; i < valueLen; i++ { |
| 470 |
values[i] = reflectValue.Index(i).Interface() |
| 471 |
} |
| 472 |
|
| 473 |
if len(values) > 0 { |
| 474 |
conds = append(conds, clause.IN{Column: clause.Column{Table: curTable, Name: clause.PrimaryKey}, Values: values}) |
| 475 |
return []clause.Expression{clause.And(conds...)} |
| 476 |
} |
| 477 |
return nil |
| 478 |
} |
| 479 |
} |
| 480 |
|
| 481 |
conds = append(conds, clause.IN{Column: clause.Column{Table: curTable, Name: clause.PrimaryKey}, Values: args}) |
| 482 |
} |
| 483 |
} |
| 484 |
} |
| 485 |
|
| 486 |
if len(conds) > 0 { |
| 487 |
return []clause.Expression{clause.And(conds...)} |
| 488 |
} |
| 489 |
return nil |
| 490 |
} |
| 491 |
|
| 492 |
// Build build sql with clauses names |
| 493 |
func (stmt *Statement) Build(clauses ...string) { |
| 494 |
var firstClauseWritten bool |
| 495 |
|
| 496 |
for _, name := range clauses { |
| 497 |
if c, ok := stmt.Clauses[name]; ok { |
| 498 |
if firstClauseWritten { |
| 499 |
stmt.WriteByte(' ') |
| 500 |
} |
| 501 |
|
| 502 |
firstClauseWritten = true |
| 503 |
if b, ok := stmt.DB.ClauseBuilders[name]; ok { |
| 504 |
b(c, stmt) |
| 505 |
} else { |
| 506 |
c.Build(stmt) |
| 507 |
} |
| 508 |
} |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
func (stmt *Statement) Parse(value interface{}) (err error) { |
| 513 |
return stmt.ParseWithSpecialTableName(value, "") |
| 514 |
} |
| 515 |
|
| 516 |
func (stmt *Statement) ParseWithSpecialTableName(value interface{}, specialTableName string) (err error) { |
| 517 |
if stmt.Schema, err = schema.ParseWithSpecialTableName(value, stmt.DB.cacheStore, stmt.DB.NamingStrategy, specialTableName); err == nil && stmt.Table == "" { |
| 518 |
if tables := strings.Split(stmt.Schema.Table, "."); len(tables) == 2 { |
| 519 |
stmt.TableExpr = &clause.Expr{SQL: stmt.Quote(stmt.Schema.Table)} |
| 520 |
stmt.Table = tables[1] |
| 521 |
return |
| 522 |
} |
| 523 |
|
| 524 |
stmt.Table = stmt.Schema.Table |
| 525 |
} |
| 526 |
return err |
| 527 |
} |
| 528 |
|
| 529 |
func (stmt *Statement) clone() *Statement { |
| 530 |
newStmt := &Statement{ |
| 531 |
TableExpr: stmt.TableExpr, |
| 532 |
Table: stmt.Table, |
| 533 |
Model: stmt.Model, |
| 534 |
Unscoped: stmt.Unscoped, |
| 535 |
Dest: stmt.Dest, |
| 536 |
ReflectValue: stmt.ReflectValue, |
| 537 |
Clauses: map[string]clause.Clause{}, |
| 538 |
Distinct: stmt.Distinct, |
| 539 |
Selects: stmt.Selects, |
| 540 |
Omits: stmt.Omits, |
| 541 |
ColumnMapping: stmt.ColumnMapping, |
| 542 |
Preloads: map[string][]interface{}{}, |
| 543 |
ConnPool: stmt.ConnPool, |
| 544 |
Schema: stmt.Schema, |
| 545 |
Context: stmt.Context, |
| 546 |
RaiseErrorOnNotFound: stmt.RaiseErrorOnNotFound, |
| 547 |
SkipHooks: stmt.SkipHooks, |
| 548 |
Result: stmt.Result, |
| 549 |
} |
| 550 |
|
| 551 |
if stmt.SQL.Len() > 0 { |
| 552 |
newStmt.SQL.WriteString(stmt.SQL.String()) |
| 553 |
newStmt.Vars = make([]interface{}, 0, len(stmt.Vars)) |
| 554 |
newStmt.Vars = append(newStmt.Vars, stmt.Vars...) |
| 555 |
} |
| 556 |
|
| 557 |
for k, c := range stmt.Clauses { |
| 558 |
newStmt.Clauses[k] = c |
| 559 |
} |
| 560 |
|
| 561 |
for k, p := range stmt.Preloads { |
| 562 |
newStmt.Preloads[k] = p |
| 563 |
} |
| 564 |
|
| 565 |
if len(stmt.Joins) > 0 { |
| 566 |
newStmt.Joins = make([]join, len(stmt.Joins)) |
| 567 |
copy(newStmt.Joins, stmt.Joins) |
| 568 |
} |
| 569 |
|
| 570 |
if len(stmt.scopes) > 0 { |
| 571 |
newStmt.scopes = make([]func(*DB) *DB, len(stmt.scopes)) |
| 572 |
copy(newStmt.scopes, stmt.scopes) |
| 573 |
} |
| 574 |
|
| 575 |
stmt.Settings.Range(func(k, v interface{}) bool { |
| 576 |
newStmt.Settings.Store(k, v) |
| 577 |
return true |
| 578 |
}) |
| 579 |
|
| 580 |
return newStmt |
| 581 |
} |
| 582 |
|
| 583 |
// SetColumn set column's value |
| 584 |
// |
| 585 |
// stmt.SetColumn("Name", "jinzhu") // Hooks Method |
| 586 |
// stmt.SetColumn("Name", "jinzhu", true) // Callbacks Method |
| 587 |
func (stmt *Statement) SetColumn(name string, value interface{}, fromCallbacks ...bool) { |
| 588 |
if v, ok := stmt.Dest.(map[string]interface{}); ok { |
| 589 |
v[name] = value |
| 590 |
} else if v, ok := stmt.Dest.([]map[string]interface{}); ok { |
| 591 |
for _, m := range v { |
| 592 |
m[name] = value |
| 593 |
} |
| 594 |
} else if stmt.Schema != nil { |
| 595 |
if field := stmt.Schema.LookUpField(name); field != nil { |
| 596 |
destValue := reflect.ValueOf(stmt.Dest) |
| 597 |
for destValue.Kind() == reflect.Ptr { |
| 598 |
destValue = destValue.Elem() |
| 599 |
} |
| 600 |
|
| 601 |
if stmt.ReflectValue != destValue { |
| 602 |
if !destValue.CanAddr() { |
| 603 |
destValueCanAddr := reflect.New(destValue.Type()) |
| 604 |
destValueCanAddr.Elem().Set(destValue) |
| 605 |
stmt.Dest = destValueCanAddr.Interface() |
| 606 |
destValue = destValueCanAddr.Elem() |
| 607 |
} |
| 608 |
|
| 609 |
switch destValue.Kind() { |
| 610 |
case reflect.Struct: |
| 611 |
stmt.AddError(field.Set(stmt.Context, destValue, value)) |
| 612 |
default: |
| 613 |
stmt.AddError(ErrInvalidData) |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
switch stmt.ReflectValue.Kind() { |
| 618 |
case reflect.Slice, reflect.Array: |
| 619 |
if len(fromCallbacks) > 0 { |
| 620 |
for i := 0; i < stmt.ReflectValue.Len(); i++ { |
| 621 |
stmt.AddError(field.Set(stmt.Context, stmt.ReflectValue.Index(i), value)) |
| 622 |
} |
| 623 |
} else { |
| 624 |
stmt.AddError(field.Set(stmt.Context, stmt.ReflectValue.Index(stmt.CurDestIndex), value)) |
| 625 |
} |
| 626 |
case reflect.Struct: |
| 627 |
if !stmt.ReflectValue.CanAddr() { |
| 628 |
stmt.AddError(ErrInvalidValue) |
| 629 |
return |
| 630 |
} |
| 631 |
|
| 632 |
stmt.AddError(field.Set(stmt.Context, stmt.ReflectValue, value)) |
| 633 |
} |
| 634 |
} else { |
| 635 |
stmt.AddError(ErrInvalidField) |
| 636 |
} |
| 637 |
} else { |
| 638 |
stmt.AddError(ErrInvalidField) |
| 639 |
} |
| 640 |
} |
| 641 |
|
| 642 |
// Changed check model changed or not when updating |
| 643 |
func (stmt *Statement) Changed(fields ...string) bool { |
| 644 |
modelValue := stmt.ReflectValue |
| 645 |
switch modelValue.Kind() { |
| 646 |
case reflect.Slice, reflect.Array: |
| 647 |
modelValue = stmt.ReflectValue.Index(stmt.CurDestIndex) |
| 648 |
} |
| 649 |
|
| 650 |
selectColumns, restricted := stmt.SelectAndOmitColumns(false, true) |
| 651 |
changed := func(field *schema.Field) bool { |
| 652 |
fieldValue, _ := field.ValueOf(stmt.Context, modelValue) |
| 653 |
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) { |
| 654 |
if mv, mok := stmt.Dest.(map[string]interface{}); mok { |
| 655 |
if fv, ok := mv[field.Name]; ok { |
| 656 |
return !utils.AssertEqual(fv, fieldValue) |
| 657 |
} else if fv, ok := mv[field.DBName]; ok { |
| 658 |
return !utils.AssertEqual(fv, fieldValue) |
| 659 |
} |
| 660 |
} else { |
| 661 |
destValue := reflect.ValueOf(stmt.Dest) |
| 662 |
for destValue.Kind() == reflect.Ptr { |
| 663 |
destValue = destValue.Elem() |
| 664 |
} |
| 665 |
if descSchema, err := schema.Parse(stmt.Dest, stmt.DB.cacheStore, stmt.DB.NamingStrategy); err == nil { |
| 666 |
if destField := descSchema.LookUpField(field.DBName); destField != nil { |
| 667 |
changedValue, zero := destField.ValueOf(stmt.Context, destValue) |
| 668 |
if v { |
| 669 |
return !utils.AssertEqual(changedValue, fieldValue) |
| 670 |
} |
| 671 |
return !zero && !utils.AssertEqual(changedValue, fieldValue) |
| 672 |
} |
| 673 |
} |
| 674 |
} |
| 675 |
} |
| 676 |
return false |
| 677 |
} |
| 678 |
|
| 679 |
if len(fields) == 0 { |
| 680 |
for _, field := range stmt.Schema.FieldsByDBName { |
| 681 |
if changed(field) { |
| 682 |
return true |
| 683 |
} |
| 684 |
} |
| 685 |
} else { |
| 686 |
for _, name := range fields { |
| 687 |
if field := stmt.Schema.LookUpField(name); field != nil { |
| 688 |
if changed(field) { |
| 689 |
return true |
| 690 |
} |
| 691 |
} |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
return false |
| 696 |
} |
| 697 |
|
| 698 |
var matchName = func() func(tableColumn string) (table, column string) { |
| 699 |
nameMatcher := regexp.MustCompile(`^(?:\W?(\w+?)\W?\.)?(?:(\*)|\W?(\w+?)\W?)$`) |
| 700 |
return func(tableColumn string) (table, column string) { |
| 701 |
if matches := nameMatcher.FindStringSubmatch(tableColumn); len(matches) == 4 { |
| 702 |
table = matches[1] |
| 703 |
star := matches[2] |
| 704 |
columnName := matches[3] |
| 705 |
if star != "" { |
| 706 |
return table, star |
| 707 |
} |
| 708 |
return table, columnName |
| 709 |
} |
| 710 |
return "", "" |
| 711 |
} |
| 712 |
}() |
| 713 |
|
| 714 |
// SelectAndOmitColumns get select and omit columns, select -> true, omit -> false |
| 715 |
func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (map[string]bool, bool) { |
| 716 |
results := map[string]bool{} |
| 717 |
notRestricted := false |
| 718 |
|
| 719 |
processColumn := func(column string, result bool) { |
| 720 |
if stmt.Schema == nil { |
| 721 |
results[column] = result |
| 722 |
} else if column == "*" { |
| 723 |
notRestricted = result |
| 724 |
for _, dbName := range stmt.Schema.DBNames { |
| 725 |
results[dbName] = result |
| 726 |
} |
| 727 |
} else if column == clause.Associations { |
| 728 |
for _, rel := range stmt.Schema.Relationships.Relations { |
| 729 |
results[rel.Name] = result |
| 730 |
} |
| 731 |
} else if field := stmt.Schema.LookUpField(column); field != nil && field.DBName != "" { |
| 732 |
results[field.DBName] = result |
| 733 |
} else if table, col := matchName(column); col != "" && (table == stmt.Table || table == "") { |
| 734 |
if col == "*" { |
| 735 |
for _, dbName := range stmt.Schema.DBNames { |
| 736 |
results[dbName] = result |
| 737 |
} |
| 738 |
} else { |
| 739 |
results[col] = result |
| 740 |
} |
| 741 |
} else { |
| 742 |
results[column] = result |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
// select columns |
| 747 |
for _, column := range stmt.Selects { |
| 748 |
processColumn(column, true) |
| 749 |
} |
| 750 |
|
| 751 |
// omit columns |
| 752 |
for _, column := range stmt.Omits { |
| 753 |
processColumn(column, false) |
| 754 |
} |
| 755 |
|
| 756 |
if stmt.Schema != nil { |
| 757 |
for _, field := range stmt.Schema.FieldsByName { |
| 758 |
name := field.DBName |
| 759 |
if name == "" { |
| 760 |
name = field.Name |
| 761 |
} |
| 762 |
|
| 763 |
if requireCreate && !field.Creatable { |
| 764 |
results[name] = false |
| 765 |
} else if requireUpdate && !field.Updatable { |
| 766 |
results[name] = false |
| 767 |
} |
| 768 |
} |
| 769 |
} |
| 770 |
|
| 771 |
return results, !notRestricted && len(stmt.Selects) > 0 |
| 772 |
} |