1. Development
1.1. Architecture
Gorm uses linkable APIs,*
is the bridge of the chain, and for each chain API it will create a new relationship.
db, err := ("postgres", "user=gorm dbname=gorm sslmode=disable") // Create a new relationshipdb = ("name = ?", "jinzhu") // Filter moreif SomeCondition { db = ("age = ?", 20) } else { db = ("age = ?", 30) } if YetAnotherCondition { db = ("active = ?", 1) }
When we start doing anything, the GORM will be based on the current*
Create a new*
Example
// Perform query operations(&user)
And based on the type of the current operation, it will call the registeredcreating
, updating
, querying
, deleting
orrow_querying
Callback to run the operation.
For the example above, callquerying
,refer toQuery callback
1.2. Write plug-in
GORM itself isCallbacks
Support is provided so you can fully customize GORM as needed
1.2.1. Register a new callback
func updateCreated(scope *Scope) { if ("Created") { ("Created", NowFunc()) } } ().Create().Register("update_created_at", updateCreated) // Register the callback of the Create process
1.2.2. Delete existing callbacks
().Create().Remove("gorm:create") // Remove the `gorm:create` callback from the Create callback
1.2.3. Replace the existing callback
().Create().Replace("gorm:create", newCreateFunction) // Replace the callback `gorm:create` with the new function `newCreateFunction` for the creation process
1.2.4. Register callback order
().Create().Before("gorm:create").Register("update_created_at", updateCreated) ().Create().After("gorm:create").Register("update_created_at", updateCreated) ().Query().After("gorm:query").Register("my_plugin:after_query", afterQuery) ().Delete().After("gorm:delete").Register("my_plugin:after_delete", afterDelete) ().Update().Before("gorm:update").Register("my_plugin:before_update", beforeUpdate) ().Create().Before("gorm:create").After("gorm:before_create").Register("my_plugin:before_create", beforeCreate)
1.2.5. Predefined callbacks
GORM defines callbacks to perform their CRUD operations, checking them before starting to write plugins.
Create callbacks
Update callbacks
Query callbacks
Delete callbacks
Row Query callbacks Row Query callbacks will be runningRow
orRows
When called, there is no registered callback by default, you can register a new callback:
func updateTableName(scope *) { (() + "_draft") // append `_draft` to table name } ().RowQuery().Register("publish:update_table_name", updateTableName)
The above is the detailed content of golang gorm development architecture and plug-in writing examples. For more information about golang gorm development architecture and plug-in writing, please pay attention to my other related articles!