Movatterモバイル変換


[0]ホーム

URL:


pq

packagemodule
v1.10.9Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2023 License:MITImports:35Imported by:52,502

Details

Repository

github.com/lib/pq

Links

README

pq - A pure Go postgres driver for Go's database/sql package

GoDoc

Install

go get github.com/lib/pq

Features

  • SSL
  • Handles bad connections fordatabase/sql
  • Scantime.Time correctly (i.e.timestamp[tz],time[tz],date)
  • Scan binary blobs correctly (i.e.bytea)
  • Package forhstore support
  • COPY FROM support
  • pq.ParseURL for converting urls to connection strings for sql.Open.
  • Many libpq compatible environment variables
  • Unix socket support
  • Notifications:LISTEN/NOTIFY
  • pgpass support
  • GSS (Kerberos) auth

Tests

go test is used for testing. SeeTESTS.md for more details.

Status

This package is currently in maintenance mode, which means:

  1. It generally does not accept new features.
  2. It does accept bug fixes and version compatability changes provided by the community.
  3. Maintainers usually do not resolve reported issues.
  4. Community members are encouraged to help each other with reported issues.

For users that require new features or reliable resolution of reported bugs, we recommend usingpgx which is under active development.

Documentation

Overview

Package pq is a pure Go Postgres driver for the database/sql package.

In most cases clients will use the database/sql package instead ofusing this package directly. For example:

import ("database/sql"_ "github.com/lib/pq")func main() {connStr := "user=pqgotest dbname=pqgotest sslmode=verify-full"db, err := sql.Open("postgres", connStr)if err != nil {log.Fatal(err)}age := 21rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)…}

You can also connect to a database using a URL. For example:

connStr := "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full"db, err := sql.Open("postgres", connStr)

Connection String Parameters

Similarly to libpq, when establishing a connection using pq you are expected tosupply a connection string containing zero or more parameters.A subset of the connection parameters supported by libpq are also supported by pq.Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem)directly in the connection string. This is different from libpq, which does not allowrun-time parameters in the connection string, instead requiring you to supplythem in the options parameter.

For compatibility with libpq, the following special connection parameters aresupported:

  • 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 unixdomain 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 notthe 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 ornot 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 filemust 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 theserver was signed by a trusted CA)
  • verify-full - Always SSL (verify that the certification presented bythe server was signed by a trusted CA and the server host namematches the one in the certificate)

Seehttp://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRINGfor more information about connection string parameters.

Use single quotes for values that contain whitespace:

"user=pqgotest password='with spaces'"

A backslash will escape the next character in values:

"user=space\ man password='it\'s valid'"

Note that the connection parameter client_encoding (which sets thetext encoding for the connection) may be set but must be "UTF8",matching with the same rules as Postgres. It is an error to provideany other value.

In addition to the parameters listed above, any run-time parameter that can beset at backend start time can be set in the connection string. For moreinformation, seehttp://www.postgresql.org/docs/current/static/runtime-config.html.

Most environment variables as specified athttp://www.postgresql.org/docs/current/static/libpq-envars.htmlsupported by libpq are also supported by pq. If any of the environmentvariables not supported by pq are set, pq will panic during connectionestablishment. Environment variables have a lower precedence than explicitlyprovided connection parameters.

The pgpass mechanism as described inhttp://www.postgresql.org/docs/current/static/libpq-pgpass.htmlis supported, but on Windows PGPASSFILE must be specified explicitly.

Queries

database/sql does not dictate any specific format for parametermarkers in query strings, and pq uses the Postgres-native ordinal markers,as shown above. The same marker can be reused for the same parameter:

rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1OR age BETWEEN $2 AND $2 + 3`, "orange", 64)

pq does not support the LastInsertId() method of the Result type in database/sql.To return the identifier of an INSERT (or UPDATE or DELETE), use the PostgresRETURNING clause with a standard Query or QueryRow call:

var userid interr := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)

For more details on RETURNING, see the Postgres documentation:

http://www.postgresql.org/docs/current/static/sql-insert.htmlhttp://www.postgresql.org/docs/current/static/sql-update.htmlhttp://www.postgresql.org/docs/current/static/sql-delete.html

For additional instructions on querying see the documentation for the database/sql package.

Data Types

Parameters pass through driver.DefaultParameterConverter before they are handledby this package. When the binary_parameters connection option is enabled,[]byte values are sent directly to the backend as data in binary format.

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 arereturned as time.Time
  • the boolean type is returned as bool
  • the bytea type is returned as []byte

All other types are returned directly from the backend as []byte values in text format.

Errors

pq may return errors of type *pq.Error which can be interrogated for error details:

if err, ok := err.(*pq.Error); ok {    fmt.Println("pq error:", err.Code.Name())}

See the pq.Error type for details.

Bulk imports

You can perform bulk imports by preparing a statement returned by pq.CopyIn (orpq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statementhandle can then be repeatedly "executed" to copy data into the target table.After all data has been processed you should call Exec() once with no argumentsto flush all buffered data. Any call to Exec() might return an error whichshould be handled appropriately, but because of the internal buffering an errorreturned by Exec() might not be related to the data passed in the call thatfailed.

CopyIn uses COPY FROM internally. It is not possible to COPY outside of anexplicit transaction in pq.

Usage example:

txn, err := db.Begin()if err != nil {log.Fatal(err)}stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age"))if err != nil {log.Fatal(err)}for _, user := range users {_, err = stmt.Exec(user.Name, int64(user.Age))if err != nil {log.Fatal(err)}}_, err = stmt.Exec()if err != nil {log.Fatal(err)}err = stmt.Close()if err != nil {log.Fatal(err)}err = txn.Commit()if err != nil {log.Fatal(err)}

Notifications

PostgreSQL supports a simple publish/subscribe model over databaseconnections. Seehttp://www.postgresql.org/docs/current/static/sql-notify.htmlfor more information about the general mechanism.

To start listening for notifications, you first have to open a new connectionto the database by calling NewListener. This connection can not be used foranything other than LISTEN / NOTIFY. Calling Listen will open a "notificationchannel"; once a notification channel is open, a notification generated on thatchannel will effect a send on the Listener.Notify channel. A notificationchannel will remain open until Unlisten is called, though connection loss mightresult in some notifications being lost. To solve this problem, Listener sendsa nil pointer over the Notify channel any time the connection is re-establishedfollowing a connection loss. The application can get information about thestate of the underlying connection by setting an event callback in the call toNewListener.

A single Listener can safely be used from concurrent goroutines, which meansthat there is often no need to create more than one Listener in yourapplication. However, a Listener is always connected to a single database, soyou will need to create a new Listener instance for every database you want toreceive notifications in.

The channel name in both Listen and Unlisten is case sensitive, and can containany characters legal in an identifier (seehttp://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERSfor more information). Note that the channel name will be truncated to 63bytes by the PostgreSQL server.

You can find a complete, working example of Listener usage athttps://godoc.org/github.com/lib/pq/example/listen.

Kerberos Support

If you need support for Kerberos authentication, add the following to your mainpackage:

import "github.com/lib/pq/auth/kerberos"func init() {pq.RegisterGSSProvider(func() (pq.Gss, error) { return kerberos.NewGSS() })}

This package is in a separate module so that users who don't need Kerberosdon't have to download unnecessary dependencies.

When imported, additional connection string parameters are supported:

  • krbsrvname - GSS (Kerberos) service name when constructing theSPN (default is `postgres`). This will be combined with the hostto form the full SPN: `krbsrvname/host`.
  • krbspn - GSS (Kerberos) SPN. This takes priority over`krbsrvname` if present.

Index

Examples

Constants

View Source
const (Efatal   = "FATAL"Epanic   = "PANIC"Ewarning = "WARNING"Enotice  = "NOTICE"Edebug   = "DEBUG"Einfo    = "INFO"Elog     = "LOG")

Error severities

Variables

View Source
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")ErrSSLKeyUnknownOwnership    =errors.New("pq: Could not get owner information for private key, may not be properly protected")ErrSSLKeyHasWorldPermissions =errors.New("pq: Private key has world access. Permissions should be u=rw,g=r (0640) if owned by root, or u=rw (0600), or less")ErrCouldNotDetectUsername =errors.New("pq: Could not detect default username. Please provide one explicitly"))

Common error types

View Source
var ErrChannelAlreadyOpen =errors.New("pq: channel is already open")

ErrChannelAlreadyOpen is returned from Listen when a channel is alreadyopen.

View Source
var ErrChannelNotOpen =errors.New("pq: channel is not open")

ErrChannelNotOpen is returned from Unlisten when a channel is not open.

Functions

funcArray

func Array(a interface{}) interface {driver.Valuersql.Scanner}

Array returns the optimal driver.Valuer and sql.Scanner for an array orslice of any dimension.

For example:

db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401}))var x []sql.NullInt64db.QueryRow(`SELECT ARRAY[235, 401]`).Scan(pq.Array(&x))

Scanning multi-dimensional arrays is not supported. Arrays where the lowerbound is not one (such as `[0:0]={1}') are not supported.

funcBufferQuoteIdentifieradded inv1.10.8

func BufferQuoteIdentifier(namestring, buffer *bytes.Buffer)

BufferQuoteIdentifier satisfies the same purpose as QuoteIdentifier, but backed by abyte buffer.

funcConnectorNoticeHandleradded inv1.4.0

func ConnectorNoticeHandler(cdriver.Connector) func(*Error)

ConnectorNoticeHandler returns the currently set notice handler, if any. Ifthe given connector is not a result of ConnectorWithNoticeHandler, nil isreturned.

funcConnectorNotificationHandleradded inv1.5.1

func ConnectorNotificationHandler(cdriver.Connector) func(*Notification)

ConnectorNotificationHandler returns the currently set notification handler, if any. Ifthe given connector is not a result of ConnectorWithNotificationHandler, nil isreturned.

funcCopyIn

func CopyIn(tablestring, columns ...string)string

CopyIn creates a COPY FROM statement which can be prepared withTx.Prepare(). The target table should be visible in search_path.

funcCopyInSchema

func CopyInSchema(schema, tablestring, columns ...string)string

CopyInSchema creates a COPY FROM statement which can be prepared withTx.Prepare().

funcDialOpen

func DialOpen(dDialer, dsnstring) (_driver.Conn, errerror)

DialOpen opens a new connection to the database using a dialer.

funcEnableInfinityTs

func EnableInfinityTs(negativetime.Time, positivetime.Time)

EnableInfinityTs controls the handling of Postgres' "-infinity" and"infinity" "timestamp"s.

If EnableInfinityTs is not called, "-infinity" and "infinity" will return[]byte("-infinity") and []byte("infinity") respectively, and potentiallycause error "sql: Scan error on column index 0: unsupported driver -> Scanpair: []uint8 -> *time.Time", when scanning into a time.Time value.

Once EnableInfinityTs has been called, all connections created using thisdriver will decode Postgres' "-infinity" and "infinity" for "timestamp","timestamp with time zone" and "date" types to the predefined minimum andmaximum times, respectively. When encoding time.Time values, any time whichequals or precedes the predefined minimum time will be encoded to"-infinity". Any values at or past the maximum time will similarly beencoded to "infinity".

If EnableInfinityTs is called with negative >= positive, it will panic.Calling EnableInfinityTs after a connection has been established results inundefined behavior. If EnableInfinityTs is called more than once, it willpanic.

funcFormatTimestamp

func FormatTimestamp(ttime.Time) []byte

FormatTimestamp formats t into Postgres' text format for timestamps.

funcNoticeHandleradded inv1.4.0

func NoticeHandler(cdriver.Conn) func(*Error)

NoticeHandler returns the notice handler on the given connection, if any. Aruntime panic occurs if c is not a pq connection. This is rarely useddirectly, use ConnectorNoticeHandler and ConnectorWithNoticeHandler instead.

funcOpen

func Open(dsnstring) (_driver.Conn, errerror)

Open opens a new connection to the database. dsn is a connection string.Most users should only use it through database/sql package from the standardlibrary.

funcParseTimestamp

func ParseTimestamp(currentLocation *time.Location, strstring) (time.Time,error)

ParseTimestamp parses Postgres' text format. It returns a time.Time incurrentLocation iff that time's offset agrees with the offset sent from thePostgres server. Otherwise, ParseTimestamp returns a time.Time with thefixed offset offset provided by the Postgres server.

funcParseURL

func ParseURL(urlstring) (string,error)

ParseURL no longer needs to be used by clients of this library since supplying a URL as aconnection string to sql.Open() is now supported:

sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full")

It remains exported here for backwards-compatibility.

ParseURL converts a url to a connection string for driver.Open.Example:

"postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full"

converts to:

"user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full"

A minimal example:

"postgres://"

This will be blank, causing driver.Open to use all of the defaults

funcQuoteIdentifier

func QuoteIdentifier(namestring)string

QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to beused as part of an SQL statement. For example:

tblname := "my_table"data := "my_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 becase sensitive when used in a query. If the input string contains a zerobyte, the result will be truncated immediately before it.

funcQuoteLiteraladded inv1.2.0

func QuoteLiteral(literalstring)string

QuoteLiteral quotes a 'literal' (e.g. a parameter, often used to pass literalto DDL and other statements that do not accept parameters) to be used as partof an SQL statement. For example:

exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))

Any single quotes in name will be escaped. Any backslashes (i.e. "\") will bereplaced by two backslashes (i.e. "\\") and the C-style escape identifierthat PostgreSQL provides ('E') will be prepended to the string.

funcRegisterGSSProvideradded inv1.7.0

func RegisterGSSProvider(newGssArgNewGSSFunc)

RegisterGSSProvider registers a GSS authentication provider. For example, ifyou need to use Kerberos to authenticate with your server, add this to yourmain package:

import "github.com/lib/pq/auth/kerberos"func init() {pq.RegisterGSSProvider(func() (pq.GSS, error) { return kerberos.NewGSS() })}

funcSetNoticeHandleradded inv1.4.0

func SetNoticeHandler(cdriver.Conn, handler func(*Error))

SetNoticeHandler sets the given notice handler on the given connection. Aruntime panic occurs if c is not a pq connection. A nil handler may be usedto unset it. This is rarely used directly, use ConnectorNoticeHandler andConnectorWithNoticeHandler instead.

Note: Notice handlers are executed synchronously by pq meaning commandswon't continue to be processed until the handler returns.

funcSetNotificationHandleradded inv1.5.0

func SetNotificationHandler(cdriver.Conn, handler func(*Notification))

SetNotificationHandler sets the given notification handler on the givenconnection. A runtime panic occurs if c is not a pq connection. A nil handlermay be used to unset it.

Note: Notification handlers are executed synchronously by pq meaning commandswon't continue to be processed until the handler returns.

Types

typeArrayDelimiter

type ArrayDelimiter interface {// ArrayDelimiter returns the delimiter character(s) for this element's type.ArrayDelimiter()string}

ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scannerto override the array delimiter used by GenericArray.

typeBoolArray

type BoolArray []bool

BoolArray represents a one-dimensional array of the PostgreSQL boolean type.

func (*BoolArray)Scan

func (a *BoolArray) Scan(src interface{})error

Scan implements the sql.Scanner interface.

func (BoolArray)Value

func (aBoolArray) Value() (driver.Value,error)

Value implements the driver.Valuer interface.

typeByteaArray

type ByteaArray [][]byte

ByteaArray represents a one-dimensional array of the PostgreSQL bytea type.

func (*ByteaArray)Scan

func (a *ByteaArray) Scan(src interface{})error

Scan implements the sql.Scanner interface.

func (ByteaArray)Value

func (aByteaArray) Value() (driver.Value,error)

Value implements the driver.Valuer interface. It uses the "hex" format whichis only supported on PostgreSQL 9.0 or newer.

typeConnectoradded inv1.1.0

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

Connector represents a fixed configuration for the pq driver with a givenname. Connector satisfies the database/sql/driver Connector interface andcan be used to create any number of DB Conn's via the database/sql OpenDBfunction.

Seehttps://golang.org/pkg/database/sql/driver/#Connector.Seehttps://golang.org/pkg/database/sql/#OpenDB.

funcNewConnector

func NewConnector(dsnstring) (*Connector,error)

NewConnector returns a connector for the pq driver in a fixed configurationwith the given dsn. The returned connector can be used to create any numberof equivalent Conn's. The returned connector is intended to be used withdatabase/sql.OpenDB.

Seehttps://golang.org/pkg/database/sql/driver/#Connector.Seehttps://golang.org/pkg/database/sql/#OpenDB.

Example
package mainimport ("database/sql""fmt""github.com/lib/pq")func main() {name := ""connector, err := pq.NewConnector(name)if err != nil {fmt.Println(err)return}db := sql.OpenDB(connector)defer db.Close()// Use the DBtxn, err := db.Begin()if err != nil {fmt.Println(err)return}txn.Rollback()}

func (*Connector)Connectadded inv1.1.0

func (c *Connector) Connect(ctxcontext.Context) (driver.Conn,error)

Connect returns a connection to the database using the fixed configurationof this Connector. Context is not used.

func (*Connector)Dialeradded inv1.10.6

func (c *Connector) Dialer(dialerDialer)

Dialer allows change the dialer used to open connections.

func (*Connector)Driveradded inv1.1.0

func (c *Connector) Driver()driver.Driver

Driver returns the underlying driver of this Connector.

typeDialer

type Dialer interface {Dial(network, addressstring) (net.Conn,error)DialTimeout(network, addressstring, timeouttime.Duration) (net.Conn,error)}

Dialer is the dialer interface. It can be used to obtain more control overhow pq creates network connections.

typeDialerContextadded inv1.1.0

type DialerContext interface {DialContext(ctxcontext.Context, network, addressstring) (net.Conn,error)}

DialerContext is the context-aware dialer interface.

typeDriver

type Driver struct{}

Driver is the Postgres database driver.

func (Driver)Open

func (dDriver) Open(namestring) (driver.Conn,error)

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 standardlibrary.

typeError

type Error struct {SeveritystringCodeErrorCodeMessagestringDetailstringHintstringPositionstringInternalPositionstringInternalQuerystringWherestringSchemastringTablestringColumnstringDataTypeNamestringConstraintstringFilestringLinestringRoutinestring}

Error represents an error communicating with the server.

Seehttp://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields

func (*Error)Error

func (err *Error) Error()string

func (*Error)Fatal

func (err *Error) Fatal()bool

Fatal returns true if the Error Severity is fatal.

func (*Error)Get

func (err *Error) Get(kbyte) (vstring)

Get implements the legacy PGError interface. New code should use the fieldsof the Error struct directly.

func (*Error)SQLStateadded inv1.10.6

func (err *Error) SQLState()string

SQLState returns the SQLState of the error.

typeErrorClass

type ErrorClassstring

ErrorClass is only the class part of an error code.

func (ErrorClass)Name

func (ecErrorClass) Name()string

Name returns the condition name of an error class. It is equivalent to thecondition name of the "standard" error code (i.e. the one having the lastthree characters "000").

typeErrorCode

type ErrorCodestring

ErrorCode is a five-character error code.

func (ErrorCode)Class

func (ecErrorCode) Class()ErrorClass

Class returns the error class, e.g. "28".

Seehttp://www.postgresql.org/docs/9.3/static/errcodes-appendix.html fordetails.

func (ErrorCode)Name

func (ecErrorCode) Name()string

Name returns a more human friendly rendering of the error code, namely the"condition name".

Seehttp://www.postgresql.org/docs/9.3/static/errcodes-appendix.html fordetails.

typeEventCallbackType

type EventCallbackType func(eventListenerEventType, errerror)

EventCallbackType is the event callback type. See also ListenerEventTypeconstants' documentation.

typeFloat32Arrayadded inv1.9.0

type Float32Array []float32

Float32Array represents a one-dimensional array of the PostgreSQL doubleprecision type.

func (*Float32Array)Scanadded inv1.9.0

func (a *Float32Array) Scan(src interface{})error

Scan implements the sql.Scanner interface.

func (Float32Array)Valueadded inv1.9.0

func (aFloat32Array) Value() (driver.Value,error)

Value implements the driver.Valuer interface.

typeFloat64Array

type Float64Array []float64

Float64Array represents a one-dimensional array of the PostgreSQL doubleprecision type.

func (*Float64Array)Scan

func (a *Float64Array) Scan(src interface{})error

Scan implements the sql.Scanner interface.

func (Float64Array)Value

func (aFloat64Array) Value() (driver.Value,error)

Value implements the driver.Valuer interface.

typeGSSadded inv1.7.0

type GSS interface {GetInitToken(hoststring, servicestring) ([]byte,error)GetInitTokenFromSpn(spnstring) ([]byte,error)Continue(inToken []byte) (donebool, outToken []byte, errerror)}

GSS provides GSSAPI authentication (e.g., Kerberos).

typeGenericArray

type GenericArray struct{ A interface{} }

GenericArray implements the driver.Valuer and sql.Scanner interfaces foran array or slice of any dimension.

func (GenericArray)Scan

func (aGenericArray) Scan(src interface{})error

Scan implements the sql.Scanner interface.

func (GenericArray)Value

func (aGenericArray) Value() (driver.Value,error)

Value implements the driver.Valuer interface.

typeInt32Arrayadded inv1.9.0

type Int32Array []int32

Int32Array represents a one-dimensional array of the PostgreSQL integer types.

func (*Int32Array)Scanadded inv1.9.0

func (a *Int32Array) Scan(src interface{})error

Scan implements the sql.Scanner interface.

func (Int32Array)Valueadded inv1.9.0

func (aInt32Array) Value() (driver.Value,error)

Value implements the driver.Valuer interface.

typeInt64Array

type Int64Array []int64

Int64Array represents a one-dimensional array of the PostgreSQL integer types.

func (*Int64Array)Scan

func (a *Int64Array) Scan(src interface{})error

Scan implements the sql.Scanner interface.

func (Int64Array)Value

func (aInt64Array) Value() (driver.Value,error)

Value implements the driver.Valuer interface.

typeListener

type Listener struct {// Channel for receiving notifications from the database.  In some cases a// nil value will be sent.  See section "Notifications" above.Notify chan *Notification// contains filtered or unexported fields}

Listener provides an interface for listening to notifications from aPostgreSQL database. For general usage information, see section"Notifications".

Listener can safely be used from concurrently running goroutines.

funcNewDialListener

func NewDialListener(dDialer,namestring,minReconnectIntervaltime.Duration,maxReconnectIntervaltime.Duration,eventCallbackEventCallbackType) *Listener

NewDialListener is like NewListener but it takes a Dialer.

funcNewListener

func NewListener(namestring,minReconnectIntervaltime.Duration,maxReconnectIntervaltime.Duration,eventCallbackEventCallbackType) *Listener

NewListener creates a new database connection dedicated to LISTEN / NOTIFY.

name should be set to a connection string to be used to establish thedatabase connection (see section "Connection String Parameters" above).

minReconnectInterval controls the duration to wait before trying tore-establish the database connection after connection loss. After eachconsecutive failure this interval is doubled, until maxReconnectInterval isreached. Successfully completing the connection establishment procedureresets the interval back to minReconnectInterval.

The last parameter eventCallback can be set to a function which will becalled by the Listener when the state of the underlying database connectionchanges. This callback will be called by the goroutine which dispatches thenotifications over the Notify channel, so you should try to avoid doingpotentially time-consuming operations from the callback.

func (*Listener)Close

func (l *Listener) Close()error

Close disconnects the Listener from the database and shuts it down.Subsequent calls to its methods will return an error. Close returns anerror if the connection has already been closed.

func (*Listener)Listen

func (l *Listener) Listen(channelstring)error

Listen starts listening for notifications on a channel. Calls to thisfunction will block until an acknowledgement has been received from theserver. Note that Listener automatically re-establishes the connectionafter connection loss, so this function may block indefinitely if theconnection can not be re-established.

Listen will only fail in three conditions:

  1. The channel is already open. The returned error will beErrChannelAlreadyOpen.
  2. The query was executed on the remote server, but PostgreSQL returned anerror message in response to the query. The returned error will be apq.Error containing the information the server supplied.
  3. Close is called on the Listener before the request could be completed.

The channel name is case-sensitive.

func (*Listener)NotificationChannel

func (l *Listener) NotificationChannel() <-chan *Notification

NotificationChannel returns the notification channel for this listener.This is the same channel as Notify, and will not be recreated during thelife time of the Listener.

func (*Listener)Ping

func (l *Listener) Ping()error

Ping the remote server to make sure it's alive. Non-nil return value meansthat there is no active connection.

func (*Listener)Unlisten

func (l *Listener) Unlisten(channelstring)error

Unlisten removes a channel from the Listener's channel list. ReturnsErrChannelNotOpen if the Listener is not listening on the specified channel.Returns immediately with no error if there is no connection. Note that youmight still get notifications for this channel even after Unlisten hasreturned.

The channel name is case-sensitive.

func (*Listener)UnlistenAll

func (l *Listener) UnlistenAll()error

UnlistenAll removes all channels from the Listener's channel list. Returnsimmediately with no error if there is no connection. Note that you mightstill get notifications for any of the deleted channels even afterUnlistenAll has returned.

typeListenerConn

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

ListenerConn is a low-level interface for waiting for notifications. Youshould use Listener instead.

funcNewListenerConn

func NewListenerConn(namestring, notificationChan chan<- *Notification) (*ListenerConn,error)

NewListenerConn creates a new ListenerConn. Use NewListener instead.

func (*ListenerConn)Close

func (l *ListenerConn) Close()error

Close closes the connection.

func (*ListenerConn)Err

func (l *ListenerConn) Err()error

Err returns the reason the connection was closed. It is not safe to callthis function until l.Notify has been closed.

func (*ListenerConn)ExecSimpleQuery

func (l *ListenerConn) ExecSimpleQuery(qstring) (executedbool, errerror)

ExecSimpleQuery executes a "simple query" (i.e. one with no bindableparameters) on the connection. The possible return values are:

  1. "executed" is true; the query was executed to completion on thedatabase server. If the query failed, err will be set to the errorreturned by the database, otherwise err will be nil.
  2. If "executed" is false, the query could not be executed on the remoteserver. err will be non-nil.

After a call to ExecSimpleQuery has returned an executed=false value, theconnection has either been closed or will be closed shortly thereafter, andall subsequently executed queries will return an error.

func (*ListenerConn)Listen

func (l *ListenerConn) Listen(channelstring) (bool,error)

Listen sends a LISTEN query to the server. See ExecSimpleQuery.

func (*ListenerConn)Ping

func (l *ListenerConn) Ping()error

Ping the remote server to make sure it's alive. Non-nil error means theconnection has failed and should be abandoned.

func (*ListenerConn)Unlisten

func (l *ListenerConn) Unlisten(channelstring) (bool,error)

Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery.

func (*ListenerConn)UnlistenAll

func (l *ListenerConn) UnlistenAll() (bool,error)

UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery.

typeListenerEventType

type ListenerEventTypeint

ListenerEventType is an enumeration of listener event types.

const (// ListenerEventConnected is emitted only when the database connection// has been initially initialized. The err argument of the callback// will always be nil.ListenerEventConnectedListenerEventType =iota// 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// 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// 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)

typeNewGSSFuncadded inv1.7.0

type NewGSSFunc func() (GSS,error)

NewGSSFunc creates a GSS authentication provider, for use withRegisterGSSProvider.

typeNoticeHandlerConnectoradded inv1.4.0

type NoticeHandlerConnector struct {driver.Connector// contains filtered or unexported fields}

NoticeHandlerConnector wraps a regular connector and sets a notice handleron it.

funcConnectorWithNoticeHandleradded inv1.4.0

func ConnectorWithNoticeHandler(cdriver.Connector, handler func(*Error)) *NoticeHandlerConnector

ConnectorWithNoticeHandler creates or sets the given handler for the givenconnector. If the given connector is a result of calling this functionpreviously, it is simply set on the given connector and returned. Otherwise,this returns a new connector wrapping the given one and setting the noticehandler. A nil notice handler may be used to unset it.

The returned connector is intended to be used with database/sql.OpenDB.

Note: Notice handlers are executed synchronously by pq meaning commandswon't continue to be processed until the handler returns.

Example
package mainimport ("database/sql""fmt""log""github.com/lib/pq")func main() {name := ""// Base connector to wrapbase, err := pq.NewConnector(name)if err != nil {log.Fatal(err)}// Wrap the connector to simply print out the messageconnector := pq.ConnectorWithNoticeHandler(base, func(notice *pq.Error) {fmt.Println("Notice sent: " + notice.Message)})db := sql.OpenDB(connector)defer db.Close()// Raise a noticesql := "DO language plpgsql $$ BEGIN RAISE NOTICE 'test notice'; END $$"if _, err := db.Exec(sql); err != nil {log.Fatal(err)}}
Output:Notice sent: test notice

func (*NoticeHandlerConnector)Connectadded inv1.4.0

Connect calls the underlying connector's connect method and then sets thenotice handler.

typeNotification

type Notification struct {// Process ID (PID) of the notifying postgres backend.BePidint// Name of the channel the notification was sent on.Channelstring// Payload, or the empty string if unspecified.Extrastring}

Notification represents a single notification from the database.

typeNotificationHandlerConnectoradded inv1.5.1

type NotificationHandlerConnector struct {driver.Connector// contains filtered or unexported fields}

NotificationHandlerConnector wraps a regular connector and sets a notification handleron it.

funcConnectorWithNotificationHandleradded inv1.5.1

func ConnectorWithNotificationHandler(cdriver.Connector, handler func(*Notification)) *NotificationHandlerConnector

ConnectorWithNotificationHandler creates or sets the given handler for the givenconnector. If the given connector is a result of calling this functionpreviously, it is simply set on the given connector and returned. Otherwise,this returns a new connector wrapping the given one and setting the notificationhandler. A nil notification handler may be used to unset it.

The returned connector is intended to be used with database/sql.OpenDB.

Note: Notification handlers are executed synchronously by pq meaning commandswon't continue to be processed until the handler returns.

func (*NotificationHandlerConnector)Connectadded inv1.5.1

Connect calls the underlying connector's connect method and then sets thenotification handler.

typeNullTime

type NullTime struct {Timetime.TimeValidbool// Valid is true if Time is not NULL}

NullTime represents a time.Time that may be null. NullTime implements thesql.Scanner interface so it can be used as a scan destination, similar tosql.NullString.

func (*NullTime)Scan

func (nt *NullTime) Scan(value interface{})error

Scan implements the Scanner interface.

func (NullTime)Value

func (ntNullTime) Value() (driver.Value,error)

Value implements the driver Valuer interface.

typePGError

type PGError interface {Error()stringFatal()boolGet(kbyte) (vstring)}

PGError is an interface used by previous versions of pq. It is providedonly to support legacy code. New code should use the Error type.

typeStringArray

type StringArray []string

StringArray represents a one-dimensional array of the PostgreSQL character types.

func (*StringArray)Scan

func (a *StringArray) Scan(src interface{})error

Scan implements the sql.Scanner interface.

func (StringArray)Value

func (aStringArray) Value() (driver.Value,error)

Value implements the driver.Valuer interface.

Source Files

View all Source files

Directories

PathSynopsis
auth
kerberosmodule
example
listen
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.
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.
Package oid contains OID constants as defined by the Postgres server.
Package oid contains OID constants as defined by the Postgres server.
Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802.
Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp