Archived
1
0

update vendored lib

This commit is contained in:
Jeff Becker 2018-11-28 17:55:31 -05:00
parent a9f8bf2f8c
commit 05ebac9aa5
No known key found for this signature in database
GPG Key ID: F357B3B42F6F9B05
32 changed files with 1304 additions and 328 deletions

View File

@ -70,4 +70,17 @@ postgresql_uninstall() {
sudo rm -rf /var/lib/postgresql
}
megacheck_install() {
# Lock megacheck version at $MEGACHECK_VERSION to prevent spontaneous
# new error messages in old code.
go get -d honnef.co/go/tools/...
git -C $GOPATH/src/honnef.co/go/tools/ checkout $MEGACHECK_VERSION
go install honnef.co/go/tools/cmd/megacheck
megacheck --version
}
golint_install() {
go get golang.org/x/lint/golint
}
$1

View File

@ -1,10 +1,9 @@
language: go
go:
- 1.5.x
- 1.6.x
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
- master
sudo: true
@ -15,7 +14,9 @@ env:
- PQGOSSLTESTS=1
- PQSSLCERTTEST_PATH=$PWD/certs
- PGHOST=127.0.0.1
- MEGACHECK_VERSION=2017.2.2
matrix:
- PGVERSION=10
- PGVERSION=9.6
- PGVERSION=9.5
- PGVERSION=9.4
@ -30,6 +31,8 @@ before_install:
- ./.travis.sh postgresql_install
- ./.travis.sh postgresql_configure
- ./.travis.sh client_configure
- ./.travis.sh megacheck_install
- ./.travis.sh golint_install
- go get golang.org/x/tools/cmd/goimports
before_script:
@ -41,5 +44,7 @@ script:
- >
goimports -d -e $(find -name '*.go') | awk '{ print } END { exit NR == 0 ? 0 : 1 }'
- go vet ./...
- megacheck -go 1.9 ./...
- golint ./...
- PQTEST_BINARY_PARAMETERS=no go test -race -v ./...
- PQTEST_BINARY_PARAMETERS=yes go test -race -v ./...

View File

