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 ¶
- Variables
- func BuildApplicationName(component string) string
- func CanonicalizeBaseType(baseType string) string
- func Connect(ctx context.Context, connString, component string) (*pgx.Conn, error)
- func ConvertSQLType(anytype string) string
- func ElementType(sqlType string) string
- func EquivalentBaseType(baseType string) string
- func EquivalentSQLTypeVariants(sqlType string) []string
- func ExtensionDependencies(name string) []string
- func ExtensionsForExpression(expression string) []string
- func ExtractBaseType(sqlType string) string
- func ExtractBaseTypeLower(sqlType string) string
- func ExtractWithClause(s string) string
- func FormatStorageParameters(clause string) string
- func GetExtensions() []string
- func GetPostgresBaseTypes() []string
- func GetPostgresKeywords() []string
- func GetPostgresTypes(includeArrays bool) []string
- func GetSQLType(anytype string) string
- func GetStdTypeFromGo(pTypeName string) string
- func HasExplicitTypeModifier(sqlType string) bool
- func IndexMethodExtension(method string) string
- func IsArrayType(sqlType string) bool
- func IsGoType(pTypeName string) bool
- func IsKnownExtension(name string) bool
- func IsKnownPGBaseType(baseType string) bool
- func IsKnownPostgresType(sqlType string) bool
- func IsSpatialType(sqlType string) bool
- func IsVectorType(sqlType string) bool
- func NormalizeEquivalentSQLType(sqlType string) string
- func NormalizePGType(baseType string) string
- func NormalizeStorageParameterValue(value string) string
- func OperatorClassExtension(opClass string) string
- func ParseConfigWithApplicationName(connString, component string) (*pgx.ConnConfig, error)
- func ParseStorageParameter(part string) (key, value string, ok bool)
- func QuoteExtensionName(name string) string
- func SerialUnderlyingType(baseType string) string
- func SortExtensions(names []string) []string
- func SpatialGeometryType(sqlType string) string
- func SpatialSRID(sqlType string) int
- func SplitStorageParameters(clause string) []string
- func SupportsLength(sqlType string) bool
- func SupportsPrecision(sqlType string) bool
- func SupportsTypeModifier(sqlType string) bool
- func TypeExtension(sqlType string) string
- func TypeModifier(sqlType string) string
- func ValidSQLType(sqltype string) bool
- type Extension
- type TypeSpec
Constants ¶
This section is empty.
Variables ¶
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",
}
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",
}
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
BuildApplicationName returns a PostgreSQL application_name in the form: relspecgo/<version>[:<component>]
func CanonicalizeBaseType ¶ added in v1.0.45
CanonicalizeBaseType resolves aliases to canonical PostgreSQL type names.
func Connect ¶ added in v1.0.47
Connect establishes a PostgreSQL connection with a default relspec application_name when the caller does not provide one in the DSN.
func ConvertSQLType ¶
func ElementType ¶ added in v1.0.45
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
EquivalentBaseType resolves broader SQL-equivalent spellings to a common comparable form.
func EquivalentSQLTypeVariants ¶ added in v1.0.56
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
ExtensionDependencies returns the extensions a given extension requires, sorted.
func ExtensionsForExpression ¶ added in v1.0.74
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
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
ExtractBaseTypeLower is ExtractBaseType with lowercase normalization.
func ExtractWithClause ¶ added in v1.0.74
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
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
GetPostgresTypes returns the registered PostgreSQL types. When includeArrays is true, each base type also includes an array variant ("type[]").
func GetSQLType ¶
func GetStdTypeFromGo ¶
func HasExplicitTypeModifier ¶ added in v1.0.45
HasExplicitTypeModifier reports if the type already includes "(...)".
func IndexMethodExtension ¶ added in v1.0.74
IndexMethodExtension returns the extension providing an index access method ("hnsw" -> "vector", "vchordrq" -> "vchord"). Built-in methods return "".
func IsArrayType ¶ added in v1.0.45
IsArrayType reports whether the SQL type has one or more [] suffixes.
func IsKnownExtension ¶ added in v1.0.74
IsKnownExtension reports whether the named extension is registered.
func IsKnownPGBaseType ¶ added in v1.0.58
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
IsKnownPostgresType reports whether a type (including array forms) exists in the registry.
func IsSpatialType ¶ added in v1.0.74
IsSpatialType reports whether the type comes from PostGIS (geometry, geography, raster, topogeometry, …).
func IsVectorType ¶ added in v1.0.74
IsVectorType reports whether the type comes from pgvector (vector, halfvec, sparsevec).
func NormalizeEquivalentSQLType ¶ added in v1.0.56
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
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
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
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
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
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
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
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
SpatialGeometryType returns the geometry subtype declared in a PostGIS type modifier ("Point", "MultiPolygonZ", …), or "" when absent.
func SpatialSRID ¶ added in v1.0.74
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
SplitStorageParameters splits a WITH clause body on top-level commas, leaving quoted and dollar-quoted values untouched.
func SupportsLength ¶ added in v1.0.45
SupportsLength reports if this SQL type accepts a single length/dimension modifier.
func SupportsPrecision ¶ added in v1.0.45
SupportsPrecision reports if this SQL type accepts precision (and possibly scale).
func SupportsTypeModifier ¶ added in v1.0.74
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
TypeExtension returns the PostgreSQL extension providing the given type ("postgis", "vector", "citext", …). Built-in types return "".
func TypeModifier ¶ added in v1.0.74
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 ¶
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
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.