Documentation ¶
Overview ¶
Package github.com/vmihailenco/pg implements a PostgreSQL client.
Example (ComplexQuery) ¶
package main import ( "fmt" "github.com/lukashes/pg" ) type ArticleFilter struct { Name string CategoryId int } func (f *ArticleFilter) FilterName() pg.Q { if f.Name == "" { return "" } return pg.MustFormatQ("AND name = ?", f.Name) } func (f *ArticleFilter) FilterCategory() pg.Q { if f.CategoryId == 0 { return "" } return pg.MustFormatQ("AND category_id = ?", f.CategoryId) } type Article struct { Name string CategoryId int } type Articles []*Article func (articles *Articles) New() interface{} { a := &Article{} *articles = append(*articles, a) return a } func CreateArticle(db *pg.DB, article *Article) error { _, err := db.ExecOne(`INSERT INTO articles VALUES (?name, ?category_id)`, article) return err } func GetArticles(db *pg.DB, f *ArticleFilter) ([]*Article, error) { var articles Articles _, err := db.Query(&articles, ` SELECT * FROM articles WHERE 1=1 ?FilterName ?FilterCategory `, f) if err != nil { return nil, err } return articles, nil } func main() { db := pg.Connect(&pg.Options{ User: "postgres", }) defer db.Close() _, err := db.Exec(`CREATE TEMP TABLE articles (name text, category_id int)`) if err != nil { panic(err) } err = CreateArticle(db, &Article{"article1", 1}) if err != nil { panic(err) } err = CreateArticle(db, &Article{"article2", 2}) if err != nil { panic(err) } articles, err := GetArticles(db, &ArticleFilter{}) if err != nil { panic(err) } fmt.Printf("%d %v %v\n", len(articles), articles[0], articles[1]) articles, err = GetArticles(db, &ArticleFilter{CategoryId: 1}) if err != nil { panic(err) } fmt.Printf("%d %v\n", len(articles), articles[0]) }
Output: 2 &{article1 1} &{article2 2} 1 &{article1 1}
Index ¶
- Variables
- func AppendQ(dst []byte, src string, params ...interface{}) ([]byte, error)
- func Decode(dst interface{}, f []byte) error
- func DecodeValue(dst reflect.Value, f []byte) error
- func IsNil(a interface{}) bool
- type Appender
- type DB
- func (db *DB) Begin() (*Tx, error)
- func (db *DB) Close() error
- func (db *DB) CopyFrom(r io.Reader, q string, args ...interface{}) (*Result, error)
- func (db *DB) CopyTo(w io.WriteCloser, q string, args ...interface{}) (*Result, error)
- func (db *DB) Exec(q string, args ...interface{}) (res *Result, err error)
- func (db *DB) ExecOne(q string, args ...interface{}) (*Result, error)
- func (db *DB) Listen(channels ...string) (*Listener, error)
- func (db *DB) Prepare(q string) (*Stmt, error)
- func (db *DB) Query(f Factory, q string, args ...interface{}) (res *Result, err error)
- func (db *DB) QueryOne(model interface{}, q string, args ...interface{}) (*Result, error)
- func (db *DB) RunInTransaction(fn func(*Tx) error) error
- type Error
- type F
- type Factory
- type IntegrityError
- type Ints
- type IntsSet
- type Listener
- type Loader
- type Options
- type Q
- type RawAppender
- type RecordReader
- type Result
- type Stmt
- func (stmt *Stmt) Close() error
- func (stmt *Stmt) Exec(args ...interface{}) (res *Result, err error)
- func (stmt *Stmt) ExecOne(args ...interface{}) (*Result, error)
- func (stmt *Stmt) Query(f Factory, args ...interface{}) (res *Result, err error)
- func (stmt *Stmt) QueryOne(model interface{}, args ...interface{}) (*Result, error)
- type Strings
- type Tx
- func (tx *Tx) Commit() error
- func (tx *Tx) Exec(q string, args ...interface{}) (*Result, error)
- func (tx *Tx) ExecOne(q string, args ...interface{}) (*Result, error)
- func (tx *Tx) Prepare(q string) (*Stmt, error)
- func (tx *Tx) Query(f Factory, q string, args ...interface{}) (*Result, error)
- func (tx *Tx) QueryOne(model interface{}, q string, args ...interface{}) (*Result, error)
- func (tx *Tx) Rollback() error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ( ErrSSLNotSupported = errorf("pg: SSL is not enabled on the server") ErrNoRows = errorf("pg: no rows in result set") ErrMultiRows = errorf("pg: multiple rows in result set") )
Functions ¶
Types ¶
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
Thread-safe.
func Connect ¶
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) func main() { db := pg.Connect(&pg.Options{ User: "postgres", }) err := db.Close() fmt.Println(err) }
Output: <nil>
func (*DB) Begin ¶
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) var db *pg.DB func init() { db = pg.Connect(&pg.Options{ User: "postgres", }) } func main() { tx, err := db.Begin() if err != nil { panic(err) } _, err = tx.Exec("CREATE TEMP TABLE test()") if err != nil { panic(err) } err = tx.Rollback() if err != nil { panic(err) } _, err = db.Exec("SELECT * FROM test") fmt.Println(err) }
Output: ERROR #42P01 relation "test" does not exist:
func (*DB) CopyFrom ¶
Example ¶
_, err := db.Exec("CREATE TEMP TABLE words(word text, len int)") if err != nil { panic(err) } r := strings.NewReader("hello,5\nfoo,3\n") _, err = db.CopyFrom(r, "COPY words FROM STDIN WITH CSV") if err != nil { panic(err) } buf := &bytes.Buffer{} _, err = db.CopyTo(&NopWriteCloser{buf}, "COPY words TO STDOUT WITH CSV") if err != nil { panic(err) } fmt.Println(buf.String())
Output: hello,5 foo,3
func (*DB) Exec ¶
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) var db *pg.DB func main() { res, err := db.Exec("CREATE TEMP TABLE test()") fmt.Println(res.Affected(), err) }
Output: 0 <nil>
func (*DB) Prepare ¶
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) var db *pg.DB func init() { db = pg.Connect(&pg.Options{ User: "postgres", }) } func main() { stmt, err := db.Prepare("SELECT $1::text, $2::text") if err != nil { panic(err) } var s1, s2 string _, err = stmt.QueryOne(pg.LoadInto(&s1, &s2), "foo", "bar") fmt.Println(s1, s2, err) }
Output: foo bar <nil>
func (*DB) Query ¶
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) type User struct { Name string Emails []string } type Users []*User func (users *Users) New() interface{} { u := &User{} *users = append(*users, u) return u } func CreateUser(db *pg.DB, user *User) error { _, err := db.ExecOne(`INSERT INTO users VALUES (?name, ?emails)`, user) return err } func GetUsers(db *pg.DB) ([]*User, error) { var users Users _, err := db.Query(&users, `SELECT * FROM users`) if err != nil { return nil, err } return users, nil } func main() { db := pg.Connect(&pg.Options{ User: "postgres", }) defer db.Close() _, err := db.Exec(`CREATE TEMP TABLE users (name text, emails text[])`) if err != nil { panic(err) } err = CreateUser(db, &User{"admin", []string{"admin1@admin", "admin2@admin"}}) if err != nil { panic(err) } err = CreateUser(db, &User{"root", []string{"root1@root", "root2@root"}}) if err != nil { panic(err) } users, err := GetUsers(db) if err != nil { panic(err) } fmt.Println(users[0], users[1]) }
Output: &{admin [admin1@admin admin2@admin]} &{root [root1@root root2@root]}
func (*DB) QueryOne ¶
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) var db *pg.DB func main() { var user struct { Name string } res, err := db.QueryOne(&user, ` WITH users (name) AS (VALUES (?)) SELECT * FROM users `, "admin") fmt.Println(res.Affected(), err) fmt.Println(user) }
Output: 1 <nil> {admin}
type IntegrityError ¶
type IntegrityError struct {
// contains filtered or unexported fields
}
type Ints ¶
type Ints []int64
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) var db *pg.DB func main() { var nums pg.Ints _, err := db.Query(&nums, "SELECT generate_series(0, 10)") fmt.Println(nums, err) }
Output: [0 1 2 3 4 5 6 7 8 9 10] <nil>
type Listener ¶
type Listener struct {
// contains filtered or unexported fields
}
Not thread-safe.
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) var db *pg.DB func init() { db = pg.Connect(&pg.Options{ User: "postgres", }) } func main() { ln, _ := db.Listen("mychan") done := make(chan struct{}) go func() { channel, payload, err := ln.Receive() fmt.Printf("%s %q %v", channel, payload, err) done <- struct{}{} }() _, _ = db.Exec("NOTIFY mychan, ?", "hello world") <-done }
Output: mychan "hello world" <nil>
type Loader ¶
var (
Discard Loader = discardLoader{}
)
type RawAppender ¶
type RecordReader ¶
type Stmt ¶
type Stmt struct {
// contains filtered or unexported fields
}
Not thread-safe.
type Strings ¶
type Strings []string
Example ¶
package main import ( "fmt" "github.com/lukashes/pg" ) var db *pg.DB func main() { var strs pg.Strings _, err := db.Query( &strs, "WITH users AS (VALUES ('foo'), ('bar')) SELECT * FROM users") fmt.Println(strs, err) }
Output: [foo bar] <nil>
Source Files ¶
Click to show internal directories.
Click to hide internal directories.