pg

Golang ORM with focus on PostgreSQL features and performance

Github星跟蹤圖

PostgreSQL client and ORM for Golang

Build Status
GoDoc

Features

Ecosystem

Get Started

go-pg requires a Go version with Modules support and uses import versioning. So please make sure to initialize a Go module before installing go-pg:

go mod init github.com/my/repo
go get github.com/go-pg/pg/v9

Look & Feel

package pg_test

import (
    "fmt"

    "github.com/go-pg/pg/v9"
    "github.com/go-pg/pg/v9/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
}

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{"admin1@admin", "admin2@admin"},
    }
    err = db.Insert(user1)
    if err != nil {
        panic(err)
    }

    err = db.Insert(&User{
        Name:   "root",
        Emails: []string{"root1@root", "root2@root"},
    })
    if err != nil {
        panic(err)
    }

    story1 := &Story{
        Title:    "Cool story",
        AuthorId: user1.Id,
    }
    err = db.Insert(story1)
    if err != nil {
        panic(err)
    }

    // Select user by primary key.
    user := &User{Id: user1.Id}
    err = db.Select(user)
    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 [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]>>
}

func createSchema(db *pg.DB) error {
    for _, model := range []interface{}{(*User)(nil), (*Story)(nil)} {
        err := db.CreateTable(model, &orm.CreateTableOptions{
            Temp: true,
        })
        if err != nil {
            return err
        }
    }
    return nil
}

See also

主要指標

概覽
名稱與所有者go-pg/pg
主編程語言Go
編程語言Makefile (語言數: 3)
平台
許可證BSD 2-Clause "Simplified" License
所有者活动
創建於2013-04-24 12:31:41
推送於2025-07-08 16:23:37
最后一次提交
發布數452
最新版本名稱v10.14.0 (發布於 )
第一版名稱v1 (發布於 2014-06-02 10:27:07)
用户参与
星數5.7k
關注者數84
派生數412
提交數2.2k
已啟用問題?
問題數1082
打開的問題數111
拉請求數776
打開的拉請求數9
關閉的拉請求數94
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?