### Generate Code Using Configuration File Source: https://github.com/go-gorm/gorm.io/blob/master/pages/es_ES/gen/gen_tool.md Example command to generate code using a configuration file. The configuration file allows for more extensive setup. ```shell gentool -c "./gen.tool" ``` -------------------------------- ### GORM 2.0 Quick Start Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/docs/v2_release_note.md A basic example demonstrating how to open a database connection using GORM with the SQLite driver, perform an auto migration, and execute common CRUD operations like create, find, update, and delete. ```go import ( "gorm.io/gorm" "gorm.io/driver/sqlite" ) func init() { db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{}) // Most CRUD API kept compatibility db.AutoMigrate(&Product{}) db.Create(&user) db.First(&user, 1) db.Model(&user).Update("Age", 18) db.Model(&user).Omit("Role").Updates(map[string]interface{}{"Name": "jinzhu", "Role": "admin"}) db.Delete(&user) } ``` -------------------------------- ### GORM Generics API Quick Start (Go) Source: https://github.com/go-gorm/gorm.io/blob/master/pages/fa_IR/docs/index.md Demonstrates basic CRUD operations (Create, Read, Update, Delete) using GORM's Generics API in Go. This API requires GORM v1.30.0 or later and uses a type-safe approach with context. ```go package main import ( "context" "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } ctx := context.Background() // Migrate the schema db.AutoMigrate(&Product{}) // Create err = gorm.G[Product](db).Create(ctx, &Product{Code: "D42", Price: 100}) // Read product, err := gorm.G[Product](db).Where("id = ?", 1).First(ctx) // find product with integer primary key products, err := gorm.G[Product](db).Where("code = ?", "D42").Find(ctx) // find product with code D42 // Update - update product's price to 200 err = gorm.G[Product](db).Where("id = ?", product.ID).Update(ctx, "Price", 200) // Update - update multiple fields err = gorm.G[Product](db).Where("id = ?", product.ID).Updates(ctx, Product{Code: "D42", Price: 100}) // Delete - delete product err = gorm.G[Product](db).Where("id = ?", product.ID).Delete(ctx) } ``` -------------------------------- ### GORM Optimizer Hints in Go Source: https://github.com/go-gorm/gorm.io/blob/master/pages/tr_TR/gen/clause.md Illustrates how to use GORM's optimizer hints in Go to guide the database query optimizer. This example shows how to set a maximum execution time for a query. It requires the 'gorm.io/hints' package. ```go import ( "context" "gorm.io/hints" ) // Assuming 'query', 'db', and 'ctx' are defined elsewhere // u := query.Use(db).User // users, err := u.WithContext(ctx).Clauses(hints.New("MAX_EXECUTION_TIME(10000)")).Find() // The generated SQL would look like: SELECT * /*+ MAX_EXECUTION_TIME(10000) */ FROM `users` ``` -------------------------------- ### DAO Initialization and Usage Examples Source: https://github.com/go-gorm/gorm.io/blob/master/pages/zh_CN/gen/dao.md Examples demonstrating how to initialize and use the GORM DAO, including using the global query instance `Q`. ```APIDOC ## DAO Initialization and Usage ### Using Global Query Instance `Q` If `gen.WithDefaultQuery` is enabled, you can use the global variable `Q`. ```go import "your_project/dal" import "gorm.io/gorm" import "gorm.io/driver/sqlite" func main() { // Initialize a *gorm.DB instance db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { // Handle error } dal.SetDefault(db) // Query the first user user, err := dal.Q.User.First() if err != nil { // Handle error } } ``` ### Initializing DAO Query Interface You can also explicitly initialize the DAO query interface. ```go import "your_project/dal" import "gorm.io/gorm" import "gorm.io/driver/sqlite" var Q dal.Query func main() { // Initialize a *gorm.DB instance db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { // Handle error } Q = dal.Use(db) // Query the first user user, err := Q.User.First() if err != nil { // Handle error } } ``` ### Further Details For more detailed usage information, refer to the following links: * [Create](./create.html) * [Update](./update.html) * [Query](./query.html) * [Delete](./delete.html) * [Associations](./associations.html) * [Transaction](./transaction.html) ``` -------------------------------- ### Gen Tool Installation and Usage Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/gen/gen_tool.md Instructions on how to install the Gen Tool and a detailed explanation of its command-line arguments and their purposes. ```APIDOC ## Gen Tool Installation and Usage ### Install ```shell go install gorm.io/gen/tools/gentool@latest ``` ### Usage ```shell gentool -h Usage of gentool: -c string config file path -db string input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html] (default "mysql") -dsn string consult[https://gorm.io/docs/connecting_to_the_database.html] -fieldNullable generate with pointer when field is nullable -fieldWithIndexTag generate field with gorm index tag -fieldWithTypeTag generate field with gorm column type tag -modelPkgName string generated model code's package name -outFile string query code file name, default: gen.go -outPath string specify a directory for output (default "./dao/query") -tables string enter the required data table or leave it blank -onlyModel only generate models (without query file) -withUnitTest generate unit test for query code -fieldSignable detect integer field's unsigned type, adjust generated data type ``` ### Command Line Options - **-c** (string): Configuration file path. Command line options have higher priority than the configuration file. - **-db** (string): Specify driver dialect (e.g., "mysql", "postgres", "sqlite", "sqlserver"). Defaults to "mysql". Refer to [https://gorm.io/docs/connecting_to_the_database.html](https://gorm.io/docs/connecting_to_the_database.html). - **-dsn** (string): Data Source Name for connecting to the database. Refer to [https://gorm.io/docs/connecting_to_the_database.html](https://gorm.io/docs/connecting_to_the_database.html). - **-fieldNullable** (boolean): Generate with a pointer when a field is nullable. - **-fieldWithIndexTag** (boolean): Generate fields with gorm index tags. - **-fieldWithTypeTag** (boolean): Generate fields with gorm column type tags. - **-modelPkgName** (string): The package name for the generated model code. - **-outFile** (string): The file name for the generated query code. Defaults to "gen.go". - **-outPath** (string): The directory to output the generated files. Defaults to "./dao/query". - **-tables** (string): Comma-separated list of table names to generate code for. If left blank, all tables will be used. Example: `"orders,users"`. - **-onlyModel** (boolean): If set, only generate model files (without query files). - **-withUnitTest** (boolean): Generate unit tests for the query code. Defaults to `false`. - **-fieldSignable** (boolean): Detect unsigned integer types and adjust the generated data type accordingly. Defaults to `false`. ### Configuration File Example (YAML) ```yaml version: "0.1" database: # consult[https://gorm.io/docs/connecting_to_the_database.html] dsn : "username:password@tcp(address:port)/db?charset=utf8mb4&parseTime=true&loc=Local" # input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html] db : "mysql" # enter the required data table or leave it blank.You can input : orders,users,goods tables : "user" # specify a directory for output outPath : "./dao/query" # query code file name, default: gen.go outFile : "" # generate unit test for query code withUnitTest : false # generated model code's package name modelPkgName : "" # generate with pointer when field is nullable fieldNullable : false # generate field with gorm index tag fieldWithIndexTag : false # generate field with gorm column type tag fieldWithTypeTag : false ``` ### Examples **Using command-line arguments:** ```shell gentool -dsn "user:pwd@tcp(localhost:3306)/database?charset=utf8mb4&parseTime=True&loc=Local" -tables "orders,doctor" gentool -c "./gen.tool" ``` ``` -------------------------------- ### Install and Initialize GORM 2.0 Source: https://github.com/go-gorm/gorm.io/blob/master/pages/de_DE/docs/v2_release_note.md Instructions for installing the GORM package and initializing a database connection using the SQLite driver. ```bash go get gorm.io/gorm ``` ```go import ( "gorm.io/gorm" "gorm.io/driver/sqlite" ) func init() { db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{}) db.AutoMigrate(&Product{}) db.Create(&user) db.First(&user, 1) } ``` -------------------------------- ### Gen Tool Installation and Usage Source: https://github.com/go-gorm/gorm.io/blob/master/pages/es_ES/gen/gen_tool.md Instructions on how to install the Gen Tool and a detailed explanation of its command-line arguments and configuration options. ```APIDOC ## Gen Tool Installation and Usage ### Install ```shell go install gorm.io/gen/tools/gentool@latest ``` ### Usage ```shell gentool -h Usage of gentool: -c string config file path -db string input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html] (default "mysql") -dsn string consult[https://gorm.io/docs/connecting_to_the_database.html] -fieldNullable generate with pointer when field is nullable -fieldWithIndexTag generate field with gorm index tag -fieldWithTypeTag generate field with gorm column type tag -modelPkgName string generated model code's package name -outFile string query code file name, default: gen.go -outPath string specify a directory for output (default "./dao/query") -tables string enter the required data table or leave it blank -onlyModel only generate models (without query file) -withUnitTest generate unit test for query code -fieldSignable detect integer field's unsigned type, adjust generated data type ``` ### Configuration Options - **c** (string): Configuration file path. Command line options have higher priority than the configuration file. - **db** (string): Specify driver dialect (e.g., "mysql", "postgres", "sqlite", "sqlserver"). Defaults to "mysql". Refer to [https://gorm.io/docs/connecting_to_the_database.html](https://gorm.io/docs/connecting_to_the_database.html). - **dsn** (string): Data Source Name for connecting to the database. Refer to [https://gorm.io/docs/connecting_to_the_database.html](https://gorm.io/docs/connecting_to_the_database.html). - **fieldNullable** (boolean): Generate with a pointer when a field is nullable. - **fieldWithIndexTag** (boolean): Generate fields with gorm index tags. - **fieldWithTypeTag** (boolean): Generate fields with gorm column type tags. - **modelPkgName** (string): The package name for the generated model code. - **outFile** (string): The file name for the generated query code. Defaults to "gen.go". - **outPath** (string): The directory to output the generated files. Defaults to "./dao/query". - **tables** (string): Comma-separated list of table names to generate code for. If left blank, all tables will be used. Example: `--tables="orders,users"`. - **onlyModel** (boolean): If true, only generate model files (without query files). - **withUnitTest** (boolean): If true, generate unit tests for the query code. Defaults to `false`. - **fieldSignable** (boolean): If true, detect unsigned integer fields and adjust the generated data type accordingly. Defaults to `false`. ### Examples ```shell gentool -dsn "user:pwd@tcp(localhost:3306)/database?charset=utf8mb4&parseTime=True&loc=Local" -tables "orders,doctor" gentool -c "./gen.tool" ``` ### Configuration File Example (YAML) ```yaml version: "0.1" database: # consult[https://gorm.io/docs/connecting_to_the_database.html] dsn : "username:password@tcp(address:port)/db?charset=utf8mb4&parseTime=true&loc=Local" # input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html] db : "mysql" # enter the required data table or leave it blank.You can input : orders,users,goods tables : "user" # specify a directory for output outPath : "./dao/query" # query code file name, default: gen.go outFile : "" # generate unit test for query code withUnitTest : false # generated model code's package name modelPkgName : "" # generate with pointer when field is nullable fieldNullable : false # generate field with gorm index tag fieldWithIndexTag : false # generate field with gorm column type tag fieldWithTypeTag : false ``` ``` -------------------------------- ### Install Gen Tool Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/gen/gen_tool.md Install the latest version of the Gen Tool binary via Go. ```shell go install gorm.io/gen/tools/gentool@latest ``` -------------------------------- ### GORM Traditional API Quick Start (Go) Source: https://github.com/go-gorm/gorm.io/blob/master/pages/fa_IR/docs/index.md Illustrates fundamental CRUD operations (Create, Read, Update, Delete) using GORM's Traditional API in Go. This API is suitable for projects not using the Generics API and directly interacts with the database instance. ```go package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Migrate the schema db.AutoMigrate(&Product{}) // Create db.Create(&Product{Code: "D42", Price: 100}) // Read var product Product db.First(&product, 1) // find product with integer primary key db.First(&product, "code = ?", "D42") // find product with code D42 // Update - update product's price to 200 db.Model(&product).Update("Price", 200) // Update - update multiple fields db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) // Delete - delete product db.Delete(&product, 1) } ``` -------------------------------- ### GORM Object Retrieval Examples (Go) Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/docs/query.md Provides examples of retrieving GORM objects, including specifying models, using table names, and handling cases where no primary key is defined. It highlights correct and incorrect usage patterns. ```go var user User var users []User // works because destination struct is passed in db.First(&user) // SELECT * FROM `users` ORDER BY `users`.`id` LIMIT 1 // works because model is specified using `db.Model()` result := map[string]interface{}{} db.Model(&User{}).First(&result) // SELECT * FROM `users` ORDER BY `users`.`id` LIMIT 1 // doesn't work result := map[string]interface{}{} db.Table("users").First(&result) // works with Take result := map[string]interface{}{} db.Table("users").Take(&result) // no primary key defined, results will be ordered by first field (i.e., `Code`) type Language struct { Code string Name string } db.First(&Language{}) // SELECT * FROM `languages` ORDER BY `languages`.`code` LIMIT 1 ``` -------------------------------- ### Install GORM Dependencies Source: https://github.com/go-gorm/gorm.io/blob/master/pages/az_AZ/docs/index.md Commands to install the GORM library and the SQLite driver using the Go package manager. ```shell go get -u gorm.io/gorm go get -u gorm.io/driver/sqlite ``` -------------------------------- ### Install GORM 2.0 Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/docs/v2_release_note.md Command to install the GORM library using go get. Note that GORM v2.0.0 was released with the git tag v1.20.0. ```go go get gorm.io/gorm // **NOTE** GORM `v2.0.0` released with git tag `v1.20.0` ``` -------------------------------- ### Run Gen Tool Examples Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/gen/gen_tool.md Execute the tool using command-line arguments or a configuration file. ```shell gentool -dsn "user:pwd@tcp(localhost:3306)/database?charset=utf8mb4&parseTime=True&loc=Local" -tables "orders,doctor" gentool -c "./gen.tool" ``` -------------------------------- ### Install GORM GEN Tool Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/gen/index.md Installs the GORM GEN code generation tool using the Go modules system. This command fetches the latest version of the package and makes it available for use in your project. ```sh go get -u gorm.io/gen ``` -------------------------------- ### Get Current Database Name with GORM Migrator Source: https://github.com/go-gorm/gorm.io/blob/master/pages/az_AZ/docs/migration.md Retrieves the name of the currently connected database using the GORM Migrator interface. ```go db.Migrator().CurrentDatabase() ``` -------------------------------- ### TiDB Example: Product Model and Operations Source: https://github.com/go-gorm/gorm.io/blob/master/pages/es_ES/docs/connecting_to_the_database.md Demonstrates defining a Product model with TiDB specific primary key and performing basic Create and Read operations. Uses the MySQL driver. ```go import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" ) type Product struct { ID uint `gorm:"primaryKey;default:auto_random()"` Code string Price uint } func main() { db, err := gorm.Open(mysql.Open("root:@tcp(127.0.0.1:4000)/test"), &gorm.Config{}) if err != nil { panic("failed to connect database") } db.AutoMigrate(&Product{}) insertProduct := &Product{Code: "D42", Price: 100} db.Create(insertProduct) fmt.Printf("insert ID: %d, Code: %s, Price: %d\n", insertProduct.ID, insertProduct.Code, insertProduct.Price) readProduct := &Product{} db.First(&readProduct, "code = ?", "D42") // find product with code D42 fmt.Printf("read ID: %d, Code: %s, Price: %d\n", readProduct.ID, readProduct.Code, readProduct.Price) } ``` -------------------------------- ### GORM Index Hints: Guide Index Selection Source: https://github.com/go-gorm/gorm.io/blob/master/pages/de_DE/docs/advanced_query.md Index hints in GORM guide the database on which indexes to use for a query. This can improve performance if the query planner selects inefficient indexes. Examples include suggesting or forcing specific indexes. ```go package main import ( "gorm.io/gorm" "gorm.io/hints" ) type User struct {} func main() { db, err := gorm.Open(/* database connection */) if err != nil { panic("failed to connect database") } // Suggesting the use of a specific index db.Clauses(hints.UseIndex("idx_user_name")).Find(&User{}) // SQL: SELECT * FROM `users` USE INDEX (`idx_user_name`) // Forcing the use of certain indexes for a JOIN operation db.Clauses(hints.ForceIndex("idx_user_name", "idx_user_id").ForJoin()).Find(&User{}) // SQL: SELECT * FROM `users` FORCE INDEX FOR JOIN (`idx_user_name`,`idx_user_id`) } ``` -------------------------------- ### Perform CRUD operations with GORM Source: https://github.com/go-gorm/gorm.io/blob/master/pages/id_ID/docs/index.md Demonstrates how to perform Create, Read, Update, and Delete operations using GORM. Includes examples for both the modern Generics API and the traditional API. ```go package main import ( "context" "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } ctx := context.Background() db.AutoMigrate(&Product{}) // Generics API gorm.G[Product](db).Create(ctx, &Product{Code: "D42", Price: 100}) product, _ := gorm.G[Product](db).Where("id = ?", 1).First(ctx) gorm.G[Product](db).Where("id = ?", product.ID).Update(ctx, "Price", 200) gorm.G[Product](db).Where("id = ?", product.ID).Delete(ctx) } ``` ```go package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } db.AutoMigrate(&Product{}) // Traditional API db.Create(&Product{Code: "D42", Price: 100}) var product Product db.First(&product, 1) db.Model(&product).Update("Price", 200) db.Delete(&product, 1) } ``` -------------------------------- ### Perform CRUD Operations with GORM Source: https://github.com/go-gorm/gorm.io/blob/master/pages/hi_IN/docs/index.md Demonstrates database schema migration and CRUD operations (Create, Read, Update, Delete) using GORM. Includes examples for both the type-safe Generics API and the traditional API. ```go package main import ( "context" "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } ctx := context.Background() db.AutoMigrate(&Product{}) // Create err = gorm.G[Product](db).Create(ctx, &Product{Code: "D42", Price: 100}) // Read product, err := gorm.G[Product](db).Where("id = ?", 1).First(ctx) products, err := gorm.G[Product](db).Where("code = ?", "D42").Find(ctx) // Update err = gorm.G[Product](db).Where("id = ?", product.ID).Update(ctx, "Price", 200) err = gorm.G[Product](db).Where("id = ?", product.ID).Updates(ctx, Product{Code: "D42", Price: 100}) // Delete err = gorm.G[Product](db).Where("id = ?", product.ID).Delete(ctx) } ``` ```go package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } db.AutoMigrate(&Product{}) // Create db.Create(&Product{Code: "D42", Price: 100}) // Read var product Product db.First(&product, 1) db.First(&product, "code = ?", "D42") // Update db.Model(&product).Update("Price", 200) db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) // Delete db.Delete(&product, 1) } ``` -------------------------------- ### Manage Database Constraints with GORM Source: https://github.com/go-gorm/gorm.io/blob/master/pages/pt_BR/docs/migration.md Provides examples for creating, dropping, and checking the existence of database constraints using GORM's `Migrator` API. This includes managing check constraints and foreign key constraints for model associations. ```go type UserIndex struct { Name string `gorm:"check:name_checker,name <> 'jinzhu'"` } // Create constraint db.Migrator().CreateConstraint(&User{}, "name_checker") // Drop constraint db.Migrator().DropConstraint(&User{}, "name_checker") // Check constraint exists db.Migrator().HasConstraint(&User{}, "name_checker") type User struct { gorm.Model CreditCards []CreditCard } type CreditCard struct { gorm.Model Number string UserID uint } // create database foreign key for user & credit_cards db.Migrator().CreateConstraint(&User{}, "CreditCards") db.Migrator().CreateConstraint(&User{}, "fk_users_credit_cards") // ALTER TABLE `credit_cards` ADD CONSTRAINT `fk_users_credit_cards` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) // check database foreign key for user & credit_cards exists or not db.Migrator().HasConstraint(&User{}, "CreditCards") db.Migrator().HasConstraint(&User{}, "fk_users_credit_cards") // drop database foreign key for user & credit_cards db.Migrator().DropConstraint(&User{}, "CreditCards") db.Migrator().DropConstraint(&User{}, "fk_users_credit_cards") ``` -------------------------------- ### Registering the Prometheus Plugin Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/docs/write_plugins.md Provides a practical example of initializing and registering the Prometheus plugin with specific configuration settings. ```go db.Use(prometheus.New(prometheus.Config{ // Configuration options here })) ``` -------------------------------- ### GORM Traditional API CRUD Operations with SQLite Source: https://github.com/go-gorm/gorm.io/blob/master/pages/pl_PL/docs/index.md Demonstrates basic Create, Read, Update, and Delete (CRUD) operations using GORM's Traditional API with a SQLite database. It includes schema migration and examples for updating single or multiple fields. ```go package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) // Use sqlite.Open("file::memory:?cache=shared") for in-memory database if err != nil { panic("failed to connect database") } // Migrate the schema db.AutoMigrate(&Product{}) // Create db.Create(&Product{Code: "D42", Price: 100}) // Read var product Product db.First(&product, 1) // find product with integer primary key db.First(&product, "code = ?", "D42") // find product with code D42 // Update - update product's price to 200 db.Model(&product).Update("Price", 200) // Update - update multiple fields db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) // Delete - delete product db.Delete(&product, 1) } ``` -------------------------------- ### Initialize and execute GORM Gen Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/gen/dao.md Demonstrates how to set up the GORM generator by configuring the output path, connecting to a database, and applying model definitions. Executing this program generates the necessary DAO interface code in the specified directory. ```go package main import ( "gorm.io/gen" "gorm.io/gorm" "gorm.io/driver/sqlite" ) func main() { g := gen.NewGenerator(gen.Config{ OutPath: "../dal", Mode: gen.WithDefaultQuery | gen.WithGeneric, FieldNullable: true, }) db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) g.UseDB(db) g.ApplyBasic(model.Customer{}, model.CreditCard{}, model.Bank{}, model.Passport{}) companyGenerator := g.GenerateModelAs("company", "MyCompany") g.ApplyBasic( g.GenerateModel("users"), companyGenerator, g.GenerateModelAs("people", "Person", gen.FieldIgnore("deleted_at"), gen.FieldNewTag("age", `json:"-"`), ), ) g.Execute() } ``` -------------------------------- ### Use Generated GORM DAO API Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/gen/index.md Demonstrates how to use the code generated by GORM GEN. It shows examples of querying a user by name using the basic DAO API and filtering users with a specific name and role using the dynamic SQL API. ```go import "your_project/query" func main() { // Basic DAO API user, err := query.User.Where(u.Name.Eq("modi")).First() // Dynamic SQL API users, err := query.User.FilterWithNameAndRole("modi", "admin") } ``` -------------------------------- ### Initialize GORM with Existing Database Connection Source: https://github.com/go-gorm/gorm.io/blob/master/pages/es_ES/docs/connecting_to_the_database.md Initialize a GORM DB instance using an existing database connection from the standard database/sql package. ```go import ( "database/sql" "gorm.io/driver/gaussdb" "gorm.io/gorm" ) sqlDB, err := sql.Open("gaussdbgo", "mydb_dsn") gormDB, err := gorm.Open(gaussdb.New(gaussdb.Config{ Conn: sqlDB, }), &gorm.Config{}) ``` -------------------------------- ### 禁用迁移时的外键约束 Source: https://github.com/go-gorm/gorm.io/blob/master/pages/zh_CN/docs/gorm_config.md 在执行 AutoMigrate 或 CreateTable 时禁用自动创建外键约束。 ```go db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ DisableForeignKeyConstraintWhenMigrating: true, }) ``` -------------------------------- ### View Gen Tool Help Source: https://github.com/go-gorm/gorm.io/blob/master/pages/ar_SA/gen/gen_tool.md Display the available command-line options and usage instructions. ```shell gentool -h Usage of gentool: -c string config file path -db string input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html] (default "mysql") -dsn string consult[https://gorm.io/docs/connecting_to_the_database.html] -fieldNullable generate with pointer when field is nullable -fieldWithIndexTag generate field with gorm index tag -fieldWithTypeTag generate field with gorm column type tag -modelPkgName string generated model code's package name -outFile string query code file name, default: gen.go -outPath string specify a directory for output (default "./dao/query") -tables string enter the required data table or leave it blank -onlyModel only generate models (without query file) -withUnitTest generate unit test for query code -fieldSignable detect integer field's unsigned type, adjust generated data type ``` -------------------------------- ### GORM Traditional API CRUD Operations Source: https://github.com/go-gorm/gorm.io/blob/master/pages/es_ES/docs/index.md Illustrates basic Create, Read, Update, and Delete (CRUD) operations using GORM's Traditional API. This example connects to a SQLite database, performs schema migration, and performs standard CRUD actions on the 'Product' model. ```go package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) // Use sqlite.Open for SQLite if err != nil { panic("failed to connect database") } // Migrate the schema db.AutoMigrate(&Product{}) // Create db.Create(&Product{Code: "D42", Price: 100}) // Read var product Product db.First(&product, 1) // find product with integer primary key db.First(&product, "code = ?", "D42") // find product with code D42 // Update - update product's price to 200 db.Model(&product).Update("Price", 200) // Update - update multiple fields db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) // Delete - delete product db.Delete(&product, 1) } ``` -------------------------------- ### Get and Use sql.DB from GORM in Go Source: https://github.com/go-gorm/gorm.io/blob/master/pages/docs/generic_interface.md Retrieves the generic `*sql.DB` interface from a `*gorm.DB` instance. This allows direct use of standard library database functions such as Ping, Close, and Stats. Note that this may return an error if the underlying connection is not a `*sql.DB`, for example, within a transaction. ```go sqlDB, err := db.DB() // Ping the database sqlDB.Ping() // Close the database connection sqlDB.Close() // Get database statistics stats := sqlDB.Stats() ``` -------------------------------- ### Oracle Database Connection String (macOS/Windows) Source: https://github.com/go-gorm/gorm.io/blob/master/pages/es_ES/docs/connecting_to_the_database.md Example of a dataSourceName for Oracle Database on macOS and Windows, including the libDir parameter for Instant Client. ```go dataSourceName := `user="scott" password="tiger" connectString="dbhost:1521/orclpdb1" libDir="/Path/to/your/instantclient_23_26"` ``` -------------------------------- ### Initialize DAO Query Interface Directly Source: https://github.com/go-gorm/gorm.io/blob/master/pages/zh_CN/gen/dao.md Shows how to initialize the DAO query interface 'Q' by directly using the 'dal.Use(db)' function. This method allows for explicit control over the database instance used by the DAO. ```go import "your_project/dal" var Q dal.Query func main() { // Initialize a *gorm.DB instance db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) Q = dal.Use(db) // query the first user user, err := Q.User.First() } ``` -------------------------------- ### Go GORM Traditional API: Safe Instance Reuse Source: https://github.com/go-gorm/gorm.io/blob/master/pages/zh_CN/docs/method_chaining.md Demonstrates how to safely reuse a GORM DB instance by understanding method chaining. Each chain starting with a method like `Where` creates a new `*gorm.Statement`, ensuring subsequent calls do not pollute previous query conditions. Finisher methods like `Find` execute the query. ```go db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) // 'db' is a newly initialized `*gorm.DB`, which is safe to reuse. db.where ("name = ?", "jinzhu").Where("age = ?", 18).Find(&users) // 第一个`Where ("name = ?", "jinzhu")`是一个启动一个 `*gorm.DB` 实例或`*gorm.Statement`的链式方法。 // The second `Where("age = ?", 18)` call adds a new condition to the existing `*gorm.Statement`. // `Find(&users)` is a finisher method, executing registered Query Callbacks, generating and running: // SELECT * FROM users WHERE name = 'jinzhu' AND age = 18; db.Where("name = ?", "jinzhu2").Where("age = ?", 20).Find(&users) // Here, `Where("name = ?", "jinzhu2")` starts a new chain, creating a fresh `*gorm.Statement`. // `Where("age = ?", 20)` adds to this new statement. // `Find(&users)` again finalizes the query, executing and generating: // SELECT * FROM users WHERE name = 'jinzhu2' AND age = 20; db.Find(&users) // Directly calling `Find(&users)` without any `Where` starts a new chain and executes: // SELECT * FROM users; ``` -------------------------------- ### Gen Tool Command-Line Example Source: https://github.com/go-gorm/gorm.io/blob/master/pages/fr_FR/gen/gen_tool.md Provides examples of how to use the gentool command with different configurations. These examples demonstrate specifying the DSN and tables, or using a configuration file. ```shell gentool -dsn "user:pwd@tcp(localhost:3306)/database?charset=utf8mb4&parseTime=True&loc=Local" -tables "orders,doctor" gentool -c "./gen.tool" ``` -------------------------------- ### Configure GORM initialization options Source: https://github.com/go-gorm/gorm.io/blob/master/pages/hi_IN/docs/gorm_config.md Examples of how to pass configuration options to the gorm.Open function to modify database behavior during startup. ```go db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ SkipDefaultTransaction: true, NamingStrategy: schema.NamingStrategy{ TablePrefix: "t_", SingularTable: true, NoLowerCase: true, NameReplacer: strings.NewReplacer("CID", "Cid"), }, NowFunc: func() time.Time { return time.Now().Local() }, DryRun: false, PrepareStmt: false, DisableAutomaticPing: true, DisableForeignKeyConstraintWhenMigrating: true, }) ``` -------------------------------- ### Gen Tool Configuration File Example Source: https://github.com/go-gorm/gorm.io/blob/master/pages/es_ES/gen/gen_tool.md A sample YAML configuration file for the Gen Tool. This file defines database connection details, table selection, and code generation options. ```yaml version: "0.1" database: # consult[https://gorm.io/docs/connecting_to_the_database.html]" dsn : "username:password@tcp(address:port)/db?charset=utf8mb4&parseTime=true&loc=Local" # input mysql or postgres or sqlite or sqlserver. consult[https://gorm.io/docs/connecting_to_the_database.html] db : "mysql" # enter the required data table or leave it blank.You can input : orders,users,goods tables : "user" # specify a directory for output outPath : "./dao/query" # query code file name, default: gen.go outFile : "" # generate unit test for query code withUnitTest : false # generated model code's package name modelPkgName : "" # generate with pointer when field is nullable fieldNullable : false # generate field with gorm index tag fieldWithIndexTag : false # generate field with gorm column type tag fieldWithTypeTag : false ``` -------------------------------- ### Install Gen Tool (Shell) Source: https://github.com/go-gorm/gorm.io/blob/master/pages/az_AZ/gen/gen_tool.md Installs the Gen Tool using the Go `install` command. This command fetches the latest version of the tool and makes it available in your system's PATH. ```shell go install gorm.io/gen/tools/gentool@latest ``` -------------------------------- ### Initialize DAO with Global Query Variable Q Source: https://github.com/go-gorm/gorm.io/blob/master/pages/zh_CN/gen/dao.md Demonstrates how to initialize and use the global query variable 'Q' for database operations when 'gen.WithDefaultQuery' is enabled. Ensure the 'dal.SetDefault(db)' function is called to set the global DB instance. ```go import "your_project/dal" func main() { // Initialize a *gorm.DB instance db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) dal.SetDefault(db) // query the first user user, err := dal.Q.User.First() } ``` -------------------------------- ### Connect and Operate with Clickhouse Driver Source: https://github.com/go-gorm/gorm.io/blob/master/pages/de_DE/docs/connecting_to_the_database.md Demonstrates how to initialize a GORM connection using the Clickhouse driver and perform basic operations like AutoMigrate, Create, and Find. It also shows how to pass custom table options specific to Clickhouse engines. ```go import ( "gorm.io/driver/clickhouse" "gorm.io/gorm" ) func main() { dsn := "tcp://localhost:9000?database=gorm&username=gorm&password=gorm&read_timeout=10&write_timeout=20" db, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{}) // Auto Migrate db.AutoMigrate(&User{}) // Set table options db.Set("gorm:table_options", "ENGINE=Distributed(cluster, default, hits)").AutoMigrate(&User{}) // Insert db.Create(&user) // Select db.Find(&user, "id = ?", 10) // Batch Insert var users = []User{user1, user2, user3} db.Create(&users) } ``` -------------------------------- ### Install GORM CLI Source: https://github.com/go-gorm/gorm.io/blob/master/pages/cli/index.md Installs the GORM CLI tool globally using the Go toolchain. ```bash go install gorm.io/cli/gorm@latest ```