uxgo

package
v0.0.0-...-3c93513 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2023 License: Apache-2.0, Apache-2.0 Imports: 34 Imported by: 0

Documentation

Index

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("ux: Unsupported command")
	ErrInFailedTransaction       = errors.New("ux: Could not complete operation in a failed transaction")
	ErrSSLNotSupported           = errors.New("ux: SSL is not enabled on the server")
	ErrSSLKeyHasWorldPermissions = errors.New("ux: Private key file has group or world access. Permissions should be u=rw (0600) or less")
	ErrCouldNotDetectUsername    = errors.New("ux: Could not detect default username. Please provide one explicitly")
)

Common error types

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

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

View Source
var ErrChannelNotOpen = errors.New("ux: 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)`, ux.Array([]int{235, 401}))

var x []sql.NullInt64
db.QueryRow('SELECT ARRAY[235, 401]').Scan(ux.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 ConnectorNoticeHandler

func ConnectorNoticeHandler(c driver.Connector) func(*Error)

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

func ConnectorNotificationHandler

func ConnectorNotificationHandler(c driver.Connector) func(*Notification)

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

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 UXres' "-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 UXres' "-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 FormatTimestamp

func FormatTimestamp(t time.Time) []byte

FormatTimestamp formats t into UXres' text format for timestamps.

func NoticeHandler

func NoticeHandler(c driver.Conn) func(*Error)

NoticeHandler returns the notice handler on the given connection, if any. A runtime panic occurs if c is not a ux connection. This is rarely used directly, use ConnectorNoticeHandler and ConnectorWithNoticeHandler instead.

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 UXgres' text format. It returns a time.Time in currentLocation iff that time's offset agrees with the offset sent from the UXres server. Otherwise, ParseTimestamp returns a time.Time with the fixed offset offset provided by the UXres 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 := ux.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.

func QuoteLiteral

func QuoteLiteral(literal string) string

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

exp_date := ux.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 be replaced by two backslashes (i.e. "\\") and the C-style escape identifier that UXSQL provides ('E') will be prepended to the string.

func RegisterGSSProvider

func RegisterGSSProvider(newGssArg NewGSSFunc)

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

import "github.com/lib/ux/auth/kerberos"

func init() {
	ux.RegisterGSSProvider(func() (ux.GSS, error) { return kerberos.NewGSS() })
}

func SetNoticeHandler

func SetNoticeHandler(c driver.Conn, handler func(*Error))

SetNoticeHandler sets the given notice handler on the given connection. A runtime panic occurs if c is not a ux connection. A nil handler may be used to unset it. This is rarely used directly, use ConnectorNoticeHandler and ConnectorWithNoticeHandler instead.

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

func SetNotificationHandler

func SetNotificationHandler(c driver.Conn, handler func(*Notification))

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

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

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 UXSQL 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 UXSQL 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 UXSQL 2.1 or newer.

type Connector

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

Connector represents a fixed configuration for the ux 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 ux 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 returns the underlying driver of this Connector.

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 ux creates network connections.

type DialerContext

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

DialerContext is the context-aware dialer interface.

type Driver

type Driver struct{}

Driver is the UXres 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 UXSQL 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 GSS

type GSS interface {
	GetInitToken(host string, service string) ([]byte, error)
	GetInitTokenFromSpn(spn string) ([]byte, error)
	Continue(inToken []byte) (done bool, outToken []byte, err error)
}

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

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 Int64Array

type Int64Array []int64

Int64Array represents a one-dimensional array of the UXSQL 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 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 UXSQL 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 UXSQL returned an error message in response to the query. The returned error will be a ux.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 ux.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 NewGSSFunc

type NewGSSFunc func() (GSS, error)

NewGSSFunc creates a GSS authentication provider, for use with RegisterGSSProvider.

type NoticeHandlerConnector

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

NoticeHandlerConnector wraps a regular connector and sets a notice handler on it.

func ConnectorWithNoticeHandler

func ConnectorWithNoticeHandler(c driver.Connector, handler func(*Error)) *NoticeHandlerConnector

ConnectorWithNoticeHandler creates or sets the given handler for the given connector. If the given connector is a result of calling this function previously, it is simply set on the given connector and returned. Otherwise, this returns a new connector wrapping the given one and setting the notice handler. 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 ux meaning commands won't continue to be processed until the handler returns.

func (*NoticeHandlerConnector) Connect

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

type Notification

type Notification struct {
	// Process ID (PID) of the notifying UXres 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 NotificationHandlerConnector

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

NotificationHandlerConnector wraps a regular connector and sets a notification handler on it.

func ConnectorWithNotificationHandler

func ConnectorWithNotificationHandler(c driver.Connector, handler func(*Notification)) *NotificationHandlerConnector

ConnectorWithNotificationHandler creates or sets the given handler for the given connector. If the given connector is a result of calling this function previously, it is simply set on the given connector and returned. Otherwise, this returns a new connector wrapping the given one and setting the notification handler. 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 ux meaning commands won't continue to be processed until the handler returns.

func (*NotificationHandlerConnector) Connect

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

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 PGError

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

PGError is an interface used by previous versions of ux. 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 UXSQL 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.

Directories

Path Synopsis
Package oid contains OID constants as defined by the UXres server.
Package oid contains OID constants as defined by the UXres 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 or F : Jump to
y or Y : Canonical URL