@ -1,5 +1,6 @@
# pq - A pure Go postgres driver for Go's database/sql package
[![GoDoc](https://godoc.org/github.com/lib/pq?status.svg)](https://godoc.org/github.com/lib/pq)
[![Build Status](https://travis-ci.org/lib/pq.svg?branch=master)](https://travis-ci.org/lib/pq)
## Install
@ -9,22 +10,11 @@
## Docs
For detailed documentation and basic usage examples, please see the package
documentation at <http://godoc.org/github.com/lib/pq>.
documentation at <https://godoc.org/github.com/lib/pq>.
## Tests
`go test` is used for testing. A running PostgreSQL server is
required, with the ability to log in. The default database to connect
to test with is "pqgotest," but it can be overridden using environment
variables.
Example:
PGHOST=/run/postgresql go test github.com/lib/pq
Optionally, a benchmark suite can be run as part of the tests:
PGHOST=/run/postgresql go test -bench .
`go test` is used for testing. See [TESTS.md](TESTS.md) for more details.
## Features

View File

@ -0,0 +1,33 @@
# Tests
## Running Tests
`go test` is used for testing. A running PostgreSQL
server is required, with the ability to log in. The
database to connect to test with is "pqgotest," on
"localhost" but these can be overridden using [environment
variables](https://www.postgresql.org/docs/9.3/static/libpq-envars.html).
Example:
PGHOST=/run/postgresql go test
## Benchmarks
A benchmark suite can be run as part of the tests:
go test -bench .
## Example setup (Docker)
Run a postgres container:
```
docker run --expose 5432:5432 postgres
```
Run tests:
```
PGHOST=localhost PGPORT=5432 PGUSER=postgres PGSSLMODE=disable PGDATABASE=postgres go test
```

View File

@ -13,7 +13,7 @@ import (
var typeByteSlice = reflect.TypeOf([]byte{})
var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
var typeSqlScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
var typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
// Array returns the optimal driver.Valuer and sql.Scanner for an array or
// slice of any dimension.
@ -278,7 +278,7 @@ func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]b
// TODO calculate the assign function for other types
// TODO repeat this section on the element type of arrays or slices (multidimensional)
{
if reflect.PtrTo(rt).Implements(typeSqlScanner) {
if reflect.PtrTo(rt).Implements(typeSQLScanner) {
// dest is always addressable because it is an element of a slice.
assign = func(src []byte, dest reflect.Value) (err error) {
ss := dest.Addr().Interface().(sql.Scanner)
@ -587,7 +587,7 @@ func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) {
}
}
var del string = ","
var del = ","
var err error
var iv interface{} = rv.Interface()

View File

@ -89,9 +89,7 @@ func TestParseArrayError(t *testing.T) {
}
func TestArrayScanner(t *testing.T) {
var s sql.Scanner
s = Array(&[]bool{})
var s sql.Scanner = Array(&[]bool{})
if _, ok := s.(*BoolArray); !ok {
t.Errorf("Expected *BoolArray, got %T", s)
}
@ -126,9 +124,7 @@ func TestArrayScanner(t *testing.T) {
}
func TestArrayValuer(t *testing.T) {
var v driver.Valuer
v = Array([]bool{})
var v driver.Valuer = Array([]bool{})
if _, ok := v.(*BoolArray); !ok {
t.Errorf("Expected *BoolArray, got %T", v)
}
@ -1193,9 +1189,7 @@ func TestGenericArrayValue(t *testing.T) {
}
func TestGenericArrayValueErrors(t *testing.T) {
var v []interface{}
v = []interface{}{func() {}}
v := []interface{}{func() {}}
if _, err := (GenericArray{v}).Value(); err == nil {
t.Errorf("Expected error for %q, got nil", v)
}

View File

@ -1,10 +1,9 @@
// +build go1.1
package pq
import (
"bufio"
"bytes"
"context"
"database/sql"
"database/sql/driver"
"io"
@ -156,7 +155,7 @@ func benchMockQuery(b *testing.B, c *conn, query string) {
b.Fatal(err)
}
defer stmt.Close()
rows, err := stmt.Query(nil)
rows, err := stmt.(driver.StmtQueryContext).QueryContext(context.Background(), nil)
if err != nil {
b.Fatal(err)
}
@ -266,7 +265,7 @@ func BenchmarkMockPreparedSelectSeries(b *testing.B) {
}
func benchPreparedMockQuery(b *testing.B, c *conn, stmt driver.Stmt) {
rows, err := stmt.Query(nil)
rows, err := stmt.(driver.StmtQueryContext).QueryContext(context.Background(), nil)
if err != nil {
b.Fatal(err)
}

View File

@ -27,16 +27,20 @@ var (
ErrNotSupported = errors.New("pq: Unsupported command")
ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction")
ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server")
ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less.")
ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly.")
ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less")
ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly")
errUnexpectedReady = errors.New("unexpected ReadyForQuery")
errNoRowsAffected = errors.New("no RowsAffected available after the empty statement")
errNoLastInsertId = errors.New("no LastInsertId available after the empty statement")
errNoLastInsertID = errors.New("no LastInsertId available after the empty statement")
)
// Driver is the Postgres database driver.
type Driver struct{}
// Open opens a new connection to the database. name is a connection string.
// Most users should only use it through database/sql package from the standard
// library.
func (d *Driver) Open(name string) (driver.Conn, error) {
return Open(name)
}
@ -78,6 +82,8 @@ func (s transactionStatus) String() string {
panic("not reached")
}
// Dialer is the dialer interface. It can be used to obtain more control over
// how pq creates network connections.
type Dialer interface {
Dial(network, address string) (net.Conn, error)
DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)
@ -131,7 +137,7 @@ type conn struct {
}
// Handle driver-side settings in parsed connection string.
func (c *conn) handleDriverSettings(o values) (err error) {
func (cn *conn) handleDriverSettings(o values) (err error) {
boolSetting := func(key string, val *bool) error {
if value, ok := o[key]; ok {
if value == "yes" {
@ -145,18 +151,14 @@ func (c *conn) handleDriverSettings(o values) (err error) {
return nil
}
err = boolSetting("disable_prepared_binary_result", &c.disablePreparedBinaryResult)
err = boolSetting("disable_prepared_binary_result", &cn.disablePreparedBinaryResult)
if err != nil {
return err
}
err = boolSetting("binary_parameters", &c.binaryParameters)
if err != nil {
return err
}
return nil
return boolSetting("binary_parameters", &cn.binaryParameters)
}
func (c *conn) handlePgpass(o values) {
func (cn *conn) handlePgpass(o values) {
// if a password was supplied, do not process .pgpass
if _, ok := o["password"]; ok {
return
@ -165,11 +167,16 @@ func (c *conn) handlePgpass(o values) {
if filename == "" {
// XXX this code doesn't work on Windows where the default filename is
// XXX %APPDATA%\postgresql\pgpass.conf
user, err := user.Current()
if err != nil {
return
// Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470
userHome := os.Getenv("HOME")
if userHome == "" {
user, err := user.Current()
if err != nil {
return
}
userHome = user.HomeDir
}
filename = filepath.Join(user.HomeDir, ".pgpass")
filename = filepath.Join(userHome, ".pgpass")
}
fileinfo, err := os.Stat(filename)
if err != nil {
@ -229,18 +236,22 @@ func (c *conn) handlePgpass(o values) {
}
}
func (c *conn) writeBuf(b byte) *writeBuf {
c.scratch[0] = b
func (cn *conn) writeBuf(b byte) *writeBuf {
cn.scratch[0] = b
return &writeBuf{
buf: c.scratch[:5],
buf: cn.scratch[:5],
pos: 1,
}
}
// Open opens a new connection to the database. name is a connection string.
// Most users should only use it through database/sql package from the standard
// library.
func Open(name string) (_ driver.Conn, err error) {
return DialOpen(defaultDialer{}, name)
}
// DialOpen opens a new connection to the database using a dialer.
func DialOpen(d Dialer, name string) (_ driver.Conn, err error) {
// Handle any panics during connection initialization. Note that we
// specifically do *not* want to use errRecover(), as that would turn any
@ -310,9 +321,8 @@ func DialOpen(d Dialer, name string) (_ driver.Conn, err error) {
u, err := userCurrent()
if err != nil {
return nil, err
} else {
o["user"] = u
}
o["user"] = u
}
cn := &conn{
@ -329,7 +339,20 @@ func DialOpen(d Dialer, name string) (_ driver.Conn, err error) {
if err != nil {
return nil, err
}
cn.ssl(o)
err = cn.ssl(o)
if err != nil {
return nil, err
}
// cn.startup panics on error. Make sure we don't leak cn.c.
panicking := true
defer func() {
if panicking {
cn.c.Close()
}
}()
cn.buf = bufio.NewReader(cn.c)
cn.startup(o)
@ -337,6 +360,7 @@ func DialOpen(d Dialer, name string) (_ driver.Conn, err error) {
if timeout, ok := o["connect_timeout"]; ok && timeout != "0" {
err = cn.c.SetDeadline(time.Time{})
}
panicking = false
return cn, err
}
@ -506,13 +530,17 @@ func (cn *conn) checkIsInTransaction(intxn bool) {
}
func (cn *conn) Begin() (_ driver.Tx, err error) {
return cn.begin("")
}
func (cn *conn) begin(mode string) (_ driver.Tx, err error) {
if cn.bad {
return nil, driver.ErrBadConn
}
defer cn.errRecover(&err)
cn.checkIsInTransaction(false)
_, commandTag, err := cn.simpleExec("BEGIN")
_, commandTag, err := cn.simpleExec("BEGIN" + mode)
if err != nil {
return nil, err
}
@ -694,7 +722,7 @@ var emptyRows noRows
var _ driver.Result = noRows{}
func (noRows) LastInsertId() (int64, error) {
return 0, errNoLastInsertId
return 0, errNoLastInsertID
}
func (noRows) RowsAffected() (int64, error) {
@ -703,7 +731,7 @@ func (noRows) RowsAffected() (int64, error) {
// Decides which column formats to use for a prepared statement. The input is
// an array of type oids, one element per result column.
func decideColumnFormats(colTyps []oid.Oid, forceText bool) (colFmts []format, colFmtData []byte) {
func decideColumnFormats(colTyps []fieldDesc, forceText bool) (colFmts []format, colFmtData []byte) {
if len(colTyps) == 0 {
return nil, colFmtDataAllText
}
@ -715,8 +743,8 @@ func decideColumnFormats(colTyps []oid.Oid, forceText bool) (colFmts []format, c
allBinary := true
allText := true
for i, o := range colTyps {
switch o {
for i, t := range colTyps {
switch t.OID {
// This is the list of types to use binary mode for when receiving them
// through a prepared statement. If a type appears in this list, it
// must also be implemented in binaryDecode in encode.go.
@ -836,16 +864,15 @@ func (cn *conn) query(query string, args []driver.Value) (_ *rows, err error) {
rows.colNames, rows.colFmts, rows.colTyps = cn.readPortalDescribeResponse()
cn.postExecuteWorkaround()
return rows, nil
} else {
st := cn.prepareTo(query, "")
st.exec(args)
return &rows{
cn: cn,
colNames: st.colNames,
colTyps: st.colTyps,
colFmts: st.colFmts,
}, nil
}
st := cn.prepareTo(query, "")
st.exec(args)
return &rows{
cn: cn,
colNames: st.colNames,
colTyps: st.colTyps,
colFmts: st.colFmts,
}, nil
}
// Implement the optional "Execer" interface for one-shot queries
@ -872,17 +899,16 @@ func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err
cn.postExecuteWorkaround()
res, _, err = cn.readExecuteResponse("Execute")
return res, err
} else {
// Use the unnamed statement to defer planning until bind
// time, or else value-based selectivity estimates cannot be
// used.
st := cn.prepareTo(query, "")
r, err := st.Exec(args)
if err != nil {
panic(err)
}
return r, err
}
// Use the unnamed statement to defer planning until bind
// time, or else value-based selectivity estimates cannot be
// used.
st := cn.prepareTo(query, "")
r, err := st.Exec(args)
if err != nil {
panic(err)
}
return r, err
}
func (cn *conn) send(m *writeBuf) {
@ -1007,30 +1033,35 @@ func (cn *conn) recv1() (t byte, r *readBuf) {
return t, r
}
func (cn *conn) ssl(o values) {
upgrade := ssl(o)
func (cn *conn) ssl(o values) error {
upgrade, err := ssl(o)
if err != nil {
return err
}
if upgrade == nil {
// Nothing to do
return
return nil
}
w := cn.writeBuf(0)
w.int32(80877103)
if err := cn.sendStartupPacket(w); err != nil {
panic(err)
if err = cn.sendStartupPacket(w); err != nil {
return err
}
b := cn.scratch[:1]
_, err := io.ReadFull(cn.c, b)
_, err = io.ReadFull(cn.c, b)
if err != nil {
panic(err)
return err
}
if b[0] != 'S' {
panic(ErrSSLNotSupported)
return ErrSSLNotSupported
}
cn.c = upgrade(cn.c)
cn.c, err = upgrade(cn.c)
return err
}
// isDriverSetting returns true iff a setting is purely for configuring the
@ -1143,10 +1174,10 @@ const formatText format = 0
const formatBinary format = 1
// One result-column format code with the value 1 (i.e. all binary).
var colFmtDataAllBinary []byte = []byte{0, 1, 0, 1}
var colFmtDataAllBinary = []byte{0, 1, 0, 1}
// No result-column format codes (i.e. all text).
var colFmtDataAllText []byte = []byte{0, 0}
var colFmtDataAllText = []byte{0, 0}
type stmt struct {
cn *conn
@ -1154,7 +1185,7 @@ type stmt struct {
colNames []string
colFmts []format
colFmtData []byte
colTyps []oid.Oid
colTyps []fieldDesc
paramTyps []oid.Oid
closed bool
}
@ -1317,7 +1348,7 @@ type rows struct {
cn *conn
finish func()
colNames []string
colTyps []oid.Oid
colTyps []fieldDesc
colFmts []format
done bool
rb readBuf
@ -1335,7 +1366,12 @@ func (rs *rows) Close() error {
switch err {
case nil:
case io.EOF:
return nil
// rs.Next can return io.EOF on both 'Z' (ready for query) and 'T' (row
// description, used with HasNextResultSet). We need to fetch messages until
// we hit a 'Z', which is done by waiting for done to be set.
if rs.done {
return nil
}
default:
return err
}
@ -1400,7 +1436,7 @@ func (rs *rows) Next(dest []driver.Value) (err error) {
dest[i] = nil
continue
}
dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i], rs.colFmts[i])
dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i].OID, rs.colFmts[i])
}
return
case 'T':
@ -1425,7 +1461,8 @@ func (rs *rows) NextResultSet() error {
//
// tblname := "my_table"
// data := "my_data"
// err = db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", pq.QuoteIdentifier(tblname)), data)
// quoted := pq.QuoteIdentifier(tblname)
// err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data)
//
// Any double quotes in name will be escaped. The quoted identifier will be
// case sensitive when used in a query. If the input string contains a zero
@ -1506,7 +1543,7 @@ func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) {
cn.send(b)
}
func (c *conn) processParameterStatus(r *readBuf) {
func (cn *conn) processParameterStatus(r *readBuf) {
var err error
param := r.string()
@ -1517,13 +1554,13 @@ func (c *conn) processParameterStatus(r *readBuf) {
var minor int
_, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor)
if err == nil {
c.parameterStatus.serverVersion = major1*10000 + major2*100 + minor
cn.parameterStatus.serverVersion = major1*10000 + major2*100 + minor
}
case "TimeZone":
c.parameterStatus.currentLocation, err = time.LoadLocation(r.string())
cn.parameterStatus.currentLocation, err = time.LoadLocation(r.string())
if err != nil {
c.parameterStatus.currentLocation = nil
cn.parameterStatus.currentLocation = nil
}
default:
@ -1531,8 +1568,8 @@ func (c *conn) processParameterStatus(r *readBuf) {
}
}
func (c *conn) processReadyForQuery(r *readBuf) {
c.txnStatus = transactionStatus(r.byte())
func (cn *conn) processReadyForQuery(r *readBuf) {
cn.txnStatus = transactionStatus(r.byte())
}
func (cn *conn) readReadyForQuery() {
@ -1547,9 +1584,9 @@ func (cn *conn) readReadyForQuery() {
}
}
func (c *conn) processBackendKeyData(r *readBuf) {
c.processID = r.int32()
c.secretKey = r.int32()
func (cn *conn) processBackendKeyData(r *readBuf) {
cn.processID = r.int32()
cn.secretKey = r.int32()
}
func (cn *conn) readParseResponse() {
@ -1567,7 +1604,7 @@ func (cn *conn) readParseResponse() {
}
}
func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []oid.Oid) {
func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []fieldDesc) {
for {
t, r := cn.recv1()
switch t {
@ -1593,7 +1630,7 @@ func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames [
}
}
func (cn *conn) readPortalDescribeResponse() (colNames []string, colFmts []format, colTyps []oid.Oid) {
func (cn *conn) readPortalDescribeResponse() (colNames []string, colFmts []format, colTyps []fieldDesc) {
t, r := cn.recv1()
switch t {
case 'T':
@ -1689,31 +1726,33 @@ func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, co
}
}
func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []oid.Oid) {
func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []fieldDesc) {
n := r.int16()
colNames = make([]string, n)
colTyps = make([]oid.Oid, n)
colTyps = make([]fieldDesc, n)
for i := range colNames {
colNames[i] = r.string()
r.next(6)
colTyps[i] = r.oid()
r.next(6)
colTyps[i].OID = r.oid()
colTyps[i].Len = r.int16()
colTyps[i].Mod = r.int32()
// format code not known when describing a statement; always 0
r.next(2)
}
return
}
func parsePortalRowDescribe(r *readBuf) (colNames []string, colFmts []format, colTyps []oid.Oid) {
func parsePortalRowDescribe(r *readBuf) (colNames []string, colFmts []format, colTyps []fieldDesc) {
n := r.int16()
colNames = make([]string, n)
colFmts = make([]format, n)
colTyps = make([]oid.Oid, n)
colTyps = make([]fieldDesc, n)
for i := range colNames {
colNames[i] = r.string()
r.next(6)
colTyps[i] = r.oid()
r.next(6)
colTyps[i].OID = r.oid()
colTyps[i].Len = r.int16()
colTyps[i].Mod = r.int32()
colFmts[i] = format(r.int16())
}
return

View File

@ -1,11 +1,10 @@
// +build go1.8
package pq
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"io/ioutil"
)
@ -19,6 +18,9 @@ func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.Na
finish := cn.watchCancel(ctx)
r, err := cn.query(query, list)
if err != nil {
if finish != nil {
finish()
}
return nil, err
}
r.finish = finish
@ -41,13 +43,30 @@ func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.Nam
// Implement the "ConnBeginTx" interface
func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
if opts.Isolation != 0 {
return nil, errors.New("isolation levels not supported")
var mode string
switch sql.IsolationLevel(opts.Isolation) {
case sql.LevelDefault:
// Don't touch mode: use the server's default
case sql.LevelReadUncommitted:
mode = " ISOLATION LEVEL READ UNCOMMITTED"
case sql.LevelReadCommitted:
mode = " ISOLATION LEVEL READ COMMITTED"
case sql.LevelRepeatableRead:
mode = " ISOLATION LEVEL REPEATABLE READ"
case sql.LevelSerializable:
mode = " ISOLATION LEVEL SERIALIZABLE"
default:
return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation)
}
if opts.ReadOnly {
return nil, errors.New("read-only transactions not supported")
mode += " READ ONLY"
} else {
mode += " READ WRITE"
}
tx, err := cn.Begin()
tx, err := cn.begin(mode)
if err != nil {
return nil, err
}
@ -87,7 +106,10 @@ func (cn *conn) cancel() error {
can := conn{
c: c,
}
can.ssl(cn.opts)
err = can.ssl(cn.opts)
if err != nil {
return err
}
w := can.writeBuf(0)
w.int32(80877102) // cancel request code

View File

@ -1,6 +1,7 @@
package pq
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
@ -28,7 +29,7 @@ func forceBinaryParameters() bool {
}
}
func openTestConnConninfo(conninfo string) (*sql.DB, error) {
func testConninfo(conninfo string) string {
defaultTo := func(envvar string, value string) {
if os.Getenv(envvar) == "" {
os.Setenv(envvar, value)
@ -43,8 +44,11 @@ func openTestConnConninfo(conninfo string) (*sql.DB, error) {
!strings.HasPrefix(conninfo, "postgresql://") {
conninfo = conninfo + " binary_parameters=yes"
}
return conninfo
}
return sql.Open("postgres", conninfo)
func openTestConnConninfo(conninfo string) (*sql.DB, error) {
return sql.Open("postgres", testConninfo(conninfo))
}
func openTestConn(t Fatalistic) *sql.DB {
@ -136,7 +140,7 @@ func TestOpenURL(t *testing.T) {
testURL("postgresql://")
}
const pgpass_file = "/tmp/pqgotest_pgpass"
const pgpassFile = "/tmp/pqgotest_pgpass"
func TestPgpass(t *testing.T) {
if os.Getenv("TRAVIS") != "true" {
@ -160,11 +164,11 @@ func TestPgpass(t *testing.T) {
rows, err := txn.Query("SELECT USER")
if err != nil {
txn.Rollback()
rows.Close()
if expected != "fail" {
t.Fatalf(reason, err)
}
} else {
rows.Close()
if expected != "ok" {
t.Fatalf(reason, err)
}
@ -172,10 +176,10 @@ func TestPgpass(t *testing.T) {
txn.Rollback()
}
testAssert("", "ok", "missing .pgpass, unexpected error %#v")
os.Setenv("PGPASSFILE", pgpass_file)
os.Setenv("PGPASSFILE", pgpassFile)
testAssert("host=/tmp", "fail", ", unexpected error %#v")
os.Remove(pgpass_file)
pgpass, err := os.OpenFile(pgpass_file, os.O_RDWR|os.O_CREATE, 0644)
os.Remove(pgpassFile)
pgpass, err := os.OpenFile(pgpassFile, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
t.Fatalf("Unexpected error writing pgpass file %#v", err)
}
@ -213,7 +217,7 @@ localhost:*:*:*:pass_C
// wrong permissions for the pgpass file means it should be ignored
assertPassword(values{"host": "example.com", "user": "foo"}, "")
// fix the permissions and check if it has taken effect
os.Chmod(pgpass_file, 0600)
os.Chmod(pgpassFile, 0600)
assertPassword(values{"host": "server", "dbname": "some_db", "user": "some_user"}, "pass_A")
assertPassword(values{"host": "example.com", "user": "foo"}, "pass_fallback")
assertPassword(values{"host": "example.com", "dbname": "some_db", "user": "some_user"}, "pass_B")
@ -221,7 +225,7 @@ localhost:*:*:*:pass_C
assertPassword(values{"host": "", "user": "some_user"}, "pass_C")
assertPassword(values{"host": "/tmp", "user": "some_user"}, "pass_C")
// cleanup
os.Remove(pgpass_file)
os.Remove(pgpassFile)
os.Setenv("PGPASSFILE", "")
}
@ -393,8 +397,8 @@ func TestEmptyQuery(t *testing.T) {
if _, err := res.RowsAffected(); err != errNoRowsAffected {
t.Fatalf("expected %s, got %v", errNoRowsAffected, err)
}
if _, err := res.LastInsertId(); err != errNoLastInsertId {
t.Fatalf("expected %s, got %v", errNoLastInsertId, err)
if _, err := res.LastInsertId(); err != errNoLastInsertID {
t.Fatalf("expected %s, got %v", errNoLastInsertID, err)
}
rows, err := db.Query("")
if err != nil {
@ -425,8 +429,8 @@ func TestEmptyQuery(t *testing.T) {
if _, err := res.RowsAffected(); err != errNoRowsAffected {
t.Fatalf("expected %s, got %v", errNoRowsAffected, err)
}
if _, err := res.LastInsertId(); err != errNoLastInsertId {
t.Fatalf("expected %s, got %v", errNoLastInsertId, err)
if _, err := res.LastInsertId(); err != errNoLastInsertID {
t.Fatalf("expected %s, got %v", errNoLastInsertID, err)
}
rows, err = stmt.Query()
if err != nil {
@ -637,6 +641,57 @@ func TestErrorDuringStartup(t *testing.T) {
}
}
type testConn struct {
closed bool
net.Conn
}
func (c *testConn) Close() error {
c.closed = true
return c.Conn.Close()
}
type testDialer struct {
conns []*testConn
}
func (d *testDialer) Dial(ntw, addr string) (net.Conn, error) {
c, err := net.Dial(ntw, addr)
if err != nil {
return nil, err
}
tc := &testConn{Conn: c}
d.conns = append(d.conns, tc)
return tc, nil
}
func (d *testDialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) {
c, err := net.DialTimeout(ntw, addr, timeout)
if err != nil {
return nil, err
}
tc := &testConn{Conn: c}
d.conns = append(d.conns, tc)
return tc, nil
}
func TestErrorDuringStartupClosesConn(t *testing.T) {
// Don't use the normal connection setup, this is intended to
// blow up in the startup packet from a non-existent user.
var d testDialer
c, err := DialOpen(&d, testConninfo("user=thisuserreallydoesntexist"))
if err == nil {
c.Close()
t.Fatal("expected dial error")
}
if len(d.conns) != 1 {
t.Fatalf("got len(d.conns) = %d, want = %d", len(d.conns), 1)
}
if !d.conns[0].closed {
t.Error("connection leaked")
}
}
func TestBadConn(t *testing.T) {
var err error
@ -935,12 +990,14 @@ func TestParseErrorInExtendedQuery(t *testing.T) {
db := openTestConn(t)
defer db.Close()
rows, err := db.Query("PARSE_ERROR $1", 1)
if err == nil {
t.Fatal("expected error")
_, err := db.Query("PARSE_ERROR $1", 1)
pqErr, _ := err.(*Error)
// Expecting a syntax error.
if err == nil || pqErr == nil || pqErr.Code != "42601" {
t.Fatalf("expected syntax error, got %s", err)
}
rows, err = db.Query("SELECT 1")
rows, err := db.Query("SELECT 1")
if err != nil {
t.Fatal(err)
}
@ -1053,16 +1110,16 @@ func TestIssue282(t *testing.T) {
db := openTestConn(t)
defer db.Close()
var search_path string
var searchPath string
err := db.QueryRow(`
SET LOCAL search_path TO pg_catalog;
SET LOCAL search_path TO pg_catalog;
SHOW search_path`).Scan(&search_path)
SHOW search_path`).Scan(&searchPath)
if err != nil {
t.Fatal(err)
}
if search_path != "pg_catalog" {
t.Fatalf("unexpected search_path %s", search_path)
if searchPath != "pg_catalog" {
t.Fatalf("unexpected search_path %s", searchPath)
}
}
@ -1205,16 +1262,11 @@ func TestParseComplete(t *testing.T) {
tpc("SELECT foo", "", 0, true) // invalid row count
}
func TestExecerInterface(t *testing.T) {
// Gin up a straw man private struct just for the type check
cn := &conn{c: nil}
var cni interface{} = cn
_, ok := cni.(driver.Execer)
if !ok {
t.Fatal("Driver doesn't implement Execer")
}
}
// Test interface conformance.
var (
_ driver.ExecerContext = (*conn)(nil)
_ driver.QueryerContext = (*conn)(nil)
)
func TestNullAfterNonNull(t *testing.T) {
db := openTestConn(t)
@ -1392,36 +1444,29 @@ func TestParseOpts(t *testing.T) {
}
func TestRuntimeParameters(t *testing.T) {
type RuntimeTestResult int
const (
ResultUnknown RuntimeTestResult = iota
ResultSuccess
ResultError // other error
)
tests := []struct {
conninfo string
param string
expected string
expectedOutcome RuntimeTestResult
conninfo string
param string
expected string
success bool
}{
// invalid parameter
{"DOESNOTEXIST=foo", "", "", ResultError},
{"DOESNOTEXIST=foo", "", "", false},
// we can only work with a specific value for these two
{"client_encoding=SQL_ASCII", "", "", ResultError},
{"datestyle='ISO, YDM'", "", "", ResultError},
{"client_encoding=SQL_ASCII", "", "", false},
{"datestyle='ISO, YDM'", "", "", false},
// "options" should work exactly as it does in libpq
{"options='-c search_path=pqgotest'", "search_path", "pqgotest", ResultSuccess},
{"options='-c search_path=pqgotest'", "search_path", "pqgotest", true},
// pq should override client_encoding in this case
{"options='-c client_encoding=SQL_ASCII'", "client_encoding", "UTF8", ResultSuccess},
{"options='-c client_encoding=SQL_ASCII'", "client_encoding", "UTF8", true},
// allow client_encoding to be set explicitly
{"client_encoding=UTF8", "client_encoding", "UTF8", ResultSuccess},
{"client_encoding=UTF8", "client_encoding", "UTF8", true},
// test a runtime parameter not supported by libpq
{"work_mem='139kB'", "work_mem", "139kB", ResultSuccess},
{"work_mem='139kB'", "work_mem", "139kB", true},
// test fallback_application_name
{"application_name=foo fallback_application_name=bar", "application_name", "foo", ResultSuccess},
{"application_name='' fallback_application_name=bar", "application_name", "", ResultSuccess},
{"fallback_application_name=bar", "application_name", "bar", ResultSuccess},
{"application_name=foo fallback_application_name=bar", "application_name", "foo", true},
{"application_name='' fallback_application_name=bar", "application_name", "", true},
{"fallback_application_name=bar", "application_name", "bar", true},
}
for _, test := range tests {
@ -1436,23 +1481,23 @@ func TestRuntimeParameters(t *testing.T) {
continue
}
tryGetParameterValue := func() (value string, outcome RuntimeTestResult) {
tryGetParameterValue := func() (value string, success bool) {
defer db.Close()
row := db.QueryRow("SELECT current_setting($1)", test.param)
err = row.Scan(&value)
if err != nil {
return "", ResultError
return "", false
}
return value, ResultSuccess
return value, true
}
value, outcome := tryGetParameterValue()
if outcome != test.expectedOutcome && outcome == ResultError {
value, success := tryGetParameterValue()
if success != test.success && !test.success {
t.Fatalf("%v: unexpected error: %v", test.conninfo, err)
}
if outcome != test.expectedOutcome {
if success != test.success {
t.Fatalf("unexpected outcome %v (was expecting %v) for conninfo \"%s\"",
outcome, test.expectedOutcome, test.conninfo)
success, test.success, test.conninfo)
}
if value != test.expected {
t.Fatalf("bad value for %s: got %s, want %s with conninfo \"%s\"",
@ -1565,10 +1610,10 @@ func TestRowsResultTag(t *testing.T) {
t.Fatal(err)
}
defer conn.Close()
q := conn.(driver.Queryer)
q := conn.(driver.QueryerContext)
for _, test := range tests {
if rows, err := q.Query(test.query, nil); err != nil {
if rows, err := q.QueryContext(context.Background(), test.query, nil); err != nil {
t.Fatalf("%s: %s", test.query, err)
} else {
r := rows.(ResultTag)
@ -1583,3 +1628,32 @@ func TestRowsResultTag(t *testing.T) {
}
}
}
// TestQuickClose tests that closing a query early allows a subsequent query to work.
func TestQuickClose(t *testing.T) {
db := openTestConn(t)
defer db.Close()
tx, err := db.Begin()
if err != nil {
t.Fatal(err)
}
rows, err := tx.Query("SELECT 1; SELECT 2;")
if err != nil {
t.Fatal(err)
}
if err := rows.Close(); err != nil {
t.Fatal(err)
}
var id int
if err := tx.QueryRow("SELECT 3").Scan(&id); err != nil {
t.Fatal(err)
}
if id != 3 {
t.Fatalf("unexpected %d", id)
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
}

View File

@ -0,0 +1,43 @@
// +build go1.10
package pq
import (
"context"
"database/sql/driver"
)
// Connector represents a fixed configuration for the pq driver with a given
// name. Connector satisfies the database/sql/driver Connector interface and
// can be used to create any number of DB Conn's via the database/sql OpenDB
// function.
//
// See https://golang.org/pkg/database/sql/driver/#Connector.
// See https://golang.org/pkg/database/sql/#OpenDB.
type connector struct {
name string
}
// Connect returns a connection to the database using the fixed configuration
// of this Connector. Context is not used.
func (c *connector) Connect(_ context.Context) (driver.Conn, error) {
return (&Driver{}).Open(c.name)
}
// Driver returnst the underlying driver of this Connector.
func (c *connector) Driver() driver.Driver {
return &Driver{}
}
var _ driver.Connector = &connector{}
// NewConnector returns a connector for the pq driver in a fixed configuration
// with the given name. The returned connector can be used to create any number
// of equivalent Conn's. The returned connector is intended to be used with
// database/sql.OpenDB.
//
// See https://golang.org/pkg/database/sql/driver/#Connector.
// See https://golang.org/pkg/database/sql/#OpenDB.
func NewConnector(name string) (driver.Connector, error) {
return &connector{name: name}, nil
}

View File

@ -0,0 +1,33 @@
// +build go1.10
package pq_test
import (
"database/sql"
"fmt"
"github.com/lib/pq"
)
func ExampleNewConnector() {
name := ""
connector, err := pq.NewConnector(name)
if err != nil {
fmt.Println(err)
return
}
db := sql.OpenDB(connector)
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
// Use the DB
txn, err := db.Begin()
if err != nil {
fmt.Println(err)
return
}
txn.Rollback()
}

View File

@ -0,0 +1,67 @@
// +build go1.10
package pq
import (
"context"
"database/sql"
"database/sql/driver"
"testing"
)
func TestNewConnector_WorksWithOpenDB(t *testing.T) {
name := ""
c, err := NewConnector(name)
if err != nil {
t.Fatal(err)
}
db := sql.OpenDB(c)
defer db.Close()
// database/sql might not call our Open at all unless we do something with
// the connection
txn, err := db.Begin()
if err != nil {
t.Fatal(err)
}
txn.Rollback()
}
func TestNewConnector_Connect(t *testing.T) {
name := ""
c, err := NewConnector(name)
if err != nil {
t.Fatal(err)
}
db, err := c.Connect(context.Background())
if err != nil {
t.Fatal(err)
}
defer db.Close()
// database/sql might not call our Open at all unless we do something with
// the connection
txn, err := db.(driver.ConnBeginTx).BeginTx(context.Background(), driver.TxOptions{})
if err != nil {
t.Fatal(err)
}
txn.Rollback()
}
func TestNewConnector_Driver(t *testing.T) {
name := ""
c, err := NewConnector(name)
if err != nil {
t.Fatal(err)
}
db, err := c.Driver().Open(name)
if err != nil {
t.Fatal(err)
}
defer db.Close()
// database/sql might not call our Open at all unless we do something with
// the connection
txn, err := db.(driver.ConnBeginTx).BeginTx(context.Background(), driver.TxOptions{})
if err != nil {
t.Fatal(err)
}
txn.Rollback()
}

View File

@ -4,13 +4,13 @@ import (
"bytes"
"database/sql"
"database/sql/driver"
"net"
"strings"
"testing"
)
func TestCopyInStmt(t *testing.T) {
var stmt string
stmt = CopyIn("table name")
stmt := CopyIn("table name")
if stmt != `COPY "table name" () FROM STDIN` {
t.Fatal(stmt)
}
@ -27,8 +27,7 @@ func TestCopyInStmt(t *testing.T) {
}
func TestCopyInSchemaStmt(t *testing.T) {
var stmt string
stmt = CopyInSchema("schema name", "table name")
stmt := CopyInSchema("schema name", "table name")
if stmt != `COPY "schema name"."table name" () FROM STDIN` {
t.Fatal(stmt)
}
@ -226,7 +225,7 @@ func TestCopyInTypes(t *testing.T) {
if text != "Héllö\n ☃!\r\t\\" {
t.Fatal("unexpected result", text)
}
if bytes.Compare(blob, []byte{0, 255, 9, 10, 13}) != 0 {
if !bytes.Equal(blob, []byte{0, 255, 9, 10, 13}) {
t.Fatal("unexpected result", blob)
}
if nothing.Valid {
@ -402,15 +401,19 @@ func TestCopyRespLoopConnectionError(t *testing.T) {
if err == nil {
t.Fatalf("expected error")
}
pge, ok := err.(*Error)
if !ok {
switch pge := err.(type) {
case *Error:
if pge.Code.Name() != "admin_shutdown" {
t.Fatalf("expected admin_shutdown, got %s", pge.Code.Name())
}
case *net.OpError:
// ignore
default:
if err == driver.ErrBadConn {
// likely an EPIPE
} else {
t.Fatalf("expected *pq.Error or driver.ErrBadConn, got %+#v", err)
t.Fatalf("unexpected error, got %+#v", err)
}
} else if pge.Code.Name() != "admin_shutdown" {
t.Fatalf("expected admin_shutdown, got %s", pge.Code.Name())
}
_ = stmt.Close()

View File

@ -11,7 +11,8 @@ using this package directly. For example:
)
func main() {
db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full")
connStr := "user=pqgotest dbname=pqgotest sslmode=verify-full"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
@ -23,7 +24,8 @@ using this package directly. For example:
You can also connect to a database using a URL. For example:
db, err := sql.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full")
connStr := "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full"
db, err := sql.Open("postgres", connStr)
Connection String Parameters
@ -43,21 +45,28 @@ supported:
* dbname - The name of the database to connect to
* user - The user to sign in as
* password - The user's password
* host - The host to connect to. Values that start with / are for unix domain sockets. (default is localhost)
* host - The host to connect to. Values that start with / are for unix
domain sockets. (default is localhost)
* port - The port to bind to. (default is 5432)
* sslmode - Whether or not to use SSL (default is require, this is not the default for libpq)
* sslmode - Whether or not to use SSL (default is require, this is not
the default for libpq)
* fallback_application_name - An application_name to fall back to if one isn't provided.
* connect_timeout - Maximum wait for connection, in seconds. Zero or not specified means wait indefinitely.
* connect_timeout - Maximum wait for connection, in seconds. Zero or
not specified means wait indefinitely.
* sslcert - Cert file location. The file must contain PEM encoded data.
* sslkey - Key file location. The file must contain PEM encoded data.
* sslrootcert - The location of the root certificate file. The file must contain PEM encoded data.
* sslrootcert - The location of the root certificate file. The file
must contain PEM encoded data.
Valid values for sslmode are:
* disable - No SSL
* require - Always SSL (skip verification)
* verify-ca - Always SSL (verify that the certificate presented by the server was signed by a trusted CA)
* verify-full - Always SSL (verify that the certification presented by the server was signed by a trusted CA and the server host name matches the one in the certificate)
* verify-ca - Always SSL (verify that the certificate presented by the
server was signed by a trusted CA)
* verify-full - Always SSL (verify that the certification presented by
the server was signed by a trusted CA and the server host name
matches the one in the certificate)
See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
for more information about connection string parameters.
@ -68,7 +77,7 @@ Use single quotes for values that contain whitespace:
A backslash will escape the next character in values:
"user=space\ man password='it\'s valid'
"user=space\ man password='it\'s valid'"
Note that the connection parameter client_encoding (which sets the
text encoding for the connection) may be set but must be "UTF8",
@ -129,7 +138,8 @@ This package returns the following types for values from the PostgreSQL backend:
- integer types smallint, integer, and bigint are returned as int64
- floating-point types real and double precision are returned as float64
- character types char, varchar, and text are returned as string
- temporal types date, time, timetz, timestamp, and timestamptz are returned as time.Time
- temporal types date, time, timetz, timestamp, and timestamptz are
returned as time.Time
- the boolean type is returned as bool
- the bytea type is returned as []byte
@ -229,7 +239,7 @@ for more information). Note that the channel name will be truncated to 63
bytes by the PostgreSQL server.
You can find a complete, working example of Listener usage at
http://godoc.org/github.com/lib/pq/listen_example.
https://godoc.org/github.com/lib/pq/example/listen.
*/
package pq

View File

@ -367,8 +367,15 @@ func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, erro
timeSep := daySep + 3
day := p.mustAtoi(str, daySep+1, timeSep)
minLen := monSep + len("01-01") + 1
isBC := strings.HasSuffix(str, " BC")
if isBC {
minLen += 3
}
var hour, minute, second int
if len(str) > monSep+len("01-01")+1 {
if len(str) > minLen {
p.expect(str, ' ', timeSep)
minSep := timeSep + 3
p.expect(str, ':', minSep)
@ -424,7 +431,8 @@ func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, erro
tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec)
}
var isoYear int
if remainderIdx+3 <= len(str) && str[remainderIdx:remainderIdx+3] == " BC" {
if isBC {
isoYear = 1 - year
remainderIdx += 3
} else {

View File

@ -4,7 +4,7 @@ import (
"bytes"
"database/sql"
"fmt"
"strings"
"regexp"
"testing"
"time"
@ -37,6 +37,8 @@ var timeTests = []struct {
}{
{"22001-02-03", time.Date(22001, time.February, 3, 0, 0, 0, 0, time.FixedZone("", 0))},
{"2001-02-03", time.Date(2001, time.February, 3, 0, 0, 0, 0, time.FixedZone("", 0))},
{"0001-12-31 BC", time.Date(0, time.December, 31, 0, 0, 0, 0, time.FixedZone("", 0))},
{"2001-02-03 BC", time.Date(-2000, time.February, 3, 0, 0, 0, 0, time.FixedZone("", 0))},
{"2001-02-03 04:05:06", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", 0))},
{"2001-02-03 04:05:06.000001", time.Date(2001, time.February, 3, 4, 5, 6, 1000, time.FixedZone("", 0))},
{"2001-02-03 04:05:06.00001", time.Date(2001, time.February, 3, 4, 5, 6, 10000, time.FixedZone("", 0))},
@ -86,15 +88,22 @@ func TestParseTs(t *testing.T) {
}
var timeErrorTests = []string{
"BC",
" BC",
"2001",
"2001-2-03",
"2001-02-3",
"2001-02-03 ",
"2001-02-03 B",
"2001-02-03 04",
"2001-02-03 04:",
"2001-02-03 04:05",
"2001-02-03 04:05 B",
"2001-02-03 04:05 BC",
"2001-02-03 04:05:",
"2001-02-03 04:05:6",
"2001-02-03 04:05:06 B",
"2001-02-03 04:05:06BC",
"2001-02-03 04:05:06.123 B",
}
@ -258,9 +267,7 @@ func TestTimestampWithOutTimezone(t *testing.T) {
t.Fatalf("Could not run query: %v", err)
}
n := r.Next()
if n != true {
if !r.Next() {
t.Fatal("Expected at least one row")
}
@ -280,8 +287,7 @@ func TestTimestampWithOutTimezone(t *testing.T) {
expected, result)
}
n = r.Next()
if n != false {
if r.Next() {
t.Fatal("Expected only one row")
}
}
@ -298,24 +304,27 @@ func TestInfinityTimestamp(t *testing.T) {
var err error
var resultT time.Time
expectedErrorStrPrefix := `sql: Scan error on column index 0: unsupported`
expectedErrorStrRegexp := regexp.MustCompile(
`^sql: Scan error on column index 0(, name "timestamp(tz)?"|): unsupported`)
type testCases []struct {
Query string
Param string
ExpectedErrStrPrefix string
ExpectedVal interface{}
Query string
Param string
ExpectedErrorStrRegexp *regexp.Regexp
ExpectedVal interface{}
}
tc := testCases{
{"SELECT $1::timestamp", "-infinity", expectedErrorStrPrefix, "-infinity"},
{"SELECT $1::timestamptz", "-infinity", expectedErrorStrPrefix, "-infinity"},
{"SELECT $1::timestamp", "infinity", expectedErrorStrPrefix, "infinity"},
{"SELECT $1::timestamptz", "infinity", expectedErrorStrPrefix, "infinity"},
{"SELECT $1::timestamp", "-infinity", expectedErrorStrRegexp, "-infinity"},
{"SELECT $1::timestamptz", "-infinity", expectedErrorStrRegexp, "-infinity"},
{"SELECT $1::timestamp", "infinity", expectedErrorStrRegexp, "infinity"},
{"SELECT $1::timestamptz", "infinity", expectedErrorStrRegexp, "infinity"},
}
// try to assert []byte to time.Time
for _, q := range tc {
err = db.QueryRow(q.Query, q.Param).Scan(&resultT)
if !strings.HasPrefix(err.Error(), q.ExpectedErrStrPrefix) {
t.Errorf("Scanning -/+infinity, expected error to have prefix %q, got %q", q.ExpectedErrStrPrefix, err)
if !q.ExpectedErrorStrRegexp.MatchString(err.Error()) {
t.Errorf("Scanning -/+infinity, expected error to match regexp %q, got %q",
q.ExpectedErrorStrRegexp, err)
}
}
// yield []byte
@ -370,17 +379,17 @@ func TestInfinityTimestamp(t *testing.T) {
t.Errorf("Scanning -infinity, expected time %q, got %q", y1500, resultT.String())
}
y_1500 := time.Date(-1500, time.January, 1, 0, 0, 0, 0, time.UTC)
ym1500 := time.Date(-1500, time.January, 1, 0, 0, 0, 0, time.UTC)
y11500 := time.Date(11500, time.January, 1, 0, 0, 0, 0, time.UTC)
var s string
err = db.QueryRow("SELECT $1::timestamp::text", y_1500).Scan(&s)
err = db.QueryRow("SELECT $1::timestamp::text", ym1500).Scan(&s)
if err != nil {
t.Errorf("Encoding -infinity, expected no error, got %q", err)
}
if s != "-infinity" {
t.Errorf("Encoding -infinity, expected %q, got %q", "-infinity", s)
}
err = db.QueryRow("SELECT $1::timestamptz::text", y_1500).Scan(&s)
err = db.QueryRow("SELECT $1::timestamptz::text", ym1500).Scan(&s)
if err != nil {
t.Errorf("Encoding -infinity, expected no error, got %q", err)
}
@ -722,8 +731,7 @@ func TestAppendEscapedText(t *testing.T) {
}
func TestAppendEscapedTextExistingBuffer(t *testing.T) {
var buf []byte
buf = []byte("123\t")
buf := []byte("123\t")
if esc := appendEscapedText(buf, "hallo\tescape"); string(esc) != "123\thallo\\tescape" {
t.Fatal(string(esc))
}

View File

@ -153,6 +153,7 @@ var errorCodeNames = map[ErrorCode]string{
"22004": "null_value_not_allowed",
"22002": "null_value_no_indicator_parameter",
"22003": "numeric_value_out_of_range",
"2200H": "sequence_generator_limit_exceeded",
"22026": "string_data_length_mismatch",
"22001": "string_data_right_truncation",
"22011": "substring_error",
@ -459,6 +460,11 @@ func errorf(s string, args ...interface{}) {
panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...)))
}
// TODO(ainar-g) Rename to errorf after removing panics.
func fmterrorf(s string, args ...interface{}) error {
return fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))
}
func errRecoverNoErrBadConn(err *error) {
e := recover()
if e == nil {
@ -487,7 +493,8 @@ func (c *conn) errRecover(err *error) {
*err = v
}
case *net.OpError:
*err = driver.ErrBadConn
c.bad = true
*err = v
case error:
if v == io.EOF || v.(error).Error() == "remote error: handshake failure" {
*err = driver.ErrBadConn

View File

@ -1,6 +1,6 @@
/*
Below you will find a self-contained Go program which uses the LISTEN / NOTIFY
Package listen is a self-contained Go program which uses the LISTEN / NOTIFY
mechanism to avoid polling the database while waiting for more work to arrive.
//
@ -77,7 +77,9 @@ mechanism to avoid polling the database while waiting for more work to arrive.
}
}
listener := pq.NewListener(conninfo, 10 * time.Second, time.Minute, reportProblem)
minReconn := 10 * time.Second
maxReconn := time.Minute
listener := pq.NewListener(conninfo, minReconn, maxReconn, reportProblem)
err = listener.Listen("getwork")
if err != nil {
panic(err)
@ -93,4 +95,4 @@ mechanism to avoid polling the database while waiting for more work to arrive.
*/
package listen_example
package listen

View File

@ -0,0 +1 @@
module github.com/lib/pq

View File

@ -1,10 +1,10 @@
// +build go1.8
package pq
import (
"context"
"database/sql"
"runtime"
"strings"
"testing"
"time"
)
@ -155,6 +155,36 @@ func TestContextCancelQuery(t *testing.T) {
}
}
// TestIssue617 tests that a failed query in QueryContext doesn't lead to a
// goroutine leak.
func TestIssue617(t *testing.T) {
db := openTestConn(t)
defer db.Close()
const N = 10
numGoroutineStart := runtime.NumGoroutine()
for i := 0; i < N; i++ {
func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err := db.QueryContext(ctx, `SELECT * FROM DOESNOTEXIST`)
pqErr, _ := err.(*Error)
// Expecting "pq: relation \"doesnotexist\" does not exist" error.
if err == nil || pqErr == nil || pqErr.Code != "42P01" {
t.Fatalf("expected undefined table error, got %v", err)
}
}()
}
numGoroutineFinish := runtime.NumGoroutine()
// We use N/2 and not N because the GC and other actors may increase or
// decrease the number of goroutines.
if numGoroutineFinish-numGoroutineStart >= N/2 {
t.Errorf("goroutine leak detected, was %d, now %d", numGoroutineStart, numGoroutineFinish)
}
}
func TestContextCancelBegin(t *testing.T) {
db := openTestConn(t)
defer db.Close()
@ -196,7 +226,9 @@ func TestContextCancelBegin(t *testing.T) {
cancel()
if err != nil {
t.Fatal(err)
} else if err := tx.Rollback(); err != nil && err != sql.ErrTxDone {
} else if err := tx.Rollback(); err != nil &&
err.Error() != "pq: canceling statement due to user request" &&
err != sql.ErrTxDone {
t.Fatal(err)
}
}()
@ -208,3 +240,80 @@ func TestContextCancelBegin(t *testing.T) {
}
}
}
func TestTxOptions(t *testing.T) {
db := openTestConn(t)
defer db.Close()
ctx := context.Background()
tests := []struct {
level sql.IsolationLevel
isolation string
}{
{
level: sql.LevelDefault,
isolation: "",
},
{
level: sql.LevelReadUncommitted,
isolation: "read uncommitted",
},
{
level: sql.LevelReadCommitted,
isolation: "read committed",
},
{
level: sql.LevelRepeatableRead,
isolation: "repeatable read",
},
{
level: sql.LevelSerializable,
isolation: "serializable",
},
}
for _, test := range tests {
for _, ro := range []bool{true, false} {
tx, err := db.BeginTx(ctx, &sql.TxOptions{
Isolation: test.level,
ReadOnly: ro,
})
if err != nil {
t.Fatal(err)
}
var isolation string
err = tx.QueryRow("select current_setting('transaction_isolation')").Scan(&isolation)
if err != nil {
t.Fatal(err)
}
if test.isolation != "" && isolation != test.isolation {
t.Errorf("wrong isolation level: %s != %s", isolation, test.isolation)
}
var isRO string
err = tx.QueryRow("select current_setting('transaction_read_only')").Scan(&isRO)
if err != nil {
t.Fatal(err)
}
if ro != (isRO == "on") {
t.Errorf("read/[write,only] not set: %t != %s for level %s",
ro, isRO, test.isolation)
}
tx.Rollback()
}
}
_, err := db.BeginTx(ctx, &sql.TxOptions{
Isolation: sql.LevelLinearizable,
})
if err == nil {
t.Fatal("expected LevelLinearizable to fail")
}
if !strings.Contains(err.Error(), "isolation level not supported") {
t.Errorf("Expected error to mention isolation level, got %q", err)
}
}

View File

@ -6,7 +6,7 @@ import (
"strings"
)
// A wrapper for transferring Hstore values back and forth easily.
// Hstore is a wrapper for transferring Hstore values back and forth easily.
type Hstore struct {
Map map[string]sql.NullString
}

View File

@ -60,7 +60,7 @@ type ListenerConn struct {
replyChan chan message
}
// Creates a new ListenerConn. Use NewListener instead.
// NewListenerConn creates a new ListenerConn. Use NewListener instead.
func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) {
return newDialListenerConn(defaultDialer{}, name, notificationChan)
}
@ -214,17 +214,17 @@ func (l *ListenerConn) listenerConnMain() {
// this ListenerConn is done
}
// Send a LISTEN query to the server. See ExecSimpleQuery.
// Listen sends a LISTEN query to the server. See ExecSimpleQuery.
func (l *ListenerConn) Listen(channel string) (bool, error) {
return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel))
}
// Send an UNLISTEN query to the server. See ExecSimpleQuery.
// Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery.
func (l *ListenerConn) Unlisten(channel string) (bool, error) {
return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel))
}
// Send `UNLISTEN *` to the server. See ExecSimpleQuery.
// UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery.
func (l *ListenerConn) UnlistenAll() (bool, error) {
return l.ExecSimpleQuery("UNLISTEN *")
}
@ -267,8 +267,8 @@ func (l *ListenerConn) sendSimpleQuery(q string) (err error) {
return nil
}
// Execute a "simple query" (i.e. one with no bindable parameters) on the
// connection. The possible return values are:
// ExecSimpleQuery executes a "simple query" (i.e. one with no bindable
// parameters) on the connection. The possible return values are:
// 1) "executed" is true; the query was executed to completion on the
// database server. If the query failed, err will be set to the error
// returned by the database, otherwise err will be nil.
@ -333,6 +333,7 @@ func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) {
}
}
// Close closes the connection.
func (l *ListenerConn) Close() error {
l.connectionLock.Lock()
if l.err != nil {
@ -346,7 +347,7 @@ func (l *ListenerConn) Close() error {
return l.cn.c.Close()
}
// Err() returns the reason the connection was closed. It is not safe to call
// Err returns the reason the connection was closed. It is not safe to call
// this function until l.Notify has been closed.
func (l *ListenerConn) Err() error {
return l.err
@ -354,32 +355,43 @@ func (l *ListenerConn) Err() error {
var errListenerClosed = errors.New("pq: Listener has been closed")
// ErrChannelAlreadyOpen is returned from Listen when a channel is already
// open.
var ErrChannelAlreadyOpen = errors.New("pq: channel is already open")
// ErrChannelNotOpen is returned from Unlisten when a channel is not open.
var ErrChannelNotOpen = errors.New("pq: channel is not open")
// ListenerEventType is an enumeration of listener event types.
type ListenerEventType int
const (
// Emitted only when the database connection has been initially
// initialized. err will always be nil.
// ListenerEventConnected is emitted only when the database connection
// has been initially initialized. The err argument of the callback
// will always be nil.
ListenerEventConnected ListenerEventType = iota
// Emitted after a database connection has been lost, either because of an
// error or because Close has been called. err will be set to the reason
// the database connection was lost.
// ListenerEventDisconnected is emitted after a database connection has
// been lost, either because of an error or because Close has been
// called. The err argument will be set to the reason the database
// connection was lost.
ListenerEventDisconnected
// Emitted after a database connection has been re-established after
// connection loss. err will always be nil. After this event has been
// emitted, a nil pq.Notification is sent on the Listener.Notify channel.
// ListenerEventReconnected is emitted after a database connection has
// been re-established after connection loss. The err argument of the
// callback will always be nil. After this event has been emitted, a
// nil pq.Notification is sent on the Listener.Notify channel.
ListenerEventReconnected
// Emitted after a connection to the database was attempted, but failed.
// err will be set to an error describing why the connection attempt did
// not succeed.
// ListenerEventConnectionAttemptFailed is emitted after a connection
// to the database was attempted, but failed. The err argument will be
// set to an error describing why the connection attempt did not
// succeed.
ListenerEventConnectionAttemptFailed
)
// EventCallbackType is the event callback type. See also ListenerEventType
// constants' documentation.
type EventCallbackType func(event ListenerEventType, err error)
// Listener provides an interface for listening to notifications from a
@ -454,9 +466,9 @@ func NewDialListener(d Dialer,
return l
}
// Returns the notification channel for this listener. This is the same
// channel as Notify, and will not be recreated during the life time of the
// Listener.
// NotificationChannel returns the notification channel for this listener.
// This is the same channel as Notify, and will not be recreated during the
// life time of the Listener.
func (l *Listener) NotificationChannel() <-chan *Notification {
return l.Notify
}
@ -625,7 +637,7 @@ func (l *Listener) disconnectCleanup() error {
// after the connection has been established.
func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error {
doneChan := make(chan error)
go func() {
go func(notificationChan <-chan *Notification) {
for channel := range l.channels {
// If we got a response, return that error to our caller as it's
// going to be more descriptive than cn.Err().
@ -639,14 +651,14 @@ func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notificatio
// close and then return the error message from the connection, as
// per ListenerConn's interface.
if err != nil {
for _ = range notificationChan {
for range notificationChan {
}
doneChan <- cn.Err()
return
}
}
doneChan <- nil
}()
}(notificationChan)
// Ignore notifications while synchronization is going on to avoid
// deadlocks. We have to send a nil notification over Notify anyway as
@ -713,6 +725,9 @@ func (l *Listener) Close() error {
}
l.isClosed = true
// Unblock calls to Listen()
l.reconnectCond.Broadcast()
return nil
}
@ -772,7 +787,7 @@ func (l *Listener) listenerConnLoop() {
}
l.emitEvent(ListenerEventDisconnected, err)
time.Sleep(nextReconnect.Sub(time.Now()))
time.Sleep(time.Until(nextReconnect))
}
}

View File

@ -123,6 +123,9 @@ func TestConnUnlisten(t *testing.T) {
}
_, err = db.Exec("NOTIFY notify_test")
if err != nil {
t.Fatal(err)
}
err = expectNotification(t, channel, "notify_test", "")
if err != nil {
@ -159,6 +162,9 @@ func TestConnUnlistenAll(t *testing.T) {
}
_, err = db.Exec("NOTIFY notify_test")
if err != nil {
t.Fatal(err)
}
err = expectNotification(t, channel, "notify_test", "")
if err != nil {

View File

@ -10,10 +10,22 @@ import (
"log"
"os"
"os/exec"
"strings"
_ "github.com/lib/pq"
)
// OID represent a postgres Object Identifier Type.
type OID struct {
ID int
Type string
}
// Name returns an upper case version of the oid type.
func (o OID) Name() string {
return strings.ToUpper(o.Type)
}
func main() {
datname := os.Getenv("PGDATABASE")
sslmode := os.Getenv("PGSSLMODE")
@ -30,6 +42,25 @@ func main() {
if err != nil {
log.Fatal(err)
}
rows, err := db.Query(`
SELECT typname, oid
FROM pg_type WHERE oid < 10000
ORDER BY oid;
`)
if err != nil {
log.Fatal(err)
}
oids := make([]*OID, 0)
for rows.Next() {
var oid OID
if err = rows.Scan(&oid.Type, &oid.ID); err != nil {
log.Fatal(err)
}
oids = append(oids, &oid)
}
if err = rows.Err(); err != nil {
log.Fatal(err)
}
cmd := exec.Command("gofmt")
cmd.Stderr = os.Stderr
w, err := cmd.StdinPipe()
@ -45,30 +76,18 @@ func main() {
if err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "// generated by 'go run gen.go'; do not edit")
fmt.Fprintln(w, "// Code generated by gen.go. DO NOT EDIT.")
fmt.Fprintln(w, "\npackage oid")
fmt.Fprintln(w, "const (")
rows, err := db.Query(`
SELECT typname, oid
FROM pg_type WHERE oid < 10000
ORDER BY oid;
`)
if err != nil {
log.Fatal(err)
}
var name string
var oid int
for rows.Next() {
err = rows.Scan(&name, &oid)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "T_%s Oid = %d\n", name, oid)
}
if err = rows.Err(); err != nil {
log.Fatal(err)
for _, oid := range oids {
fmt.Fprintf(w, "T_%s Oid = %d\n", oid.Type, oid.ID)
}
fmt.Fprintln(w, ")")
fmt.Fprintln(w, "var TypeName = map[Oid]string{")
for _, oid := range oids {
fmt.Fprintf(w, "T_%s: \"%s\",\n", oid.Type, oid.Name())
}
fmt.Fprintln(w, "}")
w.Close()
cmd.Wait()
}

View File

@ -1,4 +1,4 @@
// generated by 'go run gen.go'; do not edit
// Code generated by gen.go. DO NOT EDIT.
package oid
@ -171,3 +171,173 @@ const (
T_regrole Oid = 4096
T__regrole Oid = 4097
)
var TypeName = map[Oid]string{
T_bool: "BOOL",
T_bytea: "BYTEA",
T_char: "CHAR",
T_name: "NAME",
T_int8: "INT8",
T_int2: "INT2",
T_int2vector: "INT2VECTOR",
T_int4: "INT4",
T_regproc: "REGPROC",
T_text: "TEXT",
T_oid: "OID",
T_tid: "TID",
T_xid: "XID",
T_cid: "CID",
T_oidvector: "OIDVECTOR",
T_pg_ddl_command: "PG_DDL_COMMAND",
T_pg_type: "PG_TYPE",
T_pg_attribute: "PG_ATTRIBUTE",
T_pg_proc: "PG_PROC",
T_pg_class: "PG_CLASS",
T_json: "JSON",
T_xml: "XML",
T__xml: "_XML",
T_pg_node_tree: "PG_NODE_TREE",
T__json: "_JSON",
T_smgr: "SMGR",
T_index_am_handler: "INDEX_AM_HANDLER",
T_point: "POINT",
T_lseg: "LSEG",
T_path: "PATH",
T_box: "BOX",
T_polygon: "POLYGON",
T_line: "LINE",
T__line: "_LINE",
T_cidr: "CIDR",
T__cidr: "_CIDR",
T_float4: "FLOAT4",
T_float8: "FLOAT8",
T_abstime: "ABSTIME",
T_reltime: "RELTIME",
T_tinterval: "TINTERVAL",
T_unknown: "UNKNOWN",
T_circle: "CIRCLE",
T__circle: "_CIRCLE",
T_money: "MONEY",
T__money: "_MONEY",
T_macaddr: "MACADDR",
T_inet: "INET",
T__bool: "_BOOL",
T__bytea: "_BYTEA",
T__char: "_CHAR",
T__name: "_NAME",
T__int2: "_INT2",
T__int2vector: "_INT2VECTOR",
T__int4: "_INT4",
T__regproc: "_REGPROC",
T__text: "_TEXT",
T__tid: "_TID",
T__xid: "_XID",
T__cid: "_CID",
T__oidvector: "_OIDVECTOR",
T__bpchar: "_BPCHAR",
T__varchar: "_VARCHAR",
T__int8: "_INT8",
T__point: "_POINT",
T__lseg: "_LSEG",
T__path: "_PATH",
T__box: "_BOX",
T__float4: "_FLOAT4",
T__float8: "_FLOAT8",
T__abstime: "_ABSTIME",
T__reltime: "_RELTIME",
T__tinterval: "_TINTERVAL",
T__polygon: "_POLYGON",
T__oid: "_OID",
T_aclitem: "ACLITEM",
T__aclitem: "_ACLITEM",
T__macaddr: "_MACADDR",
T__inet: "_INET",
T_bpchar: "BPCHAR",
T_varchar: "VARCHAR",
T_date: "DATE",
T_time: "TIME",
T_timestamp: "TIMESTAMP",
T__timestamp: "_TIMESTAMP",
T__date: "_DATE",
T__time: "_TIME",
T_timestamptz: "TIMESTAMPTZ",
T__timestamptz: "_TIMESTAMPTZ",
T_interval: "INTERVAL",
T__interval: "_INTERVAL",
T__numeric: "_NUMERIC",
T_pg_database: "PG_DATABASE",
T__cstring: "_CSTRING",
T_timetz: "TIMETZ",
T__timetz: "_TIMETZ",
T_bit: "BIT",
T__bit: "_BIT",
T_varbit: "VARBIT",
T__varbit: "_VARBIT",
T_numeric: "NUMERIC",
T_refcursor: "REFCURSOR",
T__refcursor: "_REFCURSOR",
T_regprocedure: "REGPROCEDURE",
T_regoper: "REGOPER",
T_regoperator: "REGOPERATOR",
T_regclass: "REGCLASS",
T_regtype: "REGTYPE",
T__regprocedure: "_REGPROCEDURE",
T__regoper: "_REGOPER",
T__regoperator: "_REGOPERATOR",
T__regclass: "_REGCLASS",
T__regtype: "_REGTYPE",
T_record: "RECORD",
T_cstring: "CSTRING",
T_any: "ANY",
T_anyarray: "ANYARRAY",
T_void: "VOID",
T_trigger: "TRIGGER",
T_language_handler: "LANGUAGE_HANDLER",
T_internal: "INTERNAL",
T_opaque: "OPAQUE",
T_anyelement: "ANYELEMENT",
T__record: "_RECORD",
T_anynonarray: "ANYNONARRAY",
T_pg_authid: "PG_AUTHID",
T_pg_auth_members: "PG_AUTH_MEMBERS",
T__txid_snapshot: "_TXID_SNAPSHOT",
T_uuid: "UUID",
T__uuid: "_UUID",
T_txid_snapshot: "TXID_SNAPSHOT",
T_fdw_handler: "FDW_HANDLER",
T_pg_lsn: "PG_LSN",
T__pg_lsn: "_PG_LSN",
T_tsm_handler: "TSM_HANDLER",
T_anyenum: "ANYENUM",
T_tsvector: "TSVECTOR",
T_tsquery: "TSQUERY",
T_gtsvector: "GTSVECTOR",
T__tsvector: "_TSVECTOR",
T__gtsvector: "_GTSVECTOR",
T__tsquery: "_TSQUERY",
T_regconfig: "REGCONFIG",
T__regconfig: "_REGCONFIG",
T_regdictionary: "REGDICTIONARY",
T__regdictionary: "_REGDICTIONARY",
T_jsonb: "JSONB",
T__jsonb: "_JSONB",
T_anyrange: "ANYRANGE",
T_event_trigger: "EVENT_TRIGGER",
T_int4range: "INT4RANGE",
T__int4range: "_INT4RANGE",
T_numrange: "NUMRANGE",
T__numrange: "_NUMRANGE",
T_tsrange: "TSRANGE",
T__tsrange: "_TSRANGE",
T_tstzrange: "TSTZRANGE",
T__tstzrange: "_TSTZRANGE",
T_daterange: "DATERANGE",
T__daterange: "_DATERANGE",
T_int8range: "INT8RANGE",
T__int8range: "_INT8RANGE",
T_pg_shseclabel: "PG_SHSECLABEL",
T_regnamespace: "REGNAMESPACE",
T__regnamespace: "_REGNAMESPACE",
T_regrole: "REGROLE",
T__regrole: "_REGROLE",
}

View File

@ -0,0 +1,93 @@
package pq
import (
"math"
"reflect"
"time"
"github.com/lib/pq/oid"
)
const headerSize = 4
type fieldDesc struct {
// The object ID of the data type.
OID oid.Oid
// The data type size (see pg_type.typlen).
// Note that negative values denote variable-width types.
Len int
// The type modifier (see pg_attribute.atttypmod).
// The meaning of the modifier is type-specific.
Mod int
}
func (fd fieldDesc) Type() reflect.Type {
switch fd.OID {
case oid.T_int8:
return reflect.TypeOf(int64(0))
case oid.T_int4:
return reflect.TypeOf(int32(0))
case oid.T_int2:
return reflect.TypeOf(int16(0))
case oid.T_varchar, oid.T_text:
return reflect.TypeOf("")
case oid.T_bool:
return reflect.TypeOf(false)
case oid.T_date, oid.T_time, oid.T_timetz, oid.T_timestamp, oid.T_timestamptz:
return reflect.TypeOf(time.Time{})
case oid.T_bytea:
return reflect.TypeOf([]byte(nil))
default:
return reflect.TypeOf(new(interface{})).Elem()
}
}
func (fd fieldDesc) Name() string {
return oid.TypeName[fd.OID]
}
func (fd fieldDesc) Length() (length int64, ok bool) {
switch fd.OID {
case oid.T_text, oid.T_bytea:
return math.MaxInt64, true
case oid.T_varchar, oid.T_bpchar:
return int64(fd.Mod - headerSize), true
default:
return 0, false
}
}
func (fd fieldDesc) PrecisionScale() (precision, scale int64, ok bool) {
switch fd.OID {
case oid.T_numeric, oid.T__numeric:
mod := fd.Mod - headerSize
precision = int64((mod >> 16) & 0xffff)
scale = int64(mod & 0xffff)
return precision, scale, true
default:
return 0, 0, false
}
}
// ColumnTypeScanType returns the value type that can be used to scan types into.
func (rs *rows) ColumnTypeScanType(index int) reflect.Type {
return rs.colTyps[index].Type()
}
// ColumnTypeDatabaseTypeName return the database system type name.
func (rs *rows) ColumnTypeDatabaseTypeName(index int) string {
return rs.colTyps[index].Name()
}
// ColumnTypeLength returns the length of the column type if the column is a
// variable length type. If the column is not a variable length type ok
// should return false.
func (rs *rows) ColumnTypeLength(index int) (length int64, ok bool) {
return rs.colTyps[index].Length()
}
// ColumnTypePrecisionScale should return the precision and scale for decimal
// types. If not applicable, ok should be false.
func (rs *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
return rs.colTyps[index].PrecisionScale()
}

View File

@ -0,0 +1,218 @@
package pq
import (
"math"
"reflect"
"testing"
"github.com/lib/pq/oid"
)
func TestDataTypeName(t *testing.T) {
tts := []struct {
typ oid.Oid
name string
}{
{oid.T_int8, "INT8"},
{oid.T_int4, "INT4"},
{oid.T_int2, "INT2"},
{oid.T_varchar, "VARCHAR"},
{oid.T_text, "TEXT"},
{oid.T_bool, "BOOL"},
{oid.T_numeric, "NUMERIC"},
{oid.T_date, "DATE"},
{oid.T_time, "TIME"},
{oid.T_timetz, "TIMETZ"},
{oid.T_timestamp, "TIMESTAMP"},
{oid.T_timestamptz, "TIMESTAMPTZ"},
{oid.T_bytea, "BYTEA"},
}
for i, tt := range tts {
dt := fieldDesc{OID: tt.typ}
if name := dt.Name(); name != tt.name {
t.Errorf("(%d) got: %s want: %s", i, name, tt.name)
}
}
}
func TestDataType(t *testing.T) {
tts := []struct {
typ oid.Oid
kind reflect.Kind
}{
{oid.T_int8, reflect.Int64},
{oid.T_int4, reflect.Int32},
{oid.T_int2, reflect.Int16},
{oid.T_varchar, reflect.String},
{oid.T_text, reflect.String},
{oid.T_bool, reflect.Bool},
{oid.T_date, reflect.Struct},
{oid.T_time, reflect.Struct},
{oid.T_timetz, reflect.Struct},
{oid.T_timestamp, reflect.Struct},
{oid.T_timestamptz, reflect.Struct},
{oid.T_bytea, reflect.Slice},
}
for i, tt := range tts {
dt := fieldDesc{OID: tt.typ}
if kind := dt.Type().Kind(); kind != tt.kind {
t.Errorf("(%d) got: %s want: %s", i, kind, tt.kind)
}
}
}
func TestDataTypeLength(t *testing.T) {
tts := []struct {
typ oid.Oid
len int
mod int
length int64
ok bool
}{
{oid.T_int4, 0, -1, 0, false},
{oid.T_varchar, 65535, 9, 5, true},
{oid.T_text, 65535, -1, math.MaxInt64, true},
{oid.T_bytea, 65535, -1, math.MaxInt64, true},
}
for i, tt := range tts {
dt := fieldDesc{OID: tt.typ, Len: tt.len, Mod: tt.mod}
if l, k := dt.Length(); k != tt.ok || l != tt.length {
t.Errorf("(%d) got: %d, %t want: %d, %t", i, l, k, tt.length, tt.ok)
}
}
}
func TestDataTypePrecisionScale(t *testing.T) {
tts := []struct {
typ oid.Oid
mod int
precision, scale int64
ok bool
}{
{oid.T_int4, -1, 0, 0, false},
{oid.T_numeric, 589830, 9, 2, true},
{oid.T_text, -1, 0, 0, false},
}
for i, tt := range tts {
dt := fieldDesc{OID: tt.typ, Mod: tt.mod}
p, s, k := dt.PrecisionScale()
if k != tt.ok {
t.Errorf("(%d) got: %t want: %t", i, k, tt.ok)
}
if p != tt.precision {
t.Errorf("(%d) wrong precision got: %d want: %d", i, p, tt.precision)
}
if s != tt.scale {
t.Errorf("(%d) wrong scale got: %d want: %d", i, s, tt.scale)
}
}
}
func TestRowsColumnTypes(t *testing.T) {
columnTypesTests := []struct {
Name string
TypeName string
Length struct {
Len int64
OK bool
}
DecimalSize struct {
Precision int64
Scale int64
OK bool
}
ScanType reflect.Type
}{
{
Name: "a",
TypeName: "INT4",
Length: struct {
Len int64
OK bool
}{
Len: 0,
OK: false,
},
DecimalSize: struct {
Precision int64
Scale int64
OK bool
}{
Precision: 0,
Scale: 0,
OK: false,
},
ScanType: reflect.TypeOf(int32(0)),
}, {
Name: "bar",
TypeName: "TEXT",
Length: struct {
Len int64
OK bool
}{
Len: math.MaxInt64,
OK: true,
},
DecimalSize: struct {
Precision int64
Scale int64
OK bool
}{
Precision: 0,
Scale: 0,
OK: false,
},
ScanType: reflect.TypeOf(""),
},
}
db := openTestConn(t)
defer db.Close()
rows, err := db.Query("SELECT 1 AS a, text 'bar' AS bar, 1.28::numeric(9, 2) AS dec")
if err != nil {
t.Fatal(err)
}
columns, err := rows.ColumnTypes()
if err != nil {
t.Fatal(err)
}
if len(columns) != 3 {
t.Errorf("expected 3 columns found %d", len(columns))
}
for i, tt := range columnTypesTests {
c := columns[i]
if c.Name() != tt.Name {
t.Errorf("(%d) got: %s, want: %s", i, c.Name(), tt.Name)
}
if c.DatabaseTypeName() != tt.TypeName {
t.Errorf("(%d) got: %s, want: %s", i, c.DatabaseTypeName(), tt.TypeName)
}
l, ok := c.Length()
if l != tt.Length.Len {
t.Errorf("(%d) got: %d, want: %d", i, l, tt.Length.Len)
}
if ok != tt.Length.OK {
t.Errorf("(%d) got: %t, want: %t", i, ok, tt.Length.OK)
}
p, s, ok := c.DecimalSize()
if p != tt.DecimalSize.Precision {
t.Errorf("(%d) got: %d, want: %d", i, p, tt.DecimalSize.Precision)
}
if s != tt.DecimalSize.Scale {
t.Errorf("(%d) got: %d, want: %d", i, s, tt.DecimalSize.Scale)
}
if ok != tt.DecimalSize.OK {
t.Errorf("(%d) got: %t, want: %t", i, ok, tt.DecimalSize.OK)
}
if c.ScanType() != tt.ScanType {
t.Errorf("(%d) got: %v, want: %v", i, c.ScanType(), tt.ScanType)
}
}
}

View File

@ -12,7 +12,7 @@ import (
// ssl generates a function to upgrade a net.Conn based on the "sslmode" and
// related settings. The function is nil when no upgrade should take place.
func ssl(o values) func(net.Conn) net.Conn {
func ssl(o values) (func(net.Conn) (net.Conn, error), error) {
verifyCaOnly := false
tlsConf := tls.Config{}
switch mode := o["sslmode"]; mode {
@ -45,29 +45,44 @@ func ssl(o values) func(net.Conn) net.Conn {
case "verify-full":
tlsConf.ServerName = o["host"]
case "disable":
return nil
return nil, nil
default:
errorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode)
return nil, fmterrorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode)
}
sslClientCertificates(&tlsConf, o)
sslCertificateAuthority(&tlsConf, o)
sslRenegotiation(&tlsConf)
err := sslClientCertificates(&tlsConf, o)
if err != nil {
return nil, err
}
err = sslCertificateAuthority(&tlsConf, o)
if err != nil {
return nil, err
}
return func(conn net.Conn) net.Conn {
// Accept renegotiation requests initiated by the backend.
//
// Renegotiation was deprecated then removed from PostgreSQL 9.5, but
// the default configuration of older versions has it enabled. Redshift
// also initiates renegotiations and cannot be reconfigured.
tlsConf.Renegotiation = tls.RenegotiateFreelyAsClient
return func(conn net.Conn) (net.Conn, error) {
client := tls.Client(conn, &tlsConf)
if verifyCaOnly {
sslVerifyCertificateAuthority(client, &tlsConf)
err := sslVerifyCertificateAuthority(client, &tlsConf)
if err != nil {
return nil, err
}
}
return client
}
return client, nil
}, nil
}
// sslClientCertificates adds the certificate specified in the "sslcert" and
// "sslkey" settings, or if they aren't set, from the .postgresql directory
// in the user's home directory. The configured files must exist and have
// the correct permissions.
func sslClientCertificates(tlsConf *tls.Config, o values) {
func sslClientCertificates(tlsConf *tls.Config, o values) error {
// user.Current() might fail when cross-compiling. We have to ignore the
// error and continue without home directory defaults, since we wouldn't
// know from where to load them.
@ -82,13 +97,13 @@ func sslClientCertificates(tlsConf *tls.Config, o values) {
}
// https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1045
if len(sslcert) == 0 {
return
return nil
}
// https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1050:L1054
if _, err := os.Stat(sslcert); os.IsNotExist(err) {
return
return nil
} else if err != nil {
panic(err)
return err
}
// In libpq, the ssl key is only loaded if the setting is not blank.
@ -101,19 +116,21 @@ func sslClientCertificates(tlsConf *tls.Config, o values) {
if len(sslkey) > 0 {
if err := sslKeyPermissions(sslkey); err != nil {
panic(err)
return err
}
}
cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
if err != nil {
panic(err)
return err
}
tlsConf.Certificates = []tls.Certificate{cert}
return nil
}
// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting.
func sslCertificateAuthority(tlsConf *tls.Config, o values) {
func sslCertificateAuthority(tlsConf *tls.Config, o values) error {
// In libpq, the root certificate is only loaded if the setting is not blank.
//
// https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L950-L951
@ -122,22 +139,24 @@ func sslCertificateAuthority(tlsConf *tls.Config, o values) {
cert, err := ioutil.ReadFile(sslrootcert)
if err != nil {
panic(err)
return err
}
if !tlsConf.RootCAs.AppendCertsFromPEM(cert) {
errorf("couldn't parse pem in sslrootcert")
return fmterrorf("couldn't parse pem in sslrootcert")
}
}
return nil
}
// sslVerifyCertificateAuthority carries out a TLS handshake to the server and
// verifies the presented certificate against the CA, i.e. the one specified in
// sslrootcert or the system CA if sslrootcert was not specified.
func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) {
func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) error {
err := client.Handshake()
if err != nil {
panic(err)
return err
}
certs := client.ConnectionState().PeerCertificates
opts := x509.VerifyOptions{
@ -152,7 +171,5 @@ func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) {
opts.Intermediates.AddCert(cert)
}
_, err = certs[0].Verify(opts)
if err != nil {
panic(err)
}
return err
}

View File

@ -1,14 +0,0 @@
// +build go1.7
package pq
import "crypto/tls"
// Accept renegotiation requests initiated by the backend.
//
// Renegotiation was deprecated then removed from PostgreSQL 9.5, but
// the default configuration of older versions has it enabled. Redshift
// also initiates renegotiations and cannot be reconfigured.
func sslRenegotiation(conf *tls.Config) {
conf.Renegotiation = tls.RenegotiateFreelyAsClient
}

View File

@ -1,8 +0,0 @@
// +build !go1.7
package pq
import "crypto/tls"
// Renegotiation is not supported by crypto/tls until Go 1.7.
func sslRenegotiation(*tls.Config) {}

View File

@ -33,7 +33,7 @@ func TestDecodeUUIDBackend(t *testing.T) {
db := openTestConn(t)
defer db.Close()
var s string = "a0ecc91d-a13f-4fe4-9fce-7e09777cc70a"
var s = "a0ecc91d-a13f-4fe4-9fce-7e09777cc70a"
var scanned interface{}
err := db.QueryRow(`SELECT $1::uuid`, s).Scan(&scanned)