qcode

package
v3.18.5 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrUnknownValidator = errors.New("unknown validator")

Functions

func HasFilterOnColumn added in v3.15.0

func HasFilterOnColumn(ex *Exp, colName string) bool

HasFilterOnColumn walks the expression tree and returns true if any comparison references the given column name.

func IsGeoOp added in v3.2.0

func IsGeoOp(op ExpOp) bool

IsGeoOp returns true if the operator is a GIS/spatial operator

Types

type AggregrateOp

type AggregrateOp int8
const (
	AgCount AggregrateOp = iota + 1
	AgSum
	AgAvg
	AgMax
	AgMin
)

func (AggregrateOp) String

func (i AggregrateOp) String() string

type Arg

type Arg struct {
	Type  ArgType
	DType string
	Name  string
	Val   string
	Col   sdata.DBColumn
	Expr  *Exp // populated when Type == ArgTypeExpr
}

type ArgType

type ArgType int8
const (
	ArgTypeVal ArgType = iota
	ArgTypeVar
	ArgTypeCol
	ArgTypeExpr // scalar expression tree — Arg.Expr holds the *Exp root
)

type Cache

type Cache struct {
	Header string
}

type CaseArm added in v3.17.0

type CaseArm struct {
	When *Exp
	Then *Exp
}

CaseArm is a single WHEN/THEN pair inside an OpCase node. When is a boolean sub-tree (rendered via the existing renderExp); Then is a scalar sub-tree (rendered via renderScalarExp).

type ColKey

type ColKey struct {
	Name string
	Base bool
}

type Column

type Column struct {
	Col         sdata.DBColumn
	FieldFilter Filter
	FieldName   string
}

type Compiler

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

func NewCompiler

func NewCompiler(s *sdata.DBSchema, c Config) (*Compiler, error)

func (*Compiler) AddRole

func (co *Compiler) AddRole(role, schema, table string, trc TRConfig) error

func (*Compiler) Compile

func (co *Compiler) Compile(
	query []byte,
	vmap map[string]json.RawMessage,
	role, namespace string,
) (qc *QCode, err error)

func (*Compiler) Find

func (co *Compiler) Find(schema, name string) (sdata.DBTable, error)

func (*Compiler) FindPath

func (co *Compiler) FindPath(from, to, through string) ([]sdata.TPath, error)

func (*Compiler) FindPathByColumn added in v3.18.3

func (co *Compiler) FindPathByColumn(from, to, col string) ([]sdata.TPath, error)

func (*Compiler) ParseName

func (co *Compiler) ParseName(name string) string

type Config

type Config struct {
	Vars            map[string]string
	TConfig         map[string]TConfig
	DefaultBlock    bool
	DefaultLimit    int
	AnalyticsMode   bool
	DisableAgg      bool
	DisableFuncs    bool
	EnableCamelcase bool
	DBSchema        string
	Validators      map[string]Validator

	// EnableCacheTracking injects __gj_id fields with primary keys for cache row tracking
	EnableCacheTracking bool
	// contains filtered or unexported fields
}

type Constraint

type Constraint struct {
	VarName string
	// contains filtered or unexported fields
}

type DeleteConfig

type DeleteConfig struct {
	Filters []string
	Columns []string
	Block   bool
}

type Exp

type Exp struct {
	Op    ExpOp
	Joins []Join
	Order
	OrderBy bool

	Left struct {
		ID      int32
		Table   string
		Col     sdata.DBColumn
		ColName string
		Path    []string
	}
	Right struct {
		ValType  ValType
		Val      string
		ID       int32
		Table    string
		Col      sdata.DBColumn
		ColName  string
		ListType ValType
		ListVal  []string
		Path     []string
	}
	Geo      *GeoExp // GIS-specific expression data
	Children []*Exp

	// Scalar-expression payloads (set only for the corresponding Op).
	// These are unused for boolean/comparison ops; keeping them inline
	// avoids allocating a separate struct per leaf node.
	Lit      ExpLit    // OpLiteral
	CaseArms []CaseArm // OpCase
	Else     *Exp      // OpCase ELSE branch (optional)
	CastType string    // OpCast — target SQL type
	RelPath  []sdata.DBRel
	// contains filtered or unexported fields
}

type ExpLit added in v3.17.0

type ExpLit struct {
	Val     string
	ValType ValType
}

ExpLit is a literal scalar value used by OpLiteral leaves.

type ExpOp

