spec

package
v0.511.0 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: Apache-2.0 Imports: 1 Imported by: 0

README

Domain Spec Module

Normalized statement specifications used as the stable input for rule evaluation.

Files

File Responsibility
statement.go Defines the top-level normalized statement model and parser-neutral extraction interface
statement_test.go Verifies typed statement metadata behavior
metadata.go Defines optional schema context, instance facts, target-table snapshots, object-level validation snapshots, and lookup helpers for metadata-aware auditing
ddl.go Defines DDL-oriented specification types, including explicit DDL operations, richer column facts, typed index metadata, and create-table/object-lifecycle shape flags for offline and metadata-aware DDL rules
dml_impact.go Defines shared DML impact estimation enums and payload types reused across audit layers
dml.go Defines DML-oriented specification types, including operation metadata, mentioned tables, MutationTargets, and MutationTargetTables() fallback to Tables

Exports

  • Statement
  • UnsupportedDetail
  • Diagnostic
  • DiagnosticParserError
  • StatementExtractor
  • Kind
  • Dialect Includes DialectPostgreSQL for PostgreSQL routing support
  • Metadata Now carries Objects []ObjectSnapshot for non-table object validation
  • InstanceFacts
  • TableSnapshot
  • ObjectSnapshot
  • MetadataStatus
  • DDL
  • DDLOperation
  • Table
  • Column
  • Constraint
  • Index
  • IndexKind
  • ImpactSource
  • ImpactRisk
  • ImpactConfidence
  • PredicateShape
  • ImpactEstimate
  • AlterColumnChange
  • AlterColumn
  • AlterIndex
  • Alter
  • DML
  • (*DML).MutationTargetTables()
  • DMLOperation

