analyzer

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package analyzer validates and resolves SQL queries against a schema catalog.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InferTypeFromExprWithResolver added in v0.11.0

func InferTypeFromExprWithResolver(expr string, resolver TypeResolver, customTypes map[string]config.CustomTypeMapping) (goType string, nullable bool, ok bool)

InferTypeFromExprWithResolver is the public API for inferring type from an expression. Returns the Go type, nullable flag, and true if successful.

func SQLiteTypeToGo

func SQLiteTypeToGo(sqliteType string) string

SQLiteTypeToGo is a convenience function that uses default type mapping (kept for backward compatibility where no custom types are needed)

Types

type Analyzer

type Analyzer struct {
	Catalog         *model.Catalog
	CustomTypes     map[string]config.CustomTypeMapping
	ColumnOverrides map[string]config.ColumnOverride
	// contains filtered or unexported fields
}

Analyzer validates queries against the schema catalog.

func New

func New(catalog *model.Catalog) *Analyzer

New creates a new Analyzer with the given catalog.

func NewWithCustomTypes

func NewWithCustomTypes(catalog *model.Catalog, customTypes map[string]config.CustomTypeMapping) *Analyzer

NewWithCustomTypes creates a new Analyzer with the given catalog and custom type mappings.

func (*Analyzer) Analyze

func (a *Analyzer) Analyze(q parser.Query) Result

Analyze validates and resolves a parsed query.

func (*Analyzer) SQLiteTypeToGo

func (a *Analyzer) SQLiteTypeToGo(sqliteType string) string

SQLiteTypeToGo converts a SQLite type to a Go type. If a TypeResolver is set, it will be used for database-specific type mapping.

func (*Analyzer) SetColumnOverrides added in v0.11.0

func (a *Analyzer) SetColumnOverrides(overrides map[string]config.ColumnOverride)

SetColumnOverrides sets the column-specific type overrides.

func (*Analyzer) SetTypeResolver

func (a *Analyzer) SetTypeResolver(resolver TypeResolver)

SetTypeResolver sets the type resolver for database-specific type mapping.

type BatchInfo added in v0.11.0

type BatchInfo struct {
	// Kind is the originating batch command (CommandBatchExec / CommandBatchMany /
	// CommandBatchOne). It drives the generated return shape and per-item call.
	Kind block.Command
}

BatchInfo describes a :batch* query. The batch commands run the same parsed statement once per per-row param set; Kind selects the loop-based shape the code generator emits (exec -> error, one -> []Row, many -> [][]Row).

type CopyFromInfo added in v0.11.0

type CopyFromInfo struct {
	// Table is the target table name (normalized).
	Table string
	// Columns is the explicit insert column list in source order. The per-row
	// param struct fields are emitted in this same order, so the code generator
	// can flatten arguments deterministically.
	Columns []string
	// SQLTable is the target table name as written in source, preserving any
	// identifier quoting (e.g. "order" or `my-table`). The runtime VALUES builder
	// emits this verbatim so quoted/reserved identifiers stay valid SQL.
	SQLTable string
	// SQLColumns are the insert columns as written in source (same order as
	// Columns), preserving identifier quoting for the runtime VALUES prefix.
	SQLColumns []string
}

CopyFromInfo describes the INSERT target of a :copyfrom (bulk insert) query.

type Diagnostic

type Diagnostic struct {
	Path     string
	Line     int
	Column   int
	Message  string
	Severity Severity
}

Diagnostic represents an issue found during analysis.

type OptionalParam added in v0.11.0

type OptionalParam struct {
	// Name is the camelCased param name as it appears in Result.Params (e.g.
	// "minAge" for `@min_age`). Bit positions in variant masks index by this.
	Name string
	// RawName is the param name exactly as written in the SQL annotation/clause
	// (e.g. "min_age"), used by the build-time equivalence gate to bind the @rawname
	// placeholders that still appear verbatim in the canonical and variant SQL.
	RawName string
	// Column is the bare column the param filters on (e.g. "age"), used by the
	// equivalence gate to pick boundary trial values.
	Column string
	// GoType is the resolved Go scalar type of the filtered column (e.g. "string",
	// "int64"). The code generator emits the method arg as a pointer to this type.
	GoType string
	// Import / Package carry any type import needed for GoType (e.g. time.Time).
	Import  string
	Package string
}

OptionalParam is one optional equality-filter param.

type OptionalSpec added in v0.11.0

type OptionalSpec struct {
	// Params are the optional equality-filter params in source (clause) order. Bit i
	// of a variant Mask corresponds to Params[i].
	Params []OptionalParam
	// Required are the names (camelCased, as they appear in Result.Params) of the
	// non-optional bind params, in their fixed source order. They are bound first in
	// every variant, before any present optional params.
	Required []string
	// Variants holds one folded SQL string + bind ordering per subset of the
	// optional params, indexed implicitly by Mask. There are exactly 2^len(Params)
	// of them.
	Variants []OptionalVariant
}

OptionalSpec describes the constant-folded variants of a query that uses the optional-filters feature. There is one variant per subset of the optional params (2^len(Params)), keyed by a bitmask over Params (bit i set => Params[i] is present/non-nil at runtime).

type OptionalVariant added in v0.11.0

type OptionalVariant struct {
	// Mask identifies the subset: bit i set means OptionalSpec.Params[i] is present.
	Mask int
	// SQL is the folded statement with the absent optional clauses removed and the
	// present optional clauses reduced to their bare `<expr> <op> @p` predicate.
	SQL string
	// PresentParams are the camelCased names of the optional params kept in this
	// variant, in clause (source) order. At runtime, after the required params are
	// bound, these are bound in this order.
	PresentParams []string
}

OptionalVariant is one constant-folded SQL variant for a specific subset of the optional params.

type OrderBySpec added in v0.11.0

type OrderBySpec struct {
	// ParamName is the camelCased name of the `@orderby` placeholder param (always
	// "orderby"). It identifies the param dropped from Params.
	ParamName string
	// Columns is the allow-list of sort column names in source order. Every column
	// has been validated to exist in the query's tables; an unknown column instead
	// produces a SeverityError diagnostic and is omitted here.
	Columns []string
}

OrderBySpec describes a validated dynamic ORDER BY allow-list for a query.

type Result

type Result struct {
	Query       parser.Query
	Columns     []ResultColumn
	Params      []ResultParam
	Diagnostics []Diagnostic
	// CopyFrom is populated only for :copyfrom (bulk insert) queries. It carries
	// the INSERT target table and column order so the code generator can build a
	// runtime multi-row VALUES statement. Nil for all other commands.
	CopyFrom *CopyFromInfo
	// Batch is populated only for :batchexec / :batchmany / :batchone queries. It
	// carries the batch kind so the code generator emits a loop-based method that
	// runs the statement once per per-row param set (no native pgx batching). The
	// per-row params remain in Params (forming the param struct) and, for the many/
	// one kinds, the result columns remain in Columns. Nil for all other commands.
	Batch *BatchInfo
	// OrderBy is populated only for queries using the dynamic ORDER BY feature
	// (an `-- @orderby col, col2` annotation plus an `@orderby` placeholder in the
	// ORDER BY position). It carries the validated allow-list of sort columns so
	// the code generator can emit a type-safe enum + runtime-validated method. The
	// `@orderby` placeholder param is dropped from Params; this carries it forward
	// instead. Nil for every query that does not use the annotation.
	OrderBy *OrderBySpec
	// Optional is populated only for queries using the optional-filters feature
	// (an `-- @optional p1, p2` annotation plus one `(@p IS NULL OR <expr> <op> @p)`
	// clause per param). It carries the constant-folded SQL variants and per-variant
	// bind ordering so the code generator can select the right variant at runtime by
	// which optional args are non-nil. The optional params stay in Params (still
	// resolved/typed) but are also listed here so codegen can render them as
	// nullable pointers and reorder binds. Nil for every query that does not use the
	// annotation.
	Optional *OptionalSpec
}

Result contains the analysis result for a single query.

type ResultColumn

type ResultColumn struct {
	Name     string
	Table    string
	GoType   string
	Nullable bool
	Import   string
	Package  string
	// EmbedGroup is a per-query identifier (>0) shared by all columns produced
	// by a single sqlc.embed() expression. Columns with the same EmbedGroup are
	// collapsed into one nested struct field by the code generator. Zero means
	// the column is an ordinary (non-embedded) result column.
	EmbedGroup int
	// EmbedTypeName is the table name backing the embedded struct, used to
	// resolve the nested field's Go model type. Only meaningful when
	// EmbedGroup > 0.
	EmbedTypeName string
	// EmbedPointer reports whether the embedded struct should be a pointer to
	// model nullability from an outer join. True when the embed is reached via a
	// LEFT/RIGHT/FULL [OUTER] join (the nested struct is nil on a non-matching
	// child row); false for FROM relations and INNER/CROSS joins.
	EmbedPointer bool
	// EmbedSlice reports whether this column belongs to a sqlc.embed_slice()
	// (one-to-many) group. When true the code generator aggregates the child
	// rows into a nested []Child slice field instead of a single nested struct.
	// Only meaningful when EmbedGroup > 0.
	EmbedSlice bool
	// EmbedAs is the explicit alias from `sqlc.embed(table) as name`. When set it
	// renames the generated nested struct field (e.g. Writer) while EmbedTypeName
	// keeps the table name so the field's Go type is unchanged (e.g. Author). Only
	// meaningful when EmbedGroup > 0.
	EmbedAs string
}

ResultColumn describes a single output column of a query.

type ResultParam

type ResultParam struct {
	Name          string
	Style         parser.ParamStyle
	GoType        string
	Nullable      bool
	IsVariadic    bool
	VariadicCount int
	Import        string
	Package       string
}

ResultParam describes a single input parameter of a query.

type Severity

type Severity int

Severity indicates the seriousness of a diagnostic.

const (
	// SeverityWarning indicates a potential issue that doesn't prevent code generation.
	SeverityWarning Severity = iota
	// SeverityError indicates a fatal issue that prevents code generation.
	SeverityError
)

type TypeInfo

type TypeInfo struct {
	GoType      string
	UsesSQLNull bool
	Import      string
	Package     string
}

TypeInfo describes a resolved Go type.

type TypeResolver

type TypeResolver interface {
	ResolveType(sqlType string, nullable bool) TypeInfo
}

TypeResolver interface for database-specific type mapping.

Jump to

Keyboard shortcuts

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