Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
O

ozzo-dbx

> 数据库
Open source

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

670 stars0 likes1 views
WebsiteGitHub

About

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

Summary

  • Description
  • Requirements
  • Installation
  • Supported Databases
  • Getting Started
  • Connecting to Database
  • Executing Queries
  • Binding Parameters
  • Building Queries
    • Building SELECT Queries
    • Building Query Conditions
    • Building Data Manipulation Queries
    • Building Schema Manipulation Queries
  • CRUD Operations
    • Create
    • Read
    • Update
    • Delete
    • Null Handling
  • Quoting Table and Column Names
  • Cancelable Queries
  • Using Transactions
  • Logging Executed SQL Statements
  • Supporting New Databases

Other Languages

Русский

Description

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:

  • Populating data into structs and NullString maps
  • Named parameter binding
  • DB-agnostic query building methods, including SELECT queries, data manipulation queries, and schema manipulation queries
  • Inserting, updating, and deleting model structs
  • Powerful query condition building
  • Open architecture allowing addition of new database support or customization of existing support
  • Logging executed SQL statements
  • Supporting major relational databases

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.

Requirements

Go 1.22 or above.

Installation

Run the following command to install the package:

go get github.com/go-ozzo/ozzo-dbx

In 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/mysql

and import it in your main code like the following:

go
import _ "github.com/go-sql-driver/mysql"

Supported Databases

The following databases are fully supported out of box:

  • SQLite (driver key "sqlite3" for mattn/go-sqlite3 or "sqlite" for modernc.org/sqlite -- the CGo-free driver)
  • MySQL
  • PostgreSQL
  • MS SQL Server (2012 or above)
  • Oracle

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.

Getting Started

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.

…

Connecting to Database

To connect to a database, call dbx.Open() in the same way as you would do with the Open() method in database/sql.

go
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.

Executing Queries

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,

go
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:

  • Only exported struct fields can be populated.
  • A field receives data if its name is mapped to a column according to the field mapping function 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.
  • If a field has a 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.
  • For anonymous fields that are of struct type, they will be expanded and their component fields will be populated according to the rules described above.
  • For named fields that are of struct type, they will also be expanded. But their component fields will be prefixed with the struct names when being 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:

go
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.

Binding Parameters

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,

go
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,

go
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)

// ...

Cancelable Queries

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,

go
q := db.NewQuery("SELECT id, name FROM users")
err := q.WithContext(ctx).All(&users)

Building Queries

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 SELECT 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,

go
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:

sql
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.

Building Query Conditions

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,

go
// 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 `A

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Godatabasegogolangozzo

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库