From 828e6b646bbe803d1a6b9d4aba0d8ff8b84d14f4 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 25 Feb 2021 18:49:01 +0800 Subject: [PATCH] Lazy call registered scopes --- callbacks.go | 12 ++++++++++-- statement.go | 5 +++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/callbacks.go b/callbacks.go index cb14aff1..d1b8cd58 100644 --- a/callbacks.go +++ b/callbacks.go @@ -72,8 +72,10 @@ func (cs *callbacks) Raw() *processor { } func (p *processor) Execute(db *DB) { - curTime := time.Now() - stmt := db.Statement + var ( + curTime = time.Now() + stmt = db.Statement + ) if stmt.Model == nil { stmt.Model = stmt.Dest @@ -106,6 +108,12 @@ func (p *processor) Execute(db *DB) { } } + // call scopes + for _, scope := range stmt.scopes { + db = scope(db) + } + stmt.scopes = nil + for _, f := range p.fns { f(db) } diff --git a/statement.go b/statement.go index 0cb2ca32..a6ddece1 100644 --- a/statement.go +++ b/statement.go @@ -43,6 +43,7 @@ type Statement struct { CurDestIndex int attrs []interface{} assigns []interface{} + scopes []func(*DB) *DB } type join struct { @@ -481,6 +482,10 @@ func (stmt *Statement) clone() *Statement { copy(newStmt.Joins, stmt.Joins) } + for _, scope := range stmt.scopes { + stmt.scopes = append(stmt.scopes, scope) + } + stmt.Settings.Range(func(k, v interface{}) bool { newStmt.Settings.Store(k, v) return true