Debian Codegraph @

gorm.go

raw
1 package gorm
2
3 import (
4 "context"
5 "database/sql"
6 "fmt"
7 "reflect"
8 "sort"
9 "sync"
10 "time"
11
12 "gorm.io/gorm/clause"
13 "gorm.io/gorm/logger"
14 "gorm.io/gorm/schema"
15 )
16
17 // for Config.cacheStore store PreparedStmtDB key
18 const preparedStmtDBKey = "preparedStmt"
19
20 // Config GORM config
21 type Config struct {
22 // GORM perform single create, update, delete operations in transactions by default to ensure database data integrity
23 // You can disable it by setting `SkipDefaultTransaction` to true
24 SkipDefaultTransaction bool
25 DefaultTransactionTimeout time.Duration
26 DefaultContextTimeout time.Duration
27
28 // NamingStrategy tables, columns naming strategy
29 NamingStrategy schema.Namer
30 // FullSaveAssociations full save associations
31 FullSaveAssociations bool
32 // Logger
33 Logger logger.Interface
34 // NowFunc the function to be used when creating a new timestamp
35 NowFunc func() time.Time
36 // DryRun generate sql without execute
37 DryRun bool
38 // PrepareStmt executes the given query in cached statement
39 PrepareStmt bool
40 // PrepareStmt cache support LRU expired,
41 // default maxsize=int64 Max value and ttl=1h
42 PrepareStmtMaxSize int
43 PrepareStmtTTL time.Duration
44
45 // DisableAutomaticPing
46 DisableAutomaticPing bool
47 // DisableForeignKeyConstraintWhenMigrating
48 DisableForeignKeyConstraintWhenMigrating bool
49 // IgnoreRelationshipsWhenMigrating
50 IgnoreRelationshipsWhenMigrating bool
51 // DisableNestedTransaction disable nested transaction
52 DisableNestedTransaction bool
53 // AllowGlobalUpdate allow global update
54 AllowGlobalUpdate bool
55 // QueryFields executes the SQL query with all fields of the table
56 QueryFields bool
57 // CreateBatchSize default create batch size
58 CreateBatchSize int
59 // TranslateError enabling error translation
60 TranslateError bool
61 // PropagateUnscoped propagate Unscoped to every other nested statement
62 PropagateUnscoped bool
63
64 // ClauseBuilders clause builder
65 ClauseBuilders map[string]clause.ClauseBuilder
66 // ConnPool db conn pool
67 ConnPool ConnPool
68 // Dialector database dialector
69 Dialector
70 // Plugins registered plugins
71 Plugins map[string]Plugin
72
73 callbacks *callbacks
74 cacheStore *sync.Map
75 }
76
77 // Apply update config to new config
78 func (c *Config) Apply(config *Config) error {
79 if config != c {
80 *config = *c
81 }
82 return nil
83 }
84
85 // AfterInitialize initialize plugins after db connected
86 func (c *Config) AfterInitialize(db *DB) error {
87 if db != nil {
88 for _, plugin := range c.Plugins {
89 if err := plugin.Initialize(db); err != nil {
90 return err
91 }
92 }
93 }
94 return nil
95 }
96
97 // Option gorm option interface
98 type Option interface {
99 Apply(*Config) error
100 AfterInitialize(*DB) error
101 }
102
103 // DB GORM DB definition
104 type DB struct {
105 *Config
106 Error error
107 RowsAffected int64
108 Statement *Statement
109 clone int
110 }
111
112 // Session session config when create session with Session() method
113 type Session struct {
114 DryRun bool
115 PrepareStmt bool
116 NewDB bool
117 Initialized bool
118 SkipHooks bool
119 SkipDefaultTransaction bool
120 DisableNestedTransaction bool
121 AllowGlobalUpdate bool
122 FullSaveAssociations bool
123 PropagateUnscoped bool
124 QueryFields bool
125 Context context.Context
126 Logger logger.Interface
127 NowFunc func() time.Time
128 CreateBatchSize int
129 }
130
131 // Open initialize db session based on dialector
132 func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
133 config := &Config{}
134
135 sort.Slice(opts, func(i, j int) bool {
136 _, isConfig := opts[i].(*Config)
137 _, isConfig2 := opts[j].(*Config)
138 return isConfig && !isConfig2
139 })
140
141 if len(opts) > 0 {
142 if c, ok := opts[0].(*Config); ok {
143 config = c
144 } else {
145 opts = append([]Option{config}, opts...)
146 }
147 }
148
149 var skipAfterInitialize bool
150 for _, opt := range opts {
151 if opt != nil {
152 if applyErr := opt.Apply(config); applyErr != nil {
153 return nil, applyErr
154 }
155 defer func(opt Option) {
156 if skipAfterInitialize {
157 return
158 }
159 if errr := opt.AfterInitialize(db); errr != nil {
160 err = errr
161 }
162 }(opt)
163 }
164 }
165
166 if d, ok := dialector.(interface{ Apply(*Config) error }); ok {
167 if err = d.Apply(config); err != nil {
168 return
169 }
170 }
171
172 if config.NamingStrategy == nil {
173 config.NamingStrategy = schema.NamingStrategy{IdentifierMaxLength: 64} // Default Identifier length is 64
174 }
175
176 if config.Logger == nil {
177 config.Logger = logger.Default
178 }
179
180 if config.NowFunc == nil {
181 config.NowFunc = func() time.Time { return time.Now().Local() }
182 }
183
184 if dialector != nil {
185 config.Dialector = dialector
186 }
187
188 if config.Plugins == nil {
189 config.Plugins = map[string]Plugin{}
190 }
191
192 if config.cacheStore == nil {
193 config.cacheStore = &sync.Map{}
194 }
195
196 db = &DB{Config: config, clone: 1}
197
198 db.callbacks = initializeCallbacks(db)
199
200 if config.ClauseBuilders == nil {
201 config.ClauseBuilders = map[string]clause.ClauseBuilder{}
202 }
203
204 if config.Dialector != nil {
205 err = config.Dialector.Initialize(db)
206 if err != nil {
207 if db, _ := db.DB(); db != nil {
208 _ = db.Close()
209 }
210
211 // DB is not initialized, so we skip AfterInitialize
212 skipAfterInitialize = true
213 return
214 }
215
216 if config.TranslateError {
217 if _, ok := db.Dialector.(ErrorTranslator); !ok {
218 config.Logger.Warn(context.Background(), "The TranslateError option is enabled, but the Dialector %s does not implement ErrorTranslator.", db.Dialector.Name())
219 }
220 }
221 }
222
223 if config.PrepareStmt {
224 preparedStmt := NewPreparedStmtDB(db.ConnPool, config.PrepareStmtMaxSize, config.PrepareStmtTTL)
225 db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
226 db.ConnPool = preparedStmt
227 }
228
229 db.Statement = &Statement{
230 DB: db,
231 ConnPool: db.ConnPool,
232 Context: context.Background(),
233 Clauses: map[string]clause.Clause{},
234 }
235
236 if err == nil && !config.DisableAutomaticPing {
237 if pinger, ok := db.ConnPool.(interface{ Ping() error }); ok {
238 err = pinger.Ping()
239 }
240 }
241
242 if err != nil {
243 config.Logger.Error(context.Background(), "failed to initialize database, got error %v", err)
244 }
245
246 return
247 }
248
249 // Session create new db session
250 func (db *DB) Session(config *Session) *DB {
251 var (
252 txConfig = *db.Config
253 tx = &DB{
254 Config: &txConfig,
255 Statement: db.Statement,
256 Error: db.Error,
257 clone: 1,
258 }
259 )
260 if config.CreateBatchSize > 0 {
261 tx.Config.CreateBatchSize = config.CreateBatchSize
262 }
263
264 if config.SkipDefaultTransaction {
265 tx.Config.SkipDefaultTransaction = true
266 }
267
268 if config.AllowGlobalUpdate {
269 txConfig.AllowGlobalUpdate = true
270 }
271
272 if config.FullSaveAssociations {
273 txConfig.FullSaveAssociations = true
274 }
275
276 if config.PropagateUnscoped {
277 txConfig.PropagateUnscoped = true
278 }
279
280 if config.Context != nil || config.PrepareStmt || config.SkipHooks {
281 tx.Statement = tx.Statement.clone()
282 tx.Statement.DB = tx
283 }
284
285 if config.Context != nil {
286 tx.Statement.Context = config.Context
287 }
288
289 if config.PrepareStmt {
290 var preparedStmt *PreparedStmtDB
291
292 if v, ok := db.cacheStore.Load(preparedStmtDBKey); ok {
293 preparedStmt = v.(*PreparedStmtDB)
294 } else {
295 preparedStmt = NewPreparedStmtDB(db.ConnPool, db.PrepareStmtMaxSize, db.PrepareStmtTTL)
296 db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
297 }
298
299 switch t := tx.Statement.ConnPool.(type) {
300 case Tx:
301 tx.Statement.ConnPool = &PreparedStmtTX{
302 Tx: t,
303 PreparedStmtDB: preparedStmt,
304 }
305 default:
306 tx.Statement.ConnPool = &PreparedStmtDB{
307 ConnPool: db.Config.ConnPool,
308 Mux: preparedStmt.Mux,
309 Stmts: preparedStmt.Stmts,
310 }
311 }
312 txConfig.ConnPool = tx.Statement.ConnPool
313 txConfig.PrepareStmt = true
314 }
315
316 if config.SkipHooks {
317 tx.Statement.SkipHooks = true
318 }
319
320 if config.DisableNestedTransaction {
321 txConfig.DisableNestedTransaction = true
322 }
323
324 if !config.NewDB {
325 tx.clone = 2
326 }
327
328 if config.DryRun {
329 tx.Config.DryRun = true
330 }
331
332 if config.QueryFields {
333 tx.Config.QueryFields = true
334 }
335
336 if config.Logger != nil {
337 tx.Config.Logger = config.Logger
338 }
339
340 if config.NowFunc != nil {
341 tx.Config.NowFunc = config.NowFunc
342 }
343
344 if config.Initialized {
345 tx = tx.getInstance()
346 }
347
348 return tx
349 }
350
351 // WithContext change current instance db's context to ctx
352 func (db *DB) WithContext(ctx context.Context) *DB {
353 return db.Session(&Session{Context: ctx})
354 }
355
356 // Debug start debug mode
357 func (db *DB) Debug() (tx *DB) {
358 tx = db.getInstance()
359 return tx.Session(&Session{
360 Logger: db.Logger.LogMode(logger.Info),
361 })
362 }
363
364 // Set store value with key into current db instance's context
365 func (db *DB) Set(key string, value interface{}) *DB {
366 tx := db.getInstance()
367 tx.Statement.Settings.Store(key, value)
368 return tx
369 }
370
371 // Get get value with key from current db instance's context
372 func (db *DB) Get(key string) (interface{}, bool) {
373 return db.Statement.Settings.Load(key)
374 }
375
376 // InstanceSet store value with key into current db instance's context
377 func (db *DB) InstanceSet(key string, value interface{}) *DB {
378 tx := db.getInstance()
379 tx.Statement.Settings.Store(fmt.Sprintf("%p", tx.Statement)+key, value)
380 return tx
381 }
382
383 // InstanceGet get value with key from current db instance's context
384 func (db *DB) InstanceGet(key string) (interface{}, bool) {
385 return db.Statement.Settings.Load(fmt.Sprintf("%p", db.Statement) + key)
386 }
387
388 // Callback returns callback manager
389 func (db *DB) Callback() *callbacks {
390 return db.callbacks
391 }
392
393 // AddError add error to db
394 func (db *DB) AddError(err error) error {
395 if err != nil {
396 if db.Config.TranslateError {
397 if errTranslator, ok := db.Dialector.(ErrorTranslator); ok {
398 err = errTranslator.Translate(err)
399 }
400 }
401
402 if db.Error == nil {
403 db.Error = err
404 } else {
405 db.Error = fmt.Errorf("%v; %w", db.Error, err)
406 }
407 }
408 return db.Error
409 }
410
411 // DB returns `*sql.DB`
412 func (db *DB) DB() (*sql.DB, error) {
413 connPool := db.ConnPool
414 if db.Statement != nil && db.Statement.ConnPool != nil {
415 connPool = db.Statement.ConnPool
416 }
417 if tx, ok := connPool.(*sql.Tx); ok && tx != nil {
418 return (*sql.DB)(reflect.ValueOf(tx).Elem().FieldByName("db").UnsafePointer()), nil
419 }
420
421 if dbConnector, ok := connPool.(GetDBConnector); ok && dbConnector != nil {
422 if sqldb, err := dbConnector.GetDBConn(); sqldb != nil || err != nil {
423 return sqldb, err
424 }
425 }
426
427 if sqldb, ok := connPool.(*sql.DB); ok && sqldb != nil {
428 return sqldb, nil
429 }
430
431 return nil, ErrInvalidDB
432 }
433
434 func (db *DB) getInstance() *DB {
435 if db.clone > 0 {
436 tx := &DB{Config: db.Config, Error: db.Error}
437
438 if db.clone == 1 {
439 // clone with new statement
440 tx.Statement = &Statement{
441 DB: tx,
442 ConnPool: db.Statement.ConnPool,
443 Context: db.Statement.Context,
444 Clauses: map[string]clause.Clause{},
445 Vars: make([]interface{}, 0, 8),
446 SkipHooks: db.Statement.SkipHooks,
447 }
448 if db.Config.PropagateUnscoped {
449 tx.Statement.Unscoped = db.Statement.Unscoped
450 }
451 } else {
452 // with clone statement
453 tx.Statement = db.Statement.clone()
454 tx.Statement.DB = tx
455 }
456
457 return tx
458 }
459
460 return db
461 }
462
463 // Expr returns clause.Expr, which can be used to pass SQL expression as params
464 func Expr(expr string, args ...interface{}) clause.Expr {
465 return clause.Expr{SQL: expr, Vars: args}
466 }
467
468 // SetupJoinTable setup join table schema
469 func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error {
470 var (
471 tx = db.getInstance()
472 stmt = tx.Statement
473 modelSchema, joinSchema *schema.Schema
474 )
475
476 err := stmt.Parse(model)
477 if err != nil {
478 return err
479 }
480 modelSchema = stmt.Schema
481
482 err = stmt.Parse(joinTable)
483 if err != nil {
484 return err
485 }
486 joinSchema = stmt.Schema
487
488 relation, ok := modelSchema.Relationships.Relations[field]
489 isRelation := ok && relation.JoinTable != nil
490 if !isRelation {
491 return fmt.Errorf("failed to find relation: %s", field)
492 }
493
494 for _, ref := range relation.References {
495 f := joinSchema.LookUpField(ref.ForeignKey.DBName)
496 if f == nil {
497 return fmt.Errorf("missing field %s for join table", ref.ForeignKey.DBName)
498 }
499
500 f.DataType = ref.ForeignKey.DataType
501 f.GORMDataType = ref.ForeignKey.GORMDataType
502 if f.Size == 0 {
503 f.Size = ref.ForeignKey.Size
504 }
505 ref.ForeignKey = f
506 }
507
508 for name, rel := range relation.JoinTable.Relationships.Relations {
509 if _, ok := joinSchema.Relationships.Relations[name]; !ok {
510 rel.Schema = joinSchema
511 joinSchema.Relationships.Relations[name] = rel
512 }
513 }
514 relation.JoinTable = joinSchema
515
516 return nil
517 }
518
519 // Use use plugin
520 func (db *DB) Use(plugin Plugin) error {
521 name := plugin.Name()
522 if _, ok := db.Plugins[name]; ok {
523 return ErrRegistered
524 }
525 if err := plugin.Initialize(db); err != nil {
526 return err
527 }
528 db.Plugins[name] = plugin
529 return nil
530 }
531
532 // ToSQL for generate SQL string.
533 //
534 // db.ToSQL(func(tx *gorm.DB) *gorm.DB {
535 // return tx.Model(&User{}).Where(&User{Name: "foo", Age: 20})
536 // .Limit(10).Offset(5)
537 // .Order("name ASC")
538 // .First(&User{})
539 // })
540 func (db *DB) ToSQL(queryFn func(tx *DB) *DB) string {
541 tx := queryFn(db.Session(&Session{DryRun: true, SkipDefaultTransaction: true}).getInstance())
542 stmt := tx.Statement
543
544 return db.Dialector.Explain(stmt.SQL.String(), stmt.Vars...)
545 }