Notes

  • Statement may now carry optional metadata-aware context through Metadata and an additive Unsupported payload for recognized-but-unsupported statements so mixed PostgreSQL results can preserve supported statements while surfacing structured unsupported details.

  • UnsupportedDetail carries the unsupported statement index, feature name, original SQL, and reason so CLI/API surfaces can render machine-readable partial-support outcomes.

  • Diagnostic carries structured evidence about unaudited or unsupported outcomes with stable classification, safe reason, generic action_hint, audited=false, and selected dialect. Optional line and column identify the 1-based start of a bounded parser-failed statement; optional guidance_code and evidence_ref classify documented parser boundaries. The no-leak contract prohibits raw SQL text, parser near ... fragments, routine bodies, and inferred object names.

  • Statement may now carry optional metadata-aware context through Metadata:

    • Schema for request-level schema context even when no provider is attached
    • Instance for normalized server-level facts such as version and InnoDB defaults
    • TargetTable for the current metadata-backed shape of the table being audited
    • Objects for non-table object validation snapshots (types, domains, extensions, publications, subscriptions, foreign objects, event triggers, rewrite rules, annotation targets)
  • TableSnapshot includes convenience lookups for case-insensitive column/index existence checks so future rules do not need to duplicate iteration logic.

  • ObjectSnapshot carries metadata-validated state for non-table database objects with Status (confirmed/not_found/unavailable/ambiguous), Exists, Schema, Type, Name, safe Attributes, and optional AmbiguousCandidates.

  • MetadataStatus identifies the outcome of a metadata object lookup: confirmed (object exists), not_found (object absent), unavailable (lookup not performed), ambiguous (identity not uniquely resolved).

  • Metadata.FindObject and Metadata.FindObjectsByType provide case-insensitive lookup across attached object snapshots.

  • ObjectSnapshot.SafeAttributes filters out sensitive attribute keys (password, secret, token, connection, body, definition, etc.) to prevent leaking secrets through metadata projection.

  • DML.Tables preserves mentioned relations. DML.MutationTargets names the tables a statement writes. MutationTargetTables() returns MutationTargets when filled and otherwise falls back to Tables so denylist, metadata, and existence rules do not rediscover targets from AST nodes.

  • DiagnosticParserError is the named classification for a statement the dialect parser could not parse. Output adapters compare this constant instead of the string "parser_error".

  • DML.HasReturning records whether a real DML RETURNING clause was parsed. It is a structural parser fact projected from the AST (len(stmt.Returning) > 0), not a raw token scan, so an identifier or table alias named returning does not set it. It captures clause presence only; it does not carry returned column names, expressions, aliases, or any parser subtree.

  • Column now carries offline-governance facts needed by column-focused DDL rules:

    • Length
    • Charset
    • Collation
    • Unsigned
    • NotNull
    • AutoIncrement
    • HasDefault
    • DefaultValue
    • DefaultIsNull
    • DefaultIsCurrentTimestamp
    • OnUpdateCurrentTimestamp
  • DDL also carries create-table shape flags for:

    • CREATE TABLE ... LIKE
    • CREATE TABLE ... AS SELECT
    • partitioned tables
  • DDL has optional ObjectName / ObjectType for object lifecycle DDL (schema, sequence, materialized view, extension create/drop/alter). ObjectType is "database" for MySQL/TiDB database/schema statements and "schema" for PostgreSQL schema statements.

  • DDL.Operation now distinguishes create_table, create_view, alter_view, alter_table, drop_table, drop_index, drop_view, truncate_table, create_schema, drop_schema, create_sequence, alter_sequence, drop_sequence, create_materialized_view, drop_materialized_view, refresh_materialized_view, create_type, alter_type, drop_type, create_domain, alter_domain, drop_domain, create_extension, alter_extension, drop_extension, create_function, drop_function, create_procedure, drop_procedure, grant_table, revoke_table, create_event_trigger, alter_event_trigger, drop_event_trigger, create_rule, alter_rule, drop_rule, create_collation, alter_collation, drop_collation, create_statistics, alter_statistics, and drop_statistics so lifecycle rules do not rely on structural guesswork.

  • DDL preserves explicit naming-governance subjects directly on the normalized model:

    • Table.Name for table-level rules
    • Column.Name for column-level rules
    • PrimaryKey.Name plus PrimaryKey.Kind
    • Indexes[].Name plus Indexes[].Kind for unique, secondary, and fulltext index rules
    • Indexes[].AccessMethod for access method (defaults to btree when empty)
    • Indexes[].IncludedColumns for INCLUDE clause column names
    • Indexes[].HasPredicate for partial index predicate presence
    • Indexes[].HasExpressionKeys for expression index key presence
    • Indexes[].ExpressionCount for count of expression key entries
    • PrimaryKey.Cardinality plus Indexes[].Cardinality for additive metadata-aware selectivity hints, where nil means unknown and a present 0 remains distinguishable at the JSON boundary
    • Constraints[].Name plus Constraints[].Type for non-index constraints such as foreign keys and checks when extraction provides explicit names
  • DML now preserves additive impact-estimation facts without changing existing rule inputs:

    • PredicateShape for parser-neutral predicate classification
    • LookupColumns for normalized lookup-column tracking
    • MatchedKeyName and MatchedKeyKind for the best matching index hint
    • IsSingleTable to distinguish single-table from join or multi-target mutations
    • Impact for the final conservative estimate payload with estimated_rows, estimated_ratio, risk_level, confidence, source, reason_codes, and optional notes
    • offline mode derives the initial estimate from SQL shape only
    • metadata-aware mode may refine that estimate with read-only table statistics without executing the DML
  • Alter now has room for richer normalized payloads and may also carry standalone DDL action subjects, such as PostgreSQL DROP INDEX, when no table object exists:

    • Name is the canonical subject identifier:
      • existing-object actions use the pre-change name
      • pure-add actions use the created object name
      • table-option actions leave it empty
    • Column carries:
      • OldName for the existing source-side identifier when the statement names one
      • an optional target Definition reused from Column
      • rename intent is inferred from OldName plus Definition.Name, not a separate boolean
      • an optional Change block with statement-local relation facts only for semantics the statement explicitly spells out, such as nullability, default, and auto-increment
      • target type and unsigned shape still live on Definition, but are not separately labeled as touched change facts
    • Index carries OldName plus an optional target Definition reused from Index
    • Options is intentionally a flat normalized subset of table options, not a full option AST or ordering-preserving model

Dependencies

  • Upstream: application extraction and domain rule evaluation
  • Downstream: none inside the domain core

Update Rule

  • If members/interfaces/dependencies change, update this file in same change.

Documentation

Overview

Package spec defines normalized statement specifications for rule evaluation. input: DDL facts extracted from parser-specific AST adapters output: parser-neutral DDL specification components for rules pos: domain DDL specification model under the unified Statement spec note: if this file changes, update this header and module README.md.

Package spec defines normalized statement specifications for rule evaluation. input: DML facts extracted from parser-specific AST adapters output: parser-neutral DML specification components, including mentioned tables and MutationTargets for the tables a statement writes pos: domain DML specification model under the unified Statement spec note: if this file changes, update this header and module README.md.

Package spec defines normalized statement specifications for rule evaluation. input: parser-neutral DML impact estimation facts attached during audit orchestration output: shared impact contract reused across domain, report, and public API layers pos: domain DML impact model under the unified Statement spec note: if this file changes, update this header and module README.md.

