desc

package
v1.0.17 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 22 Imported by: 1

Documentation

Overview

Package desc holds the descriptors and SQL builders behind the pg package's `pg:"..."` struct-tag parsing: Table and Column definitions, the query builders that turn a Table (and, where relevant, a struct value) into CREATE TABLE, INSERT, UPDATE, DELETE and EXISTS statements, and the row-scanning code that maps a query's result rows back onto a struct. Most applications consume this package only indirectly, through pg.DB and pg.Repository[T]; it is exported mainly for the gen subpackage and for callers that need to inspect or build table/column definitions directly (e.g. a custom TableFilter).

Index

Constants

View Source
const DefaultInsertBatchSize = 500

DefaultInsertBatchSize is the default maximum number of rows per bulk-insert statement. Kept well below Postgres's 65535 bind-param ceiling so even wide structs (dozens of columns) fit without splitting mid-statement. Callers with unusually wide rows should pick a smaller size to stay under 65535 / columns.

Variables

View Source
var (
	// DefaultTag is the default struct field tag.
	DefaultTag = "pg"
	// DefaultSearchPath is the default search path for the table.
	DefaultSearchPath = "public"
)
View Source
var (
	// ToStructName returns the struct name for the table name.
	// TODO: It can go to a NewTable function.
	ToStructName = func(tableName string) string { return PascalCase(Singular(tableName)) }
	// ToStructFieldName returns the struct field name for the column name.
	ToStructFieldName = func(columnName string) string { return PascalCase(columnName) }
	// ToColumnName returns the column name for the struct field.
	ToColumnName = func(field reflect.StructField) string { return SnakeCase(field.Name) }
)

DatabaseTableTypes is a slice of TableType that contains all the table types that are database-relative.

View Source
var ErrCopyPassword = errors.New("desc: table hashes its password column in the database via crypt()/gen_salt(); COPY cannot run SQL functions per row - use InsertMany, or install a Go-side PasswordHandler")

ErrCopyPassword is returned by BuildCopyPlan when a table has a password column that PostgreSQL itself hashes on insert: via the crypt($N, gen_salt('<PasswordAlg>')) SQL fragment buildInsertPassword embeds into BuildInsertQuery/BuildBulkInsertQuery whenever Table.PasswordHandler has no Go-side Encrypt func. The COPY protocol streams raw column values straight into the table and cannot invoke a SQL function per row the way a regular INSERT can, so that db-side hashing path has no COPY equivalent at all.

Callers that hit ErrCopyPassword have two ways out: fall back to Repository.InsertMany / DB.InsertSingle for this table (both still support the db-side crypt() path), or install a Go-side desc.PasswordHandler via Schema.HandlePassword so BuildCopyPlan can encrypt the password itself, in Go, before handing each row to COPY.

View Source
var PasswordAlg = "bf" // max password length: 72, salt bits: 128, output length: 60, blowfish-based.

PasswordAlg is the password algorithm the library uses to tell postgres how to generate a password field's salt, via pgcrypto's gen_salt('<PasswordAlg>'), embedded verbatim into the crypt($N, gen_salt('<PasswordAlg>')) SQL fragment built by buildInsertPassword whenever a password column is inserted/updated without a PasswordHandler (i.e. postgres, not this library, does the hashing).

Allowed values: "bf" (default, blowfish-based), "md5", "xdes", "des". Every query that would embed PasswordAlg calls validatePasswordAlg first and fails with an error for any other value, including one crafted to break out of the surrounding SQL string literal, instead of interpolating it.

PasswordAlg must be set once, during program initialization (e.g. in an init func, or before the first query touching a password column is built), and never mutated concurrently with query building: it's a package-level variable read without synchronization by every insert/ update that has a password column.

Functions

func BuildAlterTableForeignKeysQueries

func BuildAlterTableForeignKeysQueries(td *Table) []string

BuildAlterTableForeignKeysQueries creates ALTER TABLE queries for adding foreign key constraints.

func BuildBulkInsertQuery added in v1.0.13

func BuildBulkInsertQuery(td *Table, structValues []reflect.Value, forceOnConflictExpr string, upsert bool) (string, []any, error)

BuildBulkInsertQuery builds a single multi-row INSERT statement for the given struct values. All values must be of the same type as td.

Semantics mirror BuildInsertQuery for every individual row:

  • Columns marked AutoGenerated or Presenter are never written.
  • A zero-valued field whose column carries a DB default is emitted as the literal DEFAULT keyword (not a parameter) so the default fires (e.g. clock_timestamp() for audit columns, gen_random_uuid() for UUID primary keys).
  • Password columns are handled identically to the single-row path.

The column set is the union of columns any row would write. The header is computed once from td, and per-row the value is either a $N placeholder or DEFAULT. This keeps the header stable across rows while still honoring per-row "skip zero" semantics.

Pair with DB.InsertMany / Repository.InsertMany which batch this at DefaultInsertBatchSize to stay under Postgres's 65535 bind-param cap.

func BuildBulkInsertQueryOnConflict added in v1.0.13

func BuildBulkInsertQueryOnConflict(td *Table, structValues []reflect.Value, oc OnConflict) (string, []any, error)

BuildBulkInsertQueryOnConflict is BuildBulkInsertQuery with an explicit OnConflict specification instead of the tag-driven forceOnConflictExpr/upsert behavior. Column selection, DEFAULT-vs-placeholder emission and password handling are identical to BuildBulkInsertQuery; only ON CONFLICT derivation differs, via the same oc.Columns/oc.Constraint/oc.DoNothing/ oc.SetColumns/oc.SetWhere rules BuildInsertQueryOnConflict uses. Like BuildBulkInsertQuery, it never appends RETURNING. Pair it with Repository.InsertOnConflict, not a variant that scans a primary key back.

func BuildCreateTableQuery

func BuildCreateTableQuery(td *Table) string

BuildCreateTableQuery creates a table in the database according to the given table definition.

func BuildDeleteQuery

func BuildDeleteQuery(td *Table, values []any) (string, []any, error)

BuildDeleteQuery builds and returns a SQL query for deleting one or more rows from a table.

func BuildDuplicateQuery added in v1.0.6

func BuildDuplicateQuery(td *Table, idPtr any) (string, error)

BuildDuplicateQuery returns a query that duplicates a row by its primary key.

func BuildExistsQuery

func BuildExistsQuery(td *Table, structValue reflect.Value) (string, []any, error)

BuildExistsQuery builds and returns an SQL query for checking of existing in a row in the table, based on the given struct value.

func BuildInsertQuery

func BuildInsertQuery(td *Table, structValue reflect.Value, idPtr any, forceOnConflictExpr string, upsert bool) (string, []any, error)

BuildInsertQuery builds and returns an SQL query for inserting a row into the table, based on the given struct value, arguments, and returning column. The struct value is a reflect.Value of the struct that represents the row to be inserted. The arguments are a slice of Argument that contains the column definitions and values for each field of the struct. The returning column is an optional string that specifies which column to return after the insertion, such as the primary key or any other generated value.

func BuildInsertQueryOnConflict added in v1.0.13