type ExpOp int8
const (
	OpNop ExpOp = iota
	OpAnd
	OpOr
	OpNot
	OpEquals
	OpNotEquals
	OpGreaterOrEquals
	OpLesserOrEquals
	OpGreaterThan
	OpLesserThan
	OpIn
	OpNotIn
	OpLike
	OpNotLike
	OpILike
	OpNotILike
	OpSimilar
	OpNotSimilar
	OpRegex
	OpNotRegex
	OpIRegex
	OpNotIRegex
	OpContains
	OpContainedIn
	OpHasInCommon
	OpHasKey
	OpHasKeyAny
	OpHasKeyAll
	OpIsNull
	OpIsNotNull
	OpTsQuery
	OpFalse
	OpNotDistinct
	OpDistinct
	OpEqualsTrue
	OpNotEqualsTrue
	OpSelectExists
	OpJSONPath     // JSON path operator (->)
	OpJSONPathText // JSON path text operator (->>)

	// GIS/Spatial operators
	OpGeoDistance   // ST_DWithin - distance-based filtering
	OpGeoWithin     // ST_Within - geometry A within B
	OpGeoContains   // ST_Contains - geometry A contains B
	OpGeoIntersects // ST_Intersects - geometries intersect
	OpGeoCoveredBy  // ST_CoveredBy - geometry A covered by B
	OpGeoCovers     // ST_Covers - geometry A covers B
	OpGeoTouches    // ST_Touches - geometries touch at boundary
	OpGeoOverlaps   // ST_Overlaps - geometries overlap
	OpGeoNear       // MongoDB $near / $nearSphere

	// Scalar arithmetic operators — used inside aggregate expressions
	// (e.g. SUM(unitprice * orderqty)). These never appear in WHERE
	// predicates; the validator in qcode/expr.go rejects them outside
	// expression trees. Keeping them in the same ExpOp enum lets the
	// existing Children/Left/Right machinery and dialect rendering be
	// reused. Discipline: arithmetic ops only have arithmetic children,
	// boolean ops only have boolean children, with the bridge being
	// CaseArm.When (boolean) → CaseArm.Then (scalar).
	OpAdd      // a + b (variadic)
	OpSub      // a - b (variadic; subtracts left-to-right)
	OpMul      // a * b (variadic)
	OpDiv      // a / b (binary)
	OpMod      // a % b (binary)
	OpNeg      // -a    (unary)
	OpCoalesce // COALESCE(a, b, ...)
	OpNullIf   // NULLIF(a, b)
	OpCase     // CASE WHEN ... THEN ... ELSE ... END (uses CaseArms + Else)
	OpCast     // CAST(a AS type) — uses CastType
	OpLiteral  // numeric/string/bool literal — uses Lit
	OpColRef   // column reference leaf — uses Left.Col

	// Aggregate-of-expression ops — only legal at the top level of a
	// non-aggregate's expr: argument, used for ratio-of-aggregates
	// (e.g. div(expr: { num_: { sum: { col: ... } }, den: ... })).
	OpAggSum
	OpAggAvg
	OpAggMin
	OpAggMax
	OpAggCount
)

func (ExpOp) String

func (i ExpOp) String() string

type Field

type Field struct {
	ID          int32
	ParentID    int32
	Type        FieldType
	Col         sdata.DBColumn
	Func        sdata.DBFunction
	FieldName   string
	FieldFilter Filter
	Args        []Arg
	SkipRender  SkipType
}

type FieldType

type FieldType int8
const (
	FieldTypeTable FieldType = iota
	FieldTypeCol
	FieldTypeFunc
)

func (FieldType) String

func (i FieldType) String() string

type Filter

type Filter struct {
	*Exp
}

type Fragment

type Fragment struct {
	Name  string
	Value []byte
}

type Function

type Function struct {
	Name string
	// Col       sdata.DBColumn
	Func sdata.DBFunction
	Args []Arg
	Agg  bool
}

type GeoExp added in v3.2.0

type GeoExp struct {
	// Geometry specification (one of these will be set)
	Point   []float64   // [longitude, latitude] for point
	Polygon [][]float64 // Array of [lon, lat] pairs for polygon ring
	GeoJSON []byte      // Full GeoJSON geometry object

	// Operation parameters
	Distance    float64 // Distance value for st_dwithin
	DistanceVar string  // Variable name for distance if parameterized
	Unit        GeoUnit // Distance unit (meters, km, miles, feet)
	SRID        int     // Spatial Reference ID (default 4326 = WGS84)

	// For MongoDB
	MinDistance float64 // $minDistance for $near
	Spherical   bool    // Use spherical calculations
}

GeoExp holds GIS-specific expression data

type GeoUnit added in v3.2.0

type GeoUnit int8

GeoUnit represents distance units for GIS operations

const (
	GeoUnitMeters GeoUnit = iota
	GeoUnitKilometers
	GeoUnitMiles
	GeoUnitFeet
)

func (GeoUnit) ToMeters added in v3.2.0

func (u GeoUnit) ToMeters(val float64) float64

ToMeters converts a distance value to meters based on the unit

type InsertConfig

type InsertConfig struct {
	Columns []string
	Presets map[string]string
	Block   bool
}

type Join

type Join struct {
	Filter *Exp
	Rel    sdata.DBRel
	Local  bool
}

type MColumn

type MColumn struct {
	Col       sdata.DBColumn
	FieldName string
	Alias     string
	Value     string
	Set       bool
}

type MRColumn

type MRColumn struct {
	Col  sdata.DBColumn
	VCol sdata.DBColumn
}

type MTable

type MTable struct {
	Ti sdata.DBTable
}

type MType

type MType uint8
const (
	MTInsert MType = iota + 1
	MTUpdate
	MTUpsert
	MTDelete
	MTConnect
	MTDisconnect
	MTNone
	MTKeyword
)

func (MType) String

func (i MType) String() string

type Mutate

type Mutate struct {
	Field

	ID        int32
	ParentID  int32
	SelID     int32
	DependsOn map[int32]struct{}
	Type      MType
	// CType     uint8
	Key   string
	Path  []string
	Val   json.RawMessage
	Cols  []MColumn
	RCols []MRColumn
	Ti    sdata.DBTable
	Rel   sdata.DBRel
	Where Filter
	Multi bool
	// contains filtered or unexported fields
}

type NewValidFn

type NewValidFn func(args []string) (fn ValidFn, err error)

type Order

type Order int8
const (
	OrderNone Order = iota
	OrderAsc
	OrderDesc
	OrderAscNullsFirst
	OrderAscNullsLast
	OrderDescNullsFirst
	OrderDescNullsLast
)

func (Order) String

func (o Order) String() string

type OrderBy

type OrderBy struct {
	KeyVar string
	Key    string
	Col    sdata.DBColumn
	Var    string
	Order  Order
	Func   sdata.DBFunction
	IsFunc bool
	// Alias is set when the user ordered by a SELECT-list alias rather
	// than a column name (e.g. order_by: { revenue: desc } where
	// `revenue` is an expression aggregate field's alias). The validator
	// confirms the alias resolves to a compiled field after
	// compileChildColumns runs; the renderer emits a bare quoted alias
	// (ORDER BY "revenue" DESC), which all 7 SQL dialects accept.
	Alias string
}

type Paging

type Paging struct {
	Type      PagingType
	LimitVar  string
	Limit     int32
	OffsetVar string
	Offset    int32
	Cursor    bool
	CursorVar string // "cursor" or "<fieldname>_cursor" for named cursor pagination
	NoLimit   bool
}

type PagingType

type PagingType int8
const (
	PTOffset PagingType = iota
	PTForward
	PTBackward
)

func (PagingType) String

func (i PagingType) String() string

type QCode

type QCode struct {
	Type      QType
	SType     QType
	Name      string
	ActionVar string
	ActionVal json.RawMessage
	Vars      []Var
	Selects   []Select
	Consts    []Constraint
	Roots     []int32

	Mutates   []Mutate
	MUnions   map[string][]int32
	Schema    *sdata.DBSchema
	Remotes   int32
	Cache     Cache
	Typename  bool
	Query     []byte
	Fragments []Fragment
	Warnings  []string // Non-fatal warnings (e.g., missing partition filter)
	// contains filtered or unexported fields
}

func (*QCode) ProcessConstraints

func (qc *QCode) ProcessConstraints(vmap map[string]json.RawMessage) (errs []ValidErr)

type QType

type QType int8
const (
	QTUnknown      QType = iota // Unknown
	QTQuery                     // Query
	QTSubscription              // Subcription
	QTMutation                  // Mutation
	QTInsert                    // Insert
	QTUpdate                    // Update
	QTDelete                    // Delete
	QTUpsert                    // Upsert
)

func GetQType

func GetQType(t graph.ParserType) QType

func GetQTypeByName

func GetQTypeByName(t string) QType

func (QType) String

func (i QType) String() string

type QueryConfig

type QueryConfig struct {
	Limit            int
	Filters          []string
	Columns          []string
	DisableFunctions bool
	Block            bool
}

type Schema

type Schema struct {
	Type           string
	Version        int
	Schema         string
	Columns        []sdata.DBColumn
	Functions      []sdata.DBFunction
	ClusteringKeys []TableCluster
}

func ParseSchema

func ParseSchema(b []byte) (ds Schema, err error)

type Script

type Script struct {
	Source string
	Name   string
}

type SelType

type SelType int8
const (
	SelTypeNone SelType = iota
	SelTypeUnion
	SelTypeMember
)

func (SelType) String

func (i SelType) String() string

type Select

type Select struct {
	Field
	Type     SelType
	Singular bool
	Typename bool
	Table    string
	Schema   string
	// Database is the target database for this select (multi-database support).
	// Empty string means the default database.
	Database   string
	Fields     []Field
	BCols      []Column
	IArgs      []Arg
	Where      Filter
	OrderBy    []OrderBy
	DistinctOn []sdata.DBColumn
	GroupCols  bool
	// GlobalAgg is true when this select uses aggregate functions
	// without `distinct` — i.e. the entire selection collapses to a
	// single row of global aggregates. Set in compileChildColumns
	// when aggExists && len(DistinctOn) == 0 && this is the top-level
	// select. Drives outer SELECT to skip __gj_id, BCols rendering to
	// emit nothing, and LIMIT to be omitted (a single row is the entire
	// result). Without this flag, the existing render path would emit
	// `LIMIT 20` and produce 20 degenerate per-row rows of aggregates
	// (the bug captured in broken.md).
	GlobalAgg               bool
	Paging                  Paging
	Children                []int32
	Ti                      sdata.DBTable
	Rel                     sdata.DBRel
	Joins                   []Join
	PartitionFilterRequired string
	Unrestricted            bool
	// contains filtered or unexported fields
}

func (*Select) GetInternalArg

func (sel *Select) GetInternalArg(name string) (Arg, bool)

type SkipType

type SkipType int8
const (
	SkipTypeNone SkipType = iota
	SkipTypeDrop
	SkipTypeNulled
	SkipTypeUserNeeded
	SkipTypeBlocked
	SkipTypeRemote
	// SkipTypeDatabaseJoin indicates this select targets a different database
	// and needs to be handled via cross-database join (similar to remote join
	// but for in-process database calls rather than HTTP)
	SkipTypeDatabaseJoin
)

func (SkipType) String

func (i SkipType) String() string

type TConfig

type TConfig struct {
	OrderBy map[string][][2]string
}

type TRConfig

type TRConfig struct {
	Query  QueryConfig
	Insert InsertConfig
	Update UpdateConfig
	Upsert UpsertConfig
	Delete DeleteConfig
}

type TableCluster added in v3.15.1

type TableCluster struct {
	Schema, Database, Table string
	Keys                    []string
}

TableCluster holds clustering key metadata parsed from a @cluster type directive.

type TableInfo

type TableInfo struct {
	sdata.DBTable
}

type UpdateConfig

type UpdateConfig struct {
	Filters []string
	Columns []string
	Presets map[string]string
	Block   bool
}

type UpsertConfig

type UpsertConfig struct {
	Filters []string
	Columns []string
	Presets map[string]string
	Block   bool
}

type ValType

type ValType int8
const (
	ValStr ValType = iota + 1
	ValNum
	ValBool
	ValList
	ValObj
	ValVar
	ValDBVar
	ValSubQuery
	ValPartitionBound // Renders as NOW() - INTERVAL N days (dialect-specific)
)

func (ValType) String

func (i ValType) String() string

type ValidErr

type ValidErr struct {
	FieldName  string `json:"field_name"`
	Constraint string `json:"constraint"`
}

type ValidFn

type ValidFn func(Vars, Constraint) bool

type Validation

type Validation struct {
	Source string
	Type   string
}

type Validator

type Validator struct {
	Description string
	Type        string
	List        bool
	Types       []graph.ParserType
	NewFn       NewValidFn
}

type Var

type Var struct {
	Name string
	Val  json.RawMessage
}

type Vars

type Vars map[string]json.RawMessage

Jump to

Keyboard shortcuts

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