gopgext/pg

import "gopgext/pg"

Package pg is the PostgreSQL API for extensions built with gopgext: logging, errors with SQLSTATE codes, queries (SPI) and settings (GUCs).

SQL functions are ordinary Go functions marked with a //gopgext:function comment; gopgext generates the glue that converts their arguments and results (see the gopgext README for the supported types).

Go code runs inside the backend process, on its stack, only while PostgreSQL is calling into the extension: there are no goroutines (a backend is single-threaded). main runs once, when the library is loaded.

Index#

Constants#

const (
	CodeRaiseException            = "P0001"
	CodeNoDataFound               = "P0002"
	CodeDataException             = "22000"
	CodeStringDataRightTruncation = "22001"
	CodeNumericValueOutOfRange    = "22003"
	CodeNullValueNotAllowed       = "22004"
	CodeDivisionByZero            = "22012"
	CodeInvalidParameterValue     = "22023"
	CodeInvalidTextRepresentation = "22P02"
	CodeUniqueViolation           = "23505"
	CodeCheckViolation            = "23514"
	CodeFeatureNotSupported       = "0A000"
	CodeInsufficientPrivilege     = "42501"
	CodeUndefinedTable            = "42P01"
	CodeSyntaxError               = "42601"
	CodeQueryCanceled             = "57014"
	CodeInternalError             = "XX000"
)

Some SQLSTATE codes (https://www.postgresql.org/docs/current/errcodes-appendix.html).

Variables#

var ErrNoRows = errors.New("pg: no rows in result set")

ErrNoRows is returned by Row.Scan when the query returned no rows.

Functions#

func CheckInterrupts#

func CheckInterrupts() error

CheckInterrupts returns an error if the query was canceled (by the user, statement_timeout, …): long-running functions should call it periodically and return the error, since Go code can’t be interrupted otherwise. Once it has returned an error, queries fail and PostgreSQL raises the cancel error when the function returns, whatever it returns.

func CompareStrings#

func CompareStrings(a, b string, coll Oid) (int, error)

CompareStrings compares a and b like text’s comparison operators with collation coll (varstr_cmp): -1, 0 or 1.

func Debug#

func Debug(msg string)

Debug logs msg at level DEBUG1.

func Debugf#

func Debugf(format string, args ...any)

func Exec#

func Exec(sql string, args ...any) (int64, error)

Exec runs a statement and returns the number of rows it processed (inserted, updated, deleted or returned).

func ExtensionName#

func ExtensionName() string

ExtensionName returns the extension’s name (also the prefix of its settings).

func FormatFloat8#

func FormatFloat8(x float64) string

FormatFloat8 formats x as float8’s output function does: the shortest text that reads back as x, or with extra_float_digits <= 0 that many fewer digits (%.15g by default), and NaN, Infinity, -Infinity. For data types whose output includes float8 values (like cube’s coordinates).

func FormatType#

func FormatType(typ Oid, typmod int32) string

FormatType returns the SQL name of a type with a type modifier (-1 for none), e.g. FormatType(1043, 14) is “character varying(10)”.

func HasPrivilegesOf#

func HasPrivilegesOf(role string) bool

HasPrivilegesOf reports whether the current user has the privileges of a role: is a superuser, the role, or a member of it that inherits its privileges (false if the role doesn’t exist). For example “pg_read_all_stats” for statistics about other users.

func HashBytes#

func HashBytes(b []byte) uint32

HashBytes is PostgreSQL’s hash_any of b: what hash functions of hash operator classes return (as an int32), e.g. hashtext.

func HashBytesExtended#

func HashBytesExtended(b []byte, seed uint64) uint64

HashBytesExtended is hash_any_extended: the 64-bit hash of extended hash functions (support function 2 of hash operator classes).

func Info#

func Info(msg string)

Info sends msg to the client (level INFO).

func Infof#

func Infof(format string, args ...any)

func IsComposite#

func IsComposite(typ Oid) bool

IsComposite reports whether typ is a composite type, a domain over one, or record (type_is_rowtype).

func Log#

func Log(msg string)

Log writes msg to the server log (level LOG).

func Logf#

func Logf(format string, args ...any)

func Notice#

func Notice(msg string)

Notice sends msg to the client (level NOTICE), like RAISE NOTICE.

func Noticef#

func Noticef(format string, args ...any)

func Notify#

func Notify(channel, payload string) error

Notify sends a notification on channel with payload, like NOTIFY or pg_notify(): listeners get it when the transaction commits.

func Preloading#

func Preloading() bool

Preloading reports whether the library is being loaded by shared_preload_libraries, in the postmaster at server start (only true in main and package initialization). Libraries that need it (shared memory, hooks every backend must run) can check it in main.

func ReadFile#

func ReadFile(path string) ([]byte, error)

ReadFile returns the contents of a file.

func RemoveFile#

func RemoveFile(path string) error

RemoveFile removes a file.

func SetConfig#

func SetConfig(name, value string, local bool)

SetConfig changes a setting, like SET (SET LOCAL if local) or set_config(). An invalid name or value raises the PostgreSQL error once the function returns (and SetConfig doesn’t return).

func ToLower#

func ToLower(s string, coll Oid) (string, error)

ToLower returns s in lower case with the rules of collation coll, like lower() (str_tolower). A missing collation (0) raises PostgreSQL’s “could not determine which collation to use” error, returned.

func ToUpper#

func ToUpper(s string, coll Oid) (string, error)

ToUpper returns s in upper case with the rules of collation coll, like upper().

func Warning#

func Warning(msg string)

Warning sends msg to the client and the server log (level WARNING).

func Warningf#

func Warningf(format string, args ...any)

func WriteFile#

func WriteFile(path string, data []byte) error

WriteFile replaces a file with data atomically and durably: it writes a temporary file next to it (path + “.tmp”), flushes it to disk and renames it over path.

Types#

type AnyArray#

type AnyArray = core.AnyArray

AnyArray is the SQL type anyarray: an array of any element type.

func NewAnyArray#

func NewAnyArray(elem Oid, xs []*AnyElement) AnyArray

NewAnyArray returns a one-dimensional array of type elem[] (nil elements are NULL).

func NewAnyArrayDims#

func NewAnyArrayDims(elem Oid, xs []*AnyElement, dims, lbounds []int) (AnyArray, error)

NewAnyArrayDims returns an array of elements of type elem with the given dimensions and lower bounds (nil: all 1), xs being its elements in row-major order (nil: NULL). No dimensions make an empty array.

type AnyElement#

type AnyElement = core.AnyElement

AnyElement is the SQL type anyelement: a value of the type the function is called with (Type tells which). String formats it, and ParseAny makes a value of a type from text. A polymorphic result must be of the type PostgreSQL resolved for the call (e.g. that of an anyelement argument). Values refer to PostgreSQL’s memory: valid during the call.

func FromBytes#

func FromBytes(typ Oid, b []byte) AnyElement

FromBytes returns a value of the variable-length type typ (text, bytea, json, an extension’s type stored like them) with contents b, e.g. the elements of an array built with NewAnyArrayDims. AnyElement.Bytes is the reverse.

func Input#

func Input(typ Oid, typmod int32, s *string) (*AnyElement, error)

Input converts text to a value of type typ with type modifier typmod (-1: none), with the type’s input function, as for a column of that type. A nil s runs the input function for NULL, which checks the constraints of a domain, and returns nil.

func NewRecord#

func NewRecord(typ Oid, typmod int32, values []*AnyElement) (AnyElement, error)

NewRecord returns a value of the composite type typ (typmod as for Columns) from the values of its columns, one per column of Columns (nil: NULL; dropped columns are NULL). The constraints of a domain over a composite type are checked.

func ParseAny#

func ParseAny(typ Oid, s string) (AnyElement, error)

ParseAny returns a value of type typ from its text form.

type BoolSetting#

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

BoolSetting is a boolean setting.

func NewBoolSetting#

func NewBoolSetting(name string, def bool, desc string, opts ...SettingOption) *BoolSetting

NewBoolSetting defines a boolean setting.

func (*BoolSetting) Get#

func (s *BoolSetting) Get() bool

Get returns the current value.

type CString#

type CString = core.CString

CString is the SQL type cstring, used by the input and output functions of data types: functions taking or returning one are declared with “manual” and a CREATE TYPE in sql/.

A CString argument is not copied: it refers to PostgreSQL’s memory and is only valid during the call. To keep it (in a global, a map…), copy it with strings.Clone. Results are copied.

type Column#

type Column = core.Column

Column is a column of a row: its name, type, type modifier (-1 for none); for the columns of a row result (ResultColumns) the type’s SQL name with the modifier (for messages, e.g. “character varying(10)”), for those of a composite type (Columns) whether it was dropped.

func Columns#

func Columns(typ Oid, typmod int32) ([]Column, error)

Columns returns the columns of the composite type typ, including dropped ones (Dropped): for a domain over a composite type, those of its base type; for an anonymous record, typmod identifies it (see AnyElement.RowType), else it is -1.

func ResultColumns#

func ResultColumns() ([]Column, error)

ResultColumns returns the columns the caller expects from the running function returning record (its column definition list, or its composite result type). It returns PostgreSQL’s errors when there are none: the function was called where a record can’t be used (SELECT f() instead of SELECT * FROM f() AS (…)).

type EnumSetting#

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

EnumSetting is a setting whose value is one of a list of names.

func NewEnumSetting#

func NewEnumSetting(name, def string, values []string, desc string, opts ...SettingOption) *EnumSetting

NewEnumSetting defines a setting that takes one of values (the default must be one of them; names are matched case-insensitively).

func (*EnumSetting) Get#

func (s *EnumSetting) Get() string

Get returns the current value (one of the values).

type Error#

type Error = core.Error

Error is a PostgreSQL error: returned by Exec and Query when a statement fails, and returned by SQL functions to raise an error with a given SQLSTATE (see Errorf).

A SQL function that returns an Error it got from Query/Exec unchanged re-raises the original PostgreSQL error with all its fields; any other error is raised with its Code (P0001 raise_exception if it isn’t an Error), Message, Detail and Hint.

func Errorf#

func Errorf(code string, format string, args ...any) *Error

Errorf returns an Error with the given SQLSTATE code (e.g. “22023”, see the Code constants) and a formatted message.

type FloatSetting#

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

FloatSetting is a floating-point setting.

func NewFloatSetting#

func NewFloatSetting(name string, def, min, max float64, desc string, opts ...SettingOption) *FloatSetting

NewFloatSetting defines a floating-point setting with a default and a range.

func (*FloatSetting) Get#

func (s *FloatSetting) Get() float64

Get returns the current value.

type IntSetting#

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

IntSetting is an integer setting (32 bits).

func NewIntSetting#

func NewIntSetting(name string, def, min, max int, desc string, opts ...SettingOption) *IntSetting

NewIntSetting defines an integer setting with a default and a range.

func (*IntSetting) Get#

func (s *IntSetting) Get() int

Get returns the current value.

type Internal#

type Internal = core.Internal

Internal is the SQL type internal: a pointer to some PostgreSQL structure (support functions of index operator classes, planner support, …). Go code can’t dereference it safely by itself: pass it to C code in csrc/, or use a framework package that understands it (like gopgext/gist).

type Level#

type Level int

Level is the severity of a Message: whether it goes to the client and the server log depends on client_min_messages and log_min_messages.

const (
	LevelDebug5 Level = iota
	LevelDebug4
	LevelDebug3
	LevelDebug2
	LevelDebug1
	LevelLog
	LevelInfo
	LevelNotice
	LevelWarning
)

type Message#

type Message struct {
	Level              Level
	Text, Detail, Hint string
	// HideStatement leaves the statement being run out of the server log
	// entry (errhidestmt), e.g. when the message already shows it.
	HideStatement bool
	// HideContext leaves out the context (errhidecontext).
	HideContext bool
}

Message is a message to report with more control than Log, Notice… give: any level, a detail and a hint, and whether the server log shows the statement being run and the error context with it.

func (*Message) Report#

func (m *Message) Report()

Report sends the message.

type Numeric#

type Numeric = core.Numeric

Numeric is the SQL type numeric, in its text form (“12.50”, “NaN”): use math/big or a decimal package for arithmetic. A result that isn’t a valid numeric raises numeric’s input error. (time.Time is timestamptz; it can’t represent infinite timestamps, which raise an error.)

type Oid#

type Oid = core.Oid

Oid is the SQL type oid (an object identifier). Input and receive functions of data types get the type’s OID as their second argument.

const DefaultCollation Oid = 100

DefaultCollation is the database’s default collation (DEFAULT_COLLATION_OID).

func ArgType#

func ArgType(i int) Oid

ArgType returns the actual type of argument i (from 0) of the SQL function being called, as get_fn_expr_argtype: the type of a polymorphic or record argument even when it is NULL. 0 if unknown.

func Collation#

func Collation() Oid

Collation returns the input collation of the SQL function being called: the collation PostgreSQL derived from its arguments (or a COLLATE clause), as PG_GET_COLLATION() in C. It is 0 when there is none (arguments of non-collatable types, conflicting collations) and outside calls. Pass it to ToLower, ToUpper and CompareStrings.

func DatabaseID#

func DatabaseID() Oid

DatabaseID returns the database this backend is connected to (0 outside a database, e.g. in the postmaster).

func UserID#

func UserID() Oid

UserID returns the current user (as SQL’s current_user; the owner while a SECURITY DEFINER function runs).

type Point#

type Point = core.Point

Point is the SQL type point: (X, Y). Arrays (point[]) work too.

type Record#

type Record = core.Record

Record is a row of the SQL type record: a function returning Record (RETURNS record) or iter.Seq[Record] (RETURNS SETOF record) returns rows whose columns the caller defines, with a column definition list:

SELECT * FROM crosstab('...') AS ct(row_name text, cat1 text, cat2 int);

or by declaring the function (manual, in sql/) to return a composite type. ResultColumns tells the function which columns are expected. A record has one value per column: nil (NULL), or a Go value converted to the column’s type. bool, integers, floats, string, []byte (bytea only), pg.Numeric, pg.UUID, time.Time and pg.AnyElement of the column’s type convert directly; any other combination goes through the value’s text form and the column type’s input function (so “42” fits an integer column and 42 a numeric one), as do fmt.Stringer values. A record with the wrong number of values raises PostgreSQL’s error for a mismatched column definition list.

type Row#

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

Row is the result of QueryRow.

func QueryRow#

func QueryRow(sql string, args ...any) *Row

QueryRow runs a statement that returns at most one row (more are ignored). Errors are reported by Row.Scan.

func (*Row) Scan#

func (r *Row) Scan(dest ...any) error

Scan copies the row’s columns into dest (see Rows.Scan), or returns ErrNoRows.

type Rows#

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

Rows is the result of a query.

rows, err := pg.Query("SELECT id, name FROM users WHERE age > $1", 30)
...
for rows.Next() {
	var id int64
	var name *string // NULL-able: nil for NULL
	if err := rows.Scan(&id, &name); err != nil { ... }
}

func Query#

func Query(sql string, args ...any) (*Rows, error)

Query runs a statement that returns rows. The whole result is read into memory.

func (*Rows) ColumnTypes#

func (r *Rows) ColumnTypes() []uint32

ColumnTypes returns the type OIDs of the result columns.

func (*Rows) ColumnTypmods#

func (r *Rows) ColumnTypmods() []int32

ColumnTypmods returns the type modifiers of the result columns (-1 for none, e.g. 14 for varchar(10)): see FormatType.

func (*Rows) Columns#

func (r *Rows) Columns() []string

Columns returns the names of the result columns.

func (*Rows) Len#

func (r *Rows) Len() int

Len returns the number of rows.

func (*Rows) Next#

func (r *Rows) Next() bool

Next advances to the next row; it returns false after the last one.

func (*Rows) Scan#

func (r *Rows) Scan(dest ...any) error

Scan copies the columns of the current row into dest: pointers to bool, int, int16, int32, int64, float32, float64, string, []byte or any, or pointers to pointers of those (set to nil for NULL). Numbers convert between Go types when they fit; numeric and other types convert from their text form; any value scans into a string.

func (*Rows) Values#

func (r *Rows) Values() []any

Values returns the current row as Go values: nil (NULL), bool, int64, float64, string (text and other types in their text form) or []byte.

type SettingOption#

type SettingOption int

SettingOption modifies a setting: who can change it, and when.

const (
	// Superuser makes a setting changeable by superusers only (PGC_SUSET).
	Superuser SettingOption = 1
	// Sighup makes a setting changeable only in postgresql.conf (or ALTER
	// SYSTEM) and on the command line, taking effect on a configuration
	// reload (PGC_SIGHUP).
	Sighup SettingOption = 2
	// Postmaster makes a setting changeable only at server start
	// (PGC_POSTMASTER): for libraries in shared_preload_libraries, e.g. a
	// setting that sizes shared memory.
	Postmaster SettingOption = 3

	// Units of an integer or floating-point setting: its value can be given
	// with a unit ("10s", "1MB") and SHOW prints one.
	UnitBytes        SettingOption = 1 << 8
	UnitKilobytes    SettingOption = 2 << 8
	UnitMilliseconds SettingOption = 3 << 8
	UnitSeconds      SettingOption = 4 << 8
	UnitMinutes      SettingOption = 5 << 8
)

type StringInfo#

type StringInfo = core.StringInfo

StringInfo is the buffer the receive function of a data type reads its binary input from (the SQL type internal): the function must consume all of it, with Read* calls or ReadAll. The send function is the reverse: it returns a []byte (bytea); see encoding/binary’s BigEndian.Append* for the network byte order receive functions read.

type StringSetting#

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

StringSetting is a string setting.

func NewStringSetting#

func NewStringSetting(name, def, desc string, opts ...SettingOption) *StringSetting

NewStringSetting defines a string setting.

func (*StringSetting) Get#

func (s *StringSetting) Get() string

Get returns the current value.

type UUID#

type UUID = core.UUID

UUID is the SQL type uuid: its 16 bytes. String formats it; ParseUUID parses one. (Queries take and return uuids as text: pass u.String() with $1::uuid, and scan into a string.)

func ParseUUID#

func ParseUUID(s string) (UUID, error)

ParseUUID parses a UUID in the forms PostgreSQL accepts (“a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11”, with or without hyphens and braces).

type Varlena#

type Varlena = core.Varlena

Varlena is the contents of a variable-length value (bytea, or any type stored like one, e.g. a data type declared with //gopgext:type over pg.Varlena). Unlike []byte, a Varlena argument is not copied: it refers to PostgreSQL’s memory and is only valid during the call (copy it with bytes.Clone to keep it), and it must not be modified. Results are copied.