query

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2026 License: MIT Imports: 18 Imported by: 5

Documentation

Index

Constants

View Source
const (
	WarningUpdateWithoutWhere      = "UPDATE_WITHOUT_WHERE"
	WarningDeleteWithoutWhere      = "DELETE_WITHOUT_WHERE"
	WarningSelectStarUsed          = "SELECT_STAR_USED"
	WarningLimitMissing            = "LIMIT_MISSING"
	WarningRawSQLUsed              = "RAW_SQL_USED"
	WarningBulkUpdateDetected      = "BULK_UPDATE_DETECTED"
	WarningBulkDeleteDetected      = "BULK_DELETE_DETECTED"
	WarningDestructiveSQL          = "DESTRUCTIVE_SQL_DETECTED"
	WarningWeakPredicate           = "WEAK_PREDICATE"
	WarningSuppressionExpired      = "SUPPRESSION_EXPIRED"
	WarningSuppressionNotAllowed   = "SUPPRESSION_NOT_ALLOWED"
	WarningStaticReviewPartial     = "STATIC_REVIEW_PARTIAL"
	WarningStaticReviewUnsupported = "STATIC_REVIEW_UNSUPPORTED"
)
View Source
const (
	WarningTenantFilterMissing     = "TENANT_FILTER_MISSING"
	WarningSoftDeleteFilterMissing = "SOFT_DELETE_FILTER_MISSING"
	WarningPIIColumnSelected       = "PII_COLUMN_SELECTED"
	WarningRequiredFilterMissing   = "REQUIRED_FILTER_MISSING"
)

Variables

View Source
var (
	ErrApprovalRequired       = errors.New("goquent: approval required")
	ErrApprovalReasonRequired = errors.New("goquent: approval reason required")
	ErrAccessReasonRequired   = errors.New("goquent: access reason required")
	ErrBlockedOperation       = errors.New("goquent: blocked operation")
)

Functions

func EnsurePlanExecutable added in v0.5.0

func EnsurePlanExecutable(plan *QueryPlan) error

EnsurePlanExecutable enforces approval and block rules for a finalized plan.

func RegisterTablePolicy added in v0.5.0

func RegisterTablePolicy(policy TablePolicy) error

RegisterTablePolicy registers or replaces a table policy.

func ResetPolicyRegistry added in v0.5.0

func ResetPolicyRegistry()

ResetPolicyRegistry clears registered policies. Intended for tests.

Types

type AnalysisPrecision added in v0.5.0

type AnalysisPrecision string

AnalysisPrecision describes how precisely Goquent could explain a query.

const (
	AnalysisPrecise     AnalysisPrecision = "precise"
	AnalysisPartial     AnalysisPrecision = "partial"
	AnalysisUnsupported AnalysisPrecision = "unsupported"
)

type Approval added in v0.5.0

type Approval struct {
	Reason    string     `json:"reason"`
	Scope     string     `json:"scope,omitempty"`
	CreatedBy string     `json:"created_by,omitempty"`
	CreatedAt time.Time  `json:"created_at,omitempty"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
}

Approval records an explicit approval reason for a risky operation.

type ColumnRef added in v0.5.0

type ColumnRef struct {
	Table      string `json:"table,omitempty"`
	Name       string `json:"name,omitempty"`
	Expression string `json:"expression,omitempty"`
	Raw        bool   `json:"raw,omitempty"`
	Distinct   bool   `json:"distinct,omitempty"`
	Count      bool   `json:"count,omitempty"`
	Function   string `json:"function,omitempty"`
}

ColumnRef describes a selected, inserted, or updated column.

type Evidence added in v0.5.0

type Evidence struct {
	Key   string `json:"key"`
	Value any    `json:"value,omitempty"`
}

Evidence stores machine-readable supporting details for a warning.

type JoinRef added in v0.5.0

type JoinRef struct {
	Type        string `json:"type,omitempty"`
	Table       string `json:"table,omitempty"`
	Alias       string `json:"alias,omitempty"`
	LeftColumn  string `json:"left_column,omitempty"`
	Operator    string `json:"operator,omitempty"`
	RightColumn string `json:"right_column,omitempty"`
	Subquery    bool   `json:"subquery,omitempty"`
}

JoinRef describes a JOIN visible in the query builder metadata.

type OperationType added in v0.5.0

type OperationType string

OperationType describes the structural SQL operation represented by a plan.

const (
	OperationSelect OperationType = "select"
	OperationInsert OperationType = "insert"
	OperationUpdate OperationType = "update"
	OperationDelete OperationType = "delete"
	OperationRaw    OperationType = "raw"
)

type PolicyMode added in v0.5.0

type PolicyMode string

PolicyMode controls how policy violations are represented in a QueryPlan.

const (
	PolicyModeWarn    PolicyMode = "warn"
	PolicyModeEnforce PolicyMode = "enforce"
	PolicyModeBlock   PolicyMode = "block"
)

type PredicateRef added in v0.5.0

type PredicateRef struct {
	Group       int    `json:"group,omitempty"`
	Connector   string `json:"connector,omitempty"`
	Column      string `json:"column,omitempty"`
	Operator    string `json:"operator,omitempty"`
	ValueCount  int    `json:"value_count,omitempty"`
	ValueColumn string `json:"value_column,omitempty"`
	Raw         string `json:"raw,omitempty"`
	Function    string `json:"function,omitempty"`
	Subquery    bool   `json:"subquery,omitempty"`
	Negated     bool   `json:"negated,omitempty"`
}

PredicateRef describes a WHERE-like predicate visible in the query builder metadata.

type Query

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

Query wraps goquent QueryBuilder and the executor.

func New

func New(exec executor, table string, dialect driver.Dialect) *Query

New creates a Query with given db and table.

func (*Query) AccessReason added in v0.5.0

func (q *Query) AccessReason(reason string) *Query

AccessReason records why this query needs access to sensitive columns.

func (*Query) Avg

func (q *Query) Avg(col string) *Query

Avg adds AVG aggregate function.

func (*Query) Build

func (q *Query) Build() (string, []any, error)

Build returns the SQL and args.

func (*Query) Count

func (q *Query) Count(cols ...string) (int64, error)

Count executes a COUNT query using the current conditions and returns the resulting row count.

func (*Query) CrossJoin

func (q *Query) CrossJoin(table string) *Query

CrossJoin adds CROSS JOIN clause.

func (*Query) Delete

func (q *Query) Delete() (sql.Result, error)

Delete executes a DELETE query using current conditions.

func (*Query) Distinct

func (q *Query) Distinct(cols ...string) *Query

Distinct marks columns as DISTINCT.

func (*Query) Dump

func (q *Query) Dump() (string, []any, error)

Dump returns SQL and args for debugging.

func (*Query) First

func (q *Query) First(dest any) error

First scans the first result into dest struct.

func (*Query) FirstMap

func (q *Query) FirstMap(dest *map[string]any) error

FirstMap scans first row into map.

func (*Query) Get added in v0.0.5

func (q *Query) Get(dest any) error

Get scans all rows into the slice pointed to by dest.

func (*Query) GetMaps

func (q *Query) GetMaps(dest *[]map[string]any) error

GetMaps scans all rows into slice of maps.

func (*Query) GroupBy

func (q *Query) GroupBy(cols ...string) *Query

GroupBy adds GROUP BY clause.

func (*Query) Having

func (q *Query) Having(col, cond string, val any) *Query

Having adds HAVING condition.

func (*Query) HavingRaw

func (q *Query) HavingRaw(raw string) *Query

HavingRaw adds raw HAVING condition.

func (*Query) Insert

func (q *Query) Insert(data any) (sql.Result, error)

Insert executes an INSERT with the given data.

func (*Query) InsertBatch

func (q *Query) InsertBatch(data []map[string]any) (sql.Result, error)

InsertBatch executes a bulk INSERT with the given slice of data maps.

func (*Query) InsertGetId

func (q *Query) InsertGetId(data any) (int64, error)

InsertGetId executes an INSERT and returns the auto-increment ID. For PostgreSQL, it appends a RETURNING clause for the configured primary key column because the driver does not support LastInsertId.

func (*Query) InsertOrIgnore

func (q *Query) InsertOrIgnore(data []map[string]any) (sql.Result, error)

InsertOrIgnore executes an INSERT IGNORE.

func (*Query) InsertUsing

func (q *Query) InsertUsing(columns []string, sub *Query) (sql.Result, error)

InsertUsing executes an INSERT INTO ... SELECT statement using columns from a subquery.

func (*Query) Join

func (q *Query) Join(table, localColumn, cond, target string) *Query

Join adds INNER JOIN clause.

func (*Query) JoinLateral added in v0.0.7

func (q *Query) JoinLateral(sub *Query, alias string) *Query

JoinLateral performs a LATERAL JOIN using a subquery.

func (*Query) JoinQuery added in v0.0.7

func (q *Query) JoinQuery(table string, fn func(b *qbapi.JoinClauseQueryBuilder)) *Query

JoinQuery adds a JOIN with additional ON/WHERE clauses defined in the callback.

func (*Query) JoinSubQuery added in v0.0.7

func (q *Query) JoinSubQuery(sub *Query, alias, my, condition, target string) *Query

JoinSubQuery joins a subquery with alias and join condition.

func (*Query) LeftJoin

func (q *Query) LeftJoin(table, localColumn, cond, target string) *Query

LeftJoin adds LEFT JOIN clause.

func (*Query) LeftJoinLateral added in v0.0.7

func (q *Query) LeftJoinLateral(sub *Query, alias string) *Query

LeftJoinLateral performs a LEFT LATERAL JOIN using a subquery.

func (*Query) LeftJoinQuery added in v0.0.7

func (q *Query) LeftJoinQuery(table string, fn func(b *qbapi.JoinClauseQueryBuilder)) *Query

LeftJoinQuery adds a LEFT JOIN with additional clauses defined in the callback.

func (*Query) LeftJoinSubQuery added in v0.0.7

func (q *Query) LeftJoinSubQuery(sub *Query, alias, my, condition, target string) *Query

LeftJoinSubQuery performs a LEFT JOIN using a subquery.

func (*Query) Limit

func (q *Query) Limit(n int) *Query

Limit sets a limit.

func (*Query) LockForUpdate

func (q *Query) LockForUpdate() *Query

LockForUpdate adds FOR UPDATE clause.

func (*Query) Max

func (q *Query) Max(col string) *Query

Max adds MAX aggregate function.

func (*Query) Min

func (q *Query) Min(col string) *Query

Min adds MIN aggregate function.

func (*Query) Offset

func (q *Query) Offset(n int) *Query

Offset sets offset.

func (*Query) OnlyDeleted added in v0.5.0

func (q *Query) OnlyDeleted() *Query

OnlyDeleted restricts a soft-delete policy table to deleted rows.

func (*Query) OrHaving

func (q *Query) OrHaving(col, cond string, val any) *Query

OrHaving adds OR HAVING condition.

func (*Query) OrHavingRaw

func (q *Query) OrHavingRaw(raw string) *Query

OrHavingRaw adds raw OR HAVING condition.

func (*Query) OrWhere

func (q *Query) OrWhere(col string, args ...any) *Query

OrWhere appends OR condition.

func (*Query) OrWhereBetween

func (q *Query) OrWhereBetween(col string, min, max any) *Query

OrWhereBetween adds OR WHERE BETWEEN condition.

func (*Query) OrWhereBetweenColumns

func (q *Query) OrWhereBetweenColumns(col, minCol, maxCol string) *Query

OrWhereBetweenColumns adds OR WHERE col BETWEEN minCol AND maxCol using columns.

func (*Query) OrWhereColumn

func (q *Query) OrWhereColumn(col string, args ...string) *Query

OrWhereColumn adds OR WHERE column operator column condition.

func (*Query) OrWhereColumns

func (q *Query) OrWhereColumns(columns [][]string) *Query

OrWhereColumns adds multiple column comparison conditions joined by OR.

func (*Query) OrWhereDate

func (q *Query) OrWhereDate(col, cond, date string) *Query

OrWhereDate adds OR WHERE DATE(column) comparison condition.

func (*Query) OrWhereDay

func (q *Query) OrWhereDay(col, cond, day string) *Query

OrWhereDay adds OR WHERE DAY(column) comparison condition.

func (*Query) OrWhereExists

func (q *Query) OrWhereExists(sub *Query) *Query

OrWhereExists adds OR WHERE EXISTS (subquery) condition.

func (*Query) OrWhereFullText

func (q *Query) OrWhereFullText(cols []string, search string, opts map[string]any) *Query

OrWhereFullText adds OR full-text search condition.

func (*Query) OrWhereGroup added in v0.0.7

func (q *Query) OrWhereGroup(fn func(g *Query)) *Query

OrWhereGroup groups conditions with parentheses using OR logic.

func (*Query) OrWhereIn

func (q *Query) OrWhereIn(col string, vals any) *Query

OrWhereIn adds OR WHERE IN condition.

func (*Query) OrWhereInSubQuery

func (q *Query) OrWhereInSubQuery(col string, sub *Query) *Query

OrWhereInSubQuery adds OR WHERE IN (subquery) condition.

func (*Query) OrWhereMonth

func (q *Query) OrWhereMonth(col, cond, month string) *Query

OrWhereMonth adds OR WHERE MONTH(column) comparison condition.

func (*Query) OrWhereNot added in v0.0.7

func (q *Query) OrWhereNot(fn func(g *Query)) *Query

OrWhereNot groups conditions inside OR NOT (...).

func (*Query) OrWhereNotBetween

func (q *Query) OrWhereNotBetween(col string, min, max any) *Query

OrWhereNotBetween adds OR WHERE NOT BETWEEN condition.

func (*Query) OrWhereNotBetweenColumns

func (q *Query) OrWhereNotBetweenColumns(col, minCol, maxCol string) *Query

OrWhereNotBetweenColumns adds OR WHERE col NOT BETWEEN minCol AND maxCol using columns.

func (*Query) OrWhereNotExists

func (q *Query) OrWhereNotExists(sub *Query) *Query

OrWhereNotExists adds OR WHERE NOT EXISTS (subquery) condition.

func (*Query) OrWhereNotIn

func (q *Query) OrWhereNotIn(col string, vals any) *Query

OrWhereNotIn adds OR WHERE NOT IN condition.

func (*Query) OrWhereNotInSubQuery

func (q *Query) OrWhereNotInSubQuery(col string, sub *Query) *Query

OrWhereNotInSubQuery adds OR WHERE NOT IN (subquery) condition.

func (*Query) OrWhereNotNull

func (q *Query) OrWhereNotNull(col string) *Query

OrWhereNotNull adds OR WHERE column IS NOT NULL condition.

func (*Query) OrWhereNull

func (q *Query) OrWhereNull(col string) *Query

OrWhereNull adds OR WHERE column IS NULL condition.

func (*Query) OrWhereRaw

func (q *Query) OrWhereRaw(raw string, vals map[string]any) *Query

OrWhereRaw appends raw OR WHERE condition.

func (*Query) OrWhereTime

func (q *Query) OrWhereTime(col, cond, time string) *Query

OrWhereTime adds OR WHERE TIME(column) comparison condition.

func (*Query) OrWhereYear

func (q *Query) OrWhereYear(col, cond, year string) *Query

OrWhereYear adds OR WHERE YEAR(column) comparison condition.

func (*Query) OrderBy

func (q *Query) OrderBy(col, dir string) *Query

OrderBy adds ORDER BY clause.

func (*Query) OrderByRaw

func (q *Query) OrderByRaw(raw string) *Query

OrderByRaw adds raw ORDER BY clause.

func (*Query) Plan added in v0.5.0

func (q *Query) Plan(ctx context.Context) (*QueryPlan, error)

Plan builds a QueryPlan for the current SELECT query without executing it.

func (*Query) PlanDelete added in v0.5.0

func (q *Query) PlanDelete(ctx context.Context) (*QueryPlan, error)

PlanDelete builds a DELETE plan without executing it.

func (*Query) PlanInsert added in v0.5.0

func (q *Query) PlanInsert(ctx context.Context, data any) (*QueryPlan, error)

PlanInsert builds an INSERT plan for data without executing it.

func (*Query) PlanInsertBatch added in v0.5.0

func (q *Query) PlanInsertBatch(ctx context.Context, data []map[string]any) (*QueryPlan, error)

PlanInsertBatch builds a batch INSERT plan without executing it.

func (*Query) PlanUpdate added in v0.5.0

func (q *Query) PlanUpdate(ctx context.Context, data any) (*QueryPlan, error)

PlanUpdate builds an UPDATE plan for data without executing it.

func (*Query) PrimaryKey added in v0.2.1

func (q *Query) PrimaryKey(col string) *Query

PrimaryKey sets the primary key column for the table.

func (*Query) RawSQL

func (q *Query) RawSQL() (string, error)

RawSQL returns interpolated SQL for debugging.

func (*Query) ReOrder

func (q *Query) ReOrder() *Query

ReOrder clears ORDER BY clauses.

func (*Query) RequireApproval added in v0.5.0

func (q *Query) RequireApproval(reason string) *Query

RequireApproval records an explicit reason for executing a risky query.

func (*Query) RightJoin

func (q *Query) RightJoin(table, localColumn, cond, target string) *Query

RightJoin adds RIGHT JOIN clause.

func (*Query) RightJoinQuery added in v0.0.7

func (q *Query) RightJoinQuery(table string, fn func(b *qbapi.JoinClauseQueryBuilder)) *Query

RightJoinQuery adds a RIGHT JOIN with additional clauses defined in the callback.

func (*Query) RightJoinSubQuery added in v0.0.7

func (q *Query) RightJoinSubQuery(sub *Query, alias, my, condition, target string) *Query

RightJoinSubQuery performs a RIGHT JOIN using a subquery.

func (*Query) SafeOrWhereRaw added in v0.0.7

func (q *Query) SafeOrWhereRaw(raw string, vals map[string]any) *Query

SafeOrWhereRaw appends a raw OR WHERE condition ensuring a values map is used.

func (*Query) SafeWhereRaw added in v0.0.7

func (q *Query) SafeWhereRaw(raw string, vals map[string]any) *Query

SafeWhereRaw appends a raw WHERE condition ensuring a values map is always used.

func (*Query) Select

func (q *Query) Select(cols ...string) *Query

Select sets selected columns.

func (*Query) SelectRaw

func (q *Query) SelectRaw(raw string, values ...any) *Query

SelectRaw adds a raw select expression.

func (*Query) SharedLock

func (q *Query) SharedLock() *Query

SharedLock adds LOCK IN SHARE MODE clause.

func (*Query) Skip

func (q *Query) Skip(n int) *Query

Skip is an alias of Offset.

func (*Query) Sum

func (q *Query) Sum(col string) *Query

Sum adds SUM aggregate function.

func (*Query) SuppressWarning added in v0.5.0

func (q *Query) SuppressWarning(code, reason string, opts ...SuppressionOption) *Query

SuppressWarning suppresses a suppressible warning for this query plan.

func (*Query) Take

func (q *Query) Take(n int) *Query

Take is an alias of Limit.

func (*Query) Union

func (q *Query) Union(sub *Query) *Query

Union adds a UNION with another query.

func (*Query) UnionAll

func (q *Query) UnionAll(sub *Query) *Query

UnionAll adds a UNION ALL with another query.

func (*Query) Update

func (q *Query) Update(data any) (sql.Result, error)

Update executes an UPDATE with the given data.

func (*Query) UpdateOrInsert

func (q *Query) UpdateOrInsert(cond map[string]any, values map[string]any) (sql.Result, error)

UpdateOrInsert performs UPDATE or INSERT based on condition.

func (*Query) Upsert

func (q *Query) Upsert(data []map[string]any, unique []string, updateCols []string) (sql.Result, error)

Upsert executes an UPSERT using ON DUPLICATE KEY UPDATE.

func (*Query) Where

func (q *Query) Where(col string, args ...any) *Query

Where appends a column/value comparison. Values are always treated as literals. Use WhereColumn for column-to-column comparisons.

func (*Query) WhereAll

func (q *Query) WhereAll(cols []string, cond string, val any) *Query

WhereAll adds grouped AND conditions across columns.

func (*Query) WhereAny

func (q *Query) WhereAny(cols []string, cond string, val any) *Query

WhereAny adds grouped OR conditions across columns.

func (*Query) WhereBetween

func (q *Query) WhereBetween(col string, min, max any) *Query

WhereBetween adds WHERE BETWEEN condition.

func (*Query) WhereBetweenColumns

func (q *Query) WhereBetweenColumns(col, minCol, maxCol string) *Query

WhereBetweenColumns adds WHERE col BETWEEN minCol AND maxCol using columns.

func (*Query) WhereColumn

func (q *Query) WhereColumn(col string, args ...string) *Query

WhereColumn adds WHERE column operator column condition.

func (*Query) WhereColumns

func (q *Query) WhereColumns(columns [][]string) *Query

WhereColumns adds multiple column comparison conditions joined by AND.

func (*Query) WhereDate

func (q *Query) WhereDate(col, cond, date string) *Query

WhereDate adds WHERE DATE(column) comparison condition.

func (*Query) WhereDay

func (q *Query) WhereDay(col, cond, day string) *Query

WhereDay adds WHERE DAY(column) comparison condition.

func (*Query) WhereExists

func (q *Query) WhereExists(sub *Query) *Query

WhereExists adds WHERE EXISTS (subquery) condition.

func (*Query) WhereFullText

func (q *Query) WhereFullText(cols []string, search string, opts map[string]any) *Query

WhereFullText adds full-text search condition.

func (*Query) WhereGroup added in v0.0.7

func (q *Query) WhereGroup(fn func(g *Query)) *Query

WhereGroup groups conditions with parentheses using AND logic.

func (*Query) WhereIn

func (q *Query) WhereIn(col string, vals any) *Query

WhereIn adds WHERE IN condition.

func (*Query) WhereInSubQuery

func (q *Query) WhereInSubQuery(col string, sub *Query) *Query

WhereInSubQuery adds WHERE IN (subquery) condition.

func (*Query) WhereMonth

func (q *Query) WhereMonth(col, cond, month string) *Query

WhereMonth adds WHERE MONTH(column) comparison condition.

func (*Query) WhereNot added in v0.0.7

func (q *Query) WhereNot(fn func(g *Query)) *Query

WhereNot groups conditions inside NOT (...).

func (*Query) WhereNotBetween

func (q *Query) WhereNotBetween(col string, min, max any) *Query

WhereNotBetween adds WHERE NOT BETWEEN condition.

func (*Query) WhereNotBetweenColumns

func (q *Query) WhereNotBetweenColumns(col, minCol, maxCol string) *Query

WhereNotBetweenColumns adds WHERE col NOT BETWEEN minCol AND maxCol using columns.

func (*Query) WhereNotExists

func (q *Query) WhereNotExists(sub *Query) *Query

WhereNotExists adds WHERE NOT EXISTS (subquery) condition.

func (*Query) WhereNotIn

func (q *Query) WhereNotIn(col string, vals any) *Query

WhereNotIn adds WHERE NOT IN condition.

func (*Query) WhereNotInSubQuery

func (q *Query) WhereNotInSubQuery(col string, sub *Query) *Query

WhereNotInSubQuery adds WHERE NOT IN (subquery) condition.

func (*Query) WhereNotNull

func (q *Query) WhereNotNull(col string) *Query

WhereNotNull adds WHERE column IS NOT NULL condition.

func (*Query) WhereNull

func (q *Query) WhereNull(col string) *Query

WhereNull adds WHERE column IS NULL condition.

func (*Query) WhereRaw

func (q *Query) WhereRaw(raw string, vals map[string]any) *Query

WhereRaw appends raw WHERE condition.

func (*Query) WhereTime

func (q *Query) WhereTime(col, cond, time string) *Query

WhereTime adds WHERE TIME(column) comparison condition.

func (*Query) WhereYear

func (q *Query) WhereYear(col, cond, year string) *Query

WhereYear adds WHERE YEAR(column) comparison condition.

func (*Query) WithContext added in v0.0.4

func (q *Query) WithContext(ctx context.Context) *Query

WithContext sets ctx on the query for context-aware execution.

func (*Query) WithDeleted added in v0.5.0

func (q *Query) WithDeleted() *Query

WithDeleted disables the default soft-delete filter for a policy table.

type QueryPlan added in v0.5.0

type QueryPlan struct {
	Operation          OperationType     `json:"operation"`
	SQL                string            `json:"sql"`
	Params             []any             `json:"params"`
	Tables             []TableRef        `json:"tables,omitempty"`
	Columns            []ColumnRef       `json:"columns,omitempty"`
	Joins              []JoinRef         `json:"joins,omitempty"`
	Predicates         []PredicateRef    `json:"predicates,omitempty"`
	Limit              *int64            `json:"limit,omitempty"`
	Offset             *int64            `json:"offset,omitempty"`
	EstimatedRows      *int64            `json:"estimated_rows,omitempty"`
	UsesIndex          *bool             `json:"uses_index,omitempty"`
	RiskLevel          RiskLevel         `json:"risk_level"`
	Warnings           []Warning         `json:"warnings,omitempty"`
	SuppressedWarnings []Warning         `json:"suppressed_warnings,omitempty"`
	RequiredApproval   bool              `json:"required_approval"`
	Blocked            bool              `json:"blocked,omitempty"`
	Approval           *Approval         `json:"approval,omitempty"`
	AnalysisPrecision  AnalysisPrecision `json:"analysis_precision"`
	Metadata           map[string]any    `json:"metadata,omitempty"`
}

QueryPlan explains SQL and metadata before the query is executed.

func NewRawPlan added in v0.5.0

func NewRawPlan(sqlStr string, args ...any) *QueryPlan

NewRawPlan creates a plan for caller-supplied SQL. It does not execute SQL.

func (*QueryPlan) RequiresApproval added in v0.5.0

func (p *QueryPlan) RequiresApproval() bool

RequiresApproval reports whether this plan needs explicit approval.

func (*QueryPlan) String added in v0.5.0

func (p *QueryPlan) String() string

String returns a compact pretty format suitable for logs and CLI output.

func (*QueryPlan) ToJSON added in v0.5.0

func (p *QueryPlan) ToJSON() ([]byte, error)

ToJSON returns stable, indented JSON for the plan.

type RiskConfig added in v0.5.0

type RiskConfig struct {
	Environment string                    `json:"environment,omitempty"`
	Rules       map[string]RiskRuleConfig `json:"rules,omitempty"`
}

RiskConfig customizes risk rules for an environment or caller.

type RiskEngine added in v0.5.0

type RiskEngine interface {
	CheckQuery(plan *QueryPlan) RiskResult
}

RiskEngine deterministically evaluates the structural DB risk of a query plan.

var DefaultRiskEngine RiskEngine = defaultRiskEngine{}

DefaultRiskEngine is the built-in deterministic risk engine.

func NewRiskEngine added in v0.5.0

func NewRiskEngine(config RiskConfig) RiskEngine

NewRiskEngine creates a deterministic risk engine using config overrides.

type RiskLevel added in v0.5.0

type RiskLevel string

RiskLevel is structural database risk, not a business-safety guarantee.

const (
	RiskLow         RiskLevel = "low"
	RiskMedium      RiskLevel = "medium"
	RiskHigh        RiskLevel = "high"
	RiskDestructive RiskLevel = "destructive"
	RiskBlocked     RiskLevel = "blocked"
)

type RiskResult added in v0.5.0

type RiskResult struct {
	Level            RiskLevel `json:"level"`
	Warnings         []Warning `json:"warnings,omitempty"`
	RequiredApproval bool      `json:"required_approval"`
	Blocked          bool      `json:"blocked"`
}

RiskResult is the result of applying risk rules to a query plan.

type RiskRuleConfig added in v0.5.0

type RiskRuleConfig struct {
	Enabled        *bool      `json:"enabled,omitempty"`
	Severity       *RiskLevel `json:"severity,omitempty"`
	Suppressible   *bool      `json:"suppressible,omitempty"`
	RequiresReason *bool      `json:"requires_reason,omitempty"`
}

RiskRuleConfig customizes a built-in warning rule.

type SourceLocation added in v0.5.0

type SourceLocation struct {
	File   string `json:"file,omitempty"`
	Line   int    `json:"line,omitempty"`
	Column int    `json:"column,omitempty"`
}

SourceLocation points at source code when a plan/finding is derived from static analysis.

type Suppression added in v0.5.0

type Suppression struct {
	Code      string           `json:"code"`
	Reason    string           `json:"reason"`
	Scope     SuppressionScope `json:"scope"`
	Location  *SourceLocation  `json:"location,omitempty"`
	ExpiresAt *time.Time       `json:"expires_at,omitempty"`
	Owner     string           `json:"owner,omitempty"`
}

Suppression suppresses an expected warning while keeping accountability data.

func NewSuppression added in v0.5.0

func NewSuppression(code, reason string, opts ...SuppressionOption) (Suppression, error)

NewSuppression creates a query-scoped suppression.

func ParseInlineSuppression added in v0.5.0

func ParseInlineSuppression(comment string) (Suppression, bool, error)

ParseInlineSuppression parses comments like: goquent:suppress LIMIT_MISSING reason="batch export" expires="2026-07-01"

type SuppressionOption added in v0.5.0

type SuppressionOption func(*Suppression)

SuppressionOption configures a runtime suppression.

func SuppressionExpiresAt added in v0.5.0

func SuppressionExpiresAt(t time.Time) SuppressionOption

SuppressionExpiresAt sets the expiration timestamp for a suppression.

func SuppressionOwner added in v0.5.0

func SuppressionOwner(owner string) SuppressionOption

SuppressionOwner sets the suppression owner.

type SuppressionScope added in v0.5.0

type SuppressionScope string

SuppressionScope describes where a suppression applies.

const (
	SuppressionScopeQuery  SuppressionScope = "query"
	SuppressionScopeInline SuppressionScope = "inline"
	SuppressionScopeConfig SuppressionScope = "config"
)

type TablePolicy added in v0.5.0

type TablePolicy struct {
	Table                 string     `json:"table"`
	TenantColumn          string     `json:"tenant_column,omitempty"`
	TenantMode            PolicyMode `json:"tenant_mode,omitempty"`
	SoftDeleteColumn      string     `json:"soft_delete_column,omitempty"`
	SoftDeleteMode        PolicyMode `json:"soft_delete_mode,omitempty"`
	PIIColumns            []string   `json:"pii_columns,omitempty"`
	PIIMode               PolicyMode `json:"pii_mode,omitempty"`
	RequiredFilterColumns []string   `json:"required_filter_columns,omitempty"`
	RequiredFilterMode    PolicyMode `json:"required_filter_mode,omitempty"`
}

TablePolicy describes application-specific safety policy for a table.

func PolicyForTable added in v0.5.0

func PolicyForTable(table string) (TablePolicy, bool)

PolicyForTable returns a registered policy for table.

func RegisteredTablePolicies added in v0.5.0

func RegisteredTablePolicies() []TablePolicy

RegisteredTablePolicies returns all registered table policies in stable order.

type TableRef added in v0.5.0

type TableRef struct {
	Name  string `json:"name"`
	Alias string `json:"alias,omitempty"`
}

TableRef describes a table touched by the query.

type Warning added in v0.5.0

type Warning struct {
	Code           string          `json:"code"`
	Level          RiskLevel       `json:"level"`
	Message        string          `json:"message"`
	Location       *SourceLocation `json:"location,omitempty"`
	Hint           string          `json:"hint,omitempty"`
	Evidence       []Evidence      `json:"evidence,omitempty"`
	Suppressible   bool            `json:"suppressible"`
	RequiresReason bool            `json:"requires_reason"`
}

Warning is a reviewable issue attached to a plan.

Jump to

Keyboard shortcuts

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