gitmyhub

sqlx

Go ★ 18k updated 1y ago

general purpose extensions to golang's database/sql

sqlx is a Go library that adds convenience on top of the standard database/sql package, letting you scan query results directly into structs and use named parameters without switching to a full ORM.

GoPostgreSQLMySQLSQLitesetup: easycomplexity 2/5

sqlx is a Go library that adds a friendlier layer on top of database/sql, the standard package Go programs use to talk to relational databases like PostgreSQL, MySQL, or SQLite. The standard library is solid but very low-level: you write raw SQL, get back a rows cursor, and have to scan each column into a Go variable by hand. sqlx keeps that whole approach intact while adding the convenience features most people end up wanting.

The library wraps the familiar types (DB, Tx, Stmt, Conn) with sqlx versions that have the same underlying interfaces, so existing code keeps working and you can adopt sqlx gradually. On top of that it adds three big things. First, it can marshal database rows directly into Go structs, maps, or slices, including embedded structs, using a db struct tag to match columns to fields. Second, it supports named parameters such as :first_name in both queries and prepared statements, with values supplied from a struct or a map. Third, the Get and Select helpers turn a query plus a destination variable into a single line of code: Get fills one struct, Select fills a slice. There is also a BindDriver call that lets you register the bindvar style used by less common database drivers at runtime.

You would reach for sqlx when you want to keep writing your own SQL (no ORM magic) but you are tired of the boilerplate around scanning rows into structs. It pairs well with PostgreSQL via lib/pq and other database/sql drivers shown in the examples. The codebase is written in Go, installed with go get, versioned with Go modules, and aims to stay compatible with the most recent two Go releases.

Where it fits