### Install go-sqlbuilder Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Install the go-sqlbuilder package using the go get command. ```shell go get github.com/huandu/go-sqlbuilder ``` -------------------------------- ### Interpolate SQL Arguments for MySQL Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Interpolate arguments directly into the SQL string for drivers that do not support parameterized queries, like some Redis or Elasticsearch drivers. This example is specific to MySQL. ```go sb := MySQL.NewSelectBuilder() sb.Select("name").From("user").Where( sb.NE("id", 1234), sb.E("name", "Charmy Liu"), sb.Like("desc", "%mother's day%"), ) sql, args := sb.Build() query, err := MySQL.Interpolate(sql, args) fmt.Println(query) fmt.Println(err) ``` -------------------------------- ### Instantiate Builder with PostgreSQL Flavor Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Shows how to create a SelectBuilder pre-configured with the PostgreSQL flavor for specific SQL syntax and parameter placeholders. This ensures compatibility with PostgreSQL databases. ```go PostgreSQL.NewSelectBuilder() ``` -------------------------------- ### Build WHERE Clause with Multiple Conditions Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Demonstrates building a WHERE clause with a combination of IN, Equal, and Like conditions, using AND and OR operators. The output shows the generated SQL and arguments. ```go sb := sqlbuilder.Select("id").From("user") sb.Where( sb.In("status", 1, 2, 5), sb.Or( sb.Equal("name", "foo"), sb.Like("email", "foo@%"), ), ) sql, args := sb.Build() fmt.Println(sql) fmt.Println(args) ``` -------------------------------- ### Using sql.Named for Parameterized Queries Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Demonstrates how to use `sql.Named` to create named arguments within SQL statements, allowing arguments to be reused across multiple parts of a query. ```go now := time.Now().Unix() start := sql.Named("start", now-86400) end := sql.Named("end", now+86400) sb := sqlbuilder.NewSelectBuilder() sb.Select("name") sb.From("user") sb.Where( sb.Between("created_at", start, end), sb.GE("modified_at", start), ) sql, args := sb.Build() fmt.Println(sql) fmt.Println(args) // Output: // SELECT name FROM user WHERE created_at BETWEEN @start AND @end AND modified_at >= @start // [{{} start 1514458225} {{} end 1514544625}] ``` -------------------------------- ### Clone SelectBuilder for Reusable Templates Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Demonstrates how to define a base SELECT builder template and clone it to create independent, customized query builders. This is useful for generating multiple similar queries efficiently and safely in concurrent environments. ```go package yourpkg import "github.com/huandu/go-sqlbuilder" // Global template — safe to reuse by cloning. var baseUserSelect = sqlbuilder.NewSelectBuilder(). Select("id", "name", "email"). From("users"). Where("deleted_at IS NULL") func ListActiveUsers(limit, offset int) (string, []interface{}) { sb := baseUserSelect.Clone() // independent copy sb.OrderByAsc("id") sb.Limit(limit).Offset(offset) return sb.Build() } func GetActiveUserByID(id int64) (string, []interface{}) { sb := baseUserSelect.Clone() // start from the same template sb.Where(sb.Equal("id", id)) sb.Limit(1) return sb.Build() } ``` -------------------------------- ### Build SQL with Special Syntax and Arguments Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Use the Build function to compile a format string with special syntax and arguments. This is useful for creating dynamic SQL queries. ```go sb := sqlbuilder.NewSelectBuilder() sb.Select("id").From("user").Where(sb.In("status", 1, 2)) b := sqlbuilder.Build("EXPLAIN $? LEFT JOIN SELECT * FROM $? WHERE created_at > $? AND state IN (${states}) AND modified_at BETWEEN $2 AND $?", sb, sqlbuilder.Raw("banned"), 1514458225, 1514544625, sqlbuilder.Named("states", sqlbuilder.List([]int{3, 4, 5}))) sql, args := b.Build() fmt.Println(sql) fmt.Println(args) ``` -------------------------------- ### Nested SQL Query Construction Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Illustrates how to construct nested SQL queries by using one builder as an argument for another. This is useful for creating complex subqueries. ```go sb := sqlbuilder.NewSelectBuilder() fromSb := sqlbuilder.NewSelectBuilder() statusSb := sqlbuilder.NewSelectBuilder() sb.Select("id") sb.From(sb.BuilderAs(fromSb, "user"))) sb.Where(sb.In("status", statusSb)) fromSb.Select("id").From("user").Where(fromSb.GreaterThan("level", 4)) statusSb.Select("status").From("config").Where(statusSb.Equal("state", 1)) sql, args := sb.Build() fmt.Println(sql) fmt.Println(args) // Output: // SELECT id FROM (SELECT id FROM user WHERE level > ?) AS user WHERE status IN (SELECT status FROM config WHERE state = ?) // [4 1] ``` -------------------------------- ### Struct-based SELECT Query Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Demonstrates how to build a SELECT query using a struct definition. The library maps struct fields to table columns, handling the query execution and result scanning. ```go type User struct { ID int64 `db:"id" fieldtag:"pk"` Name string `db:"name"` Status int `db:"status"` } // A global variable for creating SQL builders. // All methods of userStruct are thread-safe. var userStruct = NewStruct(new(User)) func ExampleStruct() { // Prepare SELECT query. // SELECT user.id, user.name, user.status FROM user WHERE id = 1234 sb := userStruct.SelectFrom("user") sb.Where(sb.Equal("id", 1234)) // Execute the query and scan the results into the user struct. sql, args := sb.Build() rows, _ := db.Query(sql, args...) defer rows.Close() // Scan row data and set value to user. // Assuming the following data is retrieved: // // | id | name | status | // |------|--------|--------| // | 1234 | huandu | 1 | var user User rows.Scan(userStruct.Addr(&user)...) fmt.Println(sql) fmt.Println(args) fmt.Printf("%#v", user) // Output: // SELECT user.id, user.name, user.status FROM user WHERE id = ? // [1234] // sqlbuilder.User{ID:1234, Name:"huandu", Status:1} } ``` -------------------------------- ### Struct Field Tagging Options Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Demonstrates various `db` tag options for mapping struct fields to SQL columns, including column names, aliases, field tags, and ignoring fields. ```go type ATable struct { Field1 string // If a field doesn't has a tag, use "Field1" as column name in SQL. Field2 int `db:"field2"` // Use "db" in field tag to set column name used in SQL. Field3 int64 `db:"field3" fieldtag:"foo,bar"` // Set fieldtag to a field. We can call `WithTag` to include fields with tag or `WithoutTag` to exclude fields with tag. Field4 int64 `db:"field4" fieldtag:"foo"` // If we use `s.WithTag("foo").Select("t")`, columnes of SELECT are "t.field3" and "t.field4". Field5 string `db:"field5" fieldas:"f5_alias"` // Use "fieldas" in field tag to set a column alias (AS) used in SELECT. Ignored int32 `db:"-"` // If we set field name as "-", Struct will ignore it. unexported int // Unexported field is not visible to Struct. Quoted string `db:"quoted" fieldopt:"withquote"` // Add quote to the field using back quote or double quote. See `Flavor#Quote`. Empty uint `db:"empty" fieldopt:"omitempty"` // Omit the field in UPDATE if it is a nil or zero value. Expanded Meta `db:"expanded" fieldopt:"expand"` // Force a nested struct to expand even when sqlbuilder.NoExpand is true. Payload Meta `db:"payload" fieldopt:"noexpand"` // Treat a nested struct as one column instead of expanding it. // The `omitempty` can be written as a function. // In this case, omit empty field `Tagged` when UPDATE for tag `tag1` and `tag3` but not `tag2`. Tagged string `db:"tagged" fieldopt:"omitempty(tag1,tag3)" fieldtag:"tag1,tag2,tag3"` // By default, the `SelectFrom("t")` will add the "t." to all names of fields matched tag. // We can add dot to field name to disable this behavior. FieldWithTableAlias string `db:"m.field"` } ``` -------------------------------- ### CREATE TABLE with Custom Clauses Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Construct a CREATE TABLE statement that includes custom SQL clauses like PARTITION BY and AS, often used for specific database systems like HIVE. This demonstrates the use of the SQL() method to insert arbitrary SQL segments. ```go sql := sqlbuilder.CreateTable("users"). SQL("PARTITION BY (year)"). SQL("AS"). SQL( sqlbuilder.Select("columns[0] id", "columns[1] name", "columns[2] year"). From("`all-users.csv`"). String(), ). String() fmt.Println(sql) ``` -------------------------------- ### SELECT with Arguments and Aliases Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Build a SELECT statement with dynamic arguments for the WHERE clause and an alias for a COUNT aggregate. Use NewSelectBuilder for more complex queries or when arguments need to be parameterized. ```go sb := sqlbuilder.NewSelectBuilder() sb.Select("id", "name", sb.As("COUNT(*)", "c")) sb.From("user") sb.Where(sb.In("status", 1, 2, 5)) sql, args := sb.Build() fmt.Println(sql) fmt.Println(args) ``` -------------------------------- ### Basic SELECT Statement Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Construct a simple SELECT statement with WHERE and LIMIT clauses. This is useful for basic data retrieval. ```go sql := sqlbuilder.Select("id", "name").From("demo.user"). Where("status = 1").Limit(10). String() fmt.Println(sql) ``` -------------------------------- ### Format SQL with Buildf Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Use Buildf for constructing SQL strings with embedded arguments, similar to fmt.Sprintf. It allows for complex SQL formatting, including subqueries and conditional clauses. ```go sb := sqlbuilder.NewSelectBuilder() sb.Select("id").From("user") explain := sqlbuilder.Buildf("EXPLAIN %v LEFT JOIN SELECT * FROM banned WHERE state IN (%v, %v)", sb, 1, 2) sql, args := explain.Build() fmt.Println(sql) fmt.Println(args) ``` -------------------------------- ### Nested Struct Expansion for JOIN Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Demonstrates how nested structs are automatically expanded for JOIN operations when they have `db` tags. This is useful for building complex JOIN projections from reusable structs. ```go type Post struct { ID string `db:"id"` Text string `db:"text"` } type Comment struct { Body string `db:"body"` } type PostCommentJoined struct { Post Post `db:"post"` Comment Comment `db:"comment"` } joined := sqlbuilder.NewStruct(new(PostCommentJoined)) sql, _ := joined.SelectFrom("posts post"). Join("comments comment", "post.id = comment.post_id"). Build() fmt.Println(sql) // Output: // SELECT post.id, post.text, comment.body FROM posts post JOIN comments comment ON post.id = comment.post_id ``` -------------------------------- ### Nested JOIN with Subquery Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Shows how to create nested JOINs using `BuilderAs`, allowing joins with filtered or transformed datasets represented by subqueries. ```go sb := sqlbuilder.NewSelectBuilder() nestedSb := sqlbuilder.NewSelectBuilder() // Build the nested subquery nestedSb.Select("b.id", "b.user_id") nestedSb.From("users2 AS b") nestedSb.Where(nestedSb.GreaterThan("b.age", 20)) // Build the main query with nested join sb.Select("a.id", "a.user_id") sb.From("users AS a") sb.Join( sb.BuilderAs(nestedSb, "b"), "a.user_id = b.user_id", ) sql, args := sb.Build() fmt.Println(sql) fmt.Println(args) // Output: // SELECT a.id, a.user_id FROM users AS a JOIN (SELECT b.id, b.user_id FROM users2 AS b WHERE b.age > ?) AS b ON a.user_id = b.user_id // [20] ``` -------------------------------- ### Interpolate SQL Arguments for PostgreSQL with Dollar Quoting Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Interpolate arguments into SQL for PostgreSQL, demonstrating support for dollar quoting. Note that only the last $1 is interpolated as others are within dollar-quoted strings. ```go query, err := PostgreSQL.Interpolate(" CREATE FUNCTION dup(in int, out f1 int, out f2 text) AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; SELECT * FROM dup($1);", []interface{}{42}) fmt.Println(query) fmt.Println(err) ``` -------------------------------- ### Build ORDER BY Clause with Multiple Columns Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Builds an ORDER BY clause to sort query results by multiple columns with specified directions (ASC/DESC). Use OrderByDesc and OrderByAsc for clarity and flexibility. ```go sb := sqlbuilder.NewSelectBuilder() sb.Select("id", "name", "score").From("users") sb.OrderByDesc("score").OrderByAsc("name") sql, args := sb.Build() fmt.Println(sql) ``` -------------------------------- ### Share WHERE Clause Between Builders Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Demonstrates transferring a WHERE clause from a SelectBuilder to an UpdateBuilder for reuse. Ensure the WHERE clause is compatible between the two operations. ```go sb := Select("name", "level").From("users") sb.Where( sb.Equal("id", 1234), ) fmt.Println(sb) ub := Update("users") ub.Set( ub.Add("level", 10), ) // Set the WHERE clause of UPDATE to the WHERE clause of SELECT. ub.WhereClause = sb.WhereClause fmt.Println(ub) ``` -------------------------------- ### Build UPDATE FROM Clause (PostgreSQL) Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Constructs an UPDATE statement with a FROM clause, specific to PostgreSQL, SQLite, and SQLServer. This is used when updating a table based on conditions involving other tables. ```go ub := PostgreSQL.NewUpdateBuilder() ub.Update("users") ub.Set(ub.Assign("name", "Huan Du")) ub.From("people") ub.Where("users.person_id = people.id") sql, args := ub.Build() fmt.Println(sql) fmt.Println(args) ``` -------------------------------- ### Keeping Nested Structs as Single Columns Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Illustrates how to prevent nested structs from expanding into individual columns by using `fieldopt:"noexpand"`. This is useful for handling JSON columns. ```go type Payload struct { Key string `json:"key"` } type Row struct { ID string `db:"id"` Payload Payload `db:"payload" fieldopt:"noexpand"` } st := sqlbuilder.NewStruct(new(Row)).For(sqlbuilder.PostgreSQL) sql, _ := st.SelectFrom("events e").Build() fmt.Println(sql) // Output: // SELECT e.id, e.payload FROM events e ``` -------------------------------- ### Disabling Default Nested Struct Expansion Source: https://github.com/huandu/go-sqlbuilder/blob/master/README.md Shows how to disable the default expansion of nested structs by setting `sqlbuilder.NoExpand = true`. Fields can be opted back into expansion using `fieldopt:"expand"`. ```go type Payload struct { Key string `json:"key"` } type Row struct { Payload Payload `db:"payload"` Post Post `db:"post" fieldopt:"expand"` } sqlbuilder.NoExpand = true st := sqlbuilder.NewStruct(new(Row)) fmt.Println(st.Columns()) // Output: // [payload post.id post.text] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.