v0.24.1-0...-fbf3e0f Latest Latest

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

Go to latest
Published: Jun 14, 2024 License: Apache-2.0 Imports: 27 Imported by: 39




View Source
const (
	TypeInt64    = "int64"
	TypeGeometry = "geometry"

CockroachDB types that are not part of PostgreSQL.

View Source
const (
	TypeBit     = "bit"
	TypeBitVar  = "bit varying"
	TypeBoolean = "boolean"
	TypeBool    = "bool" // boolean.
	TypeBytea   = "bytea"

	TypeCharacter = "character"
	TypeChar      = "char" // character
	TypeCharVar   = "character varying"
	TypeVarChar   = "varchar" // character varying
	TypeText      = "text"
	TypeBPChar    = "bpchar" // blank-padded character.

	TypeSmallInt = "smallint"
	TypeInteger  = "integer"
	TypeBigInt   = "bigint"
	TypeInt      = "int"  // integer.
	TypeInt2     = "int2" // smallint.
	TypeInt4     = "int4" // integer.
	TypeInt8     = "int8" // bigint.

	TypeCIDR     = "cidr"
	TypeInet     = "inet"
	TypeMACAddr  = "macaddr"
	TypeMACAddr8 = "macaddr8"

	TypeCircle  = "circle"
	TypeLine    = "line"
	TypeLseg    = "lseg"
	TypeBox     = "box"
	TypePath    = "path"
	TypePolygon = "polygon"
	TypePoint   = "point"

	TypeDate          = "date"
	TypeTime          = "time"   // time without time zone
	TypeTimeTZ        = "timetz" // time with time zone
	TypeTimeWTZ       = "time with time zone"
	TypeTimeWOTZ      = "time without time zone"
	TypeTimestamp     = "timestamp" // timestamp without time zone
	TypeTimestampTZ   = "timestamptz"
	TypeTimestampWTZ  = "timestamp with time zone"
	TypeTimestampWOTZ = "timestamp without time zone"

	TypeDouble = "double precision"
	TypeReal   = "real"
	TypeFloat8 = "float8" // double precision
	TypeFloat4 = "float4" // real
	TypeFloat  = "float"  // float(p).

	TypeNumeric = "numeric"
	TypeDecimal = "decimal" // numeric

	TypeSmallSerial = "smallserial" // smallint with auto_increment.
	TypeSerial      = "serial"      // integer with auto_increment.
	TypeBigSerial   = "bigserial"   // bigint with auto_increment.
	TypeSerial2     = "serial2"     // smallserial
	TypeSerial4     = "serial4"     // serial
	TypeSerial8     = "serial8"     // bigserial

	TypeArray       = "array"
	TypeXML         = "xml"
	TypeJSON        = "json"
	TypeJSONB       = "jsonb"
	TypeUUID        = "uuid"
	TypeMoney       = "money"
	TypeInterval    = "interval"
	TypeTSQuery     = "tsquery"
	TypeTSVector    = "tsvector"
	TypeUserDefined = "user-defined"

	TypeInt4Range      = "int4range"
	TypeInt4MultiRange = "int4multirange"
	TypeInt8Range      = "int8range"
	TypeInt8MultiRange = "int8multirange"
	TypeNumRange       = "numrange"
	TypeNumMultiRange  = "nummultirange"
	TypeTSRange        = "tsrange"
	TypeTSMultiRange   = "tsmultirange"
	TypeTSTZRange      = "tstzrange"
	TypeTSTZMultiRange = "tstzmultirange"
	TypeDateRange      = "daterange"
	TypeDateMultiRange = "datemultirange"

Standard column types (and their aliases) as defined in PostgreSQL codebase/website.

View Source
const (
	IndexTypeBTree  = "BTREE"
	IndexTypeBRIN   = "BRIN"
	IndexTypeHash   = "HASH"
	IndexTypeGIN    = "GIN"
	IndexTypeGiST   = "GIST"
	IndexTypeSPGiST = "SPGIST"

List of supported index types.

View Source
const (
	GeneratedTypeAlways    = "ALWAYS"
	GeneratedTypeByDefault = "BY_DEFAULT" // BY DEFAULT.

List of "GENERATED" types.

View Source
const (
	PartitionTypeRange = "RANGE"
	PartitionTypeList  = "LIST"
	PartitionTypeHash  = "HASH"

List of PARTITION KEY types.

View Source
const DriverName = "postgres"

DriverName holds the name used for registration.


View Source
var (

	// MarshalHCL marshals v into an Atlas HCL DDL document.
	MarshalHCL = schemahcl.MarshalerFunc(func(v any) ([]byte, error) {
		return MarshalSpec(v, hclState)
	// EvalHCL implements the schemahcl.Evaluator interface.
	EvalHCL = schemahcl.EvalFunc(evalSpec)

	// EvalHCLBytes is a helper that evaluates an HCL document from a byte slice instead
	// of from an hclparse.Parser instance.
	EvalHCLBytes = specutil.HCLBytesFunc(EvalHCL)
View Source
var DefaultDiff schema.Differ = &sqlx.Diff{DiffDriver: &diff{&conn{ExecQuerier: sqlx.NoRows}}}

DefaultDiff provides basic diffing capabilities for PostgreSQL dialects. Note, it is recommended to call Open, create a new Driver and use its Differ when a database connection is available.

View Source
var DefaultPlan migrate.PlanApplier = &planApply{conn: &conn{ExecQuerier: sqlx.NoRows}}

DefaultPlan provides basic planning capabilities for PostgreSQL dialects. Note, it is recommended to call Open, create a new Driver and use its migrate.PlanApplier when a database connection is available.

View Source
var TypeRegistry = schemahcl.NewRegistry(
		schemahcl.NewTypeSpec(TypeBit, schemahcl.WithAttributes(&schemahcl.TypeAttr{Name: "len", Kind: reflect.Int64})),
		schemahcl.AliasTypeSpec("bit_varying", TypeBitVar, schemahcl.WithAttributes(&schemahcl.TypeAttr{Name: "len", Kind: reflect.Int64})),
		schemahcl.NewTypeSpec(TypeVarChar, schemahcl.WithAttributes(schemahcl.SizeTypeAttr(false))),
		schemahcl.AliasTypeSpec("character_varying", TypeCharVar, schemahcl.WithAttributes(schemahcl.SizeTypeAttr(false))),
		schemahcl.NewTypeSpec(TypeChar, schemahcl.WithAttributes(schemahcl.SizeTypeAttr(false))),
		schemahcl.NewTypeSpec(TypeCharacter, schemahcl.WithAttributes(schemahcl.SizeTypeAttr(false))),
		schemahcl.NewTypeSpec(TypeTime, schemahcl.WithAttributes(schemahcl.PrecisionTypeAttr()), formatTime()),
		schemahcl.NewTypeSpec(TypeTimeTZ, schemahcl.WithAttributes(schemahcl.PrecisionTypeAttr()), formatTime()),
		schemahcl.NewTypeSpec(TypeTimestampTZ, schemahcl.WithAttributes(schemahcl.PrecisionTypeAttr()), formatTime()),
		schemahcl.NewTypeSpec(TypeTimestamp, schemahcl.WithAttributes(schemahcl.PrecisionTypeAttr()), formatTime()),
		schemahcl.AliasTypeSpec("double_precision", TypeDouble),
		schemahcl.NewTypeSpec(TypeFloat, schemahcl.WithAttributes(schemahcl.PrecisionTypeAttr())),
		schemahcl.NewTypeSpec(TypeNumeric, schemahcl.WithAttributes(schemahcl.PrecisionTypeAttr(), schemahcl.ScaleTypeAttr())),
		schemahcl.NewTypeSpec(TypeDecimal, schemahcl.WithAttributes(schemahcl.PrecisionTypeAttr(), schemahcl.ScaleTypeAttr())),

	schemahcl.WithSpecs(func() (specs []*schemahcl.TypeSpec) {
		for _, t := range []string{
			typeOID, typeRegClass, typeRegCollation, typeRegConfig, typeRegDictionary, typeRegNamespace,
			typeName, typeRegOper, typeRegOperator, typeRegProc, typeRegProcedure, typeRegRole, typeRegType,
			typeAny, typeAnyElement, typeAnyArray, typeAnyNonArray, typeAnyEnum, typeInternal, typeRecord,
			typeTrigger, typeEventTrigger, typeVoid, typeUnknown,
		} {
			specs = append(specs, schemahcl.NewTypeSpec(t))
		return specs
	schemahcl.WithSpecs(func() (specs []*schemahcl.TypeSpec) {
		opts := []schemahcl.TypeSpecOption{
			schemahcl.WithToSpec(func(t schema.Type) (*schemahcl.Type, error) {
				i, ok := t.(*IntervalType)
				if !ok {
					return nil, fmt.Errorf("postgres: unexpected interval type %T", t)
				spec := &schemahcl.Type{T: TypeInterval}
				if i.F != "" {
					spec.T = specutil.Var(strings.ToLower(i.F))
				if p := i.Precision; p != nil && *p != defaultTimePrecision {
					spec.Attrs = []*schemahcl.Attr{schemahcl.IntAttr("precision", *p)}
				return spec, nil
			schemahcl.WithFromSpec(func(t *schemahcl.Type) (schema.Type, error) {
				i := &IntervalType{T: TypeInterval}
				if t.T != TypeInterval {
					i.F = specutil.FromVar(t.T)
				if a, ok := attr(t, "precision"); ok {
					p, err := a.Int()
					if err != nil {
						return nil, fmt.Errorf(`postgres: parsing attribute "precision": %w`, err)
					if p != defaultTimePrecision {
						i.Precision = &p
				return i, nil
		for _, f := range []string{"interval", "second", "day to second", "hour to second", "minute to second"} {
			specs = append(specs, schemahcl.NewTypeSpec(specutil.Var(f), append(opts, schemahcl.WithAttributes(schemahcl.PrecisionTypeAttr()))...))
		for _, f := range []string{"year", "month", "day", "hour", "minute", "year to month", "day to hour", "day to minute", "hour to minute"} {
			specs = append(specs, schemahcl.NewTypeSpec(specutil.Var(f), opts...))
		return specs

TypeRegistry contains the supported TypeSpecs for the Postgres driver.


func FormatType added in v0.2.0

func FormatType(t schema.Type) (string, error)

FormatType converts schema type to its column form in the database. An error is returned if the type cannot be recognized.

func MarshalSpec

func MarshalSpec(v any, marshaler schemahcl.Marshaler) ([]byte, error)

MarshalSpec marshals v into an Atlas DDL document using a schemahcl.Marshaler.

func Open

Open opens a new PostgreSQL driver.

func ParseType added in v0.3.1

func ParseType(typ string) (schema.Type, error)

ParseType returns the schema.Type value represented by the given raw type. The raw value is expected to follow the format in PostgreSQL information schema or as an input for the CREATE TABLE statement.


type AddPKConstraint added in v0.22.0

type AddPKConstraint struct {
	Name  string        // Name of the constraint.
	Using *schema.Index // Index to use for the constraint.

AddPKConstraint to the table using the given index. Note, if the index name does not match the primary-key constraint name, PostgreSQL implicitly renames it to the constraint name.

type AddUniqueConstraint added in v0.22.0

type AddUniqueConstraint struct {
	Name  string        // Name of the constraint.
	Using *schema.Index // Index to use for the constraint.

AddUniqueConstraint to the table using the given index. Note, if the index name does not match the unique constraint name, PostgreSQL implicitly renames it to the constraint name.

type ArrayType

type ArrayType struct {
	schema.Type        // Underlying items type (e.g. varchar(255)).
	T           string // Formatted type (e.g. int[]).

ArrayType defines an array type.

func (*ArrayType) Underlying added in v0.16.0

func (a *ArrayType) Underlying() schema.Type

Underlying returns the underlying type of the array.

type BitType

type BitType struct {
	T   string
	Len int64

BitType defines a bit type.

type Cascade added in v0.3.7

type Cascade struct {

Cascade describes that a CASCADE clause should be added to the DROP [TABLE|SCHEMA] operation. Note, this clause is automatically added to DROP SCHEMA by the planner.

type CheckColumns added in v0.2.0

type CheckColumns struct {
	Columns []string

CheckColumns attribute hold the column named used by the CHECK constraints. This attribute is added on inspection for internal usage and has no meaning on migration.

type CompositeType added in v0.22.0

type CompositeType struct {
	T      string           // Type name.
	Schema *schema.Schema   // Optional schema.
	Fields []*schema.Column // Type fields, also known as attributes/columns.
	Attrs  []schema.Attr    // Extra attributes, such as OID.
	Deps   []schema.Object  // Objects this domain depends on.

CompositeType defines a composite type.

func (*CompositeType) SpecName added in v0.22.0

func (c *CompositeType) SpecName() string

SpecName returns the name of the composite type.

func (*CompositeType) SpecType added in v0.22.0

func (c *CompositeType) SpecType() string

SpecType returns the type of the composite type.

type Concurrently added in v0.7.1

type Concurrently struct {

Concurrently describes the CONCURRENTLY clause to instruct Postgres to build or drop the index concurrently without blocking the current table.

type Constraint added in v0.8.3

type Constraint struct {
	N string // constraint name
	T string // c, f, p, u, t, x.

Constraint describes a postgres constraint.

func ExcludeConstraint added in v0.22.0

func ExcludeConstraint(name string) *Constraint

ExcludeConstraint returns constraint with type "x".

func UniqueConstraint added in v0.22.0

func UniqueConstraint(name string) *Constraint

UniqueConstraint returns constraint with type "u".

func (Constraint) IsExclude added in v0.22.0

func (c Constraint) IsExclude() bool

IsExclude reports if the type is an exclude constraint.

func (Constraint) IsUnique added in v0.8.3

func (c Constraint) IsUnique() bool

IsUnique reports if the type is a unique constraint.

type ConvertUsing added in v0.22.0

type ConvertUsing struct {
	X string // Conversion expression.

ConvertUsing describes the USING clause to convert one type to another.

type CurrencyType

type CurrencyType struct {
	T string

A CurrencyType defines a currency type.

type DiffOptions added in v0.11.0

type DiffOptions struct {
	ConcurrentIndex struct {
		Drop bool `spec:"drop"`
		// Allow config "CREATE" both with "add" and "create"
		// as the documentation used both terms (accidentally).
		Add    bool `spec:"add"`
		Create bool `spec:"create"`
	} `spec:"concurrent_index"`

DiffOptions defines PostgreSQL specific schema diffing process.

type DomainType added in v0.15.0

type DomainType struct {
	T       string          // Type name.
	Schema  *schema.Schema  // Optional schema.
	Null    bool            // Nullability.
	Default schema.Expr     // Default value.
	Checks  []*schema.Check // Check constraints.
	Attrs   []schema.Attr   // Extra attributes, such as OID.
	Deps    []schema.Object // Objects this domain depends on.

DomainType represents a domain type.

func (*DomainType) Ref added in v0.15.0

func (d *DomainType) Ref() *schemahcl.Ref

Ref returns a reference to the domain type.

func (*DomainType) SpecName added in v0.19.1

func (d *DomainType) SpecName() string

SpecName returns the name of the domain.

func (*DomainType) SpecType added in v0.19.1

func (d *DomainType) SpecType() string

SpecType returns the type of the domain.

func (*DomainType) Underlying added in v0.16.0

func (d *DomainType) Underlying() schema.Type

Underlying returns the underlying type of the domain.

type Driver

type Driver struct {
	// contains filtered or unexported fields

Driver represents a PostgreSQL driver for introspecting database schemas, generating diff between schema elements and apply migrations changes.

func (*Driver) CheckClean added in v0.6.0

func (d *Driver) CheckClean(ctx context.Context, revT *migrate.TableIdent) error

CheckClean implements migrate.CleanChecker.

func (*Driver) FormatType

func (*Driver) FormatType(t schema.Type) (string, error)

FormatType converts schema type to its column form in the database.

func (*Driver) Lock added in v0.3.8

func (d *Driver) Lock(ctx context.Context, name string, timeout time.Duration) (schema.UnlockFunc, error)

Lock implements the schema.Locker interface.

func (*Driver) NormalizeRealm added in v0.3.7

func (d *Driver) NormalizeRealm(ctx context.Context, r *schema.Realm) (*schema.Realm, error)

NormalizeRealm returns the normal representation of the given database.

func (*Driver) NormalizeSchema added in v0.3.7

func (d *Driver) NormalizeSchema(ctx context.Context, s *schema.Schema) (*schema.Schema, error)

NormalizeSchema returns the normal representation of the given database.

func (*Driver) ParseType added in v0.16.0

func (*Driver) ParseType(s string) (schema.Type, error)

ParseType returns the schema.Type value represented by the given string.

func (*Driver) RealmRestoreFunc added in v0.16.0

func (d *Driver) RealmRestoreFunc(desired *schema.Realm) migrate.RestoreFunc

RealmRestoreFunc returns a function that restores the given realm to its desired state.

func (*Driver) ScanStmts added in v0.16.0

func (*Driver) ScanStmts(input string) ([]*migrate.Stmt, error)

ScanStmts implements migrate.StmtScanner.

func (*Driver) SchemaRestoreFunc added in v0.16.0

func (d *Driver) SchemaRestoreFunc(desired *schema.Schema) migrate.RestoreFunc

SchemaRestoreFunc returns a function that restores the given schema to its desired state.

func (*Driver) Snapshot added in v0.5.0

func (d *Driver) Snapshot(ctx context.Context) (migrate.RestoreFunc, error)

Snapshot implements migrate.Snapshoter.

func (*Driver) StmtBuilder added in v0.19.1

func (*Driver) StmtBuilder(opts migrate.PlanOptions) *sqlx.Builder

StmtBuilder is a helper method used to build statements with PostgreSQL formatting.

func (*Driver) Version added in v0.9.0

func (d *Driver) Version() string

Version returns the version of the connected database.

type Identity

type Identity struct {
	Generation string // ALWAYS, BY DEFAULT.
	Sequence   *Sequence

Identity defines an identity column.

type IndexColumnProperty

type IndexColumnProperty struct {
	// NullsFirst defaults to true for DESC indexes.
	NullsFirst bool
	// NullsLast defaults to true for ASC indexes.
	NullsLast bool

IndexColumnProperty describes an index column property.

type IndexInclude added in v0.6.5

type IndexInclude struct {
	Columns []*schema.Column

IndexInclude describes the INCLUDE clause allows specifying a list of column which added to the index as non-key columns.

type IndexNullsDistinct added in v0.13.0

type IndexNullsDistinct struct {
	V bool // NULLS [NOT] DISTINCT. Defaults to true.

IndexNullsDistinct describes the NULLS [NOT] DISTINCT clause.

type IndexOpClass added in v0.8.2

type IndexOpClass struct {
	Name    string                  // Name of the operator class. Qualified if schema is not the default, and required.
	Default bool                    // If it is the default operator class.
	Params  []struct{ N, V string } // Optional parameters.

IndexOpClass describers operator class of the index part.

func (*IndexOpClass) DefaultFor added in v0.8.2

func (o *IndexOpClass) DefaultFor(idx *schema.Index, part *schema.IndexPart) (bool, error)

DefaultFor reports if the operator_class is the default for the index part.

func (*IndexOpClass) Equal added in v0.8.2

func (o *IndexOpClass) Equal(x *IndexOpClass) bool

Equal reports whether o and x are the same operator class.

func (*IndexOpClass) String added in v0.8.2

func (o *IndexOpClass) String() string

String returns the string representation of the operator class.

func (*IndexOpClass) UnmarshalText added in v0.8.2

func (o *IndexOpClass) UnmarshalText(text []byte) error

UnmarshalText parses the operator class from its string representation.

type IndexPredicate

type IndexPredicate struct {
	P string

IndexPredicate describes a partial index predicate.

type IndexStorageParams added in v0.4.0

type IndexStorageParams struct {
	// AutoSummarize defines the authsummarize storage parameter.
	AutoSummarize bool
	// PagesPerRange defines pages_per_range storage
	// parameter for BRIN indexes. Defaults to 128.
	PagesPerRange int64

IndexStorageParams describes index storage parameters add with the WITH clause.

type IndexType

type IndexType struct {
	T string // BTREE, BRIN, HASH, GiST, SP-GiST, GIN.

IndexType represents an index type.

type IntervalType added in v0.4.3

type IntervalType struct {
	T         string // Type name.
	F         string // Optional field. YEAR, MONTH, ..., MINUTE TO SECOND.
	Precision *int   // Optional precision.

IntervalType defines an interval type.

type NetworkType

type NetworkType struct {
	T   string
	Len int64

A NetworkType defines a network type.

type NoInherit added in v0.2.0

type NoInherit struct {

NoInherit attribute defines the NO INHERIT flag for CHECK constraint.

type NotValid added in v0.22.0

type NotValid struct {

NotValid describes the NOT VALID clause for the creation of check and foreign-key constraints.

type OID added in v0.16.0

type OID struct {
	V int64

OID is the object identifier as defined in the Postgres catalog.

type OIDType added in v0.9.1

type OIDType struct {
	T string

OIDType defines an object identifier type.

type Operator added in v0.22.0

type Operator struct {
	// Schema where the operator is defined. If nil, the operator
	// is not managed by the current scope.
	Schema *schema.Schema
	// Operator name. Might include the schema name if the schema
	// is not managed by the current scope or extension based.
	// e.g., "public.&&".
	Name  string
	Attrs []schema.Attr

Operator describes an operator.

func NewOperator added in v0.22.0

func NewOperator(scope string, name string) *Operator

NewOperator returns the string representation of the operator.

type Partition added in v0.3.8

type Partition struct {
	// T defines the type/strategy of the partition.
	// Can be one of: RANGE, LIST, HASH.
	T string
	// Partition parts. The additional attributes
	// on each part can be used to control collation.
	Parts []*PartitionPart
	// contains filtered or unexported fields

Partition defines the spec of a partitioned table.

type PartitionPart added in v0.3.8

type PartitionPart struct {
	X     schema.Expr
	C     *schema.Column
	Attrs []schema.Attr

An PartitionPart represents an index part that can be either an expression or a column.

type PseudoType added in v0.15.0

type PseudoType struct {
	T string // e.g., void, any, cstring, etc.

PseudoType defines a non-column pseudo-type, such as function arguments and return types.

type RangeType added in v0.9.0

type RangeType struct {
	T string

A RangeType defines a range type.

type ReferenceOption added in v0.14.0

type ReferenceOption schema.ReferenceOption

ReferenceOption describes the ON DELETE and ON UPDATE options for foreign keys.

func (*ReferenceOption) Scan added in v0.14.0

func (o *ReferenceOption) Scan(v any) error

Scan implements sql.Scanner interface.

func (ReferenceOption) String added in v0.14.0

func (o ReferenceOption) String() string

String implements fmt.Stringer interface.

type Sequence added in v0.2.0

type Sequence struct {
	// Fields used by the Identity schema attribute.
	Start     int64
	Increment int64
	// Last sequence value written to disk.
	Last int64

	// Field used when defining and managing independent
	// sequences (not part of IDENTITY or serial columns).
	Name     string         // Sequence name.
	Schema   *schema.Schema // Optional schema.
	Type     schema.Type    // Sequence type.
	Cache    int64          // Cache size.
	Min, Max *int64         // Min and max values.
	Cycle    bool           // Whether the sequence cycles.
	Attrs    []schema.Attr  // Additional attributes (e.g., comments),
	Owner    struct {
		T *schema.Table
		C *schema.Column

Sequence defines (the supported) sequence options.

type SerialType

type SerialType struct {
	T         string
	Precision int
	// SequenceName holds the inspected sequence name attached to the column.
	// It defaults to <Table>_<Column>_seq when the column is created, but may
	// be different in case the table or the column was renamed.
	SequenceName string

A SerialType defines a serial type.

func (*SerialType) IntegerType added in v0.6.0

func (s *SerialType) IntegerType() *schema.IntegerType

IntegerType returns the underlying integer type this serial type represents.

func (*SerialType) SetType added in v0.6.0

func (s *SerialType) SetType(t *schema.IntegerType)

SetType sets the serial type from the given integer type.

type TextSearchType added in v0.8.2

type TextSearchType struct {
	T string

A TextSearchType defines full text search types.

type UUIDType

type UUIDType = schema.UUIDType

UUIDType is alias to schema.UUIDType. Defined here for backward compatibility reasons.

type UserDefinedType

type UserDefinedType struct {
	T string

UserDefinedType defines a user-defined type attribute.

type XMLType

type XMLType struct {
	T string

A XMLType defines an XML type.


Path Synopsis

Jump to

Keyboard shortcuts

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