Package spec defines normalized statement specifications for rule evaluation. input: optional metadata-aware audit facts such as instance variables and target-table snapshots output: parser-neutral metadata structures and lookup helpers for future rules pos: domain metadata model shared by offline and metadata-aware audit paths note: if this file changes, update this header and module README.md.

Package spec defines normalized statement specifications for rule evaluation. input: statement data extracted from parser-specific AST adapters output: parser-neutral statement models and source-located audit diagnostics for domain processing pos: domain specification model for all auditable SQL statements note: if this file changes, update this header and module README.md.

Index

Constants

View Source
const (
	// DiagnosticParserError classifies a statement the dialect parser could not parse.
	DiagnosticParserError = "parser_error"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Alter

type Alter struct {
	Action  string            `json:"action"`
	Name    string            `json:"name,omitempty"`
	Column  *AlterColumn      `json:"column,omitempty"`
	Index   *AlterIndex       `json:"index,omitempty"`
	Options map[string]string `json:"options,omitempty"`
}

Alter describes a normalized alter action. Name is the canonical subject identifier for downstream matching: existing-object actions use the pre-change name, pure additions use the created object's name, and table-option actions leave it empty.

type AlterColumn

type AlterColumn struct {
	OldName    string             `json:"old_name,omitempty"`
	Definition *Column            `json:"definition,omitempty"`
	Change     *AlterColumnChange `json:"change,omitempty"`
}

AlterColumn describes a column-focused alter payload. OldName is only populated when the action targets an existing column name. Definition carries the target column shape after the action when available. Change carries parser-neutral statement-local relation facts for upcoming source-aware alter rules.

type AlterColumnChange

type AlterColumnChange struct {
	TouchesNullability   bool `json:"touches_nullability,omitempty"`
	TouchesDefault       bool `json:"touches_default,omitempty"`
	TouchesAutoIncrement bool `json:"touches_auto_increment,omitempty"`
}

AlterColumnChange describes statement-local column-change intent. These flags are parser-neutral hints about what the ALTER statement touches; they do not claim live-schema source truth on their own.

type AlterIndex

type AlterIndex struct {
	OldName    string `json:"old_name,omitempty"`
	Definition *Index `json:"definition,omitempty"`
}

AlterIndex describes an index-focused alter payload. OldName is only populated when the action targets an existing index name. Definition carries the target index shape after the action when available.

type Column

type Column struct {
	Name                      string         `json:"name"`
	Type                      string         `json:"type,omitempty"`
	Length                    int            `json:"length,omitempty"`
	Charset                   string         `json:"charset,omitempty"`
	Collation                 string         `json:"collation,omitempty"`
	Comment                   string         `json:"comment,omitempty"`
	Unsigned                  bool           `json:"unsigned,omitempty"`
	NotNull                   bool           `json:"not_null,omitempty"`
	AutoIncrement             bool           `json:"auto_increment,omitempty"`
	HasDefault                bool           `json:"has_default,omitempty"`
	DefaultValue              string         `json:"default_value,omitempty"`
	DefaultKind               string         `json:"default_kind,omitempty"`
	DefaultIsNull             bool           `json:"default_is_null,omitempty"`
	DefaultIsCurrentTimestamp bool           `json:"default_is_current_timestamp,omitempty"`
	OnUpdateCurrentTimestamp  bool           `json:"on_update_current_timestamp,omitempty"`
	GeneratedWhen             string         `json:"generated_when,omitempty"`
	IsIdentity                bool           `json:"is_identity,omitempty"`
	IdentityOptions           map[string]any `json:"identity_options,omitempty"`
}

Column describes a table column.

type Constraint

type Constraint struct {
	Type              string   `json:"type"`
	Name              string   `json:"name,omitempty"`
	Columns           []string `json:"columns,omitempty"`
	ReferencedSchema  string   `json:"referenced_schema,omitempty"`
	ReferencedTable   string   `json:"referenced_table,omitempty"`
	ReferencedColumns []string `json:"referenced_columns,omitempty"`
}

Constraint describes a non-index table constraint worth preserving for later rules.

type DDL

type DDL struct {
	Operation   DDLOperation `json:"operation,omitempty"`
	Table       *Table       `json:"table,omitempty"`
	Columns     []Column     `json:"columns,omitempty"`
	PrimaryKey  *Index       `json:"primary_key,omitempty"`
	Indexes     []Index      `json:"indexes,omitempty"`
	Constraints []Constraint `json:"constraints,omitempty"`
	// Alter also carries standalone DDL action payloads when no table object exists.
	Alter         []Alter           `json:"alter,omitempty"`
	Options       map[string]string `json:"options,omitempty"`
	HasReferTable bool              `json:"has_refer_table,omitempty"`
	HasSelect     bool              `json:"has_select,omitempty"`
	HasPartition  bool              `json:"has_partition,omitempty"`
	ObjectName    string            `json:"object_name,omitempty"`
	ObjectType    string            `json:"object_type,omitempty"`
}

DDL contains the structural metadata extracted from a DDL statement.

type DDLOperation

type DDLOperation string

DDLOperation identifies the normalized DDL operation represented by a statement.

const (
	DDLOperationUnknown       DDLOperation = "unknown"
	DDLOperationCreateTable   DDLOperation = "create_table"
	DDLOperationCreateView    DDLOperation = "create_view"
	DDLOperationAlterView     DDLOperation = "alter_view"
	DDLOperationAlterTable    DDLOperation = "alter_table"
	DDLOperationDropTable     DDLOperation = "drop_table"
	DDLOperationDropIndex     DDLOperation = "drop_index"
	DDLOperationCreateIndex   DDLOperation = "create_index"
	DDLOperationDropView      DDLOperation = "drop_view"
	DDLOperationTruncateTable DDLOperation = "truncate_table"

	DDLOperationCreateSchema            DDLOperation = "create_schema"
	DDLOperationDropSchema              DDLOperation = "drop_schema"
	DDLOperationCreateSequence          DDLOperation = "create_sequence"
	DDLOperationAlterSequence           DDLOperation = "alter_sequence"
	DDLOperationDropSequence            DDLOperation = "drop_sequence"
	DDLOperationCreateMaterializedView  DDLOperation = "create_materialized_view"
	DDLOperationDropMaterializedView    DDLOperation = "drop_materialized_view"
	DDLOperationRefreshMaterializedView DDLOperation = "refresh_materialized_view"

	DDLOperationCreateType DDLOperation = "create_type"
	DDLOperationAlterType  DDLOperation = "alter_type"
	DDLOperationDropType   DDLOperation = "drop_type"

	DDLOperationCreateDomain DDLOperation = "create_domain"
	DDLOperationAlterDomain  DDLOperation = "alter_domain"
	DDLOperationDropDomain   DDLOperation = "drop_domain"

	DDLOperationCreateExtension DDLOperation = "create_extension"
	DDLOperationAlterExtension  DDLOperation = "alter_extension"
	DDLOperationDropExtension   DDLOperation = "drop_extension"

	DDLOperationGrantTable  DDLOperation = "grant_table"
	DDLOperationRevokeTable DDLOperation = "revoke_table"

	DDLOperationCreatePolicy DDLOperation = "create_policy"
	DDLOperationAlterPolicy  DDLOperation = "alter_policy"
	DDLOperationDropPolicy   DDLOperation = "drop_policy"

	DDLOperationCreateTrigger DDLOperation = "create_trigger"
	DDLOperationDropTrigger   DDLOperation = "drop_trigger"

	DDLOperationCreateFunction  DDLOperation = "create_function"
	DDLOperationDropFunction    DDLOperation = "drop_function"
	DDLOperationCreateProcedure DDLOperation = "create_procedure"
	DDLOperationDropProcedure   DDLOperation = "drop_procedure"

	DDLOperationAlterSchema DDLOperation = "alter_schema"

	// MySQL/TiDB extended DDL operations.
	DDLOperationRenameTable           DDLOperation = "rename_table"
	DDLOperationCreateUser            DDLOperation = "create_user"
	DDLOperationAlterUser             DDLOperation = "alter_user"
	DDLOperationDropUser              DDLOperation = "drop_user"
	DDLOperationCreateRole            DDLOperation = "create_role"
	DDLOperationDropRole              DDLOperation = "drop_role"
	DDLOperationGrant                 DDLOperation = "grant"
	DDLOperationRevoke                DDLOperation = "revoke"
	DDLOperationCreatePlacementPolicy DDLOperation = "create_placement_policy"
	DDLOperationAlterPlacementPolicy  DDLOperation = "alter_placement_policy"
	DDLOperationDropPlacementPolicy   DDLOperation = "drop_placement_policy"
	DDLOperationDropResourceGroup     DDLOperation = "drop_resource_group"

	DDLOperationAlterIndex            DDLOperation = "alter_index"
	DDLOperationAlterMaterializedView DDLOperation = "alter_materialized_view"

	DDLOperationCreatePublication DDLOperation = "create_publication"
	DDLOperationAlterPublication  DDLOperation = "alter_publication"
	DDLOperationDropPublication   DDLOperation = "drop_publication"

	DDLOperationCreateSubscription DDLOperation = "create_subscription"
	DDLOperationAlterSubscription  DDLOperation = "alter_subscription"
	DDLOperationDropSubscription   DDLOperation = "drop_subscription"

	DDLOperationCreateForeignTable DDLOperation = "create_foreign_table"
	DDLOperationAlterForeignTable  DDLOperation = "alter_foreign_table"
	DDLOperationDropForeignTable   DDLOperation = "drop_foreign_table"

	DDLOperationCreateForeignServer DDLOperation = "create_foreign_server"
	DDLOperationAlterForeignServer  DDLOperation = "alter_foreign_server"
	DDLOperationDropForeignServer   DDLOperation = "drop_foreign_server"

	DDLOperationCreateUserMapping DDLOperation = "create_user_mapping"
	DDLOperationAlterUserMapping  DDLOperation = "alter_user_mapping"
	DDLOperationDropUserMapping   DDLOperation = "drop_user_mapping"

	DDLOperationCreateForeignDataWrapper DDLOperation = "create_foreign_data_wrapper"
	DDLOperationAlterForeignDataWrapper  DDLOperation = "alter_foreign_data_wrapper"
	DDLOperationDropForeignDataWrapper   DDLOperation = "drop_foreign_data_wrapper"

	DDLOperationCommentOn     DDLOperation = "comment_on"
	DDLOperationSecurityLabel DDLOperation = "security_label"

	DDLOperationCreateEventTrigger DDLOperation = "create_event_trigger"
	DDLOperationAlterEventTrigger  DDLOperation = "alter_event_trigger"
	DDLOperationDropEventTrigger   DDLOperation = "drop_event_trigger"

	DDLOperationCreateRule DDLOperation = "create_rule"
	DDLOperationAlterRule  DDLOperation = "alter_rule"
	DDLOperationDropRule   DDLOperation = "drop_rule"

	DDLOperationCreateCollation DDLOperation = "create_collation"
	DDLOperationAlterCollation  DDLOperation = "alter_collation"
	DDLOperationDropCollation   DDLOperation = "drop_collation"

	DDLOperationCreateStatistics DDLOperation = "create_statistics"
	DDLOperationAlterStatistics  DDLOperation = "alter_statistics"
	DDLOperationDropStatistics   DDLOperation = "drop_statistics"

	DDLOperationCreateAggregate  DDLOperation = "create_aggregate"
	DDLOperationAlterAggregate   DDLOperation = "alter_aggregate"
	DDLOperationDropAggregate    DDLOperation = "drop_aggregate"
	DDLOperationCreateOperator   DDLOperation = "create_operator"
	DDLOperationAlterOperator    DDLOperation = "alter_operator"
	DDLOperationDropOperator     DDLOperation = "drop_operator"
	DDLOperationCreateConversion DDLOperation = "create_conversion"
	DDLOperationAlterConversion  DDLOperation = "alter_conversion"
	DDLOperationDropConversion   DDLOperation = "drop_conversion"

	DDLOperationCreateOperatorFamily DDLOperation = "create_operator_family"
	DDLOperationAlterOperatorFamily  DDLOperation = "alter_operator_family"
	DDLOperationDropOperatorFamily   DDLOperation = "drop_operator_family"
	DDLOperationCreateOperatorClass  DDLOperation = "create_operator_class"
	DDLOperationAlterOperatorClass   DDLOperation = "alter_operator_class"
	DDLOperationDropOperatorClass    DDLOperation = "drop_operator_class"

	DDLOperationCreateTextSearchConfiguration DDLOperation = "create_text_search_configuration"
	DDLOperationAlterTextSearchConfiguration  DDLOperation = "alter_text_search_configuration"
	DDLOperationDropTextSearchConfiguration   DDLOperation = "drop_text_search_configuration"
	DDLOperationCreateTextSearchDictionary    DDLOperation = "create_text_search_dictionary"
	DDLOperationAlterTextSearchDictionary     DDLOperation = "alter_text_search_dictionary"
	DDLOperationDropTextSearchDictionary      DDLOperation = "drop_text_search_dictionary"
	DDLOperationCreateTextSearchParser        DDLOperation = "create_text_search_parser"
	DDLOperationAlterTextSearchParser         DDLOperation = "alter_text_search_parser"
	DDLOperationDropTextSearchParser          DDLOperation = "drop_text_search_parser"
	DDLOperationCreateTextSearchTemplate      DDLOperation = "create_text_search_template"
	DDLOperationAlterTextSearchTemplate       DDLOperation = "alter_text_search_template"
	DDLOperationDropTextSearchTemplate        DDLOperation = "drop_text_search_template"

	DDLOperationCreateTransform    DDLOperation = "create_transform"
	DDLOperationCreateAccessMethod DDLOperation = "create_access_method"
	DDLOperationDropTransform      DDLOperation = "drop_transform"
	DDLOperationDropAccessMethod   DDLOperation = "drop_access_method"
	DDLOperationAlterLargeObject   DDLOperation = "alter_large_object"
)

Supported DDL operations.

type DML

type DML struct {
	Operation       DMLOperation    `json:"operation"`
	Tables          []Table         `json:"tables,omitempty"`
	MutationTargets []Table         `json:"mutation_targets,omitempty"`
	HasWhere        bool            `json:"has_where"`
	HasLimit        bool            `json:"has_limit"`
	HasOrderBy      bool            `json:"has_order_by"`
	HasSubquery     bool            `json:"has_subquery"`
	HasJoin         bool            `json:"has_join"`
	HasJoinOn       bool            `json:"has_join_on"`
	InsertRows      int             `json:"insert_rows,omitempty"`
	IsReplace       bool            `json:"is_replace,omitempty"`
	IsInsertSelect  bool            `json:"is_insert_select,omitempty"`
	HasOnDuplicate  bool            `json:"has_on_duplicate,omitempty"`
	HasReturning    bool            `json:"has_returning,omitempty"`
	PredicateShape  PredicateShape  `json:"predicate_shape,omitempty"`
	LookupColumns   []string        `json:"lookup_columns,omitempty"`
	MatchedKeyName  string          `json:"matched_key_name,omitempty"`
	MatchedKeyKind  IndexKind       `json:"matched_key_kind,omitempty"`
	IsSingleTable   bool            `json:"is_single_table,omitempty"`
	Impact          *ImpactEstimate `json:"impact,omitempty"`
}

DML contains the structural metadata extracted from a DML statement.

func (*DML) MutationTargetTables added in v0.511.0

func (d *DML) MutationTargetTables() []Table

MutationTargetTables returns the tables a DML statement writes. Extractors that have not filled MutationTargets still use Tables.

type DMLOperation

type DMLOperation string

DMLOperation identifies the normalized DML statement operation.

const (
	DMLOperationUnknown DMLOperation = "unknown"
	DMLOperationInsert  DMLOperation = "insert"
	DMLOperationUpdate  DMLOperation = "update"
	DMLOperationDelete  DMLOperation = "delete"
)

type Diagnostic added in v0.230.0

type Diagnostic struct {
	Classification string `json:"classification"`
	Reason         string `json:"reason"`
	ActionHint     string `json:"action_hint"`
	Audited        bool   `json:"audited"`
	Dialect        string `json:"dialect,omitempty"`
	GuidanceCode   string `json:"guidance_code,omitempty"`
	EvidenceRef    string `json:"evidence_ref,omitempty"`
	Line           int    `json:"line,omitempty"`
	Column         int    `json:"column,omitempty"`
}

Diagnostic carries safe, structured evidence about unaudited or unsupported outcomes.

type Dialect

type Dialect string

Dialect identifies the SQL dialect the statement belongs to.

const (
	DialectUnknown    Dialect = "unknown"
	DialectMySQL      Dialect = "mysql"
	DialectTiDB       Dialect = "tidb"
	DialectPostgreSQL Dialect = "postgresql"
)

func (Dialect) String

func (d Dialect) String() string

String returns the string form of the dialect.

type ImpactConfidence added in v0.14.0

type ImpactConfidence string

ImpactConfidence identifies how reliable the estimate source is.

const (
	ImpactConfidenceLow    ImpactConfidence = "low"
	ImpactConfidenceMedium ImpactConfidence = "medium"
	ImpactConfidenceHigh   ImpactConfidence = "high"
)

type ImpactEstimate added in v0.14.0

type ImpactEstimate struct {
	EstimatedRows  *int64           `json:"estimated_rows,omitempty"`
	EstimatedRatio *float64         `json:"estimated_ratio,omitempty"`
	RiskLevel      ImpactRisk       `json:"risk_level,omitempty"`
	Confidence     ImpactConfidence `json:"confidence,omitempty"`
	Source         ImpactSource     `json:"source,omitempty"`
	ReasonCodes    []string         `json:"reason_codes,omitempty"`
	Notes          []string         `json:"notes,omitempty"`
}

ImpactEstimate stores the conservative DML impact estimate attached to a statement.

type ImpactRisk added in v0.14.0

type ImpactRisk string

ImpactRisk identifies the conservative risk bucket for a DML statement.

const (
	ImpactRiskLow     ImpactRisk = "low"
	ImpactRiskMedium  ImpactRisk = "medium"
	ImpactRiskHigh    ImpactRisk = "high"
	ImpactRiskUnknown ImpactRisk = "unknown"
)

type ImpactSource added in v0.14.0

type ImpactSource string

ImpactSource identifies where a DML impact estimate came from.

const (
	ImpactSourceShape    ImpactSource = "shape"
	ImpactSourceMetadata ImpactSource = "metadata"
	ImpactSourcePlan     ImpactSource = "plan"
)

type Index

type Index struct {
	Name              string    `json:"name"`
	Kind              IndexKind `json:"kind,omitempty"`
	Columns           []string  `json:"columns,omitempty"`
	Cardinality       *int64    `json:"cardinality,omitempty"`
	AccessMethod      string    `json:"access_method,omitempty"`
	IncludedColumns   []string  `json:"included_columns,omitempty"`
	HasPredicate      bool      `json:"has_predicate,omitempty"`
	HasExpressionKeys bool      `json:"has_expression_keys,omitempty"`
	ExpressionCount   int       `json:"expression_count,omitempty"`
}

Index describes an index declaration.

type IndexKind

type IndexKind string

IndexKind identifies the semantic class of an index declaration.

const (
	IndexKindUnknown   IndexKind = "unknown"
	IndexKindPrimary   IndexKind = "primary"
	IndexKindSecondary IndexKind = "secondary"
	IndexKindUnique    IndexKind = "unique"
	IndexKindFulltext  IndexKind = "fulltext"
)

Supported index kinds.

type InstanceFacts

type InstanceFacts struct {
	Version                   string `json:"version,omitempty"`
	DefaultCharset            string `json:"default_charset,omitempty"`
	InnoDBLargePrefixEnabled  bool   `json:"innodb_large_prefix_enabled,omitempty"`
	InnoDBDefaultRowFormat    string `json:"innodb_default_row_format,omitempty"`
	InnoDBAdaptiveHashEnabled bool   `json:"innodb_adaptive_hash_enabled,omitempty"`
}

InstanceFacts are normalized server-level facts that influence audit behavior.

type Kind

type Kind string

Kind identifies the normalized statement family.

const (
	KindUnknown Kind = "unknown"
	KindDDL     Kind = "ddl"
	KindDML     Kind = "dml"
)

func (Kind) String

func (k Kind) String() string

String returns the string form of the statement kind.

type Metadata

type Metadata struct {
	Schema      string           `json:"schema,omitempty"`
	Instance    *InstanceFacts   `json:"instance,omitempty"`
	TargetTable *TableSnapshot   `json:"target_table,omitempty"`
	Objects     []ObjectSnapshot `json:"objects,omitempty"`
}

Metadata carries optional non-SQL facts for one statement evaluation.

func (*Metadata) FindObject added in v0.90.0

func (m *Metadata) FindObject(objectType, name string) *ObjectSnapshot

FindObject returns the first ObjectSnapshot matching the given type and name, case-insensitively. Returns nil if no match is found.

func (*Metadata) FindObjectsByType added in v0.90.0

func (m *Metadata) FindObjectsByType(objectType string) []ObjectSnapshot

FindObjectsByType returns all ObjectSnapshots matching the given type, case-insensitively.

type MetadataStatus added in v0.90.0

type MetadataStatus string

MetadataStatus identifies the outcome of a metadata object lookup.

const (
	MetadataStatusConfirmed   MetadataStatus = "confirmed"
	MetadataStatusNotFound    MetadataStatus = "not_found"
	MetadataStatusUnavailable MetadataStatus = "unavailable"
	MetadataStatusAmbiguous   MetadataStatus = "ambiguous"
)

type ObjectLookupRequest added in v0.90.0

type ObjectLookupRequest struct {
	Schema     string
	Type       string
	Name       string
	Qualifiers map[string]string
}

ObjectLookupRequest describes one object to resolve from live metadata.

type ObjectSnapshot added in v0.90.0

type ObjectSnapshot struct {
	Schema              string            `json:"schema,omitempty"`
	Type                string            `json:"type,omitempty"`
	Name                string            `json:"name,omitempty"`
	Status              MetadataStatus    `json:"status,omitempty"`
	Exists              bool              `json:"exists"`
	Attributes          map[string]string `json:"attributes,omitempty"`
	AmbiguousCandidates []string          `json:"ambiguous_candidates,omitempty"`
}

ObjectSnapshot carries the metadata-validated state of one non-table database object.

func (ObjectSnapshot) IsAmbiguous added in v0.90.0

func (o ObjectSnapshot) IsAmbiguous() bool

IsAmbiguous reports whether the object identity could not be uniquely resolved.

func (ObjectSnapshot) IsConfirmed added in v0.90.0

func (o ObjectSnapshot) IsConfirmed() bool

IsConfirmed reports whether the object was found in live metadata.

func (ObjectSnapshot) IsNotFound added in v0.90.0

func (o ObjectSnapshot) IsNotFound() bool

IsNotFound reports whether the object was confirmed absent from live metadata.

func (ObjectSnapshot) IsUnavailable added in v0.90.0

func (o ObjectSnapshot) IsUnavailable() bool

IsUnavailable reports whether metadata lookup was not performed or not possible.

func (ObjectSnapshot) SafeAttributes added in v0.90.0

func (o ObjectSnapshot) SafeAttributes() map[string]string

SafeAttributes returns only non-sensitive attributes from the snapshot. Keys matching known sensitive patterns are excluded.

type PredicateShape added in v0.14.0

type PredicateShape string

PredicateShape identifies the normalized WHERE-clause or join pattern for DML.

const (
	PredicateShapeUnknown               PredicateShape = "unknown"
	PredicateShapeMissingWhere          PredicateShape = "missing_where"
	PredicateShapeUniqueEquality        PredicateShape = "unique_equality"
	PredicateShapeIndexedPrefixEquality PredicateShape = "indexed_prefix_equality"
	PredicateShapeIndexedRange          PredicateShape = "indexed_range"
	PredicateShapeJoin                  PredicateShape = "join"
	PredicateShapeNonSargable           PredicateShape = "non_sargable"
	PredicateShapeSubquery              PredicateShape = "subquery"
)

type Statement

type Statement struct {
	Kind          Kind               `json:"kind"`
	Dialect       Dialect            `json:"dialect"`
	RawSQL        string             `json:"raw_sql"`
	NormalizedSQL string             `json:"normalized_sql,omitempty"`
	Warnings      []string           `json:"warnings,omitempty"`
	Line          int                `json:"line,omitempty"`
	Column        int                `json:"column,omitempty"`
	Metadata      *Metadata          `json:"metadata,omitempty"`
	DDL           *DDL               `json:"ddl,omitempty"`
	DML           *DML               `json:"dml,omitempty"`
	Unsupported   *UnsupportedDetail `json:"unsupported,omitempty"`
}

Statement is the normalized domain input for rule evaluation.

type StatementExtractor added in v0.15.0

type StatementExtractor interface {
	Extract(dialect Dialect, rawSQL string) (Statement, error)
}

StatementExtractor converts one parser-owned statement into the parser-neutral domain model.

type Table

type Table struct {
	Schema  string `json:"schema,omitempty"`
	Name    string `json:"name"`
	Comment string `json:"comment,omitempty"`
}

Table describes a table-level object.

type TableSnapshot

type TableSnapshot struct {
	Schema      string            `json:"schema,omitempty"`
	Exists      bool              `json:"exists"`
	Table       *Table            `json:"table,omitempty"`
	Columns     []Column          `json:"columns,omitempty"`
	PrimaryKey  *Index            `json:"primary_key,omitempty"`
	Indexes     []Index           `json:"indexes,omitempty"`
	Constraints []Constraint      `json:"constraints,omitempty"`
	Options     map[string]string `json:"options,omitempty"`
}

TableSnapshot is the current metadata-backed shape of a target table.

func (TableSnapshot) FindColumn

func (s TableSnapshot) FindColumn(name string) *Column

FindColumn returns the matching column by name, case-insensitively.

func (TableSnapshot) FindIndex

func (s TableSnapshot) FindIndex(name string) *Index

FindIndex returns the matching secondary/unique/fulltext index by name, case-insensitively.

func (TableSnapshot) HasColumn

func (s TableSnapshot) HasColumn(name string) bool

HasColumn reports whether the snapshot contains a column by name, case-insensitively.

func (TableSnapshot) HasIndex

func (s TableSnapshot) HasIndex(name string) bool

HasIndex reports whether the snapshot contains an index by name, case-insensitively.

func (TableSnapshot) HasPrimaryKey

func (s TableSnapshot) HasPrimaryKey() bool

HasPrimaryKey reports whether the snapshot currently has a primary key.

type UnsupportedDetail added in v0.15.0

type UnsupportedDetail struct {
	Index    int            `json:"index,omitempty"`
	Feature  string         `json:"feature"`
	SQL      string         `json:"sql,omitempty"`
	Reason   string         `json:"reason"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

UnsupportedDetail captures one parser-recognized but unsupported statement or feature.

Jump to

Keyboard shortcuts

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