pgsql

package module
v0.0.0-...-2915b54 Latest Latest
Warning

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

Go to latest
Published: May 13, 2013 License: BSD-3-Clause Imports: 23 Imported by: 1

README

About go-pgsql
==============

go-pgsql is a [PostgreSQL](http://www.postgresql.org) client library for the
[Go](http://golang.org) programming language.

It partially implements version 3.0 of the
[PostgreSQL](http://www.postgresql.org) frontend/backend protocol, so it
should work with servers of version 7.4 and later.

It now supports database/sql in addition to its existing interface.

Installing go-pgsql
===================

First make sure you have a working [Go](http://golang.org) installation, see
the installation guide at http://golang.org/doc/install.html

Now you should be able to install go-pgsql by running
`go get github.com/lxn/go-pgsql`

Using go-pgsql
==============

There are some examples in the
[examples](examples) directory which
should get you started.

Please open an issue on the bug tracker if you encounter a bug.

Missing Features
================

go-pgsql is currently missing support for some features, including:

- authentication types other than MD5
- SSL encrypted sessions
- some data types like bytea, ...
- canceling commands/queries
- bulk copy
- ...

Connection Info
================

To connect, you must pass a connection string to pgsql.Connect().
Much as with the libpq conninfo parameter, values are optional, and
may be overridden by environment variables at runtime, specifically:

- PGPORT - port number
- PGUSER - user name (defaults to postgres)
- PGHOST - host name/address (defaults to localhost)
- PGDATABASE - name of database (defaults to user name if not specified)

Documentation

Overview

The pgsql package implements a PostgreSQL frontend library. It is compatible with servers of version 7.4 and later.

Index

Constants

View Source
const DEFAULT_IDLE_TIMEOUT = 300 // Seconds

Variables

This section is empty.

Functions

This section is empty.

Types

type Conn

type Conn struct {
	LogLevel LogLevel
	// contains filtered or unexported fields
}

Conn represents a PostgreSQL database connection.

func Connect

func Connect(connStr string, logLevel LogLevel) (conn *Conn, err error)

Connect establishes a database connection.

Parameter settings in connStr have to be separated by whitespace and are expected in keyword = value form. Spaces around equal signs are optional. Use single quotes for empty values or values containing spaces.

Currently these keywords are supported:

host 		= Name of the host to connect to (default: localhost)
port 		= Integer port number the server listens on (default: 5432)
dbname 		= Database name (default: same as user)
user 		= User to connect as
password	= Password for password based authentication methods
timeout		= Timeout in seconds, 0 or not specified disables timeout (default: 0)

func (*Conn) Close

func (conn *Conn) Close() (err error)

Close closes the connection to the database.

func (*Conn) CopyFrom

func (conn *Conn) CopyFrom(command string, r io.Reader) (rowsAffected int64, err error)

CopyFrom sends a `COPY table FROM STDIN` SQL command to the server and returns the number of rows affected.

func (*Conn) Execute

func (conn *Conn) Execute(command string, params ...*Parameter) (rowsAffected int64, err error)

Execute sends a SQL command to the server and returns the number of rows affected.

If the results of a query are needed, use the Query method instead.

func (*Conn) Prepare

func (conn *Conn) Prepare(command string, params ...*Parameter) (stmt *Statement, err error)

Prepare returns a new prepared Statement, optimized to be executed multiple times with different parameter values.

func (*Conn) Query

func (conn *Conn) Query(command string, params ...*Parameter) (rs *ResultSet, err error)

Query sends a SQL query to the server and returns a ResultSet for row-by-row retrieval of the results.

The returned ResultSet must be closed before sending another query or command to the server over the same connection.

func (*Conn) RuntimeParameter

func (conn *Conn) RuntimeParameter(name string) (value string, ok bool)

RuntimeParameter returns the value of the specified runtime parameter.

If the value was successfully retrieved, ok is true, otherwise false.

func (*Conn) Scan

func (conn *Conn) Scan(command string, args ...interface{}) (fetched bool, err error)

Scan executes the command and scans the fields of the first row in the ResultSet, trying to store field values into the specified arguments.

The arguments must be of pointer types. If a row has been fetched, fetched will be true, otherwise false.

func (*Conn) Status

func (conn *Conn) Status() ConnStatus

Status returns the current connection status.

func (*Conn) TransactionStatus

func (conn *Conn) TransactionStatus() TransactionStatus

TransactionStatus returns the current transaction status of the connection.

func (*Conn) WithSavepoint

func (conn *Conn) WithSavepoint(isolation IsolationLevel, f func() error) (err error)

WithSavepoint creates a transaction savepoint, if the connection is in an active transaction without errors, then calls f.

If f returns an error or panicks, the transaction is rolled back to the savepoint. If the connection is in a failed transaction when calling WithSavepoint, this function immediately returns with an error, without calling f. If no transaction is in progress, instead of creating a savepoint, a new transaction is started.

func (*Conn) WithTransaction

func (conn *Conn) WithTransaction(isolation IsolationLevel, f func() error) (err error)

WithTransaction starts a new transaction, if none is in progress, then calls f.

If f returns an error or panicks, the transaction is rolled back, otherwise it is committed. If the connection is in a failed transaction when calling WithTransaction, this function immediately returns with an error, without calling f. In case of an active transaction without error, WithTransaction just calls f.

type ConnStatus

type ConnStatus int

ConnStatus represents the status of a connection.

const (
	StatusDisconnected ConnStatus = iota
	StatusReady
	StatusProcessingQuery
	StatusCopy
)

func (ConnStatus) String

func (s ConnStatus) String() string

type Error

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

Error contains detailed error information received from a PostgreSQL backend.

Many go-pgsql functions return an os.Error value. In case of a backend error, a type assertion as shown below gives you a *pgsql.Error with all details:

...
_, err := rs.FetchNext()
if err != nil {
	if pgerr, ok := err.(*pgsql.Error); ok {
		// Do something with pgerr
	}
}
...

func (*Error) Code

func (e *Error) Code() string

func (*Error) Detail

func (e *Error) Detail() string

func (*Error) Error

func (e *Error) Error() string

func (*Error) File

func (e *Error) File() string

func (*Error) Hint

func (e *Error) Hint() string

func (*Error) InternalPosition

func (e *Error) InternalPosition() string

func (*Error) InternalQuery

func (e *Error) InternalQuery() string

func (*Error) Line

func (e *Error) Line() string

func (*Error) Message

func (e *Error) Message() string

func (*Error) Position

func (e *Error) Position() string

func (*Error) Routine

func (e *Error) Routine() string

func (*Error) Severity

func (e *Error) Severity() string

func (*Error) Where

func (e *Error) Where() string

type IsolationLevel

type IsolationLevel int

IsolationLevel represents the isolation level of a transaction.

const (
	ReadCommittedIsolation IsolationLevel = iota
	SerializableIsolation
)

func (IsolationLevel) String

func (il IsolationLevel) String() string

type LogLevel

type LogLevel int

LogLevel is used to control what is written to the log.

const (
	// Log nothing.
	LogNothing LogLevel = iota

	// Log fatal errors.
	LogFatal

	// Log all errors.
	LogError

	// Log errors and warnings.
	LogWarning

	// Log errors, warnings and sent commands.
	LogCommand

	// Log errors, warnings, sent commands and additional debug info.
	LogDebug

	// Log everything.
	LogVerbose
)

type Parameter

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

Parameter is used to set the value of a parameter in a Statement.

func NewCustomTypeParameter

func NewCustomTypeParameter(name, customTypeName string) *Parameter

NewCustomTypeParameter returns a new Parameter with the specified name and custom data type.

The value of customTypeName will be used to insert a type cast into the command text for each occurrence of the parameter.

This constructor can be used for enum type parameters. In that case the value provided to SetValue is expected to be a string.

func NewParameter

func NewParameter(name string, typ Type) *Parameter

NewParameter returns a new Parameter with the specified name and type.

func (*Parameter) CustomTypeName

func (p *Parameter) CustomTypeName() string

CustomTypeName returns the custom type name of the Parameter.

func (*Parameter) Name

func (p *Parameter) Name() string

Name returns the name of the Parameter.

func (*Parameter) SetValue

func (p *Parameter) SetValue(v interface{}) (err error)

SetValue sets the current value of the Parameter.

func (*Parameter) Statement

func (p *Parameter) Statement() *Statement

Statement returns the *Statement this Parameter is associated with.

func (*Parameter) Type

func (p *Parameter) Type() Type

Type returns the PostgreSQL data type of the Parameter.

func (*Parameter) Value

func (p *Parameter) Value() interface{}

Value returns the current value of the Parameter.

type Pool

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

A Pool manages a list of connections that can be safely used by multiple goroutines.

func NewPool

func NewPool(connectParams string, minConns, maxConns int, idleTimeout time.Duration) (p *Pool, err error)

NewPool returns a new Pool that will create new connections on demand using connectParams, up to a maximum of maxConns outstanding connections. An error is returned if an initial connection cannot be created. Connections that have been idle for idleTimeout seconds will be automatically closed.

func (*Pool) Acquire

func (p *Pool) Acquire() (c *Conn, err error)

Acquire returns the next available connection, or returns an error if it failed to create a new connection. When an Acquired connection has been finished with, it should be returned to the pool via Release.

func (*Pool) Close

func (p *Pool) Close() error

Close closes any available connections and prevents the Acquiring of any new connections. It returns an error if there are any outstanding connections remaining.

func (*Pool) Release

func (p *Pool) Release(c *Conn)

Release returns the previously Acquired connection to the list of available connections.

type ResultSet

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

ResultSet reads the results of a query, row by row, and provides methods to retrieve field values of the current row.

Access is by 0-based field ordinal position.

func (*ResultSet) Any

func (rs *ResultSet) Any(ord int) (value interface{}, isNull bool, err error)

Any returns the value of the field with the specified ordinal as interface{}.

Types are mapped as follows:

PostgreSQL	Go

Bigint		int64
Boolean		bool
Char		string
Date		int64
Double		float64
Integer		int
Numeric		*big.Rat
Real		float
Smallint	int16
Text		string
Time		time.Time
TimeTZ		time.Time
Timestamp	time.Time
TimestampTZ	time.Time
Varchar		string

func (*ResultSet) Bool

func (rs *ResultSet) Bool(ord int) (value, isNull bool, err error)

Bool returns the value of the field with the specified ordinal as bool.

func (*ResultSet) Close

func (rs *ResultSet) Close() (err error)

Close closes the ResultSet, so another query or command can be sent to the server over the same connection.

func (*ResultSet) Conn

func (rs *ResultSet) Conn() *Conn

Conn returns the *Conn this ResultSet is associated with.

func (*ResultSet) FetchNext

func (rs *ResultSet) FetchNext() (hasRow bool, err error)

FetchNext reads the next row, if there is one.

In this case true is returned, otherwise false.

func (*ResultSet) FieldCount

func (rs *ResultSet) FieldCount() int

FieldCount returns the number of fields in the current result of the ResultSet.

func (*ResultSet) Float32

func (rs *ResultSet) Float32(ord int) (value float32, isNull bool, err error)

Float32 returns the value of the field with the specified ordinal as float32.

func (*ResultSet) Float64

func (rs *ResultSet) Float64(ord int) (value float64, isNull bool, err error)

Float64 returns the value of the field with the specified ordinal as float64.

func (*ResultSet) Int

func (rs *ResultSet) Int(ord int) (value int, isNull bool, err error)

Int returns the value of the field with the specified ordinal as int.

func (*ResultSet) Int16

func (rs *ResultSet) Int16(ord int) (value int16, isNull bool, err error)

Int16 returns the value of the field with the specified ordinal as int16.

func (*ResultSet) Int32

func (rs *ResultSet) Int32(ord int) (value int32, isNull bool, err error)

Int32 returns the value of the field with the specified ordinal as int32.

func (*ResultSet) Int64

func (rs *ResultSet) Int64(ord int) (value int64, isNull bool, err error)

Int64 returns the value of the field with the specified ordinal as int64.

func (*ResultSet) IsNull

func (rs *ResultSet) IsNull(ord int) (isNull bool, err error)

IsNull returns if the value of the field with the specified ordinal is null.

func (*ResultSet) Name

func (rs *ResultSet) Name(ord int) (name string, err error)

Name returns the name of the field with the specified ordinal.

func (*ResultSet) NextResult

func (rs *ResultSet) NextResult() (hasResult bool, err error)

NextResult moves the ResultSet to the next result, if there is one.

In this case true is returned, otherwise false. Statements support a single result only, use *Conn.Query if you need this functionality.

func (*ResultSet) Ordinal

func (rs *ResultSet) Ordinal(name string) int

Ordinal returns the 0-based ordinal position of the field with the specified name, or -1 if the ResultSet has no field with such a name.

func (*ResultSet) Rat

func (rs *ResultSet) Rat(ord int) (value *big.Rat, isNull bool, err error)

Rat returns the value of the field with the specified ordinal as *big.Rat.

func (*ResultSet) Scan

func (rs *ResultSet) Scan(args ...interface{}) (err error)

Scan scans the fields of the current row in the ResultSet, trying to store field values into the specified arguments.

The arguments must be of pointer types.

func (*ResultSet) ScanNext

func (rs *ResultSet) ScanNext(args ...interface{}) (fetched bool, err error)

ScanNext scans the fields of the next row in the ResultSet, trying to store field values into the specified arguments.

The arguments must be of pointer types. If a row has been fetched, fetched will be true, otherwise false.

func (*ResultSet) Statement

func (rs *ResultSet) Statement() *Statement

Statement returns the *Statement this ResultSet is associated with.

func (*ResultSet) String

func (rs *ResultSet) String(ord int) (value string, isNull bool, err error)

String returns the value of the field with the specified ordinal as string.

func (*ResultSet) Time

func (rs *ResultSet) Time(ord int) (value time.Time, isNull bool, err error)

Time returns the value of the field with the specified ordinal as *time.Time.

func (*ResultSet) TimeSeconds

func (rs *ResultSet) TimeSeconds(ord int) (value int64, isNull bool, err error)

TimeSeconds returns the value of the field with the specified ordinal as int64.

func (*ResultSet) Type

func (rs *ResultSet) Type(ord int) (typ Type, err error)

Type returns the PostgreSQL type of the field with the specified ordinal.

func (*ResultSet) Uint

func (rs *ResultSet) Uint(ord int) (value uint, isNull bool, err error)

Uint returns the value of the field with the specified ordinal as uint.

func (*ResultSet) Uint16

func (rs *ResultSet) Uint16(ord int) (value uint16, isNull bool, err error)

Uint16 returns the value of the field with the specified ordinal as uint16.

func (*ResultSet) Uint32

func (rs *ResultSet) Uint32(ord int) (value uint32, isNull bool, err error)

Uint32 returns the value of the field with the specified ordinal as uint32.

func (*ResultSet) Uint64

func (rs *ResultSet) Uint64(ord int) (value uint64, isNull bool, err error)

Uint64 returns the value of the field with the specified ordinal as uint64.

type Statement

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

Statement is a means to efficiently execute a parameterized SQL command multiple times.

Call *Conn.Prepare to create a new prepared Statement.

func (*Statement) ActualCommand

func (stmt *Statement) ActualCommand() string

ActualCommand returns the actual command text that is sent to the server.

The original command is automatically adjusted if it contains parameters so it complies with what PostgreSQL expects. Refer to the return value of this method to make sense of the position information contained in many error messages.

func (*Statement) Close

func (stmt *Statement) Close() (err error)

Close closes the Statement, releasing resources on the server.

func (*Statement) Command

func (stmt *Statement) Command() string

Command is the original command text as given to *Conn.Prepare.

func (*Statement) Conn

func (stmt *Statement) Conn() *Conn

Conn returns the *Conn this Statement is associated with.

func (*Statement) Execute

func (stmt *Statement) Execute() (rowsAffected int64, err error)

Execute executes the Statement and returns the number of rows affected.

If the results of a query are needed, use the Query method instead.

func (*Statement) IsClosed

func (stmt *Statement) IsClosed() bool

IsClosed returns if the Statement has been closed.

func (*Statement) Parameter

func (stmt *Statement) Parameter(name string) *Parameter

Parameter returns the Parameter with the specified name or nil, if the Statement has no Parameter with that name.

func (*Statement) Parameters

func (stmt *Statement) Parameters() []*Parameter

Parameters returns a slice containing the parameters of the Statement.

func (*Statement) Query

func (stmt *Statement) Query() (rs *ResultSet, err error)

Query executes the Statement and returns a ResultSet for row-by-row retrieval of the results.

The returned ResultSet must be closed before sending another query or command to the server over the same connection.

func (*Statement) Scan

func (stmt *Statement) Scan(args ...interface{}) (fetched bool, err error)

Scan executes the statement and scans the fields of the first row in the ResultSet, trying to store field values into the specified arguments.

The arguments must be of pointer types. If a row has been fetched, fetched will be true, otherwise false.

type TransactionStatus

type TransactionStatus byte

TransactionStatus represents the transaction status of a connection.

const (
	NotInTransaction    TransactionStatus = 'I'
	InTransaction       TransactionStatus = 'T'
	InFailedTransaction TransactionStatus = 'E'
)

func (TransactionStatus) String

func (s TransactionStatus) String() string

type Type

type Type int32

Type represents the PostgreSQL data type of fields and parameters.

const (
	Custom      Type = 0
	Boolean     Type = _BOOLOID
	Char        Type = _CHAROID
	Date        Type = _DATEOID
	Real        Type = _FLOAT4OID
	Double      Type = _FLOAT8OID
	Smallint    Type = _INT2OID
	Integer     Type = _INT4OID
	Bigint      Type = _INT8OID
	Numeric     Type = _NUMERICOID
	Text        Type = _TEXTOID
	Time        Type = _TIMEOID
	TimeTZ      Type = _TIMETZOID
	Timestamp   Type = _TIMESTAMPOID
	TimestampTZ Type = _TIMESTAMPTZOID
	Varchar     Type = _VARCHAROID
)

func (Type) String

func (t Type) String() string

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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