### Install GORM CLI Source: https://github.com/go-gorm/cli/blob/master/README.md Install the GORM CLI tool using the go install command. ```bash go install gorm.io/cli/gorm@latest ``` -------------------------------- ### Example usage of template-based queries Source: https://github.com/go-gorm/cli/blob/master/README.md Demonstrates how to call generated methods from a template-based query interface. Context is automatically injected if not provided. ```go // SQL: SELECT * FROM users WHERE id=123 user, err := generated.Query[User](db).GetByID(ctx, 123) // SQL: SELECT * FROM users WHERE name="jinzhu" AND age=25 (appended to current builder) users, err := generated.Query[User](db).FilterByNameAndAge("jinzhu", 25).Find(ctx) // SQL UPDATE users SET name="jinzhu", age=20, is_adult=1 WHERE id=1 err := generated.Query[User](db).UpdateUser(ctx, User{Name: "jinzhu", Age: 20}, 1) ``` -------------------------------- ### Check GORM CLI Version Source: https://context7.com/go-gorm/cli/llms.txt Print the current version of the gorm-cli tool. This command helps verify the installed version. ```bash gorm version # Output: gorm-cli version v0.2.3 ``` -------------------------------- ### Combined Filtering, Ordering, and Pagination with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Execute complex queries by combining filtering conditions, ordering, and pagination. This example filters by age and adult status, then orders by name and applies a limit. ```go users, _ = gorm.G[models.User](db). Where(generated.User.Age.Gte(18)). Where(generated.User.IsAdult.Eq(true)). Order(generated.User.Name.Asc()). Limit(50). Find(ctx) ``` -------------------------------- ### Custom JSON Field Helper in Go GORM Source: https://context7.com/go-gorm/cli/llms.txt This example demonstrates creating a custom field helper for JSON columns to handle database-specific SQL generation for JSON operations. It includes methods for equality checks and provides examples for MySQL, SQLite, and PostgreSQL. ```go package models import ( "encoding/json" "gorm.io/gorm" "gorm.io/gorm/clause" ) // JSON is a custom field helper for JSON columns with database-specific SQL generation type JSON struct { column clause.Column } func (j JSON) WithColumn(name string) JSON { c := j.column c.Name = name return JSON{column: c} } // Equal builds a JSON equality expression with database-specific syntax func (j JSON) Equal(path string, value any) clause.Expression { return jsonEqualExpr{col: j.column, path: path, val: value} } type jsonEqualExpr struct { col clause.Column path string val any } func (e jsonEqualExpr) Build(builder clause.Builder) { if stmt, ok := builder.(*gorm.Statement); ok { switch stmt.Dialector.Name() { case "mysql": v, _ := json.Marshal(e.val) clause.Expr{ SQL: "JSON_EXTRACT(?, ?) = CAST(? AS JSON)", Vars: []any{e.col, e.path, string(v)}, }.Build(builder) case "sqlite": clause.Expr{ SQL: "json_valid(?) AND json_extract(?, ?) = ?", Vars: []any{e.col, e.col, e.path, e.val}, }.Build(builder) default: // PostgreSQL clause.Expr{ SQL: "jsonb_extract_path_text(?, ?) = ?", Vars: []any{e.col, e.path[2:], e.val}, }.Build(builder) } } } // Usage example: // users, _ := gorm.G[models.User](db). // Where(generated.User.Profile.Equal("$.vip", true)). // Find(ctx) // // MySQL: JSON_EXTRACT(`profile`, "$.vip") = CAST("true" AS JSON) // SQLite: json_valid(`profile`) AND json_extract(`profile`, "$.vip") = 1 // Postgres: jsonb_extract_path_text(`profile`, "vip") = "true" ``` -------------------------------- ### Template DSL: Iteration for dynamic conditions Source: https://github.com/go-gorm/cli/blob/master/README.md Example of using the `{{for}}` directive to iterate over a collection, creating dynamic conditions within the WHERE clause. This is useful for searching with multiple tags. ```sql -- Iteration SELECT * FROM @@table {{where}} {{for _, tag := range tags}} {{if tag != ""}} tags LIKE concat('%',@tag,'%') OR {{end}} {{end}} {{end}} ``` -------------------------------- ### Template DSL: Safe parameter binding Source: https://github.com/go-gorm/cli/blob/master/README.md Example of safe parameter binding in template-based queries, ensuring that values are correctly escaped and preventing SQL injection. ```sql -- Safe parameter binding SELECT * FROM @@table WHERE id=@id AND status=@status ``` -------------------------------- ### Filter on the child before acting on associations Source: https://github.com/go-gorm/cli/blob/master/README.md Filter related child records before performing an action like `Delete`. This example removes pets named 'old' associated with a user. ```go gorm.G[User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Pets.Where(generated.Pet.Name.Eq("old")).Delete()). Update(ctx) ``` -------------------------------- ### Batch Create Pets for User with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Efficiently create multiple pets for a user in a single operation using batch creation. Ensure pets are defined as a slice of models.Pet. ```go pets := []models.Pet{ {Name: "rex"}, {Name: "spot"}, {Name: "buddy"}, } gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Pets.CreateInBatch(pets)). Update(ctx) ``` -------------------------------- ### Batch link two pets to an existing user Source: https://github.com/go-gorm/cli/blob/master/README.md Use `CreateInBatch` to efficiently link multiple related records to a parent. This is useful for creating and associating several items at once. ```go gorm.G[User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Pets.CreateInBatch([]models.Pet{{Name: "rex"}, {Name: "spot"}})). Update(ctx) ``` -------------------------------- ### Paginate Results with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Implement pagination by specifying a limit and offset for the query results. Ensures results are ordered consistently before applying pagination. ```go users, _ = gorm.G[models.User](db). Order(generated.User.ID.Asc()). Limit(10). Offset(20). Find(ctx) ``` -------------------------------- ### Create with Field Setters Source: https://github.com/go-gorm/cli/blob/master/README.md Create new records using the Set method to specify field values, including zero-values. ```go // Create with Set(...) gorm.G[User](db). Set( generated.User.Name.Set("alice"), generated.User.Age.Set(0), generated.User.Status.Set("active"), ). Create(ctx) ``` -------------------------------- ### Create a pet for each matched user Source: https://github.com/go-gorm/cli/blob/master/README.md Use the `Set` and `Update` methods to create a new related row for each matched parent. Ensure the `generated.Pet.Name` is set before creating. ```go gorm.G[User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Pets.Create(generated.Pet.Name.Set("fido"))). Update(ctx) ``` -------------------------------- ### Batch Create Languages for User with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Add multiple language associations to a user by creating entries in the join table. Ensure languages are defined as a slice of models.Language. ```go languages := []models.Language{ {Code: "en", Name: "English"}, {Code: "es", Name: "Spanish"}, } gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Languages.CreateInBatch(languages)). Update(ctx) ``` -------------------------------- ### Create Single Pet for User with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Use generated field helpers to create a single pet associated with a user. Requires the user to exist. ```go gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Pets.Create( generated.Pet.Name.Set("fido"), )). Update(ctx) ``` -------------------------------- ### Standard API with Raw Conditions Source: https://github.com/go-gorm/cli/blob/master/README.md When using the Standard API ('--typed=false'), you can mix raw SQL conditions with generated typed helpers. ```go generated.Query[User](db). Where("name = ?", "jinzhu"). // raw condition Where(generated.User.Age.Gt(18)). // typed helper Find(ctx) ``` -------------------------------- ### Template DSL: Dynamic column binding Source: https://github.com/go-gorm/cli/blob/master/README.md Demonstrates dynamic column binding using `@@column`. This allows specifying columns at runtime within template-based SQL queries. ```sql -- Dynamic column binding SELECT * FROM @@table WHERE @@column=@value ``` -------------------------------- ### Define Go Query Interface with SQL Templates Source: https://context7.com/go-gorm/cli/llms.txt Define Go interfaces with SQL template comments to generate type-safe query methods. Ensure necessary types like User and Params are defined. ```go package models import ( "time" ) type Query[T any] interface { // SELECT * FROM @@table WHERE id=@id GetByID(id int) (T, error) // SELECT * FROM @@table WHERE @@column=@value FilterWithColumn(column string, value string) (T, error) // SELECT * FROM users // {{if user.ID > 0}} // WHERE id=@user.ID // {{else if user.Name != ""}} // WHERE name=@user.Name // {{end}} QueryWith(user User) (T, error) // UPDATE @@table // {{set}} // {{if user.Name != ""}} name=@user.Name, {{end}} // {{if user.Age > 0}} age=@user.Age, {{end}} // {{if user.Age >= 18}} is_adult=1 {{else}} is_adult=0 {{end}} // {{end}} // WHERE id=@id UpdateInfo(user User, id int) error // SELECT * FROM @@table // {{where}} // {{for _, user := range users}} // {{if user.Name != "" && user.Age > 0}} // (name = @user.Name AND age=@user.Age AND role LIKE concat("%",@user.Role,"%")) OR // {{end}} // {{end}} // {{end}} Filter(users []User) ([]T, error) // where("name=@params.Name AND age=@params.Age") FilterByNameAndAge(params Params) // SELECT * FROM @@table // {{where}} // {{if !start.IsZero()}} // created_at > @start // {{end}} // {{if !end.IsZero()}} // AND created_at < @end // {{end}} // {{end}} FilterWithTime(start, end time.Time) ([]T, error) } type Params struct { Name string Age int } ``` -------------------------------- ### Order by Ascending Creation Date with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Retrieve users ordered by their creation date in ascending order. Uses the generated field helper for CreatedAt. ```go users, _ := gorm.G[models.User](db). Order(generated.User.CreatedAt.Asc()). Find(ctx) ``` -------------------------------- ### Configure GORM CLI Generation Source: https://github.com/go-gorm/cli/blob/master/README.md Declare a package-level `genconfig.Config` to customize generation. Specify `OutPath`, `FieldTypeMap` for Go type to GORM kind mapping, `FieldNameMap` for `gen` tag mapping, and `IncludeInterfaces`/`IncludeStructs` for selective generation. ```go package examples import ( "database/sql" "gorm.io/cli/gorm/field" "gorm.io/cli/gorm/genconfig" ) var _ = genconfig.Config{ OutPath: "examples/output", FieldTypeMap: map[any]any{ sql.NullTime{}: field.Time{}, }, FieldNameMap: map[string]any{ "json": JSON{}, }, IncludeInterfaces: []any{"Query*", models.Query(nil)}, IncludeStructs: []any{"User", "Account*", models.User{}}, } ``` -------------------------------- ### Iteration for Bulk Conditions Source: https://context7.com/go-gorm/cli/llms.txt Illustrates using the {{for}} directive to iterate over a collection (e.g., tags) for building bulk conditions in a WHERE clause. ```sql -- Iteration for bulk conditions SELECT * FROM @@table {{where}} {{for _, tag := range tags}} {{if tag != ""}} tags LIKE concat('%',@tag,'%') OR {{end}} {{end}} {{end}} ``` -------------------------------- ### Define GORM Models Source: https://github.com/go-gorm/cli/blob/master/README.md Define your GORM models, including associations, in Go files. ```go // examples/models/user.go type User struct { gorm.Model Name string Age int Pets []Pet `gorm:"many2many:user_pets"` } type Pet struct { gorm.Model Name string } ``` -------------------------------- ### JSON Field Mapping Configuration Source: https://github.com/go-gorm/cli/blob/master/README.md Configure `genconfig.Config` to map the `json` tag to a custom `JSON` helper. This allows for database-specific JSON query generation. ```go package examples import "gorm.io/cli/gorm/genconfig" var _ = genconfig.Config{ OutPath: "examples/output", FieldNameMap: map[string]any{ "json": JSON{}, }, } ``` -------------------------------- ### Generate GORM Code (Standard) Source: https://context7.com/go-gorm/cli/llms.txt Generate standard API code, which is still generics-based but offers relaxed typing for increased flexibility. Specify input models and output directory. ```bash gorm gen -i ./models -o ./generated --typed=false ``` -------------------------------- ### Dynamic UPDATE with Conditional SET Clause Source: https://context7.com/go-gorm/cli/llms.txt Demonstrates how to construct a dynamic UPDATE statement with a conditional SET clause using {{set}} and {{if}} directives. ```sql -- Dynamic UPDATE with SET UPDATE @@table {{set}} {{if user.Name != ""}} name=@user.Name, {{end}} {{if user.Email != ""}} email=@user.Email {{end}} {{end}} WHERE id=@id ``` -------------------------------- ### Generate GORM CLI Code Source: https://github.com/go-gorm/cli/blob/master/README.md Generate code using the GORM CLI. Use '--typed=false' for the Standard API with relaxed typing. ```bash # Default: strictly typed generics API gorm gen -i ./examples -o ./generated # Standard API (still generics-based, relaxed typing for more flexibility) gorm gen -i ./examples -o ./generated --typed=false ``` -------------------------------- ### Select Specific Fields in Go GORM Source: https://context7.com/go-gorm/cli/llms.txt Use the `Select` method to specify which columns to retrieve in a query. This is useful for performance optimization or when only a subset of data is needed. Ensure the generated types match the selected fields. ```go package main import ( "context" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Select specific fields: SELECT id, name, age FROM users users, _ := gorm.G[models.User](db). Select(generated.User.ID, generated.User.Name, generated.User.Age). Find(ctx) ``` -------------------------------- ### Configure GORM Code Generation Source: https://context7.com/go-gorm/cli/llms.txt Configure code generation using `genconfig.Config` in your Go source package. This allows customization of output paths, type mappings, and inclusion/exclusion rules. ```go package models import ( "database/sql" "gorm.io/cli/gorm/field" "gorm.io/cli/gorm/genconfig" ) var _ = genconfig.Config{ // Override output directory OutPath: "generated/output", // Map Go types to field helper types FieldTypeMap: map[any]any{ sql.NullTime{}: field.Time{}, }, // Map gen tag names to field helper types FieldNameMap: map[string]any{ "date": field.Time{}, "json": JSON{}, // Custom JSON helper }, // Whitelist specific interfaces (supports patterns) IncludeInterfaces: []any{"Query*", "*Repo"}, // Blacklist specific interfaces ExcludeInterfaces: []any{Entity(nil)}, // Whitelist specific structs (supports patterns and type literals) IncludeStructs: []any{"User", "Account*", models.User{}}, // Blacklist specific structs ExcludeStructs: []any{BaseModel{}}, } ``` -------------------------------- ### Template DSL: Dynamic UPDATE statement Source: https://github.com/go-gorm/cli/blob/master/README.md Illustrates building a dynamic UPDATE statement using `{{set}}` and `{{if}}`. Fields are included in the SET clause only if their conditions are met. ```sql -- Dynamic UPDATE UPDATE @@table {{set}} {{if user.Name != ""}} name=@user.Name, {{end}} {{if user.Email != ""}} email=@user.Email {{end}} {{end}} WHERE id=@id ``` -------------------------------- ### Template DSL: Conditional WHERE clause Source: https://github.com/go-gorm/cli/blob/master/README.md Shows how to construct a conditional WHERE clause using `{{where}}` and `{{if}}` directives. Only specified conditions are included in the final SQL. ```sql -- Conditional WHERE SELECT * FROM @@table {{where}} {{if name != ""}} name=@name {{end}} {{if age > 0}} AND age=@age {{end}} {{end}} ``` -------------------------------- ### Define Query Interface Source: https://github.com/go-gorm/cli/blob/master/README.md Define a generic query interface with SQL template comments for generating type-safe methods. ```go // examples/query.go type Query[T any] interface { // SELECT * FROM @@table WHERE id=@id GetByID(id int) (T, error) } ``` -------------------------------- ### Create Single Language Association with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Add a single language association to a user by creating a join table entry. Specify language details directly. ```go gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Languages.Create( generated.Language.Code.Set("fr"), generated.Language.Name.Set("French"), )). Update(ctx) ``` -------------------------------- ### Define Custom JSON Field Helper Source: https://github.com/go-gorm/cli/blob/master/README.md Define a custom `JSON` field helper with `WithColumn` and `Equal` methods. The `Equal` method generates database-specific SQL expressions for JSON comparisons. ```go // JSON is a field helper for JSON columns that generates different SQL for different databases. type JSON struct{ column clause.Column } func (j JSON) WithColumn(name string) JSON { c := j.column c.Name = name return JSON{column: c} } // Equal builds an expression using database-specific JSON functions to compare func (j JSON) Equal(path string, value any) clause.Expression { return jsonEqualExpr{col: j.column, path: path, val: value} } type jsonEqualExpr struct { col clause.Column path string val any } func (e jsonEqualExpr) Build(builder clause.Builder) { if stmt, ok := builder.(*gorm.Statement); ok { switch stmt.Dialector.Name() { case "mysql": v, _ := json.Marshal(e.val) clause.Expr{SQL: "JSON_EXTRACT(?, ?) = CAST(? AS JSON)", Vars: []any{e.col, e.path, string(v)}}.Build(builder) case "sqlite": clause.Expr{SQL: "json_valid(?) AND json_extract(?, ?) = ?", Vars: []any{e.col, e.col, e.path, e.val}}.Build(builder) default: clause.Expr{SQL: "jsonb_extract_path_text(?, ?) = ?", Vars: []any{e.col, e.path[2:], e.val}}.Build(builder) } } } ``` -------------------------------- ### Order by Descending Age with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Retrieve users ordered by age in descending order. Uses the generated field helper for Age. ```go users, _ = gorm.G[models.User](db). Order(generated.User.Age.Desc()). Find(ctx) ``` -------------------------------- ### Generate GORM Code (Strict) Source: https://context7.com/go-gorm/cli/llms.txt Generate strictly typed generics API code from Go interfaces and model structs. Specify input models and output directory. ```bash gorm gen -i ./models -o ./generated ``` -------------------------------- ### Field Helpers Usage Source: https://github.com/go-gorm/cli/blob/master/README.md Utilize generated field helpers for filtering, updating, and creating records. ```go // Field helpers // SELECT * FROM users WHERE age>18 users, _ := gorm.G[User](db).Where(generated.User.Age.Gt(18)).Find(ctx) // Association helpers: create a user with a pet gorm.G[User](db). Set( generated.User.Name.Set("alice"), generated.User.Pets.Create(generated.Pet.Name.Set("fido")), ). Create(ctx) ``` -------------------------------- ### Field Predicates Source: https://github.com/go-gorm/cli/blob/master/README.md Use generated field predicates for common query conditions like equality, pattern matching, ranges, and null checks. ```go // Predicates generated.User.ID.Eq(1) // id = 1 generated.User.Name.Like("%jinzhu%") // name LIKE '%jinzhu%' generated.User.Age.Between(18, 65) // age BETWEEN 18 AND 65 generated.User.Score.IsNull() // score IS NULL (e.g., sql.NullInt64) ``` -------------------------------- ### Field Updates with Expressions Source: https://github.com/go-gorm/cli/blob/master/README.md Perform updates using generated field setters, supporting expressions and zero-value assignments. Use SetExpr for custom SQL expressions. ```go // Updates (supports expressions and zero-values) gorm.G[User](db). Where(generated.User.Name.Eq("alice")), Set( generated.User.Name.Set("jinzhu"), generated.User.IsAdult.Set(false), generated.User.Score.Set(sql.NullInt64{}), generated.User.Count.Incr(1), generated.User.Age.SetExpr(clause.Expr{ SQL: "GREATEST(?, ?)", Vars: []any{clause.Column{Name: "age"}, 18}, }), ). Update(ctx) ``` -------------------------------- ### Type-Safe Query Usage Source: https://github.com/go-gorm/cli/blob/master/README.md Use the generated type-safe query API to fetch data. ```go // Type-safe query // SELECT * FROM users WHERE id=123 u, err := generated.Query[User](db).GetByID(ctx, 123) ``` -------------------------------- ### Go GORM String Field Operations Source: https://context7.com/go-gorm/cli/llms.txt Use generated string field helpers for text comparisons and manipulations. Ensure necessary imports are present. ```go package main import ( "context" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Equality: WHERE name = 'jinzhu' users, _ := gorm.G[models.User](db).Where(generated.User.Name.Eq("jinzhu")).Find(ctx) // Not equal: WHERE name != 'admin' users, _ = gorm.G[models.User](db).Where(generated.User.Name.Neq("admin")).Find(ctx) // LIKE pattern: WHERE name LIKE '%jinzhu%' users, _ = gorm.G[models.User](db).Where(generated.User.Name.Like("%jinzhu%")).Find(ctx) // NOT LIKE: WHERE name NOT LIKE '%test%' users, _ = gorm.G[models.User](db).Where(generated.User.Name.NotLike("%test%")).Find(ctx) // Case-insensitive LIKE (PostgreSQL): WHERE name ILIKE '%Jin%' users, _ = gorm.G[models.User](db).Where(generated.User.Name.ILike("%Jin%")).Find(ctx) // Regexp matching: WHERE name REGEXP '^[A-Z]' users, _ = gorm.G[models.User](db).Where(generated.User.Name.Regexp("^[A-Z]")).Find(ctx) // IN clause: WHERE role IN ('admin', 'moderator', 'user') users, _ = gorm.G[models.User](db).Where(generated.User.Role.In("admin", "moderator", "user")).Find(ctx) // String comparison (alphabetical): WHERE name > 'A' users, _ = gorm.G[models.User](db).Where(generated.User.Name.Gt("A")).Find(ctx) // Set value: SET name = 'new_name' gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Name.Set("new_name")). Update(ctx) // Concatenate: SET name = CONCAT(name, '_suffix') gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Name.Concat("_suffix")). Update(ctx) // Uppercase: SET name = UPPER(name) gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Name.Upper()). Update(ctx) // Lowercase: SET name = LOWER(name) gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Name.Lower()). Update(ctx) // Trim whitespace: SET name = TRIM(name) gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Name.Trim()). Update(ctx) // Substring: SET name = SUBSTRING(name, 1, 10) gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Name.Substring(1, 10)). Update(ctx) } ``` -------------------------------- ### Create Records with Explicit Field Values using Set in Go GORM Source: https://context7.com/go-gorm/cli/llms.txt The `Set` API allows explicit assignment of field values during record creation. This is crucial for setting default values, zero values (especially for booleans), or NULL values. Use `SetExpr` for custom SQL expressions. ```go package main import ( "context" "database/sql" "your-project/generated" "your-project/models" "gorm.io/gorm" "gorm.io/gorm/clause" ) func main() { ctx := context.Background() var db *gorm.DB // Create with explicit field values gorm.G[models.User](db). Set( generated.User.Name.Set("alice"), generated.User.Age.Set(25), generated.User.Role.Set("admin"), generated.User.IsAdult.Set(true), ). Create(ctx) // Create with zero values explicitly (important for booleans) gorm.G[models.User](db). Set( generated.User.Name.Set("bob"), generated.User.Age.Set(0), // Explicitly set to 0 generated.User.IsAdult.Set(false), // Explicitly set to false ). Create(ctx) // Create with NULL value gorm.G[models.User](db). Set( generated.User.Name.Set("charlie"), generated.User.Score.Set(sql.NullInt64{}), // NULL ). Create(ctx) // Create with custom expression gorm.G[models.User](db). Set( generated.User.Name.Set("dave"), generated.User.Age.SetExpr(clause.Expr{ SQL: "GREATEST(?, ?)", Vars: []any{clause.Column{Name: "default_age"}, 18}, }), ). Create(ctx) ``` -------------------------------- ### Add Friends (Self-Referential Many-to-Many) with GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Manage self-referential many-to-many relationships, such as adding friends to a user. This creates entries in the join table. ```go friends := []models.User{ {Name: "Bob"}, {Name: "Charlie"}, } gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Friends.CreateInBatch(friends)). Update(ctx) ``` -------------------------------- ### Define GORM Models Source: https://context7.com/go-gorm/cli/llms.txt Define GORM models with associations and custom field tags for code generation. Includes basic types, custom types, and various GORM association types. ```go package models import ( "database/sql" "time" "gorm.io/gorm" ) type User struct { gorm.Model Name string Age int Birthday *time.Time Score sql.NullInt64 LastLogin sql.NullTime Account Account Pets []*Pet Toys []Toy `gorm:"polymorphic:Owner"` CompanyID *int Company Company ManagerID *uint Manager *User Team []User `gorm:"foreignkey:ManagerID"` Languages []Language `gorm:"many2many:UserSpeak"` Friends []*User `gorm:"many2many:user_friends"` Role string IsAdult bool `gorm:"column:is_adult"` Profile string `gen:"json"` // Custom field helper via gen tag } type Account struct { gorm.Model UserID sql.NullInt64 Number string RewardPoints sql.NullInt64 } type Pet struct { gorm.Model UserID *uint Name string Toy Toy `gorm:"polymorphic:Owner;"` } type Company struct { ID int Name string } type Language struct { Code string `gorm:"primarykey"` Name string } ``` -------------------------------- ### Use Generated Query API for Type-Safe Database Operations Source: https://context7.com/go-gorm/cli/llms.txt Utilize the generated query functions with type-safe method calls for various database operations. Ensure the GORM database connection is initialized. ```go package main import ( "context" "time" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Initialize your GORM database connection // Type-safe query by ID // SQL: SELECT * FROM users WHERE id=123 user, err := generated.Query[models.User](db).GetByID(ctx, 123) // Dynamic column filtering // SQL: SELECT * FROM users WHERE email='test@example.com' user, err = generated.Query[models.User](db).FilterWithColumn(ctx, "email", "test@example.com") // Conditional query based on struct values // SQL: SELECT * FROM users WHERE name="jinzhu" user, err = generated.Query[models.User](db).QueryWith(ctx, models.User{Name: "jinzhu"}) // Conditional update with dynamic SET clause // SQL: UPDATE users SET name="jinzhu", age=20, is_adult=1 WHERE id=1 err = generated.Query[models.User](db).UpdateInfo(ctx, models.User{Name: "jinzhu", Age: 20}, 1) // Filter with time range // SQL: SELECT * FROM users WHERE created_at > '2024-01-01' AND created_at < '2024-12-31' start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) end := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC) users, err := generated.Query[models.User](db).FilterWithTime(ctx, start, end) // Chain conditions with builder pattern // SQL: SELECT * FROM users WHERE name="jinzhu" AND age=25 users, err = generated.Query[models.User](db). FilterByNameAndAge(ctx, generated.Params{Name: "jinzhu", Age: 25}). Find(ctx) } ``` -------------------------------- ### Use Custom JSON Helper in Queries Source: https://github.com/go-gorm/cli/blob/master/README.md Utilize the custom `JSON` helper in GORM queries by calling its `Equal` method. This generates database-specific SQL for JSON field comparisons. ```go // This will generate different SQL depending on the database: // MySQL: "JSON_EXTRACT(`profile`, ".$.vip") = CAST("true" AS JSON)" // SQLite: "json_valid(`profile`) AND json_extract(`profile`, ".$.vip") = 1" got, err := gorm.G[models.User](db). Where(generated.User.Profile.Equal("$.vip", true)).Take(ctx) ``` -------------------------------- ### Update Pets with Condition using GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Modify existing pets associated with a user based on specific conditions. This allows targeted updates to related records. ```go gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set( generated.User.Pets.Where(generated.Pet.Name.Eq("old_name")).Update( generated.Pet.Name.Set("new_name"), ), ). Update(ctx) ``` -------------------------------- ### Template-based query interface definition Source: https://github.com/go-gorm/cli/blob/master/README.md Define SQL queries with embedded templating using Go interfaces. Parameters are automatically bound, and implementations are generated to be type-safe. ```go type Query[T any] interface { // SELECT * FROM @@table WHERE id=@id GetByID(id int) (T, error) // SELECT * FROM @@table WHERE @@column=@value FilterWithColumn(column string, value string) (T, error) // SELECT * FROM @@table // {{where}} // {{if user.Name }} name=@user.Name {{end}} // {{if user.Age > 0}} AND age=@user.Age {{end}} // {{end}} SearchUsers(user User) ([]T, error) // UPDATE @@table // {{set}} // {{if user.Name != ""}} name=@user.Name, {{end}} // {{if user.Age > 0}} age=@user.Age, {{end}} // {{if user.Age >= 18}} is_adult=1 {{else}} is_adult=0 {{end}} // {{end}} // WHERE id=@id UpdateUser(user User, id int) error } ``` -------------------------------- ### Select Fields with Aliases in Go GORM Source: https://context7.com/go-gorm/cli/llms.txt Use the `Select` method with the `As` function to retrieve a field and assign it an alias in the result set. This is useful for renaming columns in your query output. Ensure the generated types match the selected fields. ```go package main import ( "context" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Select with alias: SELECT name AS user_name users, _ := gorm.G[models.User](db). Select(generated.User.Name.As("user_name")), Find(ctx) ``` -------------------------------- ### Go GORM Time Field Operations Source: https://context7.com/go-gorm/cli/llms.txt Use generated time field helpers for date/time comparisons and manipulations like equality, greater than, less than, between, NULL checks, adding/subtracting durations, and setting specific times. ```go package main import ( "context" "time" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB now := time.Now() // Equality: WHERE created_at = '2024-01-01' targetDate := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) users, _ := gorm.G[models.User](db).Where(generated.User.CreatedAt.Eq(targetDate)).Find(ctx) // Greater than: WHERE created_at > '2024-01-01' users, _ = gorm.G[models.User](db).Where(generated.User.CreatedAt.Gt(targetDate)).Find(ctx) // Less than: WHERE created_at < NOW() users, _ = gorm.G[models.User](db).Where(generated.User.CreatedAt.Lt(now)).Find(ctx) // Between: WHERE created_at BETWEEN '2024-01-01' AND '2024-12-31' startDate := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) endDate := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC) users, _ = gorm.G[models.User](db).Where(generated.User.CreatedAt.Between(startDate, endDate)).Find(ctx) // NULL check: WHERE birthday IS NULL users, _ = gorm.G[models.User](db).Where(generated.User.Birthday.IsNull()).Find(ctx) // Add duration: SET updated_at = DATE_ADD(updated_at, INTERVAL 86400 SECOND) gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.UpdatedAt.Add(24 * time.Hour)). Update(ctx) // Subtract duration: SET last_login = DATE_SUB(last_login, INTERVAL 3600 SECOND) gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.LastLogin.Sub(time.Hour)). Update(ctx) // Set to NOW(): SET updated_at = NOW() gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.UpdatedAt.Now()). Update(ctx) // Set specific value: SET birthday = '2000-01-15' birthday := time.Date(2000, 1, 15, 0, 0, 0, 0, time.UTC) gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Birthday.Set(birthday)). Update(ctx) } ``` -------------------------------- ### Declare JSON Tag on Model Source: https://github.com/go-gorm/cli/blob/master/README.md Tag a model field with `gen:"json"` to indicate that it should be handled by the custom JSON helper defined in `FieldNameMap`. ```go package models type User struct { // ... other fields ... // Tell the generator to use the custom JSON helper for this column Profile string `gen:"json"` } ``` -------------------------------- ### Distinct Fields in Go GORM Source: https://context7.com/go-gorm/cli/llms.txt Use the `Distinct` method to retrieve unique values for a specified column. This is equivalent to `SELECT DISTINCT column FROM table`. Ensure the generated types match the distinct fields. ```go package main import ( "context" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Distinct: SELECT DISTINCT role FROM users users, _ := gorm.G[models.User](db). Distinct(generated.User.Role). Find(ctx) ``` -------------------------------- ### Unlink All Pets using GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Remove all associations between a user and their pets without deleting the pet records themselves. This sets the foreign key to NULL. ```go gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Pets.Where().Unlink()). Update(ctx) ``` -------------------------------- ### Go GORM Boolean Field Operations Source: https://context7.com/go-gorm/cli/llms.txt Utilize generated boolean field helpers for logical comparisons and operations such as equality, NULL checks, NOT NULL checks, logical NOT, and XOR. ```go package main import ( "context" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Equality: WHERE is_adult = true users, _ := gorm.G[models.User](db).Where(generated.User.IsAdult.Eq(true)).Find(ctx) // Equality (false): WHERE is_adult = false users, _ = gorm.G[models.User](db).Where(generated.User.IsAdult.Eq(false)).Find(ctx) // NULL check: WHERE is_adult IS NULL users, _ = gorm.G[models.User](db).Where(generated.User.IsAdult.IsNull()).Find(ctx) // NOT NULL check: WHERE is_adult IS NOT NULL users, _ = gorm.G[models.User](db).Where(generated.User.IsAdult.IsNotNull()).Find(ctx) // Logical NOT: WHERE NOT is_adult users, _ = gorm.G[models.User](db).Where(generated.User.IsAdult.Not()).Find(ctx) // Logical XOR: WHERE is_adult XOR true users, _ = gorm.G[models.User](db).Where(generated.User.IsAdult.Xor(true)).Find(ctx) // Set boolean: SET is_adult = true gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.IsAdult.Set(true)). Update(ctx) // Set boolean to false: SET is_adult = false gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.IsAdult.Set(false)). Update(ctx) } ``` -------------------------------- ### Go GORM Number Field Operations Source: https://context7.com/go-gorm/cli/llms.txt Use generated number field helpers for type-safe numeric comparisons and updates. Ensure necessary imports are present. ```go package main import ( "context" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Equality: WHERE age = 25 users, _ := gorm.G[models.User](db).Where(generated.User.Age.Eq(25)).Find(ctx) // Greater than: WHERE age > 18 users, _ = gorm.G[models.User](db).Where(generated.User.Age.Gt(18)).Find(ctx) // Greater than or equal: WHERE age >= 21 users, _ = gorm.G[models.User](db).Where(generated.User.Age.Gte(21)).Find(ctx) // Less than: WHERE age < 65 users, _ = gorm.G[models.User](db).Where(generated.User.Age.Lt(65)).Find(ctx) // Between: WHERE age BETWEEN 18 AND 65 users, _ = gorm.G[models.User](db).Where(generated.User.Age.Between(18, 65)).Find(ctx) // IN clause: WHERE age IN (25, 30, 35) users, _ = gorm.G[models.User](db).Where(generated.User.Age.In(25, 30, 35)).Find(ctx) // NOT IN clause: WHERE age NOT IN (0, 999) users, _ = gorm.G[models.User](db).Where(generated.User.Age.NotIn(0, 999)).Find(ctx) // NULL check: WHERE score IS NULL users, _ = gorm.G[models.User](db).Where(generated.User.Score.IsNull()).Find(ctx) // NOT NULL check: WHERE score IS NOT NULL users, _ = gorm.G[models.User](db).Where(generated.User.Score.IsNotNull()).Find(ctx) // Increment: SET count = count + 1 gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Age.Incr(1)). Update(ctx) // Decrement: SET count = count - 1 gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Age.Decr(1)). Update(ctx) // Multiply: SET score = score * 2 gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Age.Mul(2)). Update(ctx) } ``` -------------------------------- ### Omit Specific Fields in Go GORM Source: https://context7.com/go-gorm/cli/llms.txt Use the `Omit` method to exclude specific columns from a query. This is helpful when you want to retrieve most fields but exclude sensitive or rarely used ones. Ensure the generated types match the omitted fields. ```go package main import ( "context" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Omit specific fields: SELECT all except score and profile users, _ := gorm.G[models.User](db). Omit(generated.User.Score, generated.User.Profile). Find(ctx) ``` -------------------------------- ### Go GORM Has One Association Operations Source: https://context7.com/go-gorm/cli/llms.txt Manage 'has-one' associations in Go GORM using generated field helpers for creating, updating, unlinking, and deleting associated records. ```go package main import ( "context" "your-project/generated" "your-project/models" "gorm.io/gorm" ) func main() { ctx := context.Background() var db *gorm.DB // Create user with associated account (has one) gorm.G[models.User](db). Set( generated.User.Name.Set("alice"), generated.User.Account.Create( generated.Account.Number.Set("ACC-001"), ), ). Create(ctx) // Update associated account for existing user gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set( generated.User.Account.Where(generated.Account.ID.Gt(0)).Update( generated.Account.Number.Set("ACC-002"), ), ). Update(ctx) // Unlink account (sets foreign key to NULL, keeps account record) gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Account.Where().Unlink()). Update(ctx) // Delete associated account gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set(generated.User.Account.Where().Delete()). Update(ctx) } ``` -------------------------------- ### Delete Specific Pets using GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Remove specific pets associated with a user by applying a condition. This operation deletes the related records. ```go gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set( generated.User.Pets.Where(generated.Pet.Name.Eq("old")).Delete(), ). Update(ctx) ``` -------------------------------- ### Delete Language Association using GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Delete a language association for a user, removing the join table row. This does not delete the language record itself. ```go gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set( generated.User.Languages.Where(generated.Language.Code.Eq("fr")).Delete(), ). Update(ctx) ``` -------------------------------- ### Unlink Specific Language using GORM CLI Source: https://context7.com/go-gorm/cli/llms.txt Remove a specific language association for a user by unlinking it. This only removes the join table row, not the language record. ```go gorm.G[models.User](db). Where(generated.User.ID.Eq(1)). Set( generated.User.Languages.Where(generated.Language.Code.Eq("es")).Unlink(), ). Update(ctx) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.