golang

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateCompositeType

func CreateCompositeType(
	pkgPath string,
	pgt pg.CompositeType,
	resolver PgTypeResolver,
	caser casing.Caser,
) (gotype.Type, error)

CreateCompositeType creates a struct to represent a Postgres composite type. The type is rooted under pkgPath.

func Generate

func Generate(opts GenerateOptions, queryFiles []codegen.QueryFile) error

Generate emits generated Go files for each of the queryFiles.

func NameArrayInitFunc

func NameArrayInitFunc(typ *gotype.ArrayType) string

NameArrayInitFunc returns the name for a hypothetical array init function. Kept for backward compat in name generation only.

Types

type ChIdentifierDeclarer added in v0.2.0

type ChIdentifierDeclarer struct{}

ChIdentifierDeclarer emits substituteIdentifiers, the helper a generated ClickHouse query calls to fill its {…:Identifier} holes.

One per package, however many queries take an identifier.

func NewChIdentifierDeclarer added in v0.2.0

func NewChIdentifierDeclarer() ChIdentifierDeclarer

func (ChIdentifierDeclarer) Declare added in v0.2.0

func (d ChIdentifierDeclarer) Declare(string) (string, error)

func (ChIdentifierDeclarer) DedupeKey added in v0.2.0

func (d ChIdentifierDeclarer) DedupeKey() string

type ChTypeResolver added in v0.1.0

type ChTypeResolver struct {
	// contains filtered or unexported fields
}

ChTypeResolver handles the mapping between ClickHouse and Go types.

Where PgTypeResolver looks types up by OID, this one dispatches on the structure of the ClickHouse type, because that is what a ClickHouse type name is: Nullable and Array and Map say what to do, and only the leaves need a lookup table.

func NewChTypeResolver added in v0.1.0

func NewChTypeResolver(c casing.Caser, overrides map[string]string) ChTypeResolver

func (ChTypeResolver) Resolve added in v0.1.0

func (tr ChTypeResolver) Resolve(t sqltype.Type, _ bool, pkgPath string) (gotype.Type, error)

Resolve maps a ClickHouse type to a Go type. nullable is ignored: unlike Postgres, ClickHouse states nullability in the type itself, so it is already part of t.

type CompositeTypeDeclarer

type CompositeTypeDeclarer struct {
	// contains filtered or unexported fields
}

CompositeTypeDeclarer declares a new Go struct to represent a Postgres composite type.

func NewCompositeTypeDeclarer

func NewCompositeTypeDeclarer(comp *gotype.CompositeType) CompositeTypeDeclarer

func (CompositeTypeDeclarer) Declare

func (c CompositeTypeDeclarer) Declare(pkgPath string) (string, error)

func (CompositeTypeDeclarer) DedupeKey

func (c CompositeTypeDeclarer) DedupeKey() string

type ConstantDeclarer

type ConstantDeclarer struct {
	// contains filtered or unexported fields
}

ConstantDeclarer declares a new string literal.

func NewConstantDeclarer

func NewConstantDeclarer(key, str string) ConstantDeclarer

func (ConstantDeclarer) Declare

func (c ConstantDeclarer) Declare(string) (string, error)

func (ConstantDeclarer) DedupeKey

func (c ConstantDeclarer) DedupeKey() string

type Declarer

type Declarer interface {
	// DedupeKey uniquely identifies the declaration so that we only emit
	// declarations once. Should be namespaced like enum::some_enum.
	DedupeKey() string
	// Declare returns the string of the Go code for the declaration.
	Declare(pkgPath string) (string, error)
}

Declarer is implemented by any value that needs to declare types, data, or functions before use. For example, Postgres enums map to a Go enum with a type declaration and const values. If we use the enum in any Querier function, we need to declare the enum.

type DeclarerSet

type DeclarerSet map[string]Declarer

DeclarerSet is a set of declarers, identified by the dedupe key.

func FindDeclarers added in v0.1.0

func FindDeclarers(typ gotype.Type) DeclarerSet

