Popularity
9.2
Stable
Activity
8.6
Declining
4,433
85
330
Programming language: Go
License: BSD 2-clause "Simplified" License
Tags:
ORM
Latest version: v11.0.0-alpha.4
go-pg alternatives and similar packages
Based on the "ORM" category.
Alternatively, view go-pg alternatives based on common mentions on social networks and blogs.
-
SQLBoiler
An ORM generator. Generate a featureful and blazing-fast ORM tailored to your database schema. -
upper.io/db
Single interface for interacting with different data sources through the use of adapters that wrap mature database drivers. -
go-queryset
100% type-safe ORM with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support based on GORM. -
REL
💎 Modern Database Access Layer for Golang - Testable, Extendable and Crafted Into a Clean and Elegant API
Get performance insights in less than 4 minutes
Scout APM uses tracing logic that ties bottlenecks to source code so you know the exact line of code causing performance issues and can get back to building a great product faster.
Sponsored
scoutapm.com
Do you think we are missing an alternative of go-pg or a related project?
Popular Comparisons
README
PostgreSQL client and ORM for Golang
:heart: Uptrace.dev - distributed traces, logs, and errors in one place
- Join Discord to ask questions.
- Documentation
- Reference
- Examples
- Example projects:
- GraphQL Tutorial on YouTube.
Ecosystem
- Migrations by vmihailenco and robinjoseph08.
- Genna - cli tool for generating go-pg models.
- urlstruct to decode
url.Values
into structs. - Sharding.
Features
- Basic types: integers, floats, string, bool, time.Time, net.IP, net.IPNet.
- sql.NullBool, sql.NullString, sql.NullInt64, sql.NullFloat64 and pg.NullTime.
- sql.Scanner and sql/driver.Valuer interfaces.
- Structs, maps and arrays are marshalled as JSON by default.
- PostgreSQL multidimensional Arrays using array tag and Array wrapper.
- Hstore using hstore tag and Hstore wrapper.
- Composite types.
- All struct fields are nullable by default and zero values (empty string, 0, zero time, empty map
or slice, nil ptr) are marshalled as SQL
NULL
.pg:",notnull"
is used to add SQLNOT NULL
constraint andpg:",use_zero"
to allow Go zero values. - Transactions.
- Prepared statements.
- Notifications using
LISTEN
andNOTIFY
. - Copying data using
COPY FROM
andCOPY TO
. - Timeouts and canceling queries using context.Context.
- Automatic connection pooling with circuit breaker support.
- Queries retry on network errors.
- Working with models using ORM and SQL.
- Scanning variables using ORM and SQL.
- SelectOrInsert using on-conflict.
- INSERT ... ON CONFLICT DO UPDATE using ORM.
- Bulk/batch inserts, updates, and deletes.
- Common table expressions using WITH and WrapWith.
- CountEstimate
using
EXPLAIN
to get estimated number of matching rows. - ORM supports has one, belongs to, has many, and many to many with composite/multi-column primary keys.
- Soft deletes.
- Creating tables from structs.
- ForEach that calls a function for each row returned by the query without loading all rows into the memory.
- Works with PgBouncer in transaction pooling mode.
Installation
go-pg supports 2 last Go versions and requires a Go version with modules support. So make sure to initialize a Go module:
go mod init github.com/my/repo
And then install go-pg (note v10 in the import; omitting it is a popular mistake):
go get github.com/go-pg/pg/v10
Quickstart
package pg_test
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
)
type User struct {
Id int64
Name string
Emails []string
}
func (u User) String() string {
return fmt.Sprintf("User<%d %s %v>", u.Id, u.Name, u.Emails)
}
type Story struct {
Id int64
Title string
AuthorId int64
Author *User `pg:"rel:has-one"`
}
func (s Story) String() string {
return fmt.Sprintf("Story<%d %s %s>", s.Id, s.Title, s.Author)
}
func ExampleDB_Model() {
db := pg.Connect(&pg.Options{
User: "postgres",
})
defer db.Close()
err := createSchema(db)
if err != nil {
panic(err)
}
user1 := &User{
Name: "admin",
Emails: []string{"[email protected]", "[email protected]"},
}
_, err = db.Model(user1).Insert()
if err != nil {
panic(err)
}
_, err = db.Model(&User{
Name: "root",
Emails: []string{"[email protected]", "[email protected]"},
}).Insert()
if err != nil {
panic(err)
}
story1 := &Story{
Title: "Cool story",
AuthorId: user1.Id,
}
_, err = db.Model(story1).Insert()
if err != nil {
panic(err)
}
// Select user by primary key.
user := &User{Id: user1.Id}
err = db.Model(user).WherePK().Select()
if err != nil {
panic(err)
}
// Select all users.
var users []User
err = db.Model(&users).Select()
if err != nil {
panic(err)
}
// Select story and associated author in one query.
story := new(Story)
err = db.Model(story).
Relation("Author").
Where("story.id = ?", story1.Id).
Select()
if err != nil {
panic(err)
}
fmt.Println(user)
fmt.Println(users)
fmt.Println(story)
// Output: User<1 admin [[email protected] [email protected]]>
// [User<1 admin [[email protected] [email protected]]> User<2 root [[email protected] [email protected]]>]
// Story<1 Cool story User<1 admin [[email protected] [email protected]]>>
}
// createSchema creates database schema for User and Story models.
func createSchema(db *pg.DB) error {
models := []interface{}{
(*User)(nil),
(*Story)(nil),
}
for _, model := range models {
err := db.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: true,
})
if err != nil {
return err
}
}
return nil
}