func BuildInsertQueryOnConflict(td *Table, structValue reflect.Value, idPtr any, oc OnConflict) (string, []any, error)

BuildInsertQueryOnConflict is BuildInsertQuery with an explicit OnConflict specification instead of the tag-driven forceOnConflictExpr/upsert behavior: oc.Columns or oc.Constraint (or, if both are empty, the struct's tag-derived unique/unique_index target) becomes the ON CONFLICT target, and oc.DoNothing / oc.SetColumns / oc.SetWhere control the DO NOTHING / DO UPDATE SET action.

Unlike BuildInsertQuery, which only appends RETURNING for a DO UPDATE action, BuildInsertQueryOnConflict always appends RETURNING <primary key> when idPtr is non-nil and there is a conflict target: a DO NOTHING that skips the row then yields zero returned rows, which callers such as Repository.InsertSingleOnConflict surface as ErrNoRows instead of a stale idPtr.

func BuildUpdateQuery

func BuildUpdateQuery(value any, columnsToUpdate []string, reportNotFound bool, primaryKey *Column) (string, []any, error)

BuildUpdateQuery builds and returns an SQL query for updating a row in the table, using the given struct value and the primary key.

func ConvertRowsToStruct

func ConvertRowsToStruct(td *Table, rows pgx.Rows, valuePtr any) error

ConvertRowsToStruct takes a table definition, a row of data from a database query, and a generic type T and returns a value of type T with the fields populated from the row data.

func ExtractPrimaryKeyValue added in v1.0.6

func ExtractPrimaryKeyValue(primaryKey *Column, structValue reflect.Value) (any, error)

ExtractPrimaryKeyValue takes a column definition and a reflect value of a struct

func IndirectType

func IndirectType(typ reflect.Type) reflect.Type

IndirectType returns the value of a pointer-type "typ". If "typ" is a pointer, array, chan, map or slice it returns its Elem, otherwise returns the "typ" as it is.

func IndirectValue

func IndirectValue(v any) reflect.Value

IndirectValue returns the element type (e.g. if pointer of *User it will return the User type).

func PascalCase

func PascalCase(snake string) string

PascalCase converts a given string to a friendly pascal case, e.g. - user_id to UserID - id to ID - provider_api_key to ProviderAPIKey - customer_provider to CustomerProvider

func RegisterDataType

func RegisterDataType(t DataType, names ...string)

RegisterDataType registers a new data type with the given names. It panics if the data type or any of the names already exists. This function is used to extend the supported data types by custom ones.

func Singular

func Singular(s string) string

Singular returns the singular form of the given string.

func SnakeCase

func SnakeCase(camel string) string

SnakeCase converts a given string to a friendly snake case, e.g. - userId to user_id - ID to id - ProviderAPIKey to provider_api_key - Option to option - URL to url

Types

type Argument

type Argument struct {
	Column *Column // the column definition for the argument
	Value  any     // the value for the argument
}

Argument represents a single argument for a database query It contains a column definition and a value.

type Arguments

type Arguments []Argument

Arguments is a slice of Argument.

func (*Arguments) ShiftEnd added in v1.0.3

func (args *Arguments) ShiftEnd(arg Argument)

ShiftEnd moves the argument with the given column name to the end of the slice.

func (Arguments) Values

func (args Arguments) Values() []any

Values returns a slice of values from the arguments.

type CheckConstraint

type CheckConstraint struct {
	// Expression is the CHECK constraint's boolean SQL expression, with the outer
	// CHECK(...) wrapper stripped.
	Expression string
}

CheckConstraint is a type that represents a check constraint.

type Column

type Column struct {
	Table            *Table    // the parent table reference.
	TableName        string    // the name of the table this column lives at.
	TableDescription string    // the description of the table this column lives at.
	TableType        TableType // the type of the table this column lives at.

	Name            string       // the name of the column
	Type            DataType     // the data type of the column
	Description     string       // the description of the column
	OrdinalPosition int          // the position (starting from 1) of the corresponding column in the table.
	FieldIndex      []int        // the index of the corresponding struct field
	FieldType       reflect.Type // the reflect.Type of the corresponding struct field

	/* if nil then wasn't able to resolve it by builtin method */
	FieldName    string // the name of the corresponding struct field
	TypeArgument string // an optional argument for the data type, e.g. 255 when Type is "varchar"
	PrimaryKey   bool   // a flag that indicates if the column is a primary key
	Identity     bool   // a flag that indicates if the column is an identity column, e.g. INT GENERATED ALWAYS AS IDENTITY
	// Required        bool         // a flag that indicates if the column is required (not null, let's just use the !Nullable)
	Default         string // an optional default value or sql function for the column
	CheckConstraint string // an optional check constraint for the column
	Unique          bool   // a flag that indicates if the column has a unique constraint (postgres automatically adds an index for that single one)
	// As tested, the unique=true and a single column of unique_index is the same result in the database on table creation,
	// note that because the generator does store unique_index instead of simple unique on Go generated source files.
	Conflict string // an optional conflict action for the unique constraint, e.g do nothing

	// If true this and password field is used to SelectByUsernameAndPassword repository method.
	Username bool
	// If true Postgres handles password encryption (on inserts) and decryption (on selects),
	// note that you MUST set the Schema.HandlePassword in order for this to work by both ways.
	// A flag that indicates if the column is a password column.
	Password bool
	// If true it's a shorthand of default="null".
	Nullable            bool   // a flag that indicates if the column is nullable
	ReferenceTableName  string // an optional reference table name for a foreign key constraint, e.g. user_profiles(id) -> user_profiles
	ReferenceColumnName string // an optional reference column name for a foreign key constraint, e.g. user_profiles(id) -> id
	DeferrableReference bool   // a flag that indicates if the foreign key constraint is deferrable (omits foreign key checks on transactions)
	ReferenceOnDelete   string // an optional action for deleting referenced rows when referencing rows are deleted, e.g. NO ACTION, RESTRICT, CASCADE, SET NULL and SET DEFAULT. Defaults to CASCADE.

	Index IndexType // an optional index type for the column

	// Unique indexes can really improve the performance on big data select queries
	// Read more at: https://www.postgresql.org/docs/current/indexes-unique.html
	UniqueIndex string // an optional name for a unique index on the column
	// If true then create table, insert, update and duplicate queries will omit this column.
	Presenter bool
	// If true then insert query will omit this column.
	AutoGenerated bool
	// GeneratedExpression is the SQL expression for a GENERATED ALWAYS AS (...) STORED column.
	// It sets AutoGenerated to true automatically.
	// When non-empty, the column is created as a stored generated column and excluded from INSERT/UPDATE.
	// E.g. pg:"type=int,generated=EXTRACT(EPOCH FROM prepare_duration)::int / 60"
	GeneratedExpression string
	// If true then this column->struct value is skipped from the Select queries
	Unscannable bool // a flag that indicates if the column is unscannable
	// contains filtered or unexported fields
}

Column is a type that represents a column definition for the database.

func (*Column) FieldTagString

func (c *Column) FieldTagString(strict bool) string

FieldTagString returns a string representation of the struct field tag for the column.

func (*Column) IsGenerated added in v1.0.6

func (c *Column) IsGenerated() bool

IsGenerated returns true if the column is a generated column.

func (*Column) IsGeneratedPrimaryUUID

func (c *Column) IsGeneratedPrimaryUUID() bool

IsGeneratedPrimaryUUID returns true if the column is a primary UUID column and has a default value of "gen_random_uuid()" or "uuid_generate_v4()".

func (*Column) IsGeneratedTimestamp

func (c *Column) IsGeneratedTimestamp() bool

IsGeneratedTimestamp returns true if the column is a timestamp column and has a default value of "clock_timestamp()" or "now()".

type ColumnBasicInfo

type ColumnBasicInfo struct {
	// TableName is the name of the table this column belongs to.
	TableName string
	// TableDescription is the table's comment/description, as reported by the database.
	TableDescription string
	// TableType is the kind of table (base table, view, materialized view, ...) this
	// column belongs to.
	TableType TableType
	// Name is the column's name.
	Name string
	// OrdinalPosition is the column's 1-based position within the table.
	OrdinalPosition int
	// Description is the column's comment/description, as reported by the database.
	Description string
	// Default is the column's default value or expression, as reported by the database.
	Default string
	// DataType is the column's parsed data type.
	DataType DataType
	// DataTypeArgument is an optional argument for DataType, e.g. "255" for a varchar(255).
	DataTypeArgument string
	// IsNullable reports whether the column accepts NULL values.
	IsNullable bool
	// IsIdentity reports whether the column is an identity column (GENERATED ALWAYS/BY
	// DEFAULT AS IDENTITY).
	IsIdentity bool
	// IsGenerated reports whether the column is a stored generated column
	// (GENERATED ALWAYS AS (...) STORED).
	IsGenerated bool
	// GenerationExpression is the generation expression for a generated column; it is
	// only meaningful when IsGenerated is true.
	GenerationExpression string
}

ColumnBasicInfo represents a basic column information, contains the table name, column name, ordinal position, column default value, data type, data type argument, whether the column is nullable, whether the column is identity and whether the column is generated.

func (*ColumnBasicInfo) BuildColumn

func (c *ColumnBasicInfo) BuildColumn(column *Column) error

BuildColumn implements the ColumnBuilder interface: it copies c's fields onto column, deriving column's FieldIndex, FieldName and, where resolvable, FieldType from c's OrdinalPosition, Name and DataType respectively.

type ColumnBuilder

type ColumnBuilder interface {
	BuildColumn(*Column) error
}

ColumnBuilder is an interface that is used to build a column definition.

type ColumnFilter

type ColumnFilter func(*Column) bool

ColumnFilter is a function that returns whether this column should be live inside a table.

type Constraint

type Constraint struct {
	// TableName is the name of the table this constraint belongs to.
	TableName string
	// ColumnName is the name of the column this constraint applies to. For a plain
	// (non-unique) index row it is empty immediately after scanning (see ListConstraints),
	// but Build, which ListConstraints always calls right after scanning, fills it in
	// from the constraint definition for the common single-column index case; it stays
	// empty only when the definition doesn't match Build's simple single-column index
	// pattern (e.g. a composite/multi-column index).
	ColumnName string

	// ConstraintName is the name of the constraint, as reported by the database.
	ConstraintName string
	// ConstraintType classifies the constraint (primary key, unique, foreign key, check
	// or plain index) and determines which of Unique, Check and ForeignKey, if any, Build
	// populates.
	ConstraintType ConstraintType

	// IndexType is the access method (btree, gin, ...) backing the constraint's index,
	// when ConstraintType is IndexConstraintType.
	IndexType IndexType

	// Unique holds the parsed definition when ConstraintType is UniqueConstraintType.
	Unique *UniqueConstraint
	// Check holds the parsed definition when ConstraintType is CheckConstraintType.
	Check *CheckConstraint
	// ForeignKey holds the parsed definition when ConstraintType is ForeignKeyConstraintType.
	ForeignKey *ForeignKeyConstraint
	// contains filtered or unexported fields
}

Constraint is a type that represents a constraint.

func (*Constraint) Build

func (c *Constraint) Build(constraintDefinition string)

Build implements the ColumnBuilder interface.

func (*Constraint) BuildColumn

func (c *Constraint) BuildColumn(column *Column) error

BuildColumn implements the ColumnBuilder interface.

It returns a descriptive error (naming the constraint and its raw, unparsed definition) instead of panicking, when the constraint's definition could not be parsed into its typed sub-struct (Unique, Check or ForeignKey is nil). That can happen for constraint shapes the parsing regexes don't cover yet, e.g. composite/multi-column foreign keys, multiline CHECK expressions or schema-qualified references; see parseCheckConstraint and parseForeignKeyConstraint. Callers (e.g. DB.ListColumns) must check and propagate this error rather than discard it, since it can be reached at connect time via DB.CheckSchema.

func (*Constraint) String

func (c *Constraint) String() string

String implements the fmt.Stringer interface.

If the constraint's definition could not be parsed into its typed sub-struct (Unique, Check or ForeignKey is nil: see Build/parseCheckConstraint/parseForeignKeyConstraint), String returns a placeholder built from the raw, unparsed definition instead of panicking.

type ConstraintType

type ConstraintType uint8

ConstraintType is a type that represents a constraint type.

const (
	// NoneConstraintType is a constraint type that represents no constraint.
	NoneConstraintType ConstraintType = iota
	// PrimaryKeyConstraintType is a constraint type that represents a primary key constraint.
	PrimaryKeyConstraintType
	// UniqueConstraintType is a constraint type that represents a unique constraint.
	UniqueConstraintType
	// ForeignKeyConstraintType is a constraint type that represents a foreign key constraint.
	ForeignKeyConstraintType
	// CheckConstraintType is a constraint type that represents a check constraint.
	CheckConstraintType
	// IndexConstraintType is a constraint type that represents a simple index constraint.
	IndexConstraintType // A custom type to represent a simple index, see ListConstraints.
)

func (*ConstraintType) Scan

func (t *ConstraintType) Scan(src any) error

Scan implements the sql.Scanner interface.

type CopyPlan added in v1.0.13

type CopyPlan struct {
	// ColumnNames is the ordered list of columns the COPY statement will receive, the same
	// order Row returns its values in. It never includes an AutoGenerated or Presenter column
	// (mirroring Table.NumInsertableColumns/BuildBulkInsertQuery's column-selection predicate),
	// and it omits any Default-bearing column BuildCopyPlan determined was zero in every row of
	// the plan.
	ColumnNames []string
	// contains filtered or unexported fields
}

CopyPlan holds the precomputed column list and per-row value extraction for a COPY FROM of a table's struct values, built once by BuildCopyPlan and then replayed for every row via Row.

Unlike a single- or multi-row INSERT, a COPY statement has no per-row DEFAULT: a column is either present in every row of the stream or entirely absent from it, and PostgreSQL only applies a column's DB-side default to a column that is completely missing from the COPY column list, never to an individual row within an included column. See BuildCopyPlan's doc for exactly how CopyPlan resolves that per-column, all-or-nothing decision from per-row zero-value data, including its loudly documented divergence from InsertMany: a zero value in a column BuildCopyPlan decides to include is copied as that zero value, verbatim, never as DEFAULT.

func BuildCopyPlan added in v1.0.13

func BuildCopyPlan(td *Table, structValues []reflect.Value) (*CopyPlan, error)

BuildCopyPlan computes the COPY column list for the given rows of td and validates that the table's columns are representable under the COPY protocol, returning a *CopyPlan ready to extract each row's values via Row. structValues must be non-empty and every value must be a reflect.Value of (or addressable to) td's registered struct type, exactly as BuildBulkInsertQuery expects.

Column selection proceeds in three steps:

  1. Columns marked AutoGenerated or Presenter are skipped entirely: the exact predicate Table.NumInsertableColumns encodes and BuildBulkInsertQuery's column loop uses, kept in sync with both.

  2. A password column requires a Go-side Table.PasswordHandler (installed via Schema.HandlePassword) to be usable under COPY at all: see ErrCopyPassword's doc for why. A password column with no working PasswordHandler makes BuildCopyPlan return ErrCopyPassword immediately, before step 3 runs for any column.

  3. Every remaining column with no Default is always included, verbatim, for every row. A column that DOES carry a non-empty Default gets one reflection pre-pass over every row in structValues, using wouldDefaultForRow: if every row's value for that column would have triggered DEFAULT under BuildBulkInsertQuery, the column is omitted from ColumnNames entirely, so PostgreSQL applies the column's own DB-side default (e.g. clock_timestamp(), gen_random_uuid()) to every row of the COPY. COPY only ever applies a default to a column that is completely absent from its column list. If even a single row's value is non-zero, the column is included instead, and Row sends EVERY row's value for it verbatim, including the zero-valued rows.

Unlike BuildBulkInsertQuery (which can never drop a column, since a zero-valued row just swaps in a literal DEFAULT token instead of omitting the column), step 3 above CAN end up omitting every remaining column, if every one of them carries a Default and is zero across the whole batch. BuildCopyPlan detects that case and returns a descriptive error rather than building a CopyPlan with an empty ColumnNames, which would otherwise reach PostgreSQL as a COPY statement with an empty column list and fail with a raw syntax error instead.

That last point is the sharpest divergence from InsertMany/BuildBulkInsertQuery, which decide DEFAULT-vs-value independently for each row: under COPY there is no per-row DEFAULT keyword, so a "mostly defaulted, occasionally set" column is only representable by including the column and sending its zero value literally for the rows that would otherwise have been defaulted. A zero value in an included column is therefore stored as the literal zero (e.g. an all-zeros UUID, or the timestamp's zero time.Time), never as DEFAULT. A caller that needs the DB default to fire for individual zero-valued rows of a column that is not all-zero across the whole batch must use InsertMany for that load instead of CopyFrom.

func (*CopyPlan) Row added in v1.0.13

func (p *CopyPlan) Row(structValue reflect.Value) ([]any, error)

Row extracts (and, for a Go-side password handler, encrypts) the COPY values of one struct value, in ColumnNames order, ready to hand straight to pgx.CopyFromSlice/pgx.CopyFromFunc as that row's []any.

A password column reaching Row is necessarily backed by a working Table.PasswordHandler (see BuildCopyPlan, which returns ErrCopyPassword before Row is ever called for a table that lacks one): Row encrypts it here, per row, exactly like the single- and multi-row INSERT paths do - the field must be a non-empty string, or Row returns an error naming the offending column, matching extractArguments's (desc/argument.go) and writeBulkInsertHeaderAndValues's (desc/insert_query.go) own password validation error text.

type DataType

type DataType uint8

DataType represents the sql data type for a column.

const (
	InvalidDataType DataType = iota // InvalidDataType is a placeholder for an invalid data type.
	BigInt                          // BigInt represents a signed 64-bit integer.
	BigIntArray                     // BigIntArray represents an array of signed 64-bit integers.
	BigSerial                       // BigSerial represents a 64-bit auto-incrementing integer.
	Bit                             // Bit represents a fixed-length bit string.
	BitVarying                      // BitVarying represents a variable-length bit string.
	Boolean                         // Boolean represents a logical value (true or false).
	Box                             // Box represents a rectangular box on a plane.
	Bytea                           // Bytea represents a binary string (byte array).
	Character                       // Character represents a fixed-length character string.
	CharacterArray
	CharacterVarying      // CharacterVarying represents a variable-length character string.
	CharacterVaryingArray // CharacterVaryingArray represents an array of variable-length character strings.
	Cidr                  // Cidr represents an IPv4 or IPv6 network address.
	Circle                // Circle represents a circle on a plane.
	Date                  // Date represents a calendar date (year, month, day).
	DoublePrecision       // DoublePrecision represents a double-precision floating-point number (8 bytes).
	Inet                  // Inet represents an IPv4 or IPv6 host address.
	Integer               // Integer represents a signed 32-bit integer.
	IntegerArray          // IntegerArray represents an array of signed 32-bit integers.
	IntegerDoubleArray    // IntegerDoubleArray represents an array of arrays of signed 32-bit integers.
	Array                 // Array represents an array of any dimension.
	Interval              // Interval represents a time span.
	JSON                  // JSON represents a JSON data structure in text format.
	JSONB                 // JSONB represents a JSON data structure in binary format.
	Line                  // Line represents an infinite line on a plane.
	Lseg                  // Lseg represents a line segment on a plane.
	MACAddr               // MACAddr represents a MAC (Media Access Control) address (6 bytes).
	MACAddr8              // MACAddr8 represents an EUI-64 MAC address (8 bytes).
	Money                 // Money represents a currency amount with fixed fractional precision.
	Numeric               // Numeric represents an exact numeric value with variable precision and scale.
	Path                  // Path represents a geometric path on a plane. It can be open or closed, and can have multiple subpaths.
	PgLSN                 // PgLSN represents a PostgreSQL Log Sequence Number, which is used to identify log positions in the write-ahead log (WAL).
	Point                 // Point represents a geometric point on a plane. It has two coordinates: x and y.
	Polygon               // Polygon represents a closed geometric path on a plane. It consists of one or more points that form the vertices of the polygon.
	Real                  // Real represents a single-precision floating-point number (4 bytes).
	SmallInt              // SmallInt represents a signed 16-bit integer.
	SmallSerial           // SmallSerial represents a 16-bit auto-incrementing integer.
	Serial                // Serial represents a 32-bit auto-incrementing integer.
	Text                  // Text represents a variable-length character string with unlimited length.
	TextArray             // TextArray represents an array of variable-length character strings with unlimited length.
	TextDoubleArray       // TextDoubleArray represents an array of arrays of variable-length character strings with unlimited length.
	Time                  // Time represents the time of day (without time zone).
	TimeTZ                // TimeTZ represents the time of day (with time zone).
	Timestamp             // Timestamp represents the date and time of day (without time zone).
	TimestampTZ           // TimestampTZ represents the date and time of day (with time zone).
	TsQuery               // TsQuery represents a text search query that can be used to search tsvector values.
	TsVector              // TsVector represents a text search document that contains lexemes and their positions.
	TxIDSnapshot          // TxIDSnapshot represents the state of transactions at some point in time. It can be used to implement multiversion concurrency control (MVCC).
	UUID                  // UUID represents an universally unique identifier (16 bytes).
	UUIDArray             // UUIDArray represents an array of universally unique identifiers (16 bytes).
	XML                   // XML represents an XML data structure in text format.
	// Multiranges: https://www.postgresql.org/docs/14/rangetypes.html#RANGETYPES-BUILTIN.
	Int4Range // Range of integer, int4multirange.
	Int4MultiRange
	Int8Range // Range of bigint, int8multirange.
	Int8MultiRange
	NumRange // Range of numeric, nummultirange.
	NumMultiRange
	TsRange // Range of timestamp without time zone, tsmultirange.
	TsMultirange
	TsTzRange // Range of timestamp with time zone, tstzmultirange.
	TsTzMultiRange
	DateRange // Range of date, datemultirange.
	DateMultiRange
	//
	CIText // CIText is an extension data type that provides case-insensitive
	HStore // hstore is an extension data type that provides key-value into a single column.
)

Available data types.

func ParseDataType

func ParseDataType(s string) (DataType, string)

ParseDataType converts a string to a DataType value, ignoring case and parentheses. It returns Invalid if the string does not match any of the registered data types.

func (DataType) GoType

func (t DataType) GoType() reflect.Type

GoType returns the Go type for the data type.

func (DataType) IsArray

func (t DataType) IsArray() bool

IsArray returns true if the data type is an array.

func (DataType) IsString

func (t DataType) IsString(s string) bool

IsString returns true if the given string matches any of the names of the data type, ignoring case and whitespace.

func (DataType) IsTime added in v1.0.7

func (t DataType) IsTime() bool

IsTime returns true if the data type is a time type.

func (DataType) String

func (t DataType) String() string

String returns the first name of the data type, or a formatted string if the data type is unexpected.

type Expression

type Expression struct {
	// Input is the raw filter expression text, e.g. "customers.email" or
	// "customer_profiles.fields.jsonb", parsed by parseColumnFilterExpression.
	Input string
	// ResultFieldType, when non-nil, overrides the matched column(s)' FieldType.
	ResultFieldType reflect.Type
}

Expression is a filter expression.

func NewExpression

func NewExpression(input string, fieldType reflect.Type) Expression

NewExpression returns a new Expression.

type Expressions

type Expressions []Expression

Expressions is a slice of expressions.

func (Expressions) FilterTable

func (expressions Expressions) FilterTable(t *Table) bool

FilterTable implements the TableFilter interface.

FilterTable panics if any of the expressions' Input strings is not a well-formed filter expression. It cannot return an error instead, since the exported TableFilter interface's FilterTable(*Table) bool signature has no error return, but the panic value is always a wrapped, descriptive error naming the offending expression, so a recovering caller (see pg.DB.ListTables, which uses an unexported safeFilterTable helper) can turn it back into a normal error rather than a raw panic value.

type ForeignKeyConstraint

type ForeignKeyConstraint struct {
	ColumnName          string // The column that holds the foreign key.
	ReferenceTableName  string // The table that is referenced.
	ReferenceColumnName string // The column in the referenced table.
	OnDelete            string // Action to take when the referenced row is deleted.
	OnUpdate            string // Action to take when the referenced row is updated.
	Deferrable          bool   // Whether the constraint is deferrable.
}

ForeignKeyConstraint represents a foreign key definition for a column.

A foreign key establishes a link between two tables based on a column or a set of columns. It may specify actions to be taken when the referenced row is deleted or updated, such as CASCADE, RESTRICT, NO ACTION, SET NULL, or SET DEFAULT. The constraint can also be marked as deferrable, meaning that its verification can be postponed until the end of a transaction rather than being checked immediately.

type Index

type Index struct {
	// TableName is the name of the table the index belongs to.
	TableName string
	// ColumnName is the name of the column the index is built on.
	ColumnName string

	// Name is the index's name, e.g. "<table>_<column>_idx" or "<table>_pkey".
	Name string
	// Type is the index's access method (btree, gin, ...).
	Type IndexType
}

Index is a type that represents an index definition for a column. An index is a data structure that improves the speed of data retrieval operations on a table. An index can be of different types, such as B-tree, hash, etc.

type IndexType

type IndexType uint8

IndexType is an enumeration type that represents different types of indexes in a database.

const (
	InvalidIndex IndexType = iota // InvalidIndex is the zero value for IndexType and indicates an invalid or unknown index type
	Btree                         // Btree is an index type that uses a balanced tree data structure
	Hash                          // Hash is an index type that uses a hash table data structure
	Gist                          // Gist is an index type that supports generalized search trees for various data types
	Spgist                        // Spgist is an index type that supports space-partitioned generalized search trees for various data types
	Gin                           // Gin is an index type that supports inverted indexes for various data types
	Brin                          // Brin is an index type that supports block range indexes for large tables
)

These are the possible values for IndexType.

func (*IndexType) Scan

func (t *IndexType) Scan(src any) error

Scan implements the sql.Scanner interface. A nil src or empty string leaves t unchanged; any other src must be a string matching one of the known index type names (see indexTypeText), or Scan returns an error.

func (IndexType) String

func (t IndexType) String() string

String returns the string representation of an IndexType value.

type OnConflict added in v1.0.13

type OnConflict struct {
	// Columns is the conflict-target column list, e.g. []string{"a", "b"} for
	// ON CONFLICT (a,b). Each name is validated against the table (case-insensitively, like
	// Table.GetColumnByName) and emitted quoted via pgx.Identifier.Sanitize. Empty (with an
	// empty Constraint) falls back to the struct's unique/unique_index tag derivation, exactly
	// as BuildInsertQuery/BuildBulkInsertQuery derive it for Upsert, including silently
	// producing a plain insert (no ON CONFLICT clause at all) if the struct declares no such
	// tag, so a real duplicate raises the database's own unique-violation error.
	Columns []string
	// Constraint targets ON CONSTRAINT <name> instead of a column list; mutually exclusive with
	// Columns (BuildInsertQueryOnConflict/BuildBulkInsertQueryOnConflict return an error if both
	// are set). It is quoted via pgx.Identifier.Sanitize but not otherwise validated. Table
	// descriptors don't track constraint names.
	Constraint string
	// DoNothing emits DO NOTHING instead of DO UPDATE. It cannot be combined with SetColumns or
	// SetWhere (both imply a DO UPDATE). Doing so is a validation error.
	DoNothing bool
	// SetColumns lists the columns updated as col = EXCLUDED.col on a DO UPDATE, in the given
	// order. Each name is validated and quoted the same way Columns is. Empty means every
	// inserted column outside the conflict target is updated (the current Upsert behavior).
	SetColumns []string
	// SetWhere is an optional raw SQL predicate appended as " WHERE <SetWhere>" after the DO
	// UPDATE SET list, and may reference EXCLUDED.* and the table's own columns (e.g. to only
	// overwrite a row that is actually older: "t.updated_at < EXCLUDED.updated_at"). It is
	// developer-authored SQL, written verbatim with no escaping. Never build it from
	// end-user input. Combining it with DoNothing is a validation error.
	SetWhere string
}

OnConflict describes an INSERT ... ON CONFLICT clause: the conflict target (Columns, or a named Constraint) and the action to take on a conflicting row: DO NOTHING, or DO UPDATE SET over SetColumns with an optional SetWhere predicate.

A zero-value OnConflict{} behaves like Upsert: the conflict target falls back to the struct's unique/unique_index tag derivation, and (unless DoNothing is set) every inserted column outside that target is updated from EXCLUDED.

type PasswordHandler

type PasswordHandler struct {
	// Encrypt takes a table name and a plain password as strings and returns an encrypted password as a string.
	Encrypt func(tableName, plainPassword string) (encryptedPassword string, err error)
	// Decrypt takes a table name and an encrypted password as strings and returns a plain password as a string.
	Decrypt func(tableName, encryptedPassword string) (plainPassword string, err error)
}

PasswordHandler is a type that represents a password handler for the database.

type Table

type Table struct {
	RegisteredPosition int // the position of the table in the schema

	// Type is the kind of table (base table, view, materialized view or presenter).
	Type TableType

	StructName  string       // the name of the struct that represents the table
	StructType  reflect.Type `json:"-"` // the type of the struct that represents the table
	SearchPath  string       // the search path for the table
	Name        string       // the name of the table
	Description string       // the description of the table
	Strict      bool         // if true then the select queries will return an error if a column is missing from the struct's fields
	Columns     []*Column    // a slice of pointers to Column that represents the columns of the table

	// PasswordHandler is the password handler used to encrypt/decrypt this table's
	// password column(s), set from Schema.HandlePassword when the table is registered.
	// It is nil if the schema has no password handler configured.
	PasswordHandler *PasswordHandler
}

Table is a type that represents a table definition for the database.

func ConvertStructToTable

func ConvertStructToTable(tableName string, typ reflect.Type) (*Table, error)

ConvertStructToTable takes a table name and a reflect.Type that represents a struct type and returns a pointer to a Table that represents a table definition for the database or an error if the conversion fails.

func LooseTable added in v1.0.13

func LooseTable(typ reflect.Type) (*Table, error)

LooseTable returns a cached, schema-independent *Table descriptor for typ (a struct type, or a pointer to one; it is dereferenced automatically), suitable for scanning query results into ad-hoc struct types that were never passed to Schema.Register: join results, read models, or any other SELECT whose shape doesn't correspond to a single registered table.

Unlike ConvertStructToTable (the descriptor built by Schema.Register, and the one every Repository[T] uses), LooseTable does not require a `pg` struct tag on every field: lookupFields (desc/reflect.go), which ConvertStructToTable relies on, silently skips any field without one, which is exactly why it cannot serve an untagged ad-hoc struct. LooseTable instead considers every exported field and resolves its column name, in order:

  1. The `pg` tag's "name=" option, e.g. `pg:"name=food_id"` -> "food_id".
  2. The `json` tag's name, e.g. `json:"foodId,omitempty"` -> "foodId"; a bare `json:"-"` skips the field entirely (a `json:"-,"` tag, per encoding/json's own convention, is instead read as the literal column name "-", not a skip).
  3. SnakeCase(field name) (see desc/naming.go), e.g. FoodID -> "food_id".

A field tagged `pg:"-"` is skipped outright (checked before the json tag, so a field can be hidden from LooseTable independently of its JSON marshaling). Unexported fields are always skipped.

Embedded (anonymous) struct fields are NOT promoted/flattened the way ConvertStructToTable flattens a tagged nested struct: an anonymous field becomes exactly one column of its own (named per the rules above and, being struct-kinded, normally JSON-wrapped, see below) rather than having its own fields hoisted up as top-level columns. ConvertStructToTable's flattening (lookupStructFields, desc/reflect.go) decides whether to flatten a nested struct by recursively checking whether that struct's own fields carry `pg` tags; reusing it here would silently produce nothing for an untagged ad-hoc struct (a zero-field lookupFields result), so LooseTable does not attempt it. A type that needs promoted embedded fields must be registered with Schema.Register instead, which supports it natively.

JSON auto-unmarshal: a field whose type, after removing at most one pointer indirection, has kind struct, map or slice: excluding time.Time, []byte (and *[]byte), any type where field.Type itself or a pointer to it implements sql.Scanner (the same check struct_table.go uses for every registered column, and the same interface pgx's own JSON codec special-cases ahead of its generic decode), and any type defined in github.com/jackc/pgx/v5/pgtype (e.g. pgtype.Range[T], pgtype.Array[T]: ordinary structs that do NOT implement sql.Scanner, but that pgx's own driver already scans directly from an int4range/daterange/array/... column. Marking one of them JSONB would hand pgx's native text representation, e.g. "[1,10)" or "{1,2,3}", to jsonScanner's json.Unmarshal and fail with a JSON syntax error at scan time), is marked as a JSONB column. For a non-pointer field this makes the scan path (findScanTargets, desc/scanner.go) route the column through the package's existing jsonScanner, which both decodes the JSON payload with encoding/json and tolerates a SQL NULL (jsonScanner.Scan no-ops on a nil src). For a pointer field (e.g. `Parent *ParentModel`), isPtr is left true so that branch is not entered; instead the scan path falls through to its default `Addr().Interface()` target, i.e. **ParentModel, which pgx's own pgtype.JSONCodec already decodes generically for any Go pointer-to-pointer destination (allocating the pointee on a non-null value, leaving it nil on SQL NULL), so both pointer and non-pointer struct/map/slice fields decode automatically, via two different (but both pre-existing, unmodified) code paths. Either way, `to_jsonb(x.*) AS field` and a genuine jsonb/json column both work with no extra configuration.

Every column is marked Nullable so that a plain (non-pointer) text-like field (Type Text, UUID or CharacterVarying) also benefits from the package's existing nullableScanner grace path instead of erroring on an unexpected SQL NULL. LooseTable has no schema to consult for a field's real nullability, so it conservatively assumes every column might be NULL.

The returned *Table has a zero-value Strict field (false), so scanning is intentionally non-strict: any result column with no matching field is bound to the existing no-op scanner (see convertRowsToStruct, desc/scanner.go) instead of erroring, exactly as it already does for any non-strict registered table. Its Type is TableTypePresenter, the existing TableType documented for "decod[ing] custom select queries", precisely LooseTable's purpose, so no new TableType or Table field was needed.

The result is cached per (dereferenced) reflect.Type, so repeated calls for the same type are O(1) after the first and always return the same *Table instance.

LooseTable returns an error if typ (after dereferencing any pointer) is not a struct.

Registered types are unaffected: LooseTable has no knowledge of, and never consults, any Schema: callers that already have a *Table from Schema.Register (or Schema.Get) should keep using it directly; QueryStructs/QueryStruct (the root pg package) only fall back to LooseTable when the type is not registered.

func (*Table) AddColumns

func (td *Table) AddColumns(columns ...*Column)

AddColumns adds the given columns to the table definition.

func (*Table) ColumnExists

func (td *Table) ColumnExists(name string) bool

ColumnExists returns true if the table definition contains a column.

func (*Table) FilterColumns

func (td *Table) FilterColumns(filter ColumnFilter)

FilterColumns this will modify the columns list and the columns fields. Used internally by gen tool to apply the custom type resolver into the table.

func (*Table) ForeignKeyColumnNames

func (td *Table) ForeignKeyColumnNames() []string

ForeignKeyColumnNames returns a slice of column names that have a foreign key reference to another table.

func (*Table) ForeignKeys

func (td *Table) ForeignKeys() []ForeignKeyConstraint

ForeignKeys returns a slice of ForeignKey for the table definition, based on the ReferenceTableName field of each column.

func (*Table) GetColumnByName

func (td *Table) GetColumnByName(name string) *Column

GetColumnByName returns the column definition with the given name, or nil if no such column exists in the table definition. The name comparison is case-insensitive.

func (*Table) GetHumanName added in v1.0.12

func (td *Table) GetHumanName() string

GetHumanName returns the human-friendly name of the table.

func (*Table) GetPasswordColumn

func (td *Table) GetPasswordColumn() *Column

GetPasswordColumn returns the first column marked as password.

func (*Table) GetUsernameColumn

func (td *Table) GetUsernameColumn() *Column

GetUsernameColumn returns the first column marked as username.

func (*Table) Indexes

func (td *Table) Indexes() []*Index

Indexes returns a slice of Index for the table definition, based on the Index field of each column.

func (*Table) IsReadOnly

func (td *Table) IsReadOnly() bool

IsReadOnly returns true if the table is a simple view or materialized view.

func (*Table) IsType

func (td *Table) IsType(typesToCheck ...TableType) bool

IsType returns true if the table is one of the given types (true if no typesToCheck provided).

func (*Table) JSONBuildObjectExpr added in v1.0.13

func (td *Table) JSONBuildObjectExpr(alias string) string

JSONBuildObjectExpr returns a json_build_object expression enumerating the table's scannable columns as 'col', alias."col" pairs, so embedded-object SELECTs stay in sync with the struct instead of hand-typing dozens of column names.

See SelectColumnsExpr for what "scannable" means and how alias is treated: written verbatim before each quoted column reference, never quoted or validated itself, and meant to be a short, developer-authored SQL alias rather than untrusted input. Each pair's key (the string literal on the left of the comma) is the bare column name, single-quoted; its value (on the right) is the alias-qualified, double-quoted column reference. Given a table with no scannable columns, it returns "json_build_object()".

func (*Table) ListColumnNames

func (td *Table) ListColumnNames() []string

ListColumnNames returns all the column names of the table definition, including presenters.

func (*Table) ListColumnNamesExcept added in v1.0.3

func (td *Table) ListColumnNamesExcept(except ...string) []string

ListColumnNamesExcept returns the column names of the table definition except the given ones.

func (*Table) ListColumnNamesWithoutPresenter added in v1.0.10

func (td *Table) ListColumnNamesWithoutPresenter() []string

ListColumnNamesWithoutPresenter returns the column names of the table definition.

func (*Table) ListColumnsWithoutGenerated added in v1.0.6

func (td *Table) ListColumnsWithoutGenerated() []*Column

ListColumnsWithoutGenerated returns the columns of the table definition except the generated ones.

func (*Table) ListColumnsWithoutPresenter added in v1.0.9

func (td *Table) ListColumnsWithoutPresenter() []*Column

ListColumnsWithoutPresenter returns the columns of the table definition except the presenter ones.

func (*Table) ListImportPaths

func (td *Table) ListImportPaths() []string

ListImportPaths returns a slice of import paths for the table definition, based on the FieldType field of each column.

func (*Table) NumInsertableColumns added in v1.0.13

func (td *Table) NumInsertableColumns() int

NumInsertableColumns returns the number of columns that occupy a position, either a $N bind parameter or a literal DEFAULT keyword, in the column list of a bulk-insert statement built by BuildBulkInsertQuery (desc/insert_query.go).

It mirrors, EXACTLY, BuildBulkInsertQuery's column-selection predicate (its loop over td.Columns that skips columns where c.AutoGenerated || c.Presenter is true): the two must be kept in sync, or callers that size batches from this count (e.g. Repository.InsertMany, Repository.UpsertMany) will silently drift from the SQL BuildBulkInsertQuery actually emits.

Callers use this to keep multi-row INSERT/UPSERT statements under PostgreSQL's 65535 bind-parameters-per-statement limit: max rows per batch = 65535 / NumInsertableColumns().

func (*Table) OnConflict

func (td *Table) OnConflict() (string, bool)

OnConflict returns the first (and only one valid) ON CONFLICT=$Conflict. This is used to specify what action to take when a row conflicts with an existing row in the table.

func (*Table) OrderBy added in v1.0.13

func (td *Table) OrderBy(column string, descending bool, extraColumns ...string) (string, error)

OrderBy validates a user-supplied sort column against the table's own columns plus extraColumns (for computed or aliased columns that have no *Column entry, e.g. an expression exposed under an alias in the SELECT list) and returns a quoted `"column" ASC|DESC` fragment that is safe to splice directly into an ORDER BY clause.

Dynamic ORDER BY cannot be a bind parameter. PostgreSQL only accepts $N placeholders where a value is expected, not where an identifier is (see jackc/pgx#885), so a caller that lets a user pick the sort column has no way to parameterize it. The safe alternative is to validate the column against an allowlist and then quote it, never to concatenate the raw input into SQL; OrderBy does exactly that in one call, so callers stop hand-maintaining per-endpoint allowlist globals for it.

column is matched against td's columns case-insensitively, the same rule GetColumnByName uses, or by exact (case-sensitive) membership in extraColumns. On a match against a table column the fragment quotes the descriptor's CANONICAL column name (td's own casing), not whatever casing the caller passed in; on a match against extraColumns it quotes the caller-supplied name as given, since there is no descriptor entry to canonicalize against. Quoting is done with pgx.Identifier.Sanitize, which double-quotes the identifier and doubles any embedded `"`. An unrecognized column returns a descriptive error naming just the offending column, not the full allowlist, so the error is safe to surface to a client without leaking the table's column names.

Every entry in extraColumns must be a bare, unquoted identifier: the same shape validateIdentifier already enforces for every table, column and unique index name resolved by ConvertStructToTable (letters/digits/underscore/dollar, starting with a letter or underscore; no dots, no whitespace, not empty). OrderBy checks all of them up front, before looking at column, and returns a descriptive error naming the first offending entry if any fails, regardless of whether that particular entry ends up matching column. Without this check a schema-qualified or space-containing entry would still get accepted and quoted as one bogus identifier by pgx.Identifier.Sanitize (e.g. "t.name" becomes the single quoted identifier "t.name", not the table-qualified column t."name"), surfacing later as an opaque "column does not exist" error from PostgreSQL instead of a clear one from OrderBy itself.

An empty column does not error; it falls back, in order, to a column named "created_at", then to one named "updated_at", then to the table's primary key column. If the table has none of those three, OrderBy returns an error rather than guessing a column to sort by.

descending selects the trailing " DESC" (true) or " ASC" (false) on the returned fragment.

func (*Table) PrimaryKey

func (td *Table) PrimaryKey() (*Column, bool)

PrimaryKey returns the primary key's column of the row definition and reports if there is one.

func (*Table) RemoveColumns

func (td *Table) RemoveColumns(columnNames ...string)

RemoveColumns removes the columns with the given names from the table definition.

func (*Table) RowToStruct added in v1.0.14

func (td *Table) RowToStruct[T any](rows pgx.Rows) (value T, err error)

RowToStruct takes a single row of data from a database query and a generic type T and returns a value of type T with the fields populated from the row data.

func (*Table) RowsToStruct added in v1.0.14

func (td *Table) RowsToStruct[T any](rows pgx.Rows) ([]T, error)

RowsToStruct takes a row of data from a database query and a generic type T and returns a slice of values of type T with the fields populated from the row data.

func (*Table) RowsToStructWithTotal added in v1.0.14

func (td *Table) RowsToStructWithTotal[T any](rows pgx.Rows, totalColumn string) ([]T, int64, error)

RowsToStructWithTotal is RowsToStruct that additionally captures the named int64 window column (typically "total_count", as produced by a `COUNT(*) OVER()` window function in the SELECT list) from each row instead of routing it to the no-op scanner, so a caller can read that total without T carrying an artificial field for it. The pattern this replaces smuggled the total through a fake struct field tagged `presenter`.

totalColumn is matched against each row's field descriptions case-insensitively, the same rule buildColumnLookup/findScanTargets use to match every other column, so "total_count", "Total_Count" and "TOTAL_COUNT" are all equivalent. Every column other than totalColumn resolves exactly as RowsToStruct resolves it (same lookup, same scanners, same strict-mode behavior for an unmapped column); RowsToStructWithTotal changes only how totalColumn itself is routed. `COUNT(*) OVER()` yields the same value on every row of the result set, so the last row scanned wins for the returned total; a query that doesn't uphold that guarantee (a different value per row) gets an unspecified total back.

Zero rows returns (empty, 0, nil): there is nothing to scan a total out of, following RowsToStruct's own zero-row behavior (no error, an empty slice).

func (*Table) SelectColumnsExpr added in v1.0.13

func (td *Table) SelectColumnsExpr(alias string) string

SelectColumnsExpr returns the table's scannable columns as a comma-separated, optionally alias-qualified list, for hand-written SELECT lists that must stay in sync with the struct: e.g. `f."id",f."name"` (alias "f") or `"id","name"` (alias "").

"Scannable" means the columns a SELECT * scan of this table would bind: it is ListColumnsWithoutPresenter (excluding Presenter columns, which have no physical column to select) further narrowed to exclude Unscannable ones, e.g. a generated tsvector column, which ConvertRowsToStruct's scan path always skips regardless of what the query selects.

Column names are individually quoted with pgx.Identifier.Sanitize. alias, when non-empty, is written verbatim immediately before each quoted column name followed by a literal '.'. It is never quoted, sanitized or otherwise validated, because it is meant to be a short, developer-authored SQL alias from a hand-written query (e.g. "f" in "... FROM foods f"), not untrusted input. Given a table with no scannable columns, it returns "".

func (*Table) SetStrict

func (td *Table) SetStrict(v bool) *Table

SetStrict sets the strict flag of the table definition to the given value, and returns the table definition itself for chaining. The strict flag determines whether the table definition allows extra fields that are not defined in the columns.

func (*Table) UniqueIndexes

func (td *Table) UniqueIndexes() UniqueIndexes

UniqueIndexes returns a UniqueIndexes map for the table definition, based on the UniqueIndex field of each column.

type TableFilter

type TableFilter interface {
	// FilterTable returns true if the table should be filtered out.
	FilterTable(*Table) bool
}

TableFilter is an interface that table loopers should implement.

type TableFilterFunc

type TableFilterFunc func(*Table) bool

TableFilterFunc is a function that implements the TableFilter interface.

func (TableFilterFunc) FilterTable

func (fn TableFilterFunc) FilterTable(t *Table) bool

FilterTable implements the TableFilter interface.

type TableType

type TableType uint8

TableType is a type that represents the type of a table.

const (
	// TableTypeBase is the default table type.
	TableTypeBase TableType = iota
	// TableTypeView is the view table type.
	// The table is read-only.
	TableTypeView
	// TableTypeMaterializedView is the materialized view table type.
	// The table is read-only but it can be refreshed.
	TableTypeMaterializedView
	// TableTypePresenter is the presenter table type.
	// It's not a view neither a normal table.
	// It can be used to decode custom select queries.
	TableTypePresenter
)

func ParseTableType

func ParseTableType(s string) TableType

ParseTableType parses the given string and returns the corresponding TableType.

func (TableType) IsReadOnly

func (t TableType) IsReadOnly() bool

IsReadOnly returns true if the table is a simple view or materialized view.

func (TableType) IsRefreshable

func (t TableType) IsRefreshable() bool

IsRefreshable returns true if the table is a materialized view.

type Trigger

type Trigger struct {
	Catalog           string // Catalog name of the trigger
	SearchPath        string // Search path of the trigger
	Name              string // Name of the trigger
	Manipulation      string // Type of manipulation (INSERT, UPDATE, DELETE)
	TableName         string // Name of the table the trigger is on
	ActionStatement   string // SQL statement executed by the trigger
	ActionOrientation string // Orientation of the trigger (ROW or STATEMENT)
	ActionTiming      string // Timing of the trigger (BEFORE or AFTER)
}

Trigger represents a database trigger.

type UniqueConstraint

type UniqueConstraint struct {
	// Columns holds the names of the columns the unique constraint applies to,
	// e.g. UNIQUE (title, source_url) or UNIQUE(name).
	// If length of this slice is one then this is a "unique" of its own column (unique=true),
	// otherwise is a multi column unique index e.g. "unique_index=uq_blog_posts".
	Columns []string
}

UniqueConstraint is a type that represents a unique constraint.

type UniqueIndex added in v1.0.6

type UniqueIndex struct {
	TableName string   // table name
	IndexName string   // index name
	Columns   []string // column names.
}

UniqueIndex is a struct that represents a unique index. See DB.ListUniqueIndexes method for more.

type UniqueIndexes

type UniqueIndexes map[string][]string /* key = index name, value = set of columns */

UniqueIndexes is a type that represents a map of unique index names to column names. A unique index is a constraint that ensures that no two rows in a table have the same values for a set of columns.

type Zeroer

type Zeroer interface {
	IsZero() bool // IsZero returns true if the value is zero
}

Zeroer is an interface that defines a method to check if a value is zero.

Zeroer can be implemented by custom types to report whether its current value is zero. Standard Time also implements that.

Jump to

Keyboard shortcuts

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