A Go (golang) package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabil
A Go (golang) package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabil
ozzo-dbx is a Go package that enhances the standard database/sql package by providing powerful data retrieval methods
as well as DB-agnostic query building capabilities. ozzo-dbx is not an ORM. It has the following features:
For an example on how this library is used in an application, please refer to go-rest-api which is a starter kit for building RESTful APIs in Go.
Go 1.22 or above.
Run the following command to install the package:
go get github.com/go-ozzo/ozzo-dbxIn addition, install the specific DB driver package for the kind of database to be used. Please refer to SQL database drivers for a complete list. For example, if you are using MySQL, you may install the following package:
go get github.com/go-sql-driver/mysqland import it in your main code like the following:
import _ "github.com/go-sql-driver/mysql"The following databases are fully supported out of box:
"sqlite3" for mattn/go-sqlite3 or "sqlite" for modernc.org/sqlite -- the CGo-free driver)SQLite schema operations DropColumn, RenameColumn, and RenameTable are supported via standard ALTER TABLE syntax (requires SQLite 3.25.0+ for rename, 3.35.0+ for drop column).
For other databases, the query building feature may not work as expected. You can create a custom builder to solve the problem. Please see the last section for more details.
The following code snippet shows how you can use this package in order to access data from a MySQL database.
…And the following example shows how to use the query building capability of this package.
…To connect to a database, call dbx.Open() in the same way as you would do with the Open() method in database/sql.
db, err := dbx.Open("mysql", "user:pass@hostname/db_name")The method returns a dbx.DB instance which can be used to create and execute DB queries. Note that the method
does not really establish a connection until a query is made using the returned dbx.DB instance. It also
does not check the correctness of the data source name either. Call dbx.MustOpen() to make sure the data
source name is correct.
To execute a SQL statement, first create a dbx.Query instance by calling DB.NewQuery() with the SQL statement
to be executed. And then call Query.Execute() to execute the query if the query is not meant to retrieving data.
For example,
q := db.NewQuery("UPDATE users SET status=1 WHERE id=100")
result, err := q.Execute()If the SQL statement does retrieve data (e.g. a SELECT statement), one of the following methods should be called, which will execute the query and populate the result into the specified variable(s).
Query.All(): populate all rows of the result into a slice of structs or NullString maps. Pointer slices ([]*Struct) are also supported.Query.One(): populate the first row of the result into a struct or a NullString map.Query.Column(): populate the first column of the result into a slice.Query.Row(): populate the first row of the result into a list of variables, one for each returning column.Query.Rows(): returns a dbx.Rows instance to allow retrieving data row by row.For example,
…When populating a struct, the following rules are used to determine which columns should go into which struct fields:
Query.FieldMapper.
The default field mapping function separates words in a field name by underscores and turns them into lower case.
For example, a field name FirstName will be mapped to the column name first_name, and MyID to my_id.db tag, the tag value will be used as the corresponding column name. If the db tag is a dash -,
it means the field should NOT be populated.An exception to the above struct expansion is that when a struct type implements sql.Scanner or when it is time.Time.
In this case, the field will be populated as a whole by the DB driver. Also, if a field is a pointer to some type,
the field will be allocated memory and populated with the query result if it is not null.
The following example shows how fields are populated according to the rules above:
type User struct {
id int
Type int `db:"-"`
MyName string `db:"name"`
Profile
Address Address `db:"addr"`
}
type Profile struct {
Age int
}
type Address struct {
City string
}User.id: not populated because the field is not exported;User.Type: not populated because the db tag is -;User.MyName: to be populated from the name column, according to the db tag;Profile.Age: to be populated from the age column, since Profile is an anonymous field;Address.City: to be populated from the addr.city column, since Address is a named field of struct type
and its fields will be prefixed with addr. according to the db tag.Note that if a column in the result does not have a corresponding struct field, it will be ignored. Similarly, if a struct field does not have a corresponding column in the result, it will not be populated.
A SQL statement is usually parameterized with dynamic values. For example, you may want to select the user record
according to the user ID received from the client. Parameter binding should be used in this case, and it is almost
always preferred to prevent from SQL injection attacks. Unlike database/sql which does anonymous parameter binding,
ozzo-dbx uses named parameter binding. Anonymous parameter binding is not supported, as it will mess up with named
parameters. For example,
q := db.NewQuery("SELECT id, name FROM users WHERE id={:id}")
q.Bind(dbx.Params{"id": 100})
err := q.One(&user)The above example will select the user record whose id is 100. The method Query.Bind() binds a set
of named parameters to a SQL statement which contains parameter placeholders in the format of {:ParamName}.
If a SQL statement needs to be executed multiple times with different parameter values, it may be prepared to improve the performance. For example,
q := db.NewQuery("SELECT id, name FROM users WHERE id={:id}")
q.Prepare()
defer q.Close()
q.Bind(dbx.Params{"id": 100})
err := q.One(&user)
q.Bind(dbx.Params{"id": 200})
err = q.One(&user)
// ...Queries are cancelable when they are used with context.Context. In particular, by calling Query.WithContext() you
can associate a context with a query and use the context to cancel the query while it is running. For example,
q := db.NewQuery("SELECT id, name FROM users")
err := q.WithContext(ctx).All(&users)Instead of writing plain SQLs, ozzo-dbx allows you to build SQLs programmatically, which often leads to cleaner,
more secure, and DB-agnostic code. You can build three types of queries: the SELECT queries, the data manipulation
queries, and the schema manipulation queries.
Building a SELECT query starts by calling DB.Select(). You can build different clauses of a SELECT query using
the corresponding query building methods. For example,
db, _ := dbx.Open("mysql", "user:pass@/example")
err := db.Select("id", "name").
From("users").
Where(dbx.HashExp{"id": 100}).
One(&user)The above code will generate and execute the following SQL statement:
SELECT `id`, `name` FROM `users` WHERE `id`={:p0} Notice how the table and column names are properly quoted according to the currently using database type.
And parameter binding is used to populate the value of p0 in the WHERE clause.
Every SQL keyword has a corresponding query building method. For example, SELECT corresponds to Select(),
FROM corresponds to From(), WHERE corresponds to Where(), and so on. You can chain these method calls
together, just like you would do when writing a plain SQL. Each of these methods returns the query instance
(of type dbx.SelectQuery) that is being built. Once you finish building a query, you may call methods such as
One(), All() to execute the query and populate data into variables. You may also explicitly call Build()
to build the query and turn it into a dbx.Query instance which may allow you to get the SQL statement and do
other interesting work.
ozzo-dbx supports very flexible and powerful query condition building which can be used to build SQL clauses
such as WHERE, HAVING, etc. For example,
// id=100
dbx.NewExp("id={:id}", dbx.Params{"id": 100})
// id=100 AND status=1
dbx.HashExp{"id": 100, "status": 1}
// status=1 OR age>30
dbx.Or(dbx.HashExp{"status": 1}, dbx.NewExp("age>30"))
// name LIKE '%admin%' AND name LIKE '%example%'
dbx.Like("name", "admin", "example")When building a query condition expression, its parameter values will be populated using parameter binding, which prevents SQL injection from happening. Also if an expression involves column names, they will be properly quoted. The following condition building functions are available:
dbx.NewExp(): creating a condition using the given expression string and binding parameters. For example,
dbx.NewExp("id={:id}", dbx.Params{"id":100}) would create the expression id=100.dbx.HashExp: a map type that represents name-value pairs concatenated by AND operators. For example,
dbx.HashExp{"id":100, "status":1} would create id=100 AND status=1.dbx.Not(): creating a NOT expression by prepending NOT to the given expression.dbx.And(): creating an `ANo open issues yet, or sync has not completed.