FindDeclarers finds all the Declarers needed by typ and the types nested inside it. Returns an empty set if no declarations are needed.

Input and output types ask the same question: pgx has to be told about a composite or an enum whichever direction it travels in.

func NewDeclarerSet

func NewDeclarerSet(decls ...Declarer) DeclarerSet

func (DeclarerSet) AddAll

func (d DeclarerSet) AddAll(decls ...Declarer)

func (DeclarerSet) ListAll

func (d DeclarerSet) ListAll() []Declarer

ListAll gets all declarers in the set in a stable sort order.

type Emitter

type Emitter struct {
	// contains filtered or unexported fields
}

Emitter writes a templated query file to a file.

func NewEmitter

func NewEmitter(outDir string, tmpl *template.Template) Emitter

func (Emitter) EmitAllQueryFiles

func (em Emitter) EmitAllQueryFiles(tfs []TemplatedFile) (mErr error)

EmitAllQueryFiles emits a query file for each TemplatedFile. Ensure that emitted files don't clash by prefixing with the parent directory if necessary.

type EnumTypeDeclarer

type EnumTypeDeclarer struct {
	// contains filtered or unexported fields
}

EnumTypeDeclarer declares a new string type and the const values to map to a Postgres enum.

func NewEnumTypeDeclarer

func NewEnumTypeDeclarer(enum *gotype.EnumType) EnumTypeDeclarer

func (EnumTypeDeclarer) Declare

func (e EnumTypeDeclarer) Declare(string) (string, error)

func (EnumTypeDeclarer) DedupeKey

func (e EnumTypeDeclarer) DedupeKey() string

type GenerateOptions

type GenerateOptions struct {
	// Which database the generated code talks to.
	Dialect   codegen.Dialect
	GoPkg     string
	OutputDir string
	// A map of lowercase acronyms to the upper case equivalent, like:
	// "api" => "API".
	Acronyms map[string]string
	// A map from a Postgres type name to a fully qualified Go type.
	TypeOverrides map[string]string
	// How many params to inline when calling querier methods.
	// Set to 0 to always create a struct for params.
	InlineParamCount int
}

GenerateOptions are options to control generated Go output.

type ImportPkg added in v0.0.3

type ImportPkg struct {
	PkgPath string // e.g. "github.com/jackc/pgtype"
	Alias   string // e.g. "pgtype4", or "" for no alias
}

ImportPkg is a single import entry, optionally with an alias.

func (ImportPkg) FormatImport added in v0.0.3

func (ip ImportPkg) FormatImport() string

FormatImport returns the Go import line content, e.g. `"pkg"` or `alias "pkg"`.

type ImportSet

type ImportSet struct {
	// contains filtered or unexported fields
}

ImportSet contains a set of imports required by one Go file.

func NewImportSet

func NewImportSet() *ImportSet

func (*ImportSet) AddPackage

func (s *ImportSet) AddPackage(p string)

AddPackage adds a fully qualified package path to the set, like "github.com/mbark/pggen/foo".

func (*ImportSet) AddType

func (s *ImportSet) AddType(typ gotype.Type)

AddType adds the packages needed for typ and every type nested inside it.

Only a leaf carries a package, so the whole tree has to be walked: a type like []map[string]time.Time names "time" three wrappers down.

func (*ImportSet) AliasMap added in v0.0.3

func (s *ImportSet) AliasMap() map[string]string

AliasMap returns a map from full package path to the alias that should be used when qualifying types. Returns nil if there are no collisions.

func (*ImportSet) SortedImports added in v0.0.3

func (s *ImportSet) SortedImports() []ImportPkg

SortedImports returns import entries with aliases assigned where needed to resolve short-name collisions, sorted by package path.

func (*ImportSet) SortedPackages

func (s *ImportSet) SortedPackages() []string

SortedPackages returns a new slice containing the sorted packages, suitable for an import statement.

type PaginateGroup added in v0.1.0

type PaginateGroup struct {
	Name           string           // dispatcher / original query name, e.g. "List"
	ParamsTypeName string           // unified params struct name, e.g. "ListParams"
	UnifiedInputs  []TemplatedParam // union of every variant's inputs, by PgName
	SortKeyConsts  []SortKeyConst   // distinct sort keys in the spec
	Variants       []TemplatedQuery // fanned-out variants (default first)
}

PaginateGroup is the public dispatcher for a paginate=<spec> query plus the metadata needed to emit its unified params struct and sort-key constants.

func (PaginateGroup) EmitDispatcher added in v0.1.0

func (pg PaginateGroup) EmitDispatcher() (string, error)

EmitDispatcher emits the public dispatcher method switching on SortKey and Descending to the matching variant helper.

func (PaginateGroup) EmitInterfaceMethod added in v0.1.0

func (pg PaginateGroup) EmitInterfaceMethod() (string, error)

EmitInterfaceMethod emits the dispatcher signature for the Querier interface.

func (PaginateGroup) EmitParamStruct added in v0.1.0

func (pg PaginateGroup) EmitParamStruct() string

EmitParamStruct emits the unified params struct: the union of all variant inputs plus the synthetic SortKey and Descending dispatch fields.

func (PaginateGroup) EmitResultType added in v0.1.0

func (pg PaginateGroup) EmitResultType() (string, error)

EmitResultType returns the dispatcher result type, e.g. "[]PaymentRow".

func (PaginateGroup) EmitSortKeyConsts added in v0.1.0

func (pg PaginateGroup) EmitSortKeyConsts() string

EmitSortKeyConsts emits the sort-key string constants.

type PgTypeResolver added in v0.1.0

type PgTypeResolver struct {
	// contains filtered or unexported fields
}

PgTypeResolver handles the mapping between Postgres and Go types.

func NewPgTypeResolver added in v0.1.0

func NewPgTypeResolver(c casing.Caser, overrides map[string]string) PgTypeResolver

func (PgTypeResolver) Resolve added in v0.1.0

func (tr PgTypeResolver) Resolve(t sqltype.Type, nullable bool, pkgPath string) (gotype.Type, error)

Resolve maps a Postgres type to a Go type.

type SharedRowDeclarer added in v0.1.0

type SharedRowDeclarer struct {
	// contains filtered or unexported fields
}

SharedRowDeclarer declares a shared row struct used by multiple queries that specify the same output= pragma value.

func NewSharedRowDeclarer added in v0.1.0

func NewSharedRowDeclarer(name string, columns []TemplatedColumn, dialect codegen.Dialect) SharedRowDeclarer

func (SharedRowDeclarer) Declare added in v0.1.0

func (d SharedRowDeclarer) Declare(pkgPath string) (string, error)

func (SharedRowDeclarer) DedupeKey added in v0.1.0

func (d SharedRowDeclarer) DedupeKey() string

type SortKeyConst added in v0.1.0

type SortKeyConst struct {
	ConstName string // e.g. "ListSortPaymentDate"
	Value     string // e.g. "payment_date"
}

SortKeyConst is a generated constant for a runtime sort key value.

type TemplatedColumn

type TemplatedColumn struct {
	PgName    string // original name of the Postgres column
	UpperName string // name in Go-style (UpperCamelCase) to use for the column
	LowerName string // name in Go-style (lowerCamelCase)
	Type      gotype.Type
	QualType  string // package qualified Go type to use for the column, like "pgtype.Text"
}

type TemplatedFile

type TemplatedFile struct {
	Dialect    codegen.Dialect  // the database the generated code talks to
	Pkg        TemplatedPackage // the parent package containing this file
	PkgPath    string           // full package path, like "github.com/foo/bar"
	GoPkg      string           // the name of the Go package to use for the "package foo" declaration
	SourcePath string           // absolute path to source SQL file
	Queries    []TemplatedQuery // the queries with all template information
	Imports    []ImportPkg      // Go imports, with aliases for collisions
	RawImports []string         // Go import paths (no aliases), for internal use
	// Variants are the fanned-out paginate statements, emitted as unexported
	// helper methods. Their public entry points are the PaginateGroups.
	Variants []TemplatedQuery
	// PaginateGroups are the keyset-pagination dispatchers, one per paginate
	// query, each fronting a set of Variants.
	PaginateGroups []PaginateGroup
	// True if this file is the leader file. The leader defines common code used
	// by all queries in the same directory. Only one leader per directory.
	IsLeader bool
	// Any declarations this file should declare. Only set on leader.
	Declarers []Declarer
}

TemplatedFile is the Go version of a SQL query file with all information needed to execute the codegen template.

func (TemplatedFile) EmitChGenericConn added in v0.1.0

func (tf TemplatedFile) EmitChGenericConn() string

EmitChGenericConn emits the genericConn interface with only the methods the package's queries call.

A package of read-only queries should not demand a connection that can Exec, so a caller can pass a narrower interface of its own — which is what makes a wrapper like a concurrency limiter or a tracer usable here.

type TemplatedPackage

type TemplatedPackage struct {
	Files []TemplatedFile // sorted lexicographically by path
}

TemplatedPackage is all templated files in a pggen invocation. The templated files do not necessarily reside in the same directory.

type TemplatedParam

type TemplatedParam struct {
	UpperName string // name of the param in UpperCamelCase, like 'FirstName' from pggen.arg('first_name')
	LowerName string // name of the param in lowerCamelCase, like 'firstName' from pggen.arg('first_name')
	QualType  string // package-qualified Go type to use for this param
	Type      gotype.Type
	RawName   codegen.InputParam
}

type TemplatedQuery

type TemplatedQuery struct {
	Dialect          codegen.Dialect   // the database the generated code talks to
	Name             string            // name of the query, from the comment preceding the query
	SQLVarName       string            // name of the string variable containing the SQL
	ResultKind       ast.ResultKind    // kind of result: :one, :many, or :exec
	Doc              string            // doc from the source query file, formatted for Go
	PreparedSQL      string            // SQL query, ready to run with PREPARE statement
	Inputs           []TemplatedParam  // input parameters to the query
	Outputs          []TemplatedColumn // output columns of the query
	InlineParamCount int               // inclusive count of params that will be inlined
	OutputType       string            // user-specified shared output row struct name, empty if not set
	SQLConst         string            // user-specified exported name for the SQL constant, empty if not set
	VariantGroup     string            // dispatcher name when this query is a paginate variant, else empty
	VariantKey       ast.VariantKey    // identifies the sort key + direction for a variant
}

TemplatedQuery is a query with all information required to execute the codegen template.

func (TemplatedQuery) EmitChHasIdentifiers added in v0.2.0

func (tq TemplatedQuery) EmitChHasIdentifiers() bool

EmitChHasIdentifiers reports whether the query names a table or column through an {…:Identifier} parameter.

func (TemplatedQuery) EmitChIdentifierPrelude added in v0.2.0

func (tq TemplatedQuery) EmitChIdentifierPrelude() (string, error)

EmitChIdentifierPrelude emits the substitution that fills a query's {…:Identifier} holes before it is sent.

It has to happen here and not in the driver. ClickHouse binds an Identifier itself, and safely, but clickhouse-go switches a query to server-side parameters as soon as its text holds any {…:…} — and server-side parameters travel as text the driver renders wrongly for time.Time, uuid.UUID and decimal.Decimal. Leaving one Identifier for the server would silently break every other parameter in the same query.

func (TemplatedQuery) EmitChParamNames added in v0.1.0

func (tq TemplatedQuery) EmitChParamNames() string

EmitChParamNames emits the query arguments.

ClickHouse parameters are named rather than positional: the query says {msisdns:Array(String)}, and the value is bound to that name. The type is already in the SQL, so the server does the conversion.

func (TemplatedQuery) EmitChPreparedSQL added in v0.1.0

func (tq TemplatedQuery) EmitChPreparedSQL() (string, error)

EmitChPreparedSQL emits the SQL constant, with each {name:Type} rewritten to cast(@name AS Type) so the driver binds values client-side. See ch.RewriteParams for why that is necessary.

func (TemplatedQuery) EmitChResultElem added in v0.1.0

func (tq TemplatedQuery) EmitChResultElem() (string, error)

EmitChResultElem is the Go type of a single result item.

func (TemplatedQuery) EmitChResultSignature added in v0.1.0

func (tq TemplatedQuery) EmitChResultSignature() (string, error)

EmitChResultSignature is the result part of a method signature.

ClickHouse has no analogue of pgconn.CommandTag — Exec reports only an error — so an :exec query returns a bare error rather than a pair.

func (TemplatedQuery) EmitChResultType added in v0.1.0

func (tq TemplatedQuery) EmitChResultType() (string, error)

EmitChResultType is the Go type a query method returns, ignoring the error.

func (TemplatedQuery) EmitChRowStruct added in v0.1.0

func (tq TemplatedQuery) EmitChRowStruct() string

EmitChRowStruct emits the row struct for a query.

It carries a ch tag as well as a json tag: clickhouse-go's Select and ScanStruct bind columns to fields by that tag, and they require a destination for every column the query returns.

func (TemplatedQuery) EmitChSQLRef added in v0.2.0

func (tq TemplatedQuery) EmitChSQLRef() string

EmitChSQLRef is what the query call passes as its SQL: the constant, or the local the identifier substitution produced.

func (TemplatedQuery) EmitChUsesRowStruct added in v0.1.0

func (tq TemplatedQuery) EmitChUsesRowStruct() bool

EmitChUsesRowStruct reports whether a query's result element is a generated struct rather than a single bare column. It decides between clickhouse-go's struct scanning and a plain Scan, because Select and ScanStruct only accept a struct destination.

func (TemplatedQuery) EmitChVariantIdentifierPrelude added in v0.2.0

func (tq TemplatedQuery) EmitChVariantIdentifierPrelude() (string, error)

EmitChVariantIdentifierPrelude is EmitChIdentifierPrelude for a paginate variant, which always reads its parameters from the group's unified struct however few of them it uses.

func (TemplatedQuery) EmitChVariantParamNames added in v0.2.0

func (tq TemplatedQuery) EmitChVariantParamNames() string

EmitChVariantParamNames emits a paginate variant's arguments, read from the group's unified params struct.

A variant is a private helper the dispatcher calls, so every variant takes the same struct even though each uses a different subset of its fields — which is what the cursor arguments of the sort key it was fanned out for amount to.

func (TemplatedQuery) EmitParamNames

func (tq TemplatedQuery) EmitParamNames() string

EmitParamNames emits the TemplatedQuery.Inputs into comma separated names for use in a method invocation.

func (TemplatedQuery) EmitParamStruct

func (tq TemplatedQuery) EmitParamStruct() string

EmitParamStruct emits the struct definition for query params if needed.

func (TemplatedQuery) EmitParams

func (tq TemplatedQuery) EmitParams() string

EmitParams emits the TemplatedQuery.Inputs into method parameters with both a name and type based on the number of params. For use in a method definition.

func (TemplatedQuery) EmitPreparedSQL

func (tq TemplatedQuery) EmitPreparedSQL() string

EmitPreparedSQL emits the prepared SQL query with appropriate quoting.

func (TemplatedQuery) EmitResultAssigns

func (tq TemplatedQuery) EmitResultAssigns(zeroVal string) (string, error)

EmitResultAssigns writes all the assign statements after scanning the result from pgx. In pgx v5, scanning is direct so no assigns are needed.

func (TemplatedQuery) EmitResultDecoders

func (tq TemplatedQuery) EmitResultDecoders() (string, error)

EmitResultDecoders declares all initialization required for output types. In pgx v5, scanning is direct so no decoders are needed.

func (TemplatedQuery) EmitResultElem

func (tq TemplatedQuery) EmitResultElem() (string, error)

EmitResultElem returns the string representing a single item in the overall query result type. For :one and :exec queries, this is the same as EmitResultType. For :many queries, this is the element type of the slice result type.

func (TemplatedQuery) EmitResultExpr

func (tq TemplatedQuery) EmitResultExpr(name string) (string, error)

EmitResultExpr returns the string representation of a single item to return for :one queries or to append for :many queries. Useful for figuring out if we need to use the address operator. Controls the string item and &item in:

items = append(items, item)
items = append(items, &item)

func (TemplatedQuery) EmitResultType

func (tq TemplatedQuery) EmitResultType() (string, error)

EmitResultType returns the string representing the overall query result type, meaning the return result.

func (TemplatedQuery) EmitResultTypeInit

func (tq TemplatedQuery) EmitResultTypeInit(name string) (string, error)

EmitResultTypeInit returns the initialization code for the result type with name, typically "item" or "items". For array types, we take care to not use a var declaration so that JSON serialization returns an empty array instead of null.

func (TemplatedQuery) EmitRowScanArgs

func (tq TemplatedQuery) EmitRowScanArgs() (string, error)

EmitRowScanArgs emits the args to scan a single row from a pgx.Row or pgx.Rows.

func (TemplatedQuery) EmitRowStruct

func (tq TemplatedQuery) EmitRowStruct() string

EmitRowStruct writes the struct definition for query output row if one is needed.

func (TemplatedQuery) EmitVariantParamNames added in v0.1.0

func (tq TemplatedQuery) EmitVariantParamNames() string

EmitVariantParamNames emits this variant's inputs as struct-qualified args in the variant's own order, for the call to q.conn.Query.

func (TemplatedQuery) IsVariant added in v0.1.0

func (tq TemplatedQuery) IsVariant() bool

IsVariant reports whether this query is one fanned-out statement of a paginate=<spec> query.

func (TemplatedQuery) VariantMethodName added in v0.1.0

func (tq TemplatedQuery) VariantMethodName() string

VariantMethodName is the unexported method name for a paginate variant, like "listPaymentDateDesc" or "listDefault".

func (TemplatedQuery) VariantParamsType added in v0.1.0

func (tq TemplatedQuery) VariantParamsType() string

VariantParamsType is the unified params struct name shared by all variants in the group, like "ListParams".

type Templater

type Templater struct {
	// contains filtered or unexported fields
}

Templater creates query file templates.

func NewTemplater

func NewTemplater(opts TemplaterOpts) Templater

func (Templater) TemplateAll

func (tm Templater) TemplateAll(files []codegen.QueryFile) ([]TemplatedFile, error)

TemplateAll creates query template files for each codegen.QueryFile.

type TemplaterOpts

type TemplaterOpts struct {
	Caser    casing.Caser
	Resolver TypeResolver
	Pkg      string // Go package name
	// How many params to inline when calling querier methods.
	InlineParamCount int
	// Which database the generated code talks to.
	Dialect codegen.Dialect
}

TemplaterOpts is options to control the template logic.

type TypeRegistrationDeclarer added in v0.0.3

type TypeRegistrationDeclarer struct {
	// contains filtered or unexported fields
}

TypeRegistrationDeclarer declares a RegisterTypes function that registers composite and enum types with a pgx v5 connection's TypeMap.

func NewTypeRegistrationDeclarer added in v0.0.3

func NewTypeRegistrationDeclarer(names []string) TypeRegistrationDeclarer

func (TypeRegistrationDeclarer) Declare added in v0.0.3

func (TypeRegistrationDeclarer) DedupeKey added in v0.0.3

func (t TypeRegistrationDeclarer) DedupeKey() string

type TypeResolver

type TypeResolver interface {
	Resolve(t sqltype.Type, nullable bool, pkgPath string) (gotype.Type, error)
}

TypeResolver maps a database type to the Go type that represents it. Each dialect has its own implementation because the type systems don't line up: Postgres identifies types by OID and resolves them through the catalog, while ClickHouse names them structurally, like "Array(Nullable(String))".

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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