postgres

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 23, 2023 License: Apache-2.0 Imports: 26 Imported by: 1

Documentation

Index

Constants

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"

	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.

Variables

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{}}

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.WithSpecFunc(typeSpec),
	schemahcl.WithParser(ParseType),
	schemahcl.WithSpecs(
		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(TypeInt2),
		schemahcl.NewTypeSpec(TypeInt4),
		schemahcl.NewTypeSpec(TypeInt8),
		schemahcl.NewTypeSpec(TypeInt),
		schemahcl.NewTypeSpec(TypeInteger),
		schemahcl.NewTypeSpec(TypeSmallInt),
		schemahcl.NewTypeSpec(TypeBigInt),
		schemahcl.NewTypeSpec(TypeText),
		schemahcl.NewTypeSpec(TypeBoolean),
		schemahcl.NewTypeSpec(TypeBool),
		schemahcl.NewTypeSpec(TypeBytea),
		schemahcl.NewTypeSpec(TypeCIDR),
		schemahcl.NewTypeSpec(TypeInet),
		schemahcl.NewTypeSpec(TypeMACAddr),
		schemahcl.NewTypeSpec(TypeMACAddr8),
		schemahcl.NewTypeSpec(TypeCircle),
		schemahcl.NewTypeSpec(TypeLine),
		schemahcl.NewTypeSpec(TypeLseg),
		schemahcl.NewTypeSpec(TypeBox),
		schemahcl.NewTypeSpec(TypePath),
		schemahcl.NewTypeSpec(TypePoint),
		schemahcl.NewTypeSpec(TypePolygon),
		schemahcl.NewTypeSpec(TypeDate),
		schemahcl.NewTypeSpec(TypeTime, schemahcl.WithAttributes(precisionTypeAttr()), formatTime()),
		schemahcl.NewTypeSpec(TypeTimeTZ, schemahcl.WithAttributes(precisionTypeAttr()), formatTime()),
		schemahcl.NewTypeSpec(TypeTimestampTZ, schemahcl.WithAttributes(precisionTypeAttr()), formatTime()),
		schemahcl.NewTypeSpec(TypeTimestamp, schemahcl.WithAttributes(precisionTypeAttr()), formatTime()),
		schemahcl.AliasTypeSpec("double_precision", TypeDouble),
		schemahcl.NewTypeSpec(TypeReal),
		schemahcl.NewTypeSpec(TypeFloat, schemahcl.WithAttributes(precisionTypeAttr())),
		schemahcl.NewTypeSpec(TypeFloat8),
		schemahcl.NewTypeSpec(TypeFloat4),
		schemahcl.NewTypeSpec(TypeNumeric, schemahcl.WithAttributes(precisionTypeAttr(), &schemahcl.TypeAttr{Name: "scale", Kind: reflect.Int, Required: false})),
		schemahcl.NewTypeSpec(TypeDecimal, schemahcl.WithAttributes(precisionTypeAttr(), &schemahcl.TypeAttr{Name: "scale", Kind: reflect.Int, Required: false})),
		schemahcl.NewTypeSpec(TypeSmallSerial),
		schemahcl.NewTypeSpec(TypeSerial),
		schemahcl.NewTypeSpec(TypeBigSerial),
		schemahcl.NewTypeSpec(TypeSerial2),
		schemahcl.NewTypeSpec(TypeSerial4),
		schemahcl.NewTypeSpec(TypeSerial8),
		schemahcl.NewTypeSpec(TypeXML),
		schemahcl.NewTypeSpec(TypeJSON),
		schemahcl.NewTypeSpec(TypeJSONB),
		schemahcl.NewTypeSpec(TypeUUID),
		schemahcl.NewTypeSpec(TypeMoney),
		schemahcl.NewTypeSpec(TypeTSVector),
		schemahcl.NewTypeSpec(TypeTSQuery),
		schemahcl.NewTypeSpec(TypeInt4Range),
		schemahcl.NewTypeSpec(TypeInt4MultiRange),
		schemahcl.NewTypeSpec(TypeInt8Range),
		schemahcl.NewTypeSpec(TypeInt8MultiRange),
		schemahcl.NewTypeSpec(TypeNumRange),
		schemahcl.NewTypeSpec(TypeNumMultiRange),
		schemahcl.NewTypeSpec(TypeTSRange),
		schemahcl.NewTypeSpec(TypeTSMultiRange),
		schemahcl.NewTypeSpec(TypeTSTZRange),
		schemahcl.NewTypeSpec(TypeTSTZMultiRange),
		schemahcl.NewTypeSpec(TypeDateRange),
		schemahcl.NewTypeSpec(TypeDateMultiRange),
		schemahcl.NewTypeSpec("hstore"),
		schemahcl.NewTypeSpec("sql", schemahcl.WithAttributes(&schemahcl.TypeAttr{Name: "def", Required: true, Kind: reflect.String})),
	),

	schemahcl.WithSpecs(func() (specs []*schemahcl.TypeSpec) {
		for _, t := range []string{
			typeOID, typeRegClass, typeRegCollation, typeRegConfig, typeRegDictionary, typeRegNamespace,
			typeName, typeRegOper, typeRegOperator, typeRegProc, typeRegProcedure, typeRegRole, typeRegType,
		} {
			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(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.

Functions

func FormatType

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

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.

Types

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. https://postgresql.org/docs/current/arrays.html

type BitType

type BitType struct {
	schema.Type
	T   string
	Len int64
}

BitType defines a bit type. https://postgresql.org/docs/current/datatype-bit.html

type CType

type CType struct {
	schema.Attr
	V string
}

CType describes the character classification setting (LC_CTYPE).

type Cascade

type Cascade struct {
	schema.Clause
}

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

type CheckColumns struct {
	schema.Attr
	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 Concurrently

type Concurrently struct {
	schema.Clause
}

Concurrently describes the CONCURRENTLY clause to instruct Postgres to build or drop the index concurrently without blocking the current table. https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY

type Constraint

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

Constraint describes a postgres constraint. https://postgresql.org/docs/current/catalog-pg-constraint.html

func (Constraint) IsUnique

func (c Constraint) IsUnique() bool

IsUnique reports if the type is unique constraint.

type CurrencyType

type CurrencyType struct {
	schema.Type
	T string
}

A CurrencyType defines a currency type.

type DiffOptions

type DiffOptions struct {
	ConcurrentIndex struct {
		Add  bool `spec:"add"`
		Drop bool `spec:"drop"`
	} `spec:"concurrent_index"`
}

DiffOptions defines PostgreSQL specific schema diffing process.

type Driver

type Driver struct {
	schema.Differ
	schema.Inspector
	migrate.PlanApplier
	// 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

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

CheckClean implements migrate.CleanChecker.

func (*Driver) Lock

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

Lock implements the schema.Locker interface.

func (*Driver) NormalizeRealm

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

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

NormalizeSchema returns the normal representation of the given database.

func (*Driver) Snapshot

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

Snapshot implements migrate.Snapshoter.

func (*Driver) Version

func (d *Driver) Version() string

Version returns the version of the connected database.

type Enum

type Enum struct {
	Name   string         `spec:",name"`
	Schema *schemahcl.Ref `spec:"schema"`
	Values []string       `spec:"values"`
	schemahcl.DefaultExtension
}

Enum holds a specification for an enum, that can be referenced as a column type.

type Identity

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

Identity defines an identity column.

type IndexColumnProperty

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

IndexColumnProperty describes an index column property. https://postgresql.org/docs/current/functions-info.html#FUNCTIONS-INFO-INDEX-COLUMN-PROPS

type IndexInclude

type IndexInclude struct {
	schema.Attr
	Columns []*schema.Column
}

IndexInclude describes the INCLUDE clause allows specifying a list of column which added to the index as non-key columns. https://www.postgresql.org/docs/current/sql-createindex.html

type IndexOpClass

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

IndexOpClass describers operator class of the index part. https://www.postgresql.org/docs/current/indexes-opclass.html.

func (*IndexOpClass) DefaultFor

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

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

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

func (*IndexOpClass) String

func (o *IndexOpClass) String() string

String returns the string representation of the operator class.

func (*IndexOpClass) UnmarshalText

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

UnmarshalText parses the operator class from its string representation.

type IndexPredicate

type IndexPredicate struct {
	schema.Attr
	P string
}

IndexPredicate describes a partial index predicate. https://postgresql.org/docs/current/catalog-pg-index.html

type IndexStorageParams

type IndexStorageParams struct {
	schema.Attr
	// 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. https://postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-STORAGE-PARAMETERS

type IndexType

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

IndexType represents an index type. https://postgresql.org/docs/current/indexes-types.html

type IntervalType

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

IntervalType defines an interval type. https://postgresql.org/docs/current/datatype-datetime.html

type NetworkType

type NetworkType struct {
	schema.Type
	T   string
	Len int64
}

A NetworkType defines a network type. https://postgresql.org/docs/current/datatype-net-types.html

type NoInherit

type NoInherit struct {
	schema.Attr
}

NoInherit attribute defines the NO INHERIT flag for CHECK constraint. https://postgresql.org/docs/current/catalog-pg-constraint.html

type OIDType

type OIDType struct {
	schema.Type
	T string
}

OIDType defines an object identifier type.

type Partition

type Partition struct {
	schema.Attr
	// 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

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 RangeType

type RangeType struct {
	schema.Type
	T string
}

A RangeType defines a range type. https://www.postgresql.org/docs/current/rangetypes.html

type Sequence

type Sequence struct {
	Start, Increment int64
	// Last sequence value written to disk.
	// https://postgresql.org/docs/current/view-pg-sequences.html.
	Last int64
}

Sequence defines (the supported) sequence options. https://postgresql.org/docs/current/sql-createsequence.html

type SerialType

type SerialType struct {
	schema.Type
	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. https://postgresql.org/docs/current/datatype-numeric.html#DATATYPE-SERIAL

func (*SerialType) IntegerType

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

IntegerType returns the underlying integer type this serial type represents.

func (*SerialType) SetType

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

SetType sets the serial type from the given integer type.

type TextSearchType

type TextSearchType struct {
	schema.Type
	T string
}

A TextSearchType defines full text search types. https://www.postgresql.org/docs/current/datatype-textsearch.html

type UUIDType

type UUIDType = schema.UUIDType

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

type UserDefinedType

type UserDefinedType struct {
	schema.Type
	T string
}

UserDefinedType defines a user-defined type attribute.

type XMLType

type XMLType struct {
	schema.Type
	T string
}

A XMLType defines an XML type.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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