pg

package module
v3.1.1+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 4, 2015 License: BSD-3-Clause Imports: 24 Imported by: 0

README

PostgreSQL client for Golang Build Status

Supports:

  • Basic types: integers, floats, string, bool, time.Time, and pointers to these types.
  • sql.NullBool, sql.NullString, sql.NullInt64 and sql.Float64.
  • sql.Scanner and sql/driver.Valuer interfaces.
  • Arrays.
  • Partially hstore.
  • Transactions.
  • Prepared statements.
  • Notifications: LISTEN/NOTIFY.
  • COPY FROM and COPY TO.
  • Timeouts. Client sends CancelRequest message on timeout.
  • Connection pool.
  • Queries are retried when possible.
  • PostgreSQL to Go struct mapping.

API docs: http://godoc.org/gopkg.in/pg.v2. Make sure to check examples: http://godoc.org/gopkg.in/pg.v2#pkg-examples.

Installation

Install:

go get gopkg.in/pg.v2

Changelog

v3

Not ready for production.

v2
  • Support for named placeholders:
a := &Article{Id: 1, Name: "Hello world"}
_, err := db.ExecOne(`UPDATE articles SET name = ?name WHERE id = ?id`, a)
  • CopyFrom/CopyTo support:
r := strings.NewReader("hello\t5\nworld\t5\nfoo\t3\nbar\t3\n")
res, err := t.db.CopyFrom(r, "COPY test FROM STDIN")
  • Simplify collections:
type Articles []*Article

func (articles *Articles) New() interface{} {
    a := &Article{}
    *articles = append(*articles, a)
    return a
}
v1

Initial release.

Example

package pg_test

import (
	"fmt"

	"gopkg.in/pg.v2"
)

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 ExampleDB_Query() {
	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]}
}

Documentation

Overview

Package github.com/vmihailenco/pg implements a PostgreSQL client.

Example (ComplexQuery)
Output:

2 &{1 article1 1} &{2 article2 2}
1 &{1 article1 1}
Example (Json)
Output:

&{1 map[hello:world]}

Index

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")
)
View Source
var (
	Discard = discardLoader{}
)

Functions

func AppendQ

func AppendQ(dst []byte, src string, params ...interface{}) ([]byte, error)

func Decode

func Decode(dst interface{}, f []byte) error

func DecodeValue

func DecodeValue(dst reflect.Value, f []byte) error

Types

type Appender

type Appender interface {
	Append([]byte) []byte
}

type DB

type DB struct {
	// contains filtered or unexported fields
}

Thread-safe.

func Connect

func Connect(opt *Options) *DB
Example
Output:

<nil>

func (*DB) Begin

func (db *DB) Begin() (*Tx, error)
Example
Output:

ERROR #42P01 relation "test" does not exist:

func (*DB) Close

func (db *DB) Close() error

func (*DB) CopyFrom

func (db *DB) CopyFrom(r io.Reader, q string, args ...interface{}) (*Result, error)
Example
Output:

hello,5
foo,3

func (*DB) CopyTo

func (db *DB) CopyTo(w io.WriteCloser, q string, args ...interface{}) (*Result, error)

func (*DB) Exec

func (db *DB) Exec(q string, args ...interface{}) (res *Result, err error)
Example
Output:

0 <nil>

func (*DB) ExecOne

func (db *DB) ExecOne(q string, args ...interface{}) (*Result, error)

func (*DB) Listen

func (db *DB) Listen(channels ...string) (*Listener, error)

func (*DB) Prepare

func (db *DB) Prepare(q string) (*Stmt, error)
Example
Output:

foo bar <nil>

func (*DB) Query

func (db *DB) Query(f Factory, q string, args ...interface{}) (res *Result, err error)
Example
Output:

&{admin [admin1@admin admin2@admin]} &{root [root1@root root2@root]}

func (*DB) QueryOne

func (db *DB) QueryOne(model interface{}, q string, args ...interface{}) (*Result, error)
Example
Output:

1 <nil>
{admin}

func (*DB) RunInTransaction

func (db *DB) RunInTransaction(fn func(*Tx) error) error

RunInTransaction runs a function in a transaction. If function returns an error transaction is rollbacked, otherwise transaction is committed.

type Error

type Error interface {
	Field(byte) string
}

type F

type F string

SQL field.

func (F) Append

func (f F) Append(dst []byte) []byte

type Factory

type Factory interface {
	New() interface{}
}

type IntegrityError

type IntegrityError struct {
	// contains filtered or unexported fields
}

func (IntegrityError) Error

func (err IntegrityError) Error() string

func (IntegrityError) Field

func (err IntegrityError) Field(k byte) string

type Ints

type Ints []int64
Example
Output:

[0 1 2 3 4 5 6 7 8 9 10] <nil>

func (Ints) Append

func (ints Ints) Append(dst []byte) []byte

func (*Ints) Load

func (ints *Ints) Load(colIdx int, colName string, b []byte) error

func (*Ints) New

func (ints *Ints) New() interface{}

type IntsSet

type IntsSet map[int64]struct{}

func (IntsSet) Load

func (set IntsSet) Load(colIdx int, colName string, b []byte) error

func (IntsSet) New

func (set IntsSet) New() interface{}

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

Not thread-safe.

Example
Output:

mychan "hello world" <nil>

func (*Listener) Close

func (l *Listener) Close() error

func (*Listener) Listen

func (l *Listener) Listen(channels ...string) error

func (*Listener) Receive

func (l *Listener) Receive() (channel string, payload string, err error)

func (*Listener) ReceiveTimeout

func (l *Listener) ReceiveTimeout(readTimeout time.Duration) (channel, payload string, err error)

type Loader

type Loader interface {
	Load(colIdx int, colName string, b []byte) error
}

func LoadInto

func LoadInto(values ...interface{}) Loader
Example
Output:

foo bar <nil>

func NewLoader

func NewLoader(dst interface{}) (Loader, error)

type Options

type Options struct {
	Network  string
	Host     string
	Port     string
	User     string
	Password string
	Database string
	SSL      bool

	// Params specify connection run-time configuration parameters.
	Params map[string]interface{}

	PoolSize int

	DialTimeout  time.Duration
	ReadTimeout  time.Duration
	WriteTimeout time.Duration

	IdleTimeout        time.Duration
	IdleCheckFrequency time.Duration
}

type Q

type Q string

Raw SQL query.

func FormatQ

func FormatQ(src string, params ...interface{}) (Q, error)

func MustFormatQ

func MustFormatQ(src string, params ...interface{}) Q

func (Q) Append

func (q Q) Append(dst []byte) []byte

func (Q) AppendRaw

func (q Q) AppendRaw(dst []byte) []byte

type RawAppender

type RawAppender interface {
	AppendRaw([]byte) []byte
}

type RecordReader

type RecordReader interface {
	Read() ([]string, error)
}

type Result

type Result struct {
	// contains filtered or unexported fields
}

func (*Result) Affected

func (r *Result) Affected() int

type Stmt

type Stmt struct {
	// contains filtered or unexported fields
}

Not thread-safe.

func (*Stmt) Close

func (stmt *Stmt) Close() error

func (*Stmt) Exec

func (stmt *Stmt) Exec(args ...interface{}) (res *Result, err error)

func (*Stmt) ExecOne

func (stmt *Stmt) ExecOne(args ...interface{}) (*Result, error)

func (*Stmt) Query

func (stmt *Stmt) Query(f Factory, args ...interface{}) (res *Result, err error)

func (*Stmt) QueryOne

func (stmt *Stmt) QueryOne(model interface{}, args ...interface{}) (*Result, error)

type Strings

type Strings []string
Example
Output:

[foo bar] <nil>

func (Strings) Append

func (strings Strings) Append(dst []byte) []byte

func (*Strings) Load

func (strings *Strings) Load(colIdx int, colName string, b []byte) error

func (*Strings) New

func (strings *Strings) New() interface{}

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Not thread-safe.

func (*Tx) Commit

func (tx *Tx) Commit() error

func (*Tx) Exec

func (tx *Tx) Exec(q string, args ...interface{}) (*Result, error)

func (*Tx) ExecOne

func (tx *Tx) ExecOne(q string, args ...interface{}) (*Result, error)

func (*Tx) Prepare

func (tx *Tx) Prepare(q string) (*Stmt, error)

TODO(vmihailenco): track and close prepared statements

func (*Tx) Query

func (tx *Tx) Query(f Factory, q string, args ...interface{}) (*Result, error)

func (*Tx) QueryOne

func (tx *Tx) QueryOne(model interface{}, q string, args ...interface{}) (*Result, error)

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Directories

Path Synopsis
Utility functions used in pg package.
Utility functions used in pg package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL