pgsql

package
v1.0.74 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package pgsql provides PostgreSQL-specific utilities and helpers.

Overview

The pgsql package contains PostgreSQL-specific functionality including:

  • SQL reserved keyword validation
  • Data type mappings and conversions
  • PostgreSQL-specific schema introspection helpers

Components

keywords.go - SQL reserved keywords validation

Provides functions to check if identifiers conflict with SQL reserved words
and need quoting for safe usage in PostgreSQL queries.

datatypes.go - PostgreSQL data type utilities

Contains mappings between PostgreSQL data types and their equivalents in other
systems, as well as type conversion and normalization functions.

Usage

// Check if identifier needs quoting
if pgsql.IsReservedKeyword("user") {
    // Quote the identifier
}

// Normalize data type
normalizedType := pgsql.NormalizeDataType("varchar(255)")

Purpose

This package supports the PostgreSQL reader and writer implementations by providing shared utilities for handling PostgreSQL-specific schema elements and constraints.

Index

Constants

This section is empty.

Variables

View Source
var GoToPGSQLTypes = map[string]string{
	"bool":            "boolean",
	"int64":           "bigint",
	"int":             "integer",
	"int8":            "smallint",
	"int16":           "smallint",
	"int32":           "integer",
	"uint":            "integer",
	"uint8":           "smallint",
	"uint16":          "smallint",
	"uint32":          "integer",
	"uint64":          "bigint",
	"uintptr":         "bigint",
	"znullint64":      "bigint",
	"znullint32":      "integer",
	"znullbyte":       "integer",
	"float64":         "double precision",
	"float32":         "real",
	"complex64":       "double precision",
	"complex128":      "double precision",
	"customfloat64":   "double precision",
	"string":          "text",
	"Pointer":         "bigint",
	"[]byte":          "bytea",
	"customdate":      "date",
	"customtime":      "time",
	"customtimestamp": "timestamp",
	"sqlfloat64":      "double precision",
	"sqlfloat16":      "double precision",
	"sqluuid":         "uuid",
	"sqljsonb":        "jsonb",
	"sqljson":         "json",
	"sqlint64":        "bigint",
	"sqlint32":        "integer",
	"sqlint16":        "smallint",
	"sqlbool":         "boolean",
	"sqlstring":       "text",
	"nullablejsonb":   "jsonb",
	"nullablejson":    "json",
	"nullableuuid":    "uuid",
	"sqldate":         "date",
	"sqltime":         "time",
	"sqltimestamp":    "timestamp",
	"time.Time":       "timestamp",
	"citext":          "citext",
}
View Source
var GoToStdTypes = map[string]string{
	"bool":            "boolean",
	"int64":           "bigint",
	"int":             "integer",
	"int8":            "smallint",
	"int16":           "smallint",
	"int32":           "integer",
	"uint":            "integer",
	"uint8":           "smallint",
	"uint16":          "smallint",
	"uint32":          "integer",
	"uint64":          "bigint",
	"uintptr":         "bigint",
	"znullint64":      "bigint",
	"znullint32":      "integer",
	"znullbyte":       "smallint",
	"float64":         "double",
	"float32":         "double",
	"complex64":       "double",
	"complex128":      "double",
	"customfloat64":   "double",
	"string":          "text",
	"Pointer":         "bigint",
	"[]byte":          "blob",
	"customdate":      "date",
	"customtime":      "time",
	"customtimestamp": "timestamp",
	"sqlfloat64":      "double",
	"sqlfloat16":      "double",
	"sqluuid":         "uuid",
	"sqljsonb":        "jsonb",
	"sqljson":         "json",
	"sqlint64":        "bigint",
	"sqlint32":        "integer",
	"sqlint16":        "smallint",
	"sqlbool":         "boolean",
	"sqlstring":       "text",
	"nullablejsonb":   "jsonb",
	"nullablejson":    "json",
	"nullableuuid":    "uuid",
	"sqldate":         "date",
	"sqltime":         "time",
	"sqltimestamp":    "timestamp",
	"time.Time":       "timestamp",
}
View Source
var PGTypeCanonical = map[string]string{

	"int":  "integer",
	"int4": "integer",
	"int2": "smallint",
	"int8": "bigint",

	"float4": "real",
	"float8": "double precision",

	"bool": "boolean",

	"character":         "char",
	"character varying": "varchar",
	"bpchar":            "char",

	"timestamp without time zone": "timestamp",
	"timestamp with time zone":    "timestamptz",

	"time without time zone": "time",
	"time with time zone":    "timetz",

	"decimal": "numeric",
}

PGTypeCanonical maps PostgreSQL type aliases and synonyms to their canonical base name. Input should be a base type (no dimension parameters, lowercase).

Functions

func BuildApplicationName added in v1.0.47

func BuildApplicationName(component string) string

BuildApplicationName returns a PostgreSQL application_name in the form: relspecgo/<version>[:<component>]

func CanonicalizeBaseType added in v1.0.45

func CanonicalizeBaseType(baseType string) string

CanonicalizeBaseType resolves aliases to canonical PostgreSQL type names.

func Connect added in v1.0.47

func Connect(ctx context.Context, connString, component string) (*pgx.Conn, error)

Connect establishes a PostgreSQL connection with a default relspec application_name when the caller does not provide one in the DSN.

func ConvertSQLType

func ConvertSQLType(anytype string) string

func ElementType added in v1.0.45

func ElementType(sqlType string) string

ElementType returns the underlying element type for array types. For non-array types, it returns the input unchanged.

func EquivalentBaseType added in v1.0.56

func EquivalentBaseType(baseType string) string

EquivalentBaseType resolves broader SQL-equivalent spellings to a common comparable form.

func EquivalentSQLTypeVariants added in v1.0.56

func EquivalentSQLTypeVariants(sqlType string) []string

EquivalentSQLTypeVariants returns equivalent PostgreSQL spellings for a SQL type. Examples: - varchar(255) -> ["varchar(255)", "character varying(255)"] - timestamptz -> ["timestamptz", "timestamp with time zone"]

func ExtensionDependencies added in v1.0.74

func ExtensionDependencies(name string) []string

ExtensionDependencies returns the extensions a given extension requires, sorted.

func ExtensionsForExpression added in v1.0.74

func ExtensionsForExpression(expression string) []string

ExtensionsForExpression returns the extensions whose functions appear in a SQL expression such as a column default, check constraint, index predicate, or view body. The result is sorted and deduplicated.

func ExtractBaseType added in v1.0.45

func ExtractBaseType(sqlType string) string

ExtractBaseType returns the type without outer array suffixes and modifiers. Examples: - varchar(255) -> varchar - text[] -> text - numeric(10,2)[] -> numeric

func ExtractBaseTypeLower added in v1.0.45

func ExtractBaseTypeLower(sqlType string) string

ExtractBaseTypeLower is ExtractBaseType with lowercase normalization.

func ExtractWithClause added in v1.0.74

func ExtractWithClause(s string) string

ExtractWithClause returns the contents of the first WITH (...) clause in s, without the surrounding parentheses. Parentheses inside quoted and dollar-quoted values are ignored, so a vchord TOML block survives intact. Returns "" when there is no WITH clause.

func FormatStorageParameters added in v1.0.74

func FormatStorageParameters(clause string) string

FormatStorageParameters renders a WITH clause body as a canonical "key = value" list, dropping anything malformed. Returns "" when nothing survives.

func GetExtensions added in v1.0.74

func GetExtensions() []string

GetExtensions returns every registered extension name, sorted.

func GetPostgresBaseTypes added in v1.0.45

func GetPostgresBaseTypes() []string

GetPostgresBaseTypes returns a sorted-ish stable list of registered base type names.

func GetPostgresKeywords

func GetPostgresKeywords() []string

func GetPostgresTypes added in v1.0.45

func GetPostgresTypes(includeArrays bool) []string

GetPostgresTypes returns the registered PostgreSQL types. When includeArrays is true, each base type also includes an array variant ("type[]").

func GetSQLType

func GetSQLType(anytype string) string

func GetStdTypeFromGo

func GetStdTypeFromGo(pTypeName string) string

func HasExplicitTypeModifier added in v1.0.45

func HasExplicitTypeModifier(sqlType string) bool

HasExplicitTypeModifier reports if the type already includes "(...)".

func IndexMethodExtension added in v1.0.74

func IndexMethodExtension(method string) string

IndexMethodExtension returns the extension providing an index access method ("hnsw" -> "vector", "vchordrq" -> "vchord"). Built-in methods return "".

func IsArrayType added in v1.0.45

func IsArrayType(sqlType string) bool

IsArrayType reports whether the SQL type has one or more [] suffixes.

func IsGoType

func IsGoType(pTypeName string) bool

func IsKnownExtension added in v1.0.74

func IsKnownExtension(name string) bool

IsKnownExtension reports whether the named extension is registered.

func IsKnownPGBaseType added in v1.0.58

func IsKnownPGBaseType(baseType string) bool

IsKnownPGBaseType reports whether the given name (after NormalizePGType) is a recognized built-in PostgreSQL type. Custom types (e.g. vector, postgis) return false.

func IsKnownPostgresType added in v1.0.45

func IsKnownPostgresType(sqlType string) bool

IsKnownPostgresType reports whether a type (including array forms) exists in the registry.

func IsSpatialType added in v1.0.74

func IsSpatialType(sqlType string) bool

IsSpatialType reports whether the type comes from PostGIS (geometry, geography, raster, topogeometry, …).

func IsVectorType added in v1.0.74

func IsVectorType(sqlType string) bool

IsVectorType reports whether the type comes from pgvector (vector, halfvec, sparsevec).

func NormalizeEquivalentSQLType added in v1.0.56

func NormalizeEquivalentSQLType(sqlType string) string

NormalizeEquivalentSQLType returns a normalized SQL type string suitable for equality checks. Equivalent spellings such as "character varying(255)" and "varchar(255)" normalize identically.

func NormalizePGType added in v1.0.58

func NormalizePGType(baseType string) string

NormalizePGType maps a PostgreSQL base type (no dimension parameters) to its canonical form. Unknown types are returned as-is (lowercased).

func NormalizeStorageParameterValue added in v1.0.74

func NormalizeStorageParameterValue(value string) string

NormalizeStorageParameterValue unquotes a value that PostgreSQL rendered as a string but that is really a number, so that pg_indexes output (lists='100') and hand-written models (lists=100) normalize identically. Non-numeric quoted values keep their quotes because some access methods require a string (pg_search's key_field='id').

func OperatorClassExtension added in v1.0.74

func OperatorClassExtension(opClass string) string

OperatorClassExtension returns the extension providing an operator class ("gin_trgm_ops" -> "pg_trgm"). Built-in operator classes return "".

func ParseConfigWithApplicationName added in v1.0.47

func ParseConfigWithApplicationName(connString, component string) (*pgx.ConnConfig, error)

ParseConfigWithApplicationName parses a connection string and applies a default application_name when one is not explicitly provided by the caller.

func ParseStorageParameter added in v1.0.74

func ParseStorageParameter(part string) (key, value string, ok bool)

ParseStorageParameter splits one "key = value" storage parameter. It reports false for anything that is not a well-formed parameter, which is how comment prose is filtered out.

func QuoteExtensionName added in v1.0.74

func QuoteExtensionName(name string) string

QuoteExtensionName quotes an extension name when it is not a bare SQL identifier, e.g. uuid-ossp -> "uuid-ossp".

func SerialUnderlyingType added in v1.0.70

func SerialUnderlyingType(baseType string) string

SerialUnderlyingType returns the underlying integer type for a serial pseudo-type (e.g. "bigserial" -> "bigint"). If baseType (after NormalizePGType) is not a serial type, it is returned unchanged.

func SortExtensions added in v1.0.74

func SortExtensions(names []string) []string

SortExtensions orders extension names so that dependencies come first (postgis before postgis_topology, vector before vchord), with alphabetical order breaking ties. Duplicates are removed; unknown names are kept and sorted alphabetically.

func SpatialGeometryType added in v1.0.74

func SpatialGeometryType(sqlType string) string

SpatialGeometryType returns the geometry subtype declared in a PostGIS type modifier ("Point", "MultiPolygonZ", …), or "" when absent.

func SpatialSRID added in v1.0.74

func SpatialSRID(sqlType string) int

SpatialSRID returns the SRID declared in a PostGIS type modifier, or 0 when absent. Example: geometry(Point,4326) -> 4326.

func SplitStorageParameters added in v1.0.74

func SplitStorageParameters(clause string) []string

SplitStorageParameters splits a WITH clause body on top-level commas, leaving quoted and dollar-quoted values untouched.

func SupportsLength added in v1.0.45

func SupportsLength(sqlType string) bool

SupportsLength reports if this SQL type accepts a single length/dimension modifier.

func SupportsPrecision added in v1.0.45

func SupportsPrecision(sqlType string) bool

SupportsPrecision reports if this SQL type accepts precision (and possibly scale).

func SupportsTypeModifier added in v1.0.74

func SupportsTypeModifier(sqlType string) bool

SupportsTypeModifier reports if this SQL type carries an opaque "(...)" modifier that must be preserved verbatim (e.g. vector(1536), geometry(Point,4326)).

func TypeExtension added in v1.0.74

func TypeExtension(sqlType string) string

TypeExtension returns the PostgreSQL extension providing the given type ("postgis", "vector", "citext", …). Built-in types return "".

func TypeModifier added in v1.0.74

func TypeModifier(sqlType string) string

TypeModifier returns the raw "(...)" modifier of a SQL type without the parentheses, or "" when the type has none. Array suffixes are ignored. Example: geometry(PointZ,4326)[] -> "PointZ,4326".

func ValidSQLType

func ValidSQLType(sqltype string) bool

Types

type Extension added in v1.0.74

type Extension struct {
	Name        string
	Category    string
	Description string

	// Requires lists extensions that must be created before this one.
	Requires []string

	// IndexMethods are access methods usable as Index.Type.
	IndexMethods []string

	// OperatorClasses are operator classes the extension installs.
	OperatorClasses []string

	// Functions are function names whose use implies the extension.
	Functions []string

	// FunctionPrefixes match whole families of functions (e.g. "st_" for PostGIS).
	FunctionPrefixes []string
}

Extension describes a PostgreSQL extension RelSpec recognizes, along with the schema artefacts that imply it: the types it provides (declared on TypeSpec.Extension), the index access methods and operator classes it installs, and the functions whose use in a default, check constraint, index predicate, or view body requires it.

func LookupExtension added in v1.0.74

func LookupExtension(name string) (Extension, bool)

LookupExtension returns the registered extension by name.

type TypeSpec added in v1.0.45

type TypeSpec struct {
	SupportsLength    bool
	SupportsPrecision bool

	// SupportsTypeModifier marks types whose "(...)" modifier is opaque and must be
	// preserved verbatim (e.g. vector(1536), geometry(Point,4326)) instead of being
	// decomposed into Length/Precision/Scale.
	SupportsTypeModifier bool

	// Extension is the PostgreSQL extension providing the type; empty for built-ins.
	Extension string
}

TypeSpec describes PostgreSQL type capabilities used by parsers/writers.

Jump to

Keyboard shortcuts

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