A flexible and powerful SQL string builder library plus a zero-config ORM.
A flexible and powerful SQL string builder library plus a zero-config ORM.
WHERE clauseWHERE clause among buildersORDER BY clauseStruct as a light weight ORMJOINsql.Named in a builderargs in the sqlThe sqlbuilder package offers a comprehensive suite of SQL string concatenation utilities. It is designed to facilitate the construction of SQL statements compatible with Go's standard library sql.DB and sql.Stmt interfaces, focusing on optimizing the performance of SQL statement creation and minimizing memory usage.
The primary objective of this package's design was to craft a SQL construction library that operates independently of specific database drivers and business logic. It is tailored to accommodate the diverse needs of enterprise environments, including the use of custom database drivers, adherence to specialized operational standards, integration into heterogeneous systems, and handling of non-standard SQL in intricate scenarios. Following its open-source release, the package has undergone extensive testing within a large-scale enterprise context, successfully managing the workload of hundreds of millions of orders daily and nearly ten million transactions daily, thus highlighting its robust performance and scalability.
This package is not restricted to any particular database driver and does not automatically establish connections with any database systems. It does not presuppose the execution of the generated SQL, making it versatile for a broad spectrum of application scenarios that involve the construction of SQL-like statements. It is equally well-suited for further development aimed at creating more business-specific database interaction packages, ORMs, and similar tools.
Install this package by executing the following command:
go get github.com/huandu/go-sqlbuilderWe can rapidly construct SQL statements using this package.
sql := sqlbuilder.Select("id", "name").From("demo.user").
Where("status = 1").Limit(10).
String()
fmt.Println(sql)
// Output:
// SELECT id, name FROM demo.user WHERE status = 1 LIMIT 10In common scenarios, it is necessary to escape all user inputs. To achieve this, initialize a builder at the outset.
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)
// Output:
// SELECT id, name, COUNT(*) AS c FROM user WHERE status IN (?, ?, ?)
// [1 2 5]This package includes the following pre-defined builders. API documentation and usage examples are available in the godoc online documentation.
CREATE TABLE.SELECT.INSERT.UPDATE.DELETE.UNION and UNION ALL.WITH name (col1, col2) AS (SELECT ...).fmt.Sprintf-like syntax.${key} to reference values by key in a map.A unique method, SQL(sql string), is implemented across all statement builders, enabling the insertion of any arbitrary SQL segment into a builder during SQL construction. This feature is particularly beneficial for crafting SQL statements that incorporate non-standard syntax required by OLTP or OLAP systems.
// Build a SQL to create a HIVE table.
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)
// Output:
// CREATE TABLE users PARTITION BY (year) AS SELECT columns[0] id, columns[1] name, columns[2] year FROM `all-users.csv`Below are several utility methods designed to address special cases.
[]interface{}. For example, invoking Flatten([]interface{"foo", []int{2, 3}}) yields []interface{}{"foo", 2, 3}. This method is compatible with builder methods such as In, NotIn, Values, etc., facilitating the conversion of a typed array into []interface{} or the merging of inputs.Flatten, with the exception that its return value is specifically intended for use as builder arguments. For example, Buildf("my_func(%v)", List([]int{1, 2, 3})).Build() generates SQL my_func(?, ?, ?) with arguments []interface{}{1, 2, 3}.Buildf("SELECT %v", Raw("NOW()")).Build() results in SQL SELECT NOW().For detailed instructions on utilizing these builders, consult the examples provided on GoDoc.
WHERE clauseWHERE clause is the most important part of a SQL. We can use Where method to add one or more conditions to a builder.
To simplify the construction of WHERE clauses, a utility type named Cond is provided for condition building. All builders that support WHERE clauses possess an anonymous Cond field, enabling the invocation of Cond methods on these builders.
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)
// Output:
// SELECT id FROM user WHERE status IN (?, ?, ?) AND (name = ? OR email LIKE ?)
// [1 2 5 foo foo@%]There are many methods for building conditions.
field = value.field <> value.field > value.field >= value.field < value.field <= value.field IN (value1, value2, ...).field NOT IN (value1, value2, ...).field LIKE value.field ILIKE value.field NOT LIKE value.field NOT ILIKE value.field BETWEEN lower AND upper.field NOT BETWEEN lower AND upper.field IS NULL.field IS NOT NULL.EXISTS (subquery).NOT EXISTS (subquery).NOT expr.field op ANY (value1, value2, ...).field op ALL (value1, value2, ...).field op SOME (value1, value2, ...).field IS DISTINCT FROM value.field IS NOT DISTINCT FROM value.There are also some methods to combine conditions.
WHERE clause among buildersDue to the importance of the WHERE statement in SQL, we often need to continuously append conditions and even share some common WHERE conditions among different builders. Therefore, we abstract the WHERE statement into a WhereClause struct, which can be used to create reusable WHERE conditions.
The following example illustrates how to transfer a WHERE clause from
No open issues yet, or sync has not completed.