GORM provides Session
method, which is a New Session Method
, it allows to create a new session mode with configuration:
// Session Configuration |
DryRun
Generates SQL
without executing. It can be used to prepare or test generated SQL, for example:
// session mode |
To generate the final SQL, you could use following code:
// NOTE: the SQL is not always safe to execute, GORM only uses it for logs, it might cause SQL injection |
Подготовить
PreparedStmt
creates prepared statements when executing any SQL and caches them to speed up future calls, for example:
// globally mode, all DB operations will create prepared statements and cache them |
NewDB
Create a new DB without conditions with option NewDB
, for example:
tx := db.Where("name = ?", "jinzhu").Session(&gorm.Session{NewDB: true}) |
Initialized
Create a new initialized DB, which is not Method Chain/Goroutine Safe anymore, refer Method Chaining
tx := db.Session(&gorm.Session{Initialized: true}) |
Skip Hooks
If you want to skip Hooks
methods, you can use the SkipHooks
session mode, for example:
DB.Session(&gorm.Session{SkipHooks: true}).Create(&user) |
DisableNestedTransaction
When using Transaction
method inside a DB transaction, GORM will use SavePoint(savedPointName)
, RollbackTo(savedPointName)
to give you the nested transaction support. You can disable it by using the DisableNestedTransaction
option, for example:
db.Session(&gorm.Session{ |
AllowGlobalUpdate
GORM doesn’t allow global update/delete by default, will return ErrMissingWhereClause
error. You can set this option to true to enable it, for example:
db.Session(&gorm.Session{ |
FullSaveAssociations
GORM will auto-save associations and its reference using Upsert when creating/updating a record. If you want to update associations’ data, you should use the FullSaveAssociations
mode, for example:
db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user) |
Context
With the Context
option, you can set the Context
for following SQL operations, for example:
timeoutCtx, _ := context.WithTimeout(context.Background(), time.Second) |
GORM also provides shortcut method WithContext
, here is the definition:
func (db *DB) WithContext(ctx context.Context) *DB { |
Logger
Gorm allows customizing built-in logger with the Logger
option, for example:
newLogger := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), |
Checkout Logger for more details.
NowFunc
NowFunc
allows changing the function to get current time of GORM, for example:
db.Session(&Session{ |
Debug
Debug
is a shortcut method to change session’s Logger
to debug mode, here is the definition:
func (db *DB) Debug() (tx *DB) { |
QueryFields
Select by fields
db.Session(&gorm.Session{QueryFields: true}).Find(&user) |
CreateBatchSize
Default batch size
users = [5000]User{{Name: "jinzhu", Pets: []Pet{pet1, pet2, pet3}}...} |