pg-go compares three Go libraries for Postgres access: goqu, squirrel and gorm.
repositorydefines one contract: domain types, aStoreinterface with user, post and comment repositories, pagination parameters, and sentinel errors.goqurepo,squirrelrepoandgormrepoimplement that contract once each. Every implementation owns its row types and struct tags and maps them to the shared domain types.integrationruns the same test suite against all three:- Postgres runs in a container started with testcontainers. It is migrated with goose and seeded once, then restored from a snapshot before every test.
- The expected results of each scenario are stored once in
integration/testdata/results, and all three implementations must return exactly that data. - A pgx query tracer records the SQL that each library sends to Postgres. It is stored per scenario and implementation in
integration/testdata/sql.
- Every library runs with its default options. Only the wiring needed to talk to Postgres is configured: the goqu Postgres dialect and squirrel's
$nplaceholders. - All three libraries use the same driver: pgx through
database/sql.
The seed in seed/seed.sql is plain SQL. It uses generate_series with modular arithmetic, so the data is identical on every run, and the IDs are readable fixed UUIDs. It generates about 4,100 rows without difficulty.
- CRUD operations: create, read, update and delete, with
RETURNING. - Bulk insert: 100 rows in one statement.
- Runtime query building: a REST-style list with optional filters, sorting by two fields, limit, offset and a total count.
- Joins and nested mapping: one-to-one into a nested struct, and one-to-many two levels deep.
- Aggregates:
COUNT(DISTINCT),MAX,GROUP BY,HAVING, and window functions. - Postgres features:
ON CONFLICTupsert,WITH,WITH RECURSIVE, andFOR UPDATE SKIP LOCKED. - Escape hatches: how much raw SQL each scenario needs.
- Errors: not found and unique violation.
- Transactions: commit, rollback on error, savepoints, and one transaction shared by several repositories.
native: the library's API expresses the construct.fragment: the library's API plus raw SQL pieces for what it can't express, such asgoqu.L,squirrel.Expr/Prefix/Suffix, or a gorm string condition with a Postgres function.raw: the construct under test is handwritten SQL run through the library.
Plain column conditions such as gorm's Where("id = ?", id) or squirrel's OrderBy("id ASC") count as native, because strings are the normal API of those libraries.
Each scenario name links to the SQL that the three libraries generate.
- squirrel has no
RETURNINGbuilder, so it is added withSuffix("RETURNING *"). age()and interval literals have no builder API in any of the three libraries.- The
WITHstatement is written withRaw. The inner query is built with gorm and passed in as a subquery argument. - sqlx scans nested structs, but the aliased column list (
post.id AS "post.id") is built by hand. - The joined rows are grouped into nested structs in Go.
- The library has no savepoint API, so nested
InTxrunsSAVEPOINT,ROLLBACK TO SAVEPOINTandRELEASE SAVEPOINTby hand.
All three libraries return identical results for every scenario. The full list of scenarios, including the not-found and invalid-input cases, is in integration.
| Scenario | goqu | squirrel | gorm |
|---|---|---|---|
users_list_filtered (count + page) |
2 | 2 | 2 |
posts_get_with_author |
1 | 1 | 1 |
posts_list_recent_with_comments |
1 | 1 | 3 |
users_create |
1 | 1 | 3 (BEGIN, INSERT, COMMIT) |
| Need | goqu | squirrel | gorm |
|---|---|---|---|
| Single row not found | ScanStruct returns found == false |
sqlx.GetContext returns sql.ErrNoRows |
First returns gorm.ErrRecordNotFound; RowsAffected == 0 for updates and deletes |
| Unique violation | errors.As into *pgconn.PgError with code 23505 |
Same | Same, because TranslateError is off by default |
| Package | Non-blank lines |
|---|---|
goqurepo |
627 |
squirrelrepo |
615 |
gormrepo |
521 |
Version v9.19.0, the latest release, published 2023-11-21.
- Easy:
- Column lists come from struct tags, including nested structs scanned through dotted aliases (
"author"."id" AS "author.id"). WITH,WITH RECURSIVE,UNION ALL,ON CONFLICT,RETURNINGandFOR UPDATE SKIP LOCKEDall have builder methods.
- Column lists come from struct tags, including nested structs scanned through dotted aliases (
- Workarounds:
- There is no savepoint API.
WithTxhas no context parameter, so transactions useBeginTx.- Postgres functions, intervals and arithmetic such as
"t"."depth" + 1needgoqu.L.
- Defaults that shape the SQL:
- Values are written directly into the SQL text, because prepared mode is off.
Eq(true)renders asIS TRUE.ScanStructandCountaddLIMIT 1.
Version v1.5.4, the latest release, published 2023-03-17. Its README declares the project "complete": bug fixes are still merged, slowly.
- Easy:
- It has the smallest API, with conditions as maps (
Eq,Like,Gt). - Builders are immutable, so the list filters are built once and reused for both the count and the page.
- It has the smallest API, with conditions as maps (
- Workarounds:
- squirrel doesn't scan rows; sqlx does.
- There are no builders for
RETURNING,ON CONFLICT,FOR UPDATE,WITHorUNION; they all go throughPrefix/Suffixstrings. - A builder nested inside
Expris rendered with its own placeholder format. CTE subqueries are therefore built withsquirrel.Select(?placeholders), and only the outer statement converts them to$n.
- Defaults that shape the SQL:
- Placeholders default to
?, which Postgres rejects, soPlaceholderFormat(squirrel.Dollar)is required.
- Placeholders default to
Version v1.31.2, the latest release, published 2026-06-22.
- Easy:
Create,UpdatesandDeletecombine withclause.Returning,clause.OnConflictandclause.Locking.Joins("Author")loads a one-to-one relation in the same query.Preload("Comments.Reactions")loads nested one-to-many relations without manual grouping.- A nested
Transactionuses a savepoint automatically.
- Workarounds:
- Row types need
TableName,default:uuid_generate_v4()on IDs, andautoUpdateTime:falseonUpdatedAt. Without that tag, gorm setsupdated_atitself on insert. - A chained query must become a
Sessionbefore it can be reused for both the count and the page. - There is no CTE support, so
WITHstatements useRaw.
- Row types need
- Defaults that shape the SQL:
- Every single write is wrapped in
BEGIN/COMMIT. Createreturns only"id".FirstaddsORDER BYprimary key andLIMIT 1.Preloadruns one query per level.- Nested transactions use random savepoint names. They are stored as
sp<random>in the SQL files. - The default logger prints errors to stdout, including "record not found".
- Every single write is wrapped in
Prerequisites: a Docker-compatible runtime and mise, which installs the Go toolchain and the goose CLI.
mise install
go test ./...Rewrite the stored SQL for every implementation, and the expected results from goqu:
go test ./integration -updateRun one scenario for one library:
go test ./integration -run 'TestUsers/users_list_filtered/gorm'Create a new migration:
goose --dir migrations create <name> sqlmigrations/ goose migrations, embedded for the tests
seed/ plain SQL seed and fixture IDs
repository/ shared contract
goqurepo/ goqu implementation
squirrelrepo/ squirrel + sqlx implementation
gormrepo/ gorm implementation
integration/ shared test suite, expected results and recorded SQL