### Install builder package with go get Source: https://xorm.io/docs/chapter-13/readme Install the builder package using go get. Requires Go 1.8+. ```bash go get xorm.io/builder ``` -------------------------------- ### Install reverse tool with go get Source: https://xorm.io/docs/chapter-14/readme Install the reverse tool from source using Go's package manager. Requires CGO to be installed on the system. ```bash go get xorm.io/reverse ``` -------------------------------- ### Insert examples using builder.Insert Source: https://xorm.io/docs/chapter-13/readme Shows three ways to build INSERT statements: with values, from a SELECT, and with specific columns. The first example returns SQL and args; the others use ToBoundSQL. ```go sql, args, err := builder.Insert(Eq{"c": 1, "d": 2}).Into("table1").ToSQL() // INSERT INTO table1 SELECT * FROM table2 sql, err := builder.Insert().Into("table1").Select().From("table2").ToBoundSQL() // INSERT INTO table1 (a, b) SELECT b, c FROM table2 sql, err = builder.Insert("a, b").Into("table1").Select("b, c").From("table2").ToBoundSQL() ``` -------------------------------- ### Before event example Source: https://xorm.io/docs/chapter-12/readme Example of using the Before event with engine.Before(before).Insert(&obj). The before function is called before any process. ```go before := func(bean interface{}){ fmt.Println("before", bean) } engine.Before(before).Insert(&obj) ``` -------------------------------- ### After event example Source: https://xorm.io/docs/chapter-12/readme Example of using the After event with engine.After(after).Insert(&obj). The after function is called after any process. ```go after := func(bean interface{}){ fmt.Println("after", bean) } engine.After(after).Insert(&obj) ``` -------------------------------- ### LeastConnPolicy example Source: https://xorm.io/docs/chapter-01/3.policy Creates an engine group with the LeastConnPolicy, which selects the slave with the least number of connections. ```go import ( _ "github.com/lib/pq" "xorm.io/xorm" ) var eg *xorm.EngineGroup func main() { conns := []string{ "postgres://postgres:root@localhost:5432/test?sslmode=disable;", "postgres://postgres:root@localhost:5432/test1?sslmode=disable;", "postgres://postgres:root@localhost:5432/test2?sslmode=disable", } var err error eg, err = xorm.NewEngineGroup("postgres", conns, xorm.LeastConnPolicy()) } ``` -------------------------------- ### Select examples using builder.Select Source: https://xorm.io/docs/chapter-13/readme Shows various SELECT queries: simple, with joins, from subquery, from union, with order by, and with limit. Note that for LIMIT you must set a specific dialect. ```go // Simple Query sql, args, err := Select("c, d").From("table1").Where(Eq{"a": 1}).ToSQL() // With join sql, args, err = Select("c, d").From("table1").LeftJoin("table2", Eq{"table1.id": 1}.And(Lt{"table2.id": 3})). RightJoin("table3", "table2.id = table3.tid").Where(Eq{"a": 1}).ToSQL() // From sub query sql, args, err := Select("sub.id").From(Select("c").From("table1").Where(Eq{"a": 1}), "sub").Where(Eq{"b": 1}).ToSQL() // From union query sql, args, err = Select("sub.id").From( Select("id").From("table1").Where(Eq{"a": 1}).Union("all", Select("id").From("table1").Where(Eq{"a": 2})),"sub"). Where(Eq{"b": 1}).ToSQL() // With order by sql, args, err = Select("a", "b", "c").From("table1").Where(Eq{"f1": "v1", "f2": "v2"}). OrderBy("a ASC").ToSQL() // With limit. // Be careful! You should set up specific dialect for builder before performing a query with LIMIT sql, args, err = Dialect(MYSQL).Select("a", "b", "c").From("table1").OrderBy("a ASC"). Limit(5, 10).ToSQL() ``` -------------------------------- ### WeightRandomPolicy example Source: https://xorm.io/docs/chapter-01/3.policy Creates an engine group with the WeightRandomPolicy, which selects a slave randomly with weights. The weights are provided as a slice of integers, e.g., []int{2, 3}. ```go import ( _ "github.com/lib/pq" "xorm.io/xorm" ) var eg *xorm.EngineGroup func main() { conns := []string{ "postgres://postgres:root@localhost:5432/test?sslmode=disable;", "postgres://postgres:root@localhost:5432/test1?sslmode=disable;", "postgres://postgres:root@localhost:5432/test2?sslmode=disable", } var err error // set the weights eg, err = xorm.NewEngineGroup("postgres", conns, xorm.WeightRandomPolicy([]int{2, 3})) } ``` -------------------------------- ### RoundRobinPolicy example Source: https://xorm.io/docs/chapter-01/3.policy Creates an engine group with the RoundRobinPolicy, which selects slaves in a round-robin fashion. ```go import ( _ "github.com/lib/pq" "xorm.io/xorm" ) var eg *xorm.EngineGroup func main() { conns := []string{ "postgres://postgres:root@localhost:5432/test?sslmode=disable;", "postgres://postgres:root@localhost:5432/test1?sslmode=disable;", "postgres://postgres:root@localhost:5432/test2?sslmode=disable", } var err error eg, err = xorm.NewEngineGroup("postgres", conns, xorm.RoundRobinPolicy()) } ``` -------------------------------- ### WeightRoundRobinPolicy example Source: https://xorm.io/docs/chapter-01/3.policy Creates an engine group with the WeightRoundRobinPolicy, which selects slaves in a round-robin fashion with weights. The weights are provided as a slice of integers, e.g., []int{2, 3}. ```go import ( _ "github.com/lib/pq" "xorm.io/xorm" ) var eg *xorm.EngineGroup func main() { conns := []string{ "postgres://postgres:root@localhost:5432/test?sslmode=disable;", "postgres://postgres:root@localhost:5432/test1?sslmode=disable;", "postgres://postgres:root@localhost:5432/test2?sslmode=disable", } var err error // set the weights eg, err = xorm.NewEngineGroup("postgres", conns, xorm.WeightRoundRobinPolicy([]int{2, 3})) } ``` -------------------------------- ### Find with Where and Limit Source: https://xorm.io/docs/chapter-05/4.find Combines Find with Where and Limit to filter by condition and paginate. The example fetches users with id > 3, limit 10, offset 20. ```go var allusers []Userinfo err := engine.Where("id > ?", "3").Limit(10,20).Find(&allusers) //Get id>3 limit 10 offset 20 ``` -------------------------------- ### RandomPolicy example Source: https://xorm.io/docs/chapter-01/3.policy Creates an engine group with the RandomPolicy, which selects a slave randomly. Uses PostgreSQL connection strings. ```go import ( _ "github.com/lib/pq" "xorm.io/xorm" ) var eg *xorm.EngineGroup func main() { conns := []string{ "postgres://postgres:root@localhost:5432/test?sslmode=disable;", "postgres://postgres:root@localhost:5432/test1?sslmode=disable;", "postgres://postgres:root@localhost:5432/test2?sslmode=disable", } var err error eg, err = xorm.NewEngineGroup("postgres", conns, xorm.RandomPolicy()) } ``` -------------------------------- ### Set a simple file logger with engine.SetLogger Source: https://xorm.io/docs/chapter-01/readme Configures the engine to write logs to a file by creating a file and using log.NewSimpleLogger as the logger. The example shows error handling when creating the file. ```go f, err := os.Create("sql.log") if err != nil { println(err.Error()) return } engine.SetLogger(log.NewSimpleLogger(f)) ``` -------------------------------- ### Basic Find into slice and map Source: https://xorm.io/docs/chapter-05/4.find Fetches all records into a slice of structs or a map keyed by int64. The map example uses the primary key as the map key. ```go var everyone []Userinfo err := engine.Find(&everyone) users := make(map[int64]Userinfo) err := engine.Find(&users) ``` -------------------------------- ### Get one record by ID or field Source: https://xorm.io/docs/chapter-05/3.get Fetches a single record by primary key or by a unique field value. The first example uses the ID field directly or the ID() method, the second uses a name field. Returns a boolean 'has' and an error. ```go var user = User{ID:27} has, err := engine.Get(&user) // or has, err := engine.ID(27).Get(&user) var user = User{Name:"xlw"} has, err := engine.Get(&user) ``` -------------------------------- ### Select - Specify select part Source: https://xorm.io/docs/chapter-05/1.conditions Specifies the select part when using Find, Iterate, or Get. ```go engine.Select("a.*, (select name from b limit 1) as name").Find(&beans) ``` ```go engine.Select("a.*, (select name from b limit 1) as name").Get(&bean) ``` -------------------------------- ### GroupPolicy interface example Source: https://xorm.io/docs/chapter-01/3.policy Defines the GroupPolicy interface for implementing a custom load balance policy. The Slave method returns an *Engine based on the *EngineGroup. ```go type GroupPolicy interface { Slave(*EngineGroup) *Engine } ``` -------------------------------- ### Execute SQL query with engine.Query Source: https://xorm.io/docs/chapter-08/readme Use engine.Query to execute a SELECT SQL statement. It returns results and an error. The example shows a query on the userinfo table. ```go sql := "select * from userinfo" results, err := engine.Query(sql) ``` -------------------------------- ### Find with struct query Source: https://xorm.io/docs/chapter-05/4.find Uses a struct as a query condition to filter results. The example fetches all users with Name="xlw", limit 10, offset 0. ```go var tenusers []Userinfo err := engine.Limit(10).Find(&tenusers, &Userinfo{Name:"xlw"}) //Get All Name="xlw" limit 10 offset 0 ``` -------------------------------- ### Soft delete behavior with Delete() and Get() Source: https://xorm.io/docs/chapter-07/1.deleted Demonstrates that calling `Delete()` on a record with a `deleted` tag updates the `deleted_at` field instead of removing the row. Subsequent `Get()` calls return `false, nil`, and repeated `Delete()` calls return `0, nil`. ```go var user User engine.ID(1).Get(&user) // SELECT * FROM user WHERE id = ? engine.ID(1).Delete(&user) // UPDATE user SET ..., deleted_at = ? WHERE id = ? engine.ID(1).Get(&user) // Call Get again, this time it will return false, nil engine.ID(1).Delete(&user) // Call delete again, it will return 0, nil ``` -------------------------------- ### Find with Cols to select specific columns Source: https://xorm.io/docs/chapter-05/4.find Uses the Cols function to select only specified columns. The example fetches only the id and name columns. ```go var tenusers []Userinfo err := engine.Cols("id", "name").Find(&tenusers) //Find only id and name ``` -------------------------------- ### NoAutoCondition example Source: https://xorm.io/docs/chapter-05/2.overrides Shows the difference between default behavior and using NoAutoCondition. The first query automatically adds the bean's ID condition, while the second disables that automatic condition. ```go engine.Where("name = ?", "lunny").Get(&User{ID:1}) // SELECT * FROM user where name='lunny' AND id = 1 LIMIT 1 engine.Where("name = ?", "lunny").NoAutoCondition().Get(&User{ID:1}) // SELECT * FROM user where name='lunny' LIMIT 1 ``` -------------------------------- ### Perform optimistic lock update Source: https://xorm.io/docs/chapter-06/1.lock The version starts at 1 upon insertion. Ensure the original version value is present when calling Update to trigger the optimistic lock check. ```go var user User engine.ID(1).Get(&user) // SELECT * FROM user WHERE id = ? engine.ID(1).Update(&user) // UPDATE user SET ..., version = version + 1 WHERE id = ? AND version = ? ``` -------------------------------- ### Find single column into slice of ints Source: https://xorm.io/docs/chapter-05/4.find Fetches a single column into a slice of int64 using Table and Cols. The example retrieves all ids from the user table. ```go var ints []int64 err := engine.Table("user").Cols("id").Find(&ints) ``` -------------------------------- ### Insert record with created tag Source: https://xorm.io/docs/chapter-04/1.created When calling `Insert()` or `InsertOne()`, the `CreatedAt` field is automatically filled with `time.Now()` (or `time.Now().Unix()` for integer fields). The example shows inserting a user and the resulting SQL comment. ```go var user User engine.Insert(&user) // INSERT user (created...) VALUES (?...) ``` -------------------------------- ### Retrieve and permanently delete with Unscoped() Source: https://xorm.io/docs/chapter-07/1.deleted Use `Unscoped()` to bypass soft delete and retrieve a soft-deleted record with `Get()` (returns `true, nil`) or permanently delete it with `Delete()`. ```go var user User engine.ID(1).Unscoped().Get(&user) // Then you will return true, nil engine.ID(1).Unscoped().Delete(&user) // Then this record will be really deleted ``` -------------------------------- ### Find with In function Source: https://xorm.io/docs/chapter-05/4.find Uses the In function to filter records where the specified column value is in a given list. The example fetches all users with id in (1, 3, 5). ```go var tenusers []Userinfo err := engine.In("id", 1, 3, 5).Find(&tenusers) //Get All id in (1, 3, 5) ``` -------------------------------- ### Clear cache after Exec with engine.ClearCache Source: https://xorm.io/docs/chapter-11/readme Shows how to clear the cache after using the Exec method. When using Exec, you should clear the cache to avoid stale data. The example updates a user record and then clears the cache for the User type. ```go engine.Exec("update user set name = ? where id = ?", "xlw", 1) engine.ClearCache(new(User)) ``` -------------------------------- ### Sum method: sum a column with condition Source: https://xorm.io/docs/chapter-05/9.sums Use the Sum method to calculate the sum of a column (e.g., "money") with a SQL condition. The result is returned as a float64. The example defines a SumStruct with Id, Money, and Rate fields and uses engine.Where("id >?", 1) to filter rows. ```go type SumStruct struct { Id int64 Money int Rate float32 } ss := new(SumStruct) var err error var total float64 total, err = engine.Where("id >?", 1).Sum(ss, "money") fmt.Printf("money is %d", int(total)) ``` -------------------------------- ### Sums method: sum multiple columns with condition Source: https://xorm.io/docs/chapter-05/9.sums Use the Sums method to calculate the sum of multiple columns (e.g., "money" and "rate") with a SQL condition. The results are returned as a slice of float64. The example uses engine.Where("id >?", 1) to filter rows. ```go ss := new(SumStruct) var err error var totals []float64 totals, err = engine.Where("id >?", 1).Sums(ss, "money", "rate") fmt.Printf("money is %d, rate is %.2f", int(total[0]), total[1]) ``` -------------------------------- ### SumInt method: sum an integer column with condition Source: https://xorm.io/docs/chapter-05/9.sums Use the SumInt method to calculate the sum of an integer column (e.g., "money") with a SQL condition. The result is returned as an int64. The example defines a SumStruct and uses engine.Where("id >?", 1) to filter rows. ```go type SumStruct struct { Id int64 Money int Rate float32 } ss := new(SumStruct) total, err:= engine.Where("id >?", 1).SumInt(ss, "money") fmt.Printf("money is %d", total) ``` -------------------------------- ### Set xorm time zone with engine.TZLocation Source: https://xorm.io/docs/chapter-04/1.created Change the time zone used by xorm for the `created` tag. By default, xorm uses the local time zone; setting `engine.TZLocation` overrides it. The example loads the Asia/Shanghai location. ```go engine.TZLocation, _ = time.LoadLocation("Asia/Shanghai") ``` -------------------------------- ### SumsInt method: sum multiple integer columns with condition Source: https://xorm.io/docs/chapter-05/9.sums Use the SumsInt method to calculate the sum of multiple integer columns (e.g., "money") with a SQL condition. The results are returned as a slice of int64. The example uses engine.Where("id >?", 1) to filter rows. ```go ss := new(SumStruct) var err error var totals []int64 totals, err = engine.Where("id >?", 1).SumsInt(ss, "money") fmt.Printf("money is %d", total[0]) ``` -------------------------------- ### Log to syslog with engine.SetLogger Source: https://xorm.io/docs/chapter-01/readme Sets up logging to syslog using the syslog package. Creates a syslog writer with LOG_DEBUG priority and a tag, then wraps it in a simple logger with ShowSQL enabled before assigning it to the engine. ```go logWriter, err := syslog.New(syslog.LOG_DEBUG, "rest-xorm-example") if err != nil { log.Fatalf("Fail to create xorm system logger: %v\n", err) } logger := log.NewSimpleLogger(logWriter) logger.ShowSQL(true) engine.SetLogger(logger) ``` -------------------------------- ### Create EngineGroup with connection strings Source: https://xorm.io/docs/chapter-01/2.engine_group Initializes an EngineGroup by passing a driver name and a slice of connection strings, where the first string is treated as the master. ```go import ( _ "github.com/lib/pq" "xorm.io/xorm" ) var eg *xorm.EngineGroup func main() { conns := []string{ "postgres://postgres:root@localhost:5432/test?sslmode=disable;", // first one is master "postgres://postgres:root@localhost:5432/test1?sslmode=disable;", // slave "postgres://postgres:root@localhost:5432/test2?sslmode=disable", // slave } var err error eg, err = xorm.NewEngineGroup("postgres", conns) } ``` -------------------------------- ### Transaction with session.Begin() and session.Commit() Source: https://xorm.io/docs/chapter-10/readme Use this snippet to wrap multiple database operations in a transaction. Create a session with engine.NewSession(), call session.Begin() before any action, and session.Commit() after all actions. Remember to defer session.Close() and call session.Rollback() on any error. ```go session := engine.NewSession() defer session.Close() // add Begin() before any action err := session.Begin() user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()} _, err = session.Insert(&user1) if err != nil { session.Rollback() return } user2 := Userinfo{Username: "yyy"} _, err = session.Where("id = ?", 2).Update(&user2) if err != nil { session.Rollback() return } _, err = session.Exec("delete from userinfo where username = ?", user2.Username) if err != nil { session.Rollback() return } // add Commit() after all actions err = session.Commit() if err != nil { return } ``` -------------------------------- ### Create multiple SQLite engines with xorm.NewEngine Source: https://xorm.io/docs/chapter-01/readme Creates ten SQLite engines in a loop using the mattn/go-sqlite3 driver. Each engine connects to a separate database file named test0.db through test9.db. The engines are stored in a slice. ```go import ( _ "github.com/mattn/go-sqlite3" "xorm.io/xorm" ) var engines []*xorm.Engine func main() { for i:=0; i < 10; i++ { engine, err := xorm.NewEngine("sqlite3", fmt.Sprintf("./test%d.db", i)) engines = append(engines, engine) } } ``` -------------------------------- ### Create a MySQL engine with xorm.NewEngine Source: https://xorm.io/docs/chapter-01/readme Creates a single XORM engine for a MySQL database using the go-sql-driver/mysql driver. The connection string follows the format used by sql.Open. The engine is stored in a package-level variable for later use. ```go import ( _ "github.com/go-sql-driver/mysql" "xorm.io/xorm" ) var engine *xorm.Engine func main() { var err error engine, err = xorm.NewEngine("mysql", "root:123@/test?charset=utf8") } ``` -------------------------------- ### Implement the Conversion interface Source: https://xorm.io/docs/chapter-02/4.columns Define custom mapping rules between struct fields and database data by implementing the Conversion interface. ```go type Conversion interface { FromDB([]byte) error ToDB() ([]byte, error) } ``` -------------------------------- ### Create EngineGroup with Engine instances Source: https://xorm.io/docs/chapter-01/2.engine_group Initializes an EngineGroup by explicitly creating master and slave Engine instances first. ```go import ( _ "github.com/lib/pq" "xorm.io/xorm" ) var eg *xorm.EngineGroup func main() { var err error master, err := xorm.NewEngine("postgres", "postgres://postgres:root@localhost:5432/test?sslmode=disable") if err != nil { return } slave1, err := xorm.NewEngine("postgres", "postgres://postgres:root@localhost:5432/test1?sslmode=disable") if err != nil { return } slave2, err := xorm.NewEngine("postgres", "postgres://postgres:root@localhost:5432/test2?sslmode=disable") if err != nil { return } slaves := []*xorm.Engine{slave1, slave2} eg, err = xorm.NewEngineGroup(master, slaves) } ``` -------------------------------- ### AllCols - Query or update all columns Source: https://xorm.io/docs/chapter-05/1.conditions Queries or updates all columns. ```go engine.AllCols().ID(1).Update(&user) // UPDATE user SET name = ?, age =?, gender =? WHERE id = 1 ``` -------------------------------- ### Define User struct with version tag Source: https://xorm.io/docs/chapter-06/1.lock Add the `xorm:"version"` tag to an integer field in your struct to enable optimistic locking. ```go type User struct { Id int64 Name string Version int `xorm:"version"` } ``` -------------------------------- ### And: Combine conditions with AND Source: https://xorm.io/docs/chapter-13/readme Connects one or more conditions using AND. ```go import . "xorm.io/builder" sql, args, _ := ToSQL(And(Eq{"a":1}, Like{"b", "c"}, Neq{"d", 2})) // a=? AND b LIKE ? AND d<>? [1, %c%, 2] ``` -------------------------------- ### Query with composite primary key Source: https://xorm.io/docs/chapter-15/readme Use the xorm.PK type to specify multiple primary key values in the ID method. ```go engine.ID(xorm.PK{1, 2}) ``` -------------------------------- ### Execute raw SQL for complex joins Source: https://xorm.io/docs/chapter-15/readme Use the SQL method for complex join statements that are difficult to express with the Join builder. ```go err := engine.SQL("select * from userinfo, userdetail where userinfo.detail_id = userdetail.id").Find(&users) //assert(User.Userinfo.Id != 0 && User.Userdetail.Id != 0) ``` -------------------------------- ### Query with SQL function Source: https://xorm.io/docs/chapter-05/5.join Alternative approach using raw SQL to query joined data. ```go var users []UserGroup err := engine.SQL("select user.*, group.name from user, group where user.group_id = group.id").Find(&users) ``` -------------------------------- ### Define Group and User structs Source: https://xorm.io/docs/chapter-05/5.join Basic struct definitions for the Group and User tables. ```go type Group struct { ID int64 Name string } ``` ```go type User struct { ID int64 Name string GroupId int64 `xorm:"index"` } ``` -------------------------------- ### Query with multiple composite structs Source: https://xorm.io/docs/chapter-05/5.join Compositing multiple structs to retrieve fields from both User and Group tables. ```go type UserGroup struct { User `xorm:"extends"` Group `xorm:"extends"` } func (UserGroup) TableName() string { return "user" } var users []UserGroup err := engine.Join("INNER", "group", "group.id = user.group_id").Find(&users) ``` -------------------------------- ### Query with conditions Source: https://xorm.io/docs/chapter-05/5.join Applying Where clauses and additional conditions to a join query. ```go engine.Table("user").Join("INNER", "group", "group.id = user.group_id"). Join("INNER", "type", "type.id = user.type_id"). Where("user.name like ?", "%"+name+"%").Find(&users, &User{Name:name}) ``` -------------------------------- ### Execute SQL update command Source: https://xorm.io/docs/chapter-09/readme Use the Exec method to perform SQL operations like update, insert, or delete. The method returns the result and an error. ```go sql := "update userinfo set username=? where id=?" res, err := engine.Exec(sql, "xiaolun", 1) ``` -------------------------------- ### Gt, Gte, Lt, Lte: Comparison conditions Source: https://xorm.io/docs/chapter-13/readme Conditions for greater than, greater than or equal, less than, and less than or equal. Supports chaining with And and Or. ```go import . "xorm.io/builder" sql, args, _ := ToSQL(Gt{"a", 1}.And(Gte{"b", 2})) // a>? AND b>=? [1, 2] sql, args, _ := ToSQL(Lt{"a", 1}.Or(Lte{"b", 2})) // a? [1, %c%, 2] sql, args, _ := ToSQL(Or(Eq{"a":1}, And(Like{"b", "c"}, Neq{"d", 2}))) // a=? OR (b LIKE ? AND d<>?) [1, %c%, 2] ``` -------------------------------- ### Check existence with Table method Source: https://xorm.io/docs/chapter-05/10.exist Checks if any record exists in the specified table. ```go has, err = testEngine.Table("record_exist").Exist() // SELECT * FROM record_exist LIMIT 1 ``` -------------------------------- ### Union: Combine SELECT queries with builder.Union Source: https://xorm.io/docs/chapter-13/readme Combines multiple SELECT queries using UNION ALL, UNION DISTINCT, and plain UNION. The empty string for the first Union call results in a plain UNION. ```go sql, args, err := Select("*").From("a").Where(Eq{"status": "1"}). Union("all", Select("*").From("a").Where(Eq{"status": "2"})). Union("distinct", Select("*").From("a").Where(Eq{"status": "3"})). Union("", Select("*").From("a").Where(Eq{"status": "4"})). ToSQL() ``` -------------------------------- ### Configure PrefixMapper for Table Naming Source: https://xorm.io/docs/chapter-02/2.prefix Uses NewPrefixMapper to prepend a string to table names, causing the User struct to map to prefix_user instead of user. ```go tbMapper := names.NewPrefixMapper(names.SnakeMapper{}, "prefix_") engine.SetTableMapper(tbMapper) ``` -------------------------------- ### And - Conditional AND Source: https://xorm.io/docs/chapter-05/1.conditions Adds a conditional AND to the query. ```go engine.Where(...).And(...).Get(&order) ``` -------------------------------- ### Exists and NotExists: EXISTS conditions Source: https://xorm.io/docs/chapter-13/readme Generates EXISTS and NOT EXISTS conditions with a subquery. ```go import . "xorm.io/builder" sql, args, _ := ToSQL(Exists(Select("a").From("table"))) // EXISTS (SELECT a FROM table) sql, args, _ := ToSQL(NotExists(Select("a").From("table"))) // NOT EXISTS (SELECT a FROM table) ``` -------------------------------- ### Delete: Generate DELETE SQL with builder.Delete Source: https://xorm.io/docs/chapter-13/readme Generates a DELETE statement for table1 where a=1. Returns the SQL string, arguments, and error. ```go sql, args, err := Delete(Eq{"a": 1}).From("table1").ToSQL() ``` -------------------------------- ### Update All Columns with AllCols Source: https://xorm.io/docs/chapter-06/readme Use AllCols to update every column in the struct, including zero or empty fields. ```go affected, err := engine.ID(id).AllCols().Update(&user) ``` -------------------------------- ### Define column properties with struct tags Source: https://xorm.io/docs/chapter-02/4.columns Use the xorm struct tag to define SQL column attributes like nullability, uniqueness, and comments. ```go type User struct { Id int64 Name string `xorm:"varchar(25) not null unique 'usr_name' comment('NickName')"` } ``` -------------------------------- ### Neq: Not equal conditions with builder.Neq Source: https://xorm.io/docs/chapter-13/readme Neq is the same as Eq but generates NOT EQUAL conditions. Supports multiple conditions, And/Or chaining, and NOT IN clauses for slice values. ```go import . "xorm.io/builder" sql, args, _ := ToSQL(Neq{"a":1}) // a<>? [1] sql, args, _ := ToSQL(Neq{"b":"c"}.And(Neq{"c": 0})) // b<>? AND c<>? ["c", 0] sql, args, _ := ToSQL(Neq{"b":"c", "c":0}) // b<>? AND c<>? ["c", 0] sql, args, _ := ToSQL(Neq{"b":"c"}.Or(Neq{"b":"d"})) // b<>? OR b<>? ["c", "d"] sql, args, _ := ToSQL(Neq{"b": []string{"c", "d"}}) // b NOT IN (?,?) ["c", "d"] sql, args, _ := ToSQL(Neq{"b": 1, "c":[]int{2, 3}}) // b<>? AND c NOT IN (?,?) [1, 2, 3] ``` -------------------------------- ### Update with Map and Table Source: https://xorm.io/docs/chapter-06/readme Uses a map[string]interface{} to update specific columns, even zero values. The table must be specified via a struct pointer or string. ```go affected, err := engine.Table(new(User)).ID(id).Update(map[string]interface{}{"age":0}) affected, err := engine.Table("user").ID(id).Update(map[string]interface{}{"age":0}) ``` -------------------------------- ### Query with Join and composite struct Source: https://xorm.io/docs/chapter-05/5.join Using a composite struct with the 'extends' tag to map joined table results. ```go type UserGroup struct { User `xorm:"extends"` Name string } func (UserGroup) TableName() string { return "user" } var users []UserGroup err := engine.Join("INNER", "group", "group.id = user.group_id").Find(&users) ``` -------------------------------- ### Set database time location Source: https://xorm.io/docs/chapter-15/readme Configure the engine's TZLocation property to set the desired time zone. ```go location, err = time.LoadLocation("Asia/Shanghai") engine.TZLocation = location ``` -------------------------------- ### ID - Primary key as query condition Source: https://xorm.io/docs/chapter-05/1.conditions Uses the primary key as a query condition. For composite primary keys, use schemas.PK with values in the same order as the struct fields. ```go var user User engine.ID(1).Get(&user) // SELECT * FROM user Where id = 1 ``` ```go engine.ID(schemas.PK{1, "name"}).Get(&user) // SELECT * FROM user Where id =1 AND name= 'name' ``` -------------------------------- ### Update Zero Values with Cols Source: https://xorm.io/docs/chapter-06/readme Use Cols to specify columns to update even if they are zero or empty. Call with the column name as argument. ```go affected, err := engine.ID(id).Cols("age").Update(&user) ``` -------------------------------- ### IsNull and NotNull: NULL checks Source: https://xorm.io/docs/chapter-13/readme Generates IS NULL and IS NOT NULL conditions. ```go import . "xorm.io/builder" sql, args, _ := ToSQL(IsNull{"a"}) // a IS NULL [] sql, args, _ := ToSQL(NotNull{"b"}) // b IS NOT NULL [] ``` -------------------------------- ### Enable global LRU cache with engine.SetDefaultCacher Source: https://xorm.io/docs/chapter-11/readme Enables the built-in LRU memory cache provider globally for all tables. The cache is disabled by default. The first argument to NewLRUCacher is the memory store, and the second is the cache size (1000). ```go cacher := caches.NewLRUCacher(caches.NewMemoryStore(), 1000) engine.SetDefaultCacher(cacher) ``` -------------------------------- ### Expr: Custom SQL expressions with builder.Expr Source: https://xorm.io/docs/chapter-13/readme Allows custom SQL expressions. Can be used as a standalone condition or as a value in Eq. ```go import . "xorm.io/builder" sql, args, _ := ToSQL(Expr("a = ? ", 1)) // a = ? [1] sql, args, _ := ToSQL(Eq{"a": Expr("select id from table where c = ?", 1)}) // a=(select id from table where c = ?) [1] ``` -------------------------------- ### EngineGroup API methods Source: https://xorm.io/docs/chapter-01/2.engine_group Methods available on the EngineGroup instance for managing connections and policies. ```go func NewEngineGroup(args1 interface{}, args2 interface{}, policies ...GroupPolicy) (*EngineGroup, error) ``` ```go func (eg *EngineGroup) Master() *Engine ``` ```go func (eg *EngineGroup) Slave() *Engine ``` ```go func (eg *EngineGroup) Slaves() []*Engine ``` ```go func (eg *EngineGroup) GetSlave(i int) *Engine ``` ```go func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup ``` -------------------------------- ### Check existence with Table and Where Source: https://xorm.io/docs/chapter-05/10.exist Checks if a record exists in the specified table matching the Where condition. ```go has, err = testEngine.Table("record_exist").Where("name = ?", "test1").Exist() // SELECT * FROM record_exist WHERE name = ? LIMIT 1 ``` -------------------------------- ### Insert multiple records by slice of pointers Source: https://xorm.io/docs/chapter-04/readme Inserts multiple records from a slice of pointers into one table. Each element is a pointer to a User struct. ```go users := make([]*User, 1) users[0] = new(User) users[0].Name = "name0" ... affected, err := engine.Insert(&users) ``` -------------------------------- ### In - Conditional IN Source: https://xorm.io/docs/chapter-05/1.conditions Adds a SQL conditional IN. Accepts a slice as parameters or a builder.Builder as a subquery. ```go // select from table where column in (1,2,3) engine.In("cloumn", 1, 2, 3).Find() ``` ```go // select from table where column in (1,2,3) engine.In("column", []int{1, 2, 3}).Find() ``` ```go // select from table where column in (select column from table2 where a = 1) engine.In("column", builder.Select("column").From("table2").Where(builder.Eq{"a":1})).Find() ``` -------------------------------- ### Check existence with struct conditions Source: https://xorm.io/docs/chapter-05/10.exist Checks if a record exists matching the fields defined in the struct instance. ```go has, err = testEngine.Exist(&RecordExist{ Name: "test1", }) // SELECT * FROM record_exist WHERE name = ? LIMIT 1 ``` -------------------------------- ### Cols - Specify query or update columns Source: https://xorm.io/docs/chapter-05/1.conditions Explicitly specifies query or update columns. ```go engine.Cols("age", "name").Get(&usr) // SELECT age, name FROM user limit 1 ``` ```go engine.Cols("age", "name").Find(&users) // SELECT age, name FROM user ``` ```go engine.Cols("age", "name").Update(&user) // UPDATE user SET age=? AND name=? ``` -------------------------------- ### Check existence with struct Source: https://xorm.io/docs/chapter-05/10.exist Checks if any record exists for the provided struct type. ```go has, err := testEngine.Exist(new(RecordExist)) // SELECT * FROM record_exist LIMIT 1 ``` -------------------------------- ### In and NotIn: IN and NOT IN conditions Source: https://xorm.io/docs/chapter-13/readme Generates IN and NOT IN conditions. Accepts variadic arguments or a slice. Can use Expr for subqueries. ```go import . "xorm.io/builder" sql, args, _ := ToSQL(In("a", 1, 2, 3)) // a IN (?,?,?) [1,2,3] sql, args, _ := ToSQL(In("a", []int{1, 2, 3})) // a IN (?,?,?) [1,2,3] sql, args, _ := ToSQL(NotIn("a", Expr("select id from b where c = ?", 1)))) // a NOT IN (select id from b where c = ?) [1] ``` -------------------------------- ### Insert multiple objects on multiple tables Source: https://xorm.io/docs/chapter-04/readme Inserts multiple objects from slices into multiple tables in one call. Both slices are passed by pointer. ```go users := make([]User, 1) users[0].Name = "name0" ... questions := make([]Question, 1) questions[0].Content = "whywhywhwy?" affected, err := engine.Insert(&users, &questions) ``` -------------------------------- ### Iterate over records with callback Source: https://xorm.io/docs/chapter-05/6.iterate Use engine.Iterate to process each record individually. The callback receives the index and the bean, which can be type-asserted to the concrete struct. The query condition is applied via Where. ```go err := engine.Where("age > ? or name=?)", 30, "xlw").Iterate(new(Userinfo), func(i int, bean interface{})error{ user := bean.(*Userinfo) //do somthing use i and user }) ``` -------------------------------- ### Check existence with Where clause Source: https://xorm.io/docs/chapter-05/10.exist Checks if a record exists matching the specified Where condition. ```go has, err = testEngine.Where("name = ?", "test1").Exist(&RecordExist{}) // SELECT * FROM record_exist WHERE name = ? LIMIT 1 ``` -------------------------------- ### Basic Update with Struct Pointer Source: https://xorm.io/docs/chapter-06/readme Updates a record by passing a struct pointer. Only non-empty and non-zero fields are updated. Returns affected count, but SQLITE returns count of update conditions not actual affected records. ```go user := new(User) user.Name = "myname" affected, err := engine.ID(id).Update(user) ``` -------------------------------- ### Insert two objects onto two tables Source: https://xorm.io/docs/chapter-04/readme Inserts two objects into two different tables in a single call. The objects are passed as separate arguments. ```go user := new(User) user.Name = "myname" question := new(Question) question.Content = "whywhywhwy?" affected, err := engine.Insert(user, question) ``` -------------------------------- ### Count records with Where condition Source: https://xorm.io/docs/chapter-05/7.count Uses an ORM pointer struct to count records that satisfy a specific condition. ```go user := new(User) total, err := engine.Where("id >?", 1).Count(user) ``` -------------------------------- ### Insert multiple objects by slice Source: https://xorm.io/docs/chapter-04/readme Inserts multiple objects from a slice of structs into one table. The slice is passed by pointer to engine.Insert. ```go users := make([]User, 1) users[0].Name = "name0" ... affected, err := engine.Insert(&users) ``` -------------------------------- ### Insert one or multiple objects on multiple tables Source: https://xorm.io/docs/chapter-04/readme Inserts a single object and a slice of objects into multiple tables in one call. The single object is passed directly, the slice by pointer. ```go user := new(User) user.Name = "myname" ... questions := make([]Question, 1) questions[0].Content = "whywhywhwy?" affected, err := engine.Insert(user, &questions) ``` -------------------------------- ### Set SameMapper for all mappings Source: https://xorm.io/docs/chapter-02/1.mapping Changes the default SnakeMapper to SameMapper for both table and column names using engine.SetMapper. ```go engine.SetMapper(names.SameMapper{}) ``` -------------------------------- ### Alias - Set table alias Source: https://xorm.io/docs/chapter-05/1.conditions Sets an alias name for the table so it can be used in conditions. ```go engine.Alias("o").Where("o.name = ?", name).Get(&order) ``` -------------------------------- ### Desc - Descending ordering Source: https://xorm.io/docs/chapter-05/1.conditions Orders results in descending order on one or more fields. ```go engine.Asc("id").Desc("time").Find(&orders) ``` -------------------------------- ### Insert one object with engine.Insert Source: https://xorm.io/docs/chapter-04/readme Inserts a single object into the database. After insertion, the ID field is automatically populated if it is an autoincremented column. ```go user := new(User) user.Name = "myname" affected, err := engine.Insert(user) ``` -------------------------------- ### Perform Join operations with extends tag Source: https://xorm.io/docs/chapter-15/readme Use the extends tag on struct fields to map joined tables. Ensure the order of fields in the struct matches the order in the JOIN SQL statement to avoid incorrect data mapping. ```go type Userinfo struct { Id int64 Name string DetailId int64 } type Userdetail struct { Id int64 Gender int } type User struct { Userinfo `xorm:"extends"` Userdetail `xorm:"extends"` } var users = make([]User, 0) err := engine.Table(&Userinfo{}).Join("LEFT", "userdetail", "userinfo.detail_id = userdetail.id").Find(&users) //assert(User.Userinfo.Id != 0 && User.Userdetail.Id != 0) ``` -------------------------------- ### Iterate query results with Rows Source: https://xorm.io/docs/chapter-05/8.rows Use Rows to iterate over query results with manual control. It returns a rows object that must be closed with defer. Scan each row into the provided struct inside the loop. ```go user := new(User) rows, err := engine.Where("id >?", 1).Rows(user) if err != nil { } defer rows.Close() for rows.Next() { err = rows.Scan(user) //... } ``` -------------------------------- ### Enable cache for a specific table with engine.MapCacher Source: https://xorm.io/docs/chapter-11/readme Enables caching for a specific table only, using the LRU memory cache provider. This is used when only some tables need caching, rather than enabling it globally. ```go cacher := caches.NewLRUCacher(caches.NewMemoryStore(), 1000) engine.MapCacher(&user, cacher) ```