Skip to content

Latest commit

History

1,632 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PostgreSQL client and ORM for Golang

Build StatusGoDoc

Features:

Get Started

go get -u github.com/go-pg/pg

Look & Feel

package pg_test
import (
"fmt""github.com/go-pg/pg""github.com/go-pg/pg/orm"
)
typeUserstruct {
Idint64NamestringEmails []string
}
func (uUser) String() string {
returnfmt.Sprintf("User<%d %s %v>", u.Id, u.Name, u.Emails)
}
typeStorystruct {
Idint64TitlestringAuthorIdint64Author*User
}
func (sStory) String() string {
returnfmt.Sprintf("Story<%d %s %s>", s.Id, s.Title, s.Author)
}
funcExampleDB_Model() {
db:=pg.Connect(&pg.Options{
User: "postgres",
})
deferdb.Close()
err:=createSchema(db)
iferr!=nil {
panic(err)
}
user1:=&User{
Name: "admin",
Emails: []string{"admin1@admin", "admin2@admin"},
}
err=db.Insert(user1)
iferr!=nil {
panic(err)
}
err=db.Insert(&User{
Name: "root",
Emails: []string{"root1@root", "root2@root"},
})
iferr!=nil {
panic(err)
}
story1:=&Story{
Title: "Cool story",
AuthorId: user1.Id,
}
err=db.Insert(story1)
iferr!=nil {
panic(err)
}
// Select user by primary key.user:=&User{Id: user1.Id}
err=db.Select(user)
iferr!=nil {
panic(err)
}
// Select all users.varusers []Usererr=db.Model(&users).Select()
iferr!=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()
iferr!=nil {
panic(err)
}
fmt.Println(user)
fmt.Println(users)
fmt.Println(story)
// Output: User<1 admin [admin1@admin admin2@admin]>// [User<1 admin [admin1@admin admin2@admin]> User<2 root [root1@root root2@root]>]// Story<1 Cool story User<1 admin [admin1@admin admin2@admin]>>
}
funccreateSchema(db*pg.DB) error {
for_, model:=range []interface{}{(*User)(nil), (*Story)(nil)} {
err:=db.CreateTable(model, &orm.CreateTableOptions{
Temp: true,
})
iferr!=nil {
returnerr
}
}
returnnil
}

See also

About

Golang ORM with focus on PostgreSQL features and performance

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages