postgresql

package module
v0.0.0-...-500e2a6 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2016 License: BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

The package postgresql-go provide a thin wrapper around the C library for accessing PostgreSQL databases. Nearly all of the functions in this package translate directly into calls to libpq.

This package does not provide a driver for the package database/sql, although it could provide the basis for a pure Go driver. The goal is to provide the thinnest access to the standard API, while maintaining type safety.

If the documentation in this package is unclear or incomplete, please refer to the full documentation for libpq, which is far more complete.

Index

Examples

Constants

View Source
const (
	OidInvalid     = Oid(C.InvalidOid)
	OidBool        = Oid(16)
	OidByteArray   = Oid(17)
	OidInt8        = Oid(18)
	OidInt16       = Oid(21)
	OidInt32       = Oid(23)
	OidInt64       = Oid(20)
	OidString      = Oid(25)
	OidFloat32     = Oid(700)
	OidFloat64     = Oid(701)
	OidInt16Array  = Oid(1005)
	OidInt32Array  = Oid(1007)
	OidInt64Array  = Oid(1016)
	OidStringArray = Oid(1009)
)

These Oids are an incomplete list of the types supported by PostgreSQL, but they represent the values that this library knows how to convert back and forth with Go. As such, they represent native types in Go.

View Source
const (
	// The string sent to the server was empty
	EMPTY_QUERY = ExecStatus(C.PGRES_EMPTY_QUERY)
	// The command completed successfully, but returned no data
	COMMAND_OK = ExecStatus(C.PGRES_COMMAND_OK)
	// The command completed successfully, and returned data
	TUPLES_OK      = ExecStatus(C.PGRES_TUPLES_OK)
	COPY_OUT       = ExecStatus(C.PGRES_COPY_OUT)
	COPY_IN        = ExecStatus(C.PGRES_COPY_IN)
	BAD_RESPONSE   = ExecStatus(C.PGRES_BAD_RESPONSE)
	NONFATAL_ERROR = ExecStatus(C.PGRES_NONFATAL_ERROR)
	FATAL_ERROR    = ExecStatus(C.PGRES_FATAL_ERROR)
	COPY_BOTH      = ExecStatus(C.PGRES_COPY_BOTH)
)
View Source
const (
	// The server is running and appears to be accepting connections
	PING_OK = Ping(C.PQPING_OK)
	// The server is running but is in a state that disallows connections (startup, shutdown, or crash recovery)
	PING_REJECT = Ping(C.PQPING_REJECT)
	// The server could not be contacted
	PING_NO_RESPONSE = Ping(C.PQPING_NO_RESPONSE)
	// No attempt was made to contact the server
	PING_NO_ATTEMPT = Ping(C.PQPING_NO_ATTEMPT)
)
View Source
const (
	ERRORS_TERSE   = Verbosity(C.PQERRORS_TERSE)
	ERRORS_DEFAULT = Verbosity(C.PQERRORS_DEFAULT)
	ERRORS_VERBOSE = Verbosity(C.PQERRORS_VERBOSE)
)
View Source
const (
	// Connection to the database server succeeded
	CONNECTION_OK = ConnectionStatus(C.CONNECTION_OK)
	// Connection to the database server failed
	CONNECTION_BAD = ConnectionStatus(C.CONNECTION_BAD)
)
View Source
const (
	// Currently idle
	TRANS_IDLE = TransactionStatus(C.PQTRANS_IDLE)
	// A command is in progress
	TRANS_ACTIVE = TransactionStatus(C.PQTRANS_ACTIVE)
	// Idle, in a valid transaction block
	TRANS_INTRANS = TransactionStatus(C.PQTRANS_INTRANS)
	// Idle, in a failed transaction block
	TRANS_INERROR = TransactionStatus(C.PQTRANS_INERROR)
	// Unknown status, the connection to the database is bad
	TRANS_UNKNOWN = TransactionStatus(C.PQTRANS_UNKNOWN)
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientEncoding

type ClientEncoding int

A ClientEncoding represents the encoding used by the connection.

func (ClientEncoding) String

func (c ClientEncoding) String() string

String converts the numeric representation of a client encoding to a symbolic string.

type Connection

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

A Connection represents a connection to a PostgreSQL backend server. An application can have several connections open simultaneously.

This type wraps the PGconn object in the C library.

func NewConnection

func NewConnection(connection_info string) *Connection

NewConnection makes a new connection to the database server. The connection is opened using the parameters taken from the string connection_info.

Note that NewConnection (nearly) always returns a non-nil object. To check for errors, use a call to the method Status.

The function wraps the PQconnectdb function in the C library.

Example
// The following string will need to be replaced with the correct
// connection string for your server.  Refer to the PostgreSQL
// documentation.
connection_info := os.Getenv("PQ")
if connection_info == "" {
	connection_info = "dbname=postgres"
}

// Whether it succeeds or fails, you will always receive a connection
// object.  Check the status to determine if the connection was
// successful or not.
conn := NewConnection(connection_info)
defer conn.Close()
if conn.Status() != CONNECTION_OK {
	fmt.Printf("Connection to database failed: %s", conn.ErrorMessage())
	return
}

fmt.Println("Connection succeeded.")
Output:

Connection succeeded.

func (*Connection) ClientEncoding

func (c *Connection) ClientEncoding() ClientEncoding

ClientEncoding returns the client encoding.

This method wraps the function PQclientEncoding in the C library.

func (*Connection) Close

func (c *Connection) Close()

Close closes the connection to the database server, and frees any memory used by the Connection object.

This method is safe to call on nil pointers.

This method wraps the PQfinish function in the C library.

func (*Connection) Database

func (c *Connection) Database() string

Database returns the database name of the connection.

This method wraps the function PQdb in the C library.

func (*Connection) DescribedPrepared

func (c *Connection) DescribedPrepared(stmt_name string) *Result

DescribedPrepared returns a Result value that, while it does not contain any rows, can be used to query the statement's properties, such as what parameters need to be bound, and what fields will be returned when the statement is executed.

This function wraps the PQdescribePrepared function in the C library.

func (*Connection) ErrorMessage

func (c *Connection) ErrorMessage() string

ErrorMessage returns the most recent error message associated with the connection. The error message may contain multiple lines.

This method wraps the function PQerrorMessage in the C library.

func (*Connection) EscapeIdentifier

func (c *Connection) EscapeIdentifier(str string) (string, error)

EscapeIdentifier returns an escaped string for use as an identifier within an SQL command.

This method wraps the function PQescapeIdentifier in the C library.

func (*Connection) EscapeLiteral

func (c *Connection) EscapeLiteral(str string) (string, error)

EscapeLiteral returns an escaped string for use within a literal SQL command.

This method wraps the function PQescapeLiteral in the C library.

func (*Connection) Exec

func (c *Connection) Exec(command string, parameters ...interface{}) *Result

Exec submits a command to the server, and wais for the results. Please refer to the PostgreSQL documentation for details on the format of the SQL statement, and the use of parameters.

Note that Exec (nearly) always returns a non-nil object. To check for errors, use a call to the method Status on the returned object.

This method wraps the functions PQexec and PQexecParams in the C library. The correct function is selected depending on whether or not parameters are supplied.

Example
connection_info := os.Getenv("PQ")
if connection_info == "" {
	connection_info = "dbname=postgres"
}

conn := NewConnection(connection_info)
defer conn.Close()
if conn.Status() != CONNECTION_OK {
	fmt.Printf("Connection to database failed: %s", conn.ErrorMessage())
	return
}

res := conn.Exec("BEGIN")
if res.Status() != COMMAND_OK {
	fmt.Printf("BEGIN command failed: %s", conn.ErrorMessage())
	res.Close()
	return
}
res.Close()

res = conn.Exec("DECLARE myportal CURSOR FOR select * from pg_database")
if res.Status() != COMMAND_OK {
	fmt.Printf("DECLARE CURSOR failed: %s", conn.ErrorMessage())
	res.Close()
	return
}

res = conn.Exec("FETCH ALL in myportal")
if res.Status() != TUPLES_OK {
	fmt.Printf("FETCH ALL failed: %s", conn.ErrorMessage())
	res.Close()
	return
}

// First, print out the attribute names
nFields := res.NFields()
for i := 0; i < nFields; i++ {
	fmt.Printf("%-15s", res.FieldName(i))
}
fmt.Println("\n\n")

// Second, print our the rows
nRows := res.NTuples()
for i := 0; i < nRows; i++ {
	for j := 0; j < nFields; j++ {
		fmt.Printf("%-15s", res.Value(i, j))
	}
}
res.Close()

// Close the portal
res = conn.Exec("CLOSE myportal")
res.Close()

// End the transaction
res = conn.Exec("END")
res.Close()
Output:

func (*Connection) ExecCommand

func (c *Connection) ExecCommand(command string, params ...interface{}) error

ExecCommand submits an SQL command to the database server for processing. This method is a utility function for the case when the SQL command should not return any rows, and handles clean-up of the Result object internally.

If there was an error in executing the SQL command, or if the command return any rows, this function will return an error.

Example
connection_info := os.Getenv("PQ")
if connection_info == "" {
	connection_info = "dbname=postgres"
}

conn := NewConnection(connection_info)
defer conn.Close()
if conn.Status() != CONNECTION_OK {
	fmt.Printf("Connection to database failed: %s", conn.ErrorMessage())
	return
}

err := conn.ExecCommand("BEGIN")
if err != nil {
	fmt.Printf("BEGIN command failed: %s", err)
	return
}

err = conn.ExecCommand("DECLARE myportal CURSOR FOR select * from pg_database")
if err != nil {
	fmt.Printf("DECLARE CURSOR failed: %s", err)
	return
}

res := conn.Exec("FETCH ALL in myportal")
defer res.Close()
if res.Status() != TUPLES_OK {
	fmt.Printf("FETCH ALL failed: %s", conn.ErrorMessage())
	return
}

// First, print out the attribute names
nFields := res.NFields()
for i := 0; i < nFields; i++ {
	fmt.Printf("%-15s", res.FieldName(i))
}
fmt.Println("\n\n")

// Second, print our the rows
nRows := res.NTuples()
for i := 0; i < nRows; i++ {
	for j := 0; j < nFields; j++ {
		fmt.Printf("%-15s", res.Value(i, j))
	}
}

// Close the portal, ignoring any error
conn.ExecCommand("CLOSE myportal")

// End the transaction
conn.ExecCommand("END")
Output:

func (*Connection) ExecPrepared

func (c *Connection) ExecPrepared(stmt_name string, parameters ...interface{}) *Result

ExecPrepared binds parameters to a prepared statement, and then executes that statement.

This function wraps the PQexecPrepared function in the C library.

func (*Connection) Host

func (c *Connection) Host() string

Host returns the host name of the connection.

This method wraps the function PQhost in the C library.

func (*Connection) Options

func (c *Connection) Options() string

Options returns the command-line options passed of the connection request.

This method wraps the function PQoptions in the C library.

func (*Connection) ParameterStatus

func (c *Connection) ParameterStatus(param_name string) string

ParameterStatus returns the current parameter setting for the database server.

This method wraps the function PQparameterStatus in the C library.

func (*Connection) Password

func (c *Connection) Password() string

Password returns the password of the connection.

This method wraps the function PQpass in the C library.

func (*Connection) Port

func (c *Connection) Port() string

Port returns the port of the connection.

This method wraps the function PQport in the C library.

func (*Connection) Prepare

func (c *Connection) Prepare(stmt_name, query string) error

Prepare parses an SQL statement, and creates a prepared statement. The statement is not executed immediately (see ExecPrepared).

This function wraps the PQprepare function in the C library.

func (*Connection) ProtocolVersion

func (c *Connection) ProtocolVersion() int

ProtocolVersion returns the communication protocol being used.

This method wraps the function PQprotocolVersion in the C library.

func (*Connection) Reset

func (c *Connection) Reset()

Reset resets the communication channel to the server.

This method wraps the PQreset function in the C library.

func (*Connection) ServerVersion

func (c *Connection) ServerVersion() int

ServerVersion returns an integer representing the database server version.

This method wraps the function PQserverVersion in the C library.

func (*Connection) SetClientEncoding

func (c *Connection) SetClientEncoding(encoding string) (ok bool)

SetClientEncoding set the encoding that you want to use.

This method wraps the function PQsetClientEncoding in the C library.

func (*Connection) SetErrorVerbosity

func (c *Connection) SetErrorVerbosity(verbosity Verbosity) Verbosity

SetErrorVerbosity determines the verbosity of messages returned by ErrorMessage on Connection and Result objects.

This method wraps the function PQsetErrorVerbosity in the C library.

func (*Connection) Status

func (c *Connection) Status() ConnectionStatus

Status returns the status of the connection.

This method wraps the function PQstatus in the C library.

func (*Connection) TransactionStatus

func (c *Connection) TransactionStatus() TransactionStatus

TransactionStatus returns the current in-transaction status of the database server.

This method wraps the function PQtransactionStatus in the C library.

func (*Connection) User

func (c *Connection) User() string

User returns the user name of the connection.

This method wraps the function PQuser in the C library.

type ConnectionStatus

type ConnectionStatus int

ConnectionStatus represent the state of a connection.

This type wraps the ConnStatusType object in the C library.

type ExecCommandError

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

An ExecCommandError contains the error information obtained when a call to ExecCommand fails.

func (*ExecCommandError) Error

func (e *ExecCommandError) Error() string

type ExecStatus

type ExecStatus int

An ExecStatus represents the type of result that was obtained by executing a query.

This type wraps the ExecStatusType enum in the C library.

func (ExecStatus) String

func (e ExecStatus) String() string

String returns a string containing a description of the ExecStatus.

This method wraps the function PQresStatus in the C library.

type Oid

type Oid uint64

An Oid is an object identifier used internally by PostgreSQL. Most users of this library should not need to use this type.

This type wraps the Oid typedef in the C library.

type Ping

type Ping int

A Ping represents the result of a call to check the server status. See the function NewPing.

This type wraps the PGPing object in the C library.

func NewPing

func NewPing(connection_info string) Ping

NewPing reports the status of a database server. It accepts connection parameters identical to NewConnection.

This function wraps the PQping function in the C library.

type Result

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

A Result represents the response to a query. If the query contains any rows, that data can be accessed through this object.

This type wraps the PGresult object in the C library.

func (*Result) Close

func (r *Result) Close()

Close frees the storage associated with the Result.

This method wraps the function PQclear in the C library.

func (*Result) CmdStatus

func (r *Result) CmdStatus() string

CmdStatus returns the status text from the SQL statement used to generate the Result.

This method wraps the function PQcmdStatus in the C library.

func (*Result) CmdTuples

func (r *Result) CmdTuples() int64

CmdTuples returns the number of rows affected by the SQL statement.

This method wraps the function PQcmdTuples in the C library.

func (*Result) ErrorMessage

func (r *Result) ErrorMessage() string

ErrorMessage returns the error message associated with the Result.

This method wraps the function PQresultErrorMessage in the C library.

func (*Result) FieldName

func (r *Result) FieldName(column_number int) string

FieldName returns the name of the column given the column number.

This method wraps the function PQfname in the C library.

func (*Result) FieldNumber

func (r *Result) FieldNumber(column_name string) int

FieldNumber returns the column number that has the given name.

This method wraps the function PQfnumber in the C library.

func (*Result) FieldSize

func (r *Result) FieldSize(column_number int) int

FieldSize return the reserved size used to hold values in this column of the query. For variable sized items, use the method ValueLen.

This method wraps the function PQfsize in the C library.

func (*Result) FieldTable

func (r *Result) FieldTable(column_number int) Oid

FieldTable return the Oid of the table that contains the data for this column of the query.

This method wraps the function PQftable in the C library.

func (*Result) FieldTableColumn

func (r *Result) FieldTableColumn(column_number int) int

FieldTableColumn return the column number from the table that contains the data for this column of the query.

This method wraps the function PQftablecol in the C library.

func (*Result) FieldType

func (r *Result) FieldType(column_number int) Oid

FieldType return an Oid indicating the type of this column of the query.

This method wraps the function PQftype in the C library.

func (*Result) IsNull

func (r *Result) IsNull(row_number, column_number int) bool

IsNull returns true if the datum in the specified row and column is null.

This method wraps the function PQgetisnull in the C library.

func (*Result) NFields

func (r *Result) NFields() int

NFields returns the number of fields in each row of the query result.

This method wraps the function PQnfields in the C library.

func (*Result) NParams

func (r *Result) NParams() int

NParams returns the number of parameters required to complete a prepared statement. This method is only useful on a result returned by the method DescribePrepared.

This method wraps the function PQnparams in the C library.

func (*Result) NTuples

func (r *Result) NTuples() int

NTuples returns the number of rows (tuples) in the query result.

This method wraps the function PQntuples in the C library.

func (*Result) OidValue

func (r *Result) OidValue() Oid

OidValue returns the Oid of the row inserted by the SQL statement.

This method wraps the function PQoidValue in the C library.

func (*Result) ParamType

func (r *Result) ParamType(param_number int) Oid

ParamType returns the Oid describing the expected type of the specified parameter. This method is only useful on a result returned by the method DescribePrepared.

This method wraps the function PQparamtype in the C library.

func (*Result) Status

func (r *Result) Status() ExecStatus

Status returns the status of the Result.

This method wraps the function PQresultStatus in the C library.

func (*Result) Value

func (r *Result) Value(row_number, column_number int) interface{}

Value returns the value of the datum in the specified row and column. The value is converted from the format understood by PostgreSQL into a type in Go, but the range of types supported by PostgreSQL is much wider than this library understands. However, most native types are understood.

This method wraps the function PQgetvalue in the C library.

func (*Result) ValueLen

func (r *Result) ValueLen(row_number, column_number int) int

ValueLen returns the size of the datum in the specified row and column.

This method wraps the function PQgetlength in the C library.

type TransactionStatus

type TransactionStatus int

TransactionStatus represents the transaction state of the database server.

This type wraps the PQtransactionStatus object in the C library.

type Verbosity

type Verbosity int

A Verbosity represent the verbosity mode of a database connection.

This type wraps the PGVerbosity enum in the C library.

Jump to

Keyboard shortcuts

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