nzgo

package module
v11.1.1-0...-5051c4a Latest Latest
Warning

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

Go to latest
Published: May 26, 2021 License: MIT Imports: 35 Imported by: 0

README

nzgo - a pure Go language driver for IBM Performance Server for PostgreSQL

This project provides a native Go language database driver for IBM Performance Server for PostgreSQL.

GoDoc

Install

go get github.com/IBM/nzgo

Docs

For detailed documentation and basic usage examples, please see the package documentation at https://godoc.org/github.com/IBM/nzgo.

Tests

go test is used for testing. See TESTS.md for more details.

Features

  • TLSv1.2 crypto support
  • LDAP support
  • Transaction support: begin, rollback, commit
  • Full support for all IBM PDA data types
  • Full DDL, DML query syntax support for IBM PDA
  • Full external table support (load and unload)
  • Configurable logging feature
  • Prepared statement support
  • Support JSON, JSONB and JSONPATH datatypes

Thank you (alphabetical)

Some of these contributions are from the original library lib/pq whose code still exists in here. Below are the contributors for IBM PDA specific code.

  • Abhiskek Jog (abhishekjog)
  • Sandeep Powar (sandippawar1412)
  • Shabbir Mohammad (shabbir10july)

Documentation

Overview

Package nzgo is a pure Go language driver for the database/sql package to work with IBM PDA (aka Netezza)

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

import (
	"database/sql"

	_ "github.com/IBM/nzgo"
)

func main() {
	connStr := "user=nz dbname=db1 sslmode=verify-full"
	db, err := sql.Open("nzgo", connStr)
	if err != nil {
		log.Fatal(err)
	}

	age := 21
	rows, err := db.Query("SELECT name FROM users WHERE age = ?", age)
	…
}

Logging

nzgo defines a simple logger interface. Set LogLevel to control logging verbosity and LogPath to specify log file path. In order to enable logging for the driver, you need to write below code in your application

var elog nzgo.NZLogger
elog.LogLevel = "off"
elog.LogPath = "C:\\Logs\\"
elog.Initialize()

Declaring elog variable and calling elog.Initialize() function is mandatory else application would fail with error "runtime error: invalid memory address or nil pointer dereference".

You can configure LogLevel and LogPath (i.e. log file directory) as per your requirement.

You may skip initializing LogLevel and LogPath values. In such case, it would take default values. Default value for LogLevel is DEBUG while for LogPath is same directory as your application.

Other valid values for 'LogLevel' are : "OFF" , "DEBUG", "INFO" and "FATAL"

SecurityLevel

The level of security (SSL/TLS) that the driver uses for the connection to the data store.

onlyUnSecured: The driver does not use SSL. preferredUnSecured: If the server provides a choice, the driver does not use SSL. preferredSecured: If the server provides a choice, the driver uses SSL. onlySecured: The driver does not connect unless an SSL connection is available.

Similarly, Netezza server has above securityLevel.

Cases which would fail: Client tries to connect with 'Only secured' or 'Preferred secured' mode while server is 'Only Unsecured' mode. Client tries to connect with 'Only secured' or 'Preferred secured' mode while server is 'Preferred Unsecured' mode. Client tries to connect with 'Only Unsecured' or 'Preferred Unsecured' mode while server is 'Only Secured' mode. Client tries to connect with 'Only Unsecured' or 'Preferred Unsecured' mode while server is 'Preferred Secured' mode.

Below are the securityLevel you can pass in connection string :

0: Preferred Unsecured session
1: Only Unsecured session
2: Preferred Secured session
3: Only Secured session

Connection String

Use Open to create a database handle with connection parameters:

db, err := sql.Open("nzgo", "<connection string>")

The Go Netezza Driver supports the following connection syntaxes (or data source name formats):

"host=localhost user=admin dbname=db1 port=5480 password=password sslmode=require sslrootcert=C:/Users/root31.crt securityLevel=3"

In this case, application is running from NPS server itself so using 'localhost'. Golang driver should connect on port 5480(postgres port). The user is admin, password is password, database is db1, sslmode is require, and the location of the root certificate file is C:/Users/root31.crt with securityLevel as 'Only Secured session'

Connection Parameters

When establishing a connection using nzgo you are expected to supply a connection string containing zero or more parameters. Below are subset of the connection parameters supported by nzgo.

The following special connection parameters are 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)
  • port - The port to bind to. (default is 5480)
  • sslmode - Whether or not to use SSL (default is require)
  • 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.

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)

Use single quotes for values that contain whitespace:

"user=nz 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 the text encoding for the connection) may be set but must be "UTF8", matching with the same rules as Postgres. It is an error to provide any other value.

Queries

database/sql does not dictate any specific format for parameter markers in query strings, but nzgo uses the Netezza-specific parameter markers i.e. '?', as shown below.

rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = ?
	OR age = ? `, "orange", 64)

First parameter marker in the query would be replaced by first arguement, second parameter marker in the query would be replaced by second arguement and so on.

nzgo supports the RowsAffected() method of the Result type in database/sql.

var row int
result, err := db.Exec(`INSERT INTO users(name, favorite_fruit, age)
	VALUES('beatrice', 'starfruit', 93) )
if err == nil {
	row, _ := result.RowsAffected()
}

For additional instructions on querying see the documentation for the database/sql package. nzgo also supports transaction queries as specified in database/sql package https://github.com/golang/go/wiki/SQLInterface.

Transactions are started by calling Begin.

tx, err := conn.Begin()
if err != nil {
	return err
}
// Rollback is safe to call even if the tx is already closed, so if
// the tx commits successfully, this is a no-op
defer tx.Rollback()

_, err = tx.Exec("insert into foo(id) values (1)")
if err != nil {
	return err
}

err = tx.Commit()
if err != nil {
	return err
}

Supported Data Types

This package returns the following types for values from the Netezza backend:

  • integer types byteint, smallint, integer, and bigint are returned as int8, int 16, int 32 and int64 respectively
  • floating-point types real and double precision are returned as float32 and float64 respectively
  • character types char, varchar, nchar and nvarchar are returned as string
  • temporal types date, time, timetz, timestamp, interval and timestamptz are returned as string
  • numeric and geometry are returned as string
  • the boolean type is returned as bool

External table

You can unload data from an IBM Netezza database table on a Netezza host system to a remote client. This unload does not remove rows from the database but instead stores the unloaded data in a flat file (external table) that is suitable for loading back into a Netezza database. Below query would create a file 'et1.txt' on remote system from Netezza table t2 with data delimeted by '|'.

result, err := db.Exec("create external table et1 'C:\\et1.txt' using (remotesource 'golang' delim '|') as select * from t2;")
if err != nil {
	fmt.Println("Error in creating external table", err)
} else {
	fmt.Println("External Table created successfully")
}

See https://www.ibm.com/support/knowledgecenter/en/SSULQD_7.2.1/com.ibm.nz.load.doc/t_load_unloading_data_remote_client_sys.html for more information about external table

Index

Constants

View Source
const (
	EXTAB_SOCK_DATA  = 1 + iota // block of records
	EXTAB_SOCK_ERROR            // error message
	EXTAB_SOCK_DONE             // normal wrap-up
	EXTAB_SOCK_FLUSH            // Flush the current buffer/data
)

External table stuff (copied from nde/client/exttable.h)

View Source
const (
	PGRES_EMPTY_QUERY = 0 + iota
	PGRES_COMMAND_OK  /* a query command that doesn't return */
	/* anything was executed properly by the backend */
	PGRES_TUPLES_OK /* a query command that returns tuples */
	/* was executed properly by the backend */
	PGRES_FIELDS_OK  /* field information from a query was successful */
	PGRES_END_TUPLES /* all is ok till here; all after this is error */
	PGRES_NONFATAL_ERROR
	PGRES_FATAL_ERROR
	PGRES_BAD_RESPONSE   /* an unexpected response was recv'd from the backend */
	PGRES_INTERNAL_ERROR /* memory allocation error in driver */
)
View Source
const (
	NzTypeRecAddr = 1 + iota // !NOTE-bmz need to add this to all switch stmts
	NzTypeDouble
	NzTypeInt
	NzTypeFloat
	NzTypeMoney
	NzTypeDate
	NzTypeNumeric
	NzTypeTime
	NzTypeTimestamp
	NzTypeInterval
	NzTypeTimeTz
	NzTypeBool
	NzTypeInt1
	NzTypeBinary
	NzTypeChar
	NzTypeVarChar
	NzDEPR_Text   // OBSOLETE 3.0: BLAST Era Large 'text' Object, (Postgres 'text' datatype overload, too)
	NzTypeUnknown // corresponds to PG UNKNOWNOID data type - an untyped string literal
	NzTypeInt2
	NzTypeInt8
	NzTypeVarFixedChar
	NzTypeGeometry
	NzTypeVarBinary
	NzDEPR_Blob // OBSOLETE 3.0: BLAST Era Large 'binary' Object
	NzTypeNChar
	NzTypeNVarChar
	NzDEPR_NText // OBSOLETE 3.0: BLAST Era Large 'nchar text' Object

	NzTypeJson // 30
	NzTypeJsonb
	NzTypeJsonpath
	NzTypeLastEntry // KEEP THIS ENTRY LAST - used internally to size an array
)
View Source
const (
	CONN_NOT_CONNECTED = 0 + iota /* Connection has not been established */
	CONN_CONNECTED                /* Connection is up and has been established */
	CONN_EXECUTING                /* the connection is currently executing a statement */
	CONN_FETCHING                 /* the connection is currently executing a select */
	CONN_CANCELLED                /* the connection is currently cancelling a statement */
)
View Source
const (
	CP_VERSION_1 = 1 + iota
	CP_VERSION_2
	CP_VERSION_3
	CP_VERSION_4
	CP_VERSION_5
	CP_VERSION_6
)
View Source
const (
	NPS_CLIENT = 0 + iota
	IPS_CLIENT
)

Client type

View Source
const (
	AUTH_REQ_OK = 0 + iota
	AUTH_REQ_KRB4
	AUTH_REQ_KRB5
	AUTH_REQ_PASSWORD
	AUTH_REQ_CRYPT
	AUTH_REQ_MD5
	AUTH_REQ_SHA256
)

Authentication types

View Source
const (
	HSV2_INVALID_OPCODE = 0 + iota
	HSV2_CLIENT_BEGIN
	HSV2_DB
	HSV2_USER
	HSV2_OPTIONS
	HSV2_TTY
	HSV2_REMOTE_PID
	HSV2_PRIOR_PID
	HSV2_CLIENT_TYPE
	HSV2_PROTOCOL
	HSV2_HOSTCASE
	HSV2_SSL_NEGOTIATE
	HSV2_SSL_CONNECT
	HSV2_APPNAME
	HSV2_CLIENT_OS
	HSV2_CLIENT_HOST_NAME
	HSV2_CLIENT_OS_USER
	HSV2_64BIT_VARLENA_ENABLED
)

* This is used by the postmaster and clients in their handshake. * This indicates type of information being exchanged between NPS and driver.

View Source
const (
	HSV2_CLIENT_DONE = 1000 + iota
	HSV2_SERVER_BEGIN
	HSV2_PWD
	HSV2_SERVER_DONE = 2000
)
View Source
const (
	PG_PROTOCOL_3 = 3 + iota
	PG_PROTOCOL_4
	PG_PROTOCOL_5
)
View Source
const (
	Efatal   = "FATAL"
	Epanic   = "PANIC"
	Ewarning = "WARNING"
	Enotice  = "NOTICE"
	Edebug   = "DEBUG"
	Einfo    = "INFO"
	Elog     = "LOG"
)

Error severities

View Source
const HI32_MASK uint64 = 0xffffffff00000000
View Source
const MAX_NUMERIC_DIGIT_COUNT = 4
View Source
const NDIGIT_INT64 bool = false
View Source
const (
	NPSCLIENT_TYPE_GOLANG = 12
)

Client Type

View Source
const NUMERIC_MAX_PRECISION = 38
View Source
const USE_MUL_DOUBLE bool = false

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")
	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")
)

Common error types

View Source
var (
	Debug *log.Logger
	Info  *log.Logger
	Fatal *log.Logger
)
View Source
var ErrChannelAlreadyOpen = errors.New("pq: channel is already open")

ErrChannelAlreadyOpen is returned from Listen when a channel is already open.

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

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

Functions

func Array

func Array(a interface{}) interface {
	driver.Valuer
	sql.Scanner
}

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

For example:

db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401}))

var x []sql.NullInt64
db.QueryRow('SELECT ARRAY[235, 401]').Scan(pq.Array(&x))

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

func CTable_FieldAt

func CTable_FieldAt(tupdesc DbosTupleDesc, recP readBuf, field int) readBuf

func CTable_i_fieldNumericDigit32Count

func CTable_i_fieldNumericDigit32Count(tupdesc DbosTupleDesc, coldex int) int

func CTable_i_fieldPrecision

func CTable_i_fieldPrecision(tupdesc DbosTupleDesc, coldex int) int

func CTable_i_fieldScale

func CTable_i_fieldScale(tupdesc DbosTupleDesc, coldex int) int

func CTable_i_fieldSize

func CTable_i_fieldSize(tupdesc DbosTupleDesc, coldex int) int

func CTable_i_fieldType

func CTable_i_fieldType(tupdesc DbosTupleDesc, coldex int) int

func CTable_i_fixedFieldPtr

func CTable_i_fixedFieldPtr(recP readBuf, offset int) readBuf

func CTable_i_varFieldPtr

func CTable_i_varFieldPtr(recP readBuf, fixedOffset int, varDex int) readBuf

func CopyIn

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

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

func CopyInSchema

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

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

func DialOpen

func DialOpen(d Dialer, dsn string) (_ driver.Conn, err error)

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

func EnableInfinityTs

func EnableInfinityTs(negative time.Time, positive time.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 potentially cause error "sql: Scan error on column index 0: unsupported driver -> Scan pair: []uint8 -> *time.Time", when scanning into a time.Time value.

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

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

func EncodeTimeOnly

func EncodeTimeOnly(tm *timeStamp, fusec float64, tzp int) (str string)

EncodeTimeOnly() * Encode time fields only.

func EncodeTimeSpan

func EncodeTimeSpan(tm *timeStamp, fsec float64) (str string)

func FormatTimestamp

func FormatTimestamp(t time.Time) []byte

FormatTimestamp formats t into Postgres' text format for timestamps.

func GOLANG_numeric_load_var

func GOLANG_numeric_load_var(varP *NumericVar, dataP []TNumericDigit, precision int, scale int, digitCount int)

func Init

func Init()

Create logger handler with some predefined prefix setting, * this will be overwritten in actual logging. * Mostly this setting is not used

func IntervalToText

func IntervalToText(span *Interval) string

func Open

func Open(dsn string) (_ driver.Conn, err error)

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 standard library.

func ParseTimestamp

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

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

func ParseURL

func ParseURL(url string) (string, error)

ParseURL no longer needs to be used by clients of this library since supplying a URL as a connection 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

func QuoteIdentifier

func QuoteIdentifier(name string) string

QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be used 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 be case sensitive when used in a query. If the input string contains a zero byte, the result will be truncated immediately before it.

Types

type ArrayDelimiter

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.Scanner to override the array delimiter used by GenericArray.

type BoolArray

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 (a BoolArray) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type ByteaArray

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 (a ByteaArray) Value() (driver.Value, error)

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

type Configuration

type Configuration struct {
	LogLevel string
}

Configuration setup

type Connector

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

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.

func NewConnector

func NewConnector(dsn string) (*Connector, error)

NewConnector returns a connector for the pq driver in a fixed configuration with the given dsn. 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 (*Connector) Connect

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

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

func (*Connector) Driver

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

Driver returnst the underlying driver of this Connector.

type DATE_STRUCT

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

type DbosTupleDesc

type DbosTupleDesc struct {
	DateStyle    int
	EuroDates    int
	DBcharset    int
	EnableTime24 int
	// contains filtered or unexported fields
}

type Dialer

type Dialer interface {
	Dial(network, address string) (net.Conn, error)
	DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)
}

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

type DialerContext

type DialerContext interface {
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

type Driver

type Driver struct{}

Driver is the Postgres database driver.

func (*Driver) Open

func (d *Driver) Open(name string) (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 standard library.

type Error

type Error struct {
	Severity         string
	Code             ErrorCode
	Message          string
	Detail           string
	Hint             string
	Position         string
	InternalPosition string
	InternalQuery    string
	Where            string
	Schema           string
	Table            string
	Column           string
	DataTypeName     string
	Constraint       string
	File             string
	Line             string
	Routine          string
}

Error represents an error communicating with the server.

See http://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(k byte) (v string)

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

type ErrorClass

type ErrorClass string

ErrorClass is only the class part of an error code.

func (ErrorClass) Name

func (ec ErrorClass) Name() string

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

type ErrorCode

type ErrorCode string

ErrorCode is a five-character error code.

func (ErrorCode) Class

func (ec ErrorCode) Class() ErrorClass

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

See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for details.

func (ErrorCode) Name

func (ec ErrorCode) Name() string

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

See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for details.

type EventCallbackType

type EventCallbackType func(event ListenerEventType, err error)

EventCallbackType is the event callback type. See also ListenerEventType constants' documentation.

type Float64Array

type Float64Array []float64

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

func (*Float64Array) Scan

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

Scan implements the sql.Scanner interface.

func (Float64Array) Value

func (a Float64Array) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type GenericArray

type GenericArray struct{ A interface{} }

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

func (GenericArray) Scan

func (a GenericArray) Scan(src interface{}) error

Scan implements the sql.Scanner interface.

func (GenericArray) Value

func (a GenericArray) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type HSV2Msg

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

type HsVersion

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

NPS handshake version negotiation packet structure

type Int64Array

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 (a Int64Array) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type Interval

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

type Listener

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 a PostgreSQL database. For general usage information, see section "Notifications".

Listener can safely be used from concurrently running goroutines.

func NewDialListener

func NewDialListener(d Dialer,
	name string,
	minReconnectInterval time.Duration,
	maxReconnectInterval time.Duration,
	eventCallback EventCallbackType) *Listener

NewDialListener is like NewListener but it takes a Dialer.

func NewListener

func NewListener(name string,
	minReconnectInterval time.Duration,
	maxReconnectInterval time.Duration,
	eventCallback EventCallbackType) *Listener

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

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

minReconnectInterval controls the duration to wait before trying to re-establish the database connection after connection loss. After each consecutive failure this interval is doubled, until maxReconnectInterval is reached. Successfully completing the connection establishment procedure resets the interval back to minReconnectInterval.

The last parameter eventCallback can be set to a function which will be called by the Listener when the state of the underlying database connection changes. This callback will be called by the goroutine which dispatches the notifications over the Notify channel, so you should try to avoid doing potentially 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 an error if the connection has already been closed.

func (*Listener) Listen

func (l *Listener) Listen(channel string) error

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

Listen will only fail in three conditions:

  1. The channel is already open. The returned error will be ErrChannelAlreadyOpen.
  2. The query was executed on the remote server, but PostgreSQL returned an error message in response to the query. The returned error will be a pq.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 the life 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 means that there is no active connection.

func (*Listener) Unlisten

func (l *Listener) Unlisten(channel string) error

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

The channel name is case-sensitive.

func (*Listener) UnlistenAll

func (l *Listener) UnlistenAll() error

UnlistenAll removes all channels from the Listener's channel list. Returns immediately with no error if there is no connection. Note that you might still get notifications for any of the deleted channels even after UnlistenAll has returned.

type ListenerConn

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

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

func NewListenerConn

func NewListenerConn(name string, 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 call this function until l.Notify has been closed.

func (*ListenerConn) ExecSimpleQuery

func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error)

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.
  2. If "executed" is false, the query could not be executed on the remote server. err will be non-nil.

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

func (*ListenerConn) Listen

func (l *ListenerConn) Listen(channel string) (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 the connection has failed and should be abandoned.

func (*ListenerConn) Unlisten

func (l *ListenerConn) Unlisten(channel string) (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.

type ListenerEventType

type ListenerEventType int

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.
	ListenerEventConnected ListenerEventType = 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
)

type NZLogger

type NZLogger struct {
	LogLevel string
	LogPath  string
}

Valid log levels : DEBUG, INFO, FATAL, OFF

func (NZLogger) Debugf

func (elog NZLogger) Debugf(fname string, s string, args ...interface{})

Wrappers to print functions to change pefix format

func (NZLogger) Debugln

func (elog NZLogger) Debugln(args ...interface{})

Used for adding debug log without format

func (NZLogger) Fatalf

func (elog NZLogger) Fatalf(fname string, s string, args ...interface{})

Fatal logs error and panic, forcing application to exit with message on stdout

func (NZLogger) Fatalln

func (elog NZLogger) Fatalln(args ...interface{})

func (NZLogger) Infoln

func (elog NZLogger) Infoln(args ...interface{})

func (NZLogger) Initialize

func (elog NZLogger) Initialize()

Initialize logger and set output to file

type Notification

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

Notification represents a single notification from the database.

type NullTime

type NullTime struct {
	Time  time.Time
	Valid bool // Valid is true if Time is not NULL
}

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

func (*NullTime) Scan

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

Scan implements the Scanner interface.

func (NullTime) Value

func (nt NullTime) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type NumericVar

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

type PGError

type PGError interface {
	Error() string
	Fatal() bool
	Get(k byte) (v string)
}

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

type StringArray

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 (a StringArray) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type TIMESTAMP_STRUCT

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

type TIME_STRUCT

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

type TNumericData

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

type TNumericDigit

type TNumericDigit uint32

type TimeTzADT

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

Directories

Path Synopsis
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.

Jump to

Keyboard shortcuts

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