MCPcopy
hub / github.com/go-gorm/gorm / Count

Method Count

finisher_api.go:454–514  ·  view source on GitHub ↗
(count *int64)

Source from the content-addressed store, hash-verified

452}
453
454func (db *DB) Count(count *int64) (tx *DB) {
455 tx = db.getInstance()
456 if tx.Statement.Model == nil {
457 tx.Statement.Model = tx.Statement.Dest
458 defer func() {
459 tx.Statement.Model = nil
460 }()
461 }
462
463 if selectClause, ok := db.Statement.Clauses["SELECT"]; ok {
464 defer func() {
465 tx.Statement.Clauses["SELECT"] = selectClause
466 }()
467 } else {
468 defer delete(tx.Statement.Clauses, "SELECT")
469 }
470
471 if len(tx.Statement.Selects) == 0 {
472 tx.Statement.AddClause(clause.Select{Expression: clause.Expr{SQL: "count(*)"}})
473 } else if !strings.HasPrefix(strings.TrimSpace(strings.ToLower(tx.Statement.Selects[0])), "count(") {
474 expr := clause.Expr{SQL: "count(*)"}
475
476 if len(tx.Statement.Selects) == 1 {
477 dbName := tx.Statement.Selects[0]
478 fields := strings.FieldsFunc(dbName, utils.IsInvalidDBNameChar)
479 if len(fields) == 1 || (len(fields) == 3 && (strings.ToUpper(fields[1]) == "AS" || fields[1] == ".")) {
480 if tx.Statement.Parse(tx.Statement.Model) == nil {
481 if f := tx.Statement.Schema.LookUpField(dbName); f != nil {
482 dbName = f.DBName
483 }
484 }
485
486 if tx.Statement.Distinct {
487 expr = clause.Expr{SQL: "COUNT(DISTINCT(?))", Vars: []interface{}{clause.Column{Name: dbName}}}
488 } else if dbName != "*" {
489 expr = clause.Expr{SQL: "COUNT(?)", Vars: []interface{}{clause.Column{Name: dbName}}}
490 }
491 }
492 }
493
494 tx.Statement.AddClause(clause.Select{Expression: expr})
495 }
496
497 if orderByClause, ok := db.Statement.Clauses["ORDER BY"]; ok {
498 if _, ok := db.Statement.Clauses["GROUP BY"]; !ok {
499 delete(tx.Statement.Clauses, "ORDER BY")
500 defer func() {
501 tx.Statement.Clauses["ORDER BY"] = orderByClause
502 }()
503 }
504 }
505
506 tx.Statement.Dest = count
507 tx = tx.callbacks.Query().Execute(tx)
508
509 if _, ok := db.Statement.Clauses["GROUP BY"]; ok || tx.RowsAffected != 1 {
510 *count = tx.RowsAffected
511 }

Callers

nothing calls this directly

Calls 6

getInstanceMethod · 0.95
AddClauseMethod · 0.80
ParseMethod · 0.80
LookUpFieldMethod · 0.80
ExecuteMethod · 0.80
QueryMethod · 0.80

Tested by

no test coverage detected