spec

package
v0.34.0 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 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, 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 and extracted target tables for rule applicability

Exports

  • Statement
  • UnsupportedDetail
  • StatementExtractor
  • Kind
  • Dialect Includes DialectPostgreSQL for PostgreSQL routing support
  • Metadata
  • InstanceFacts
  • TableSnapshot
  • DDL
  • DDLOperation
  • Table
  • Column
  • Constraint
  • Index
  • IndexKind
  • ImpactSource
  • ImpactRisk
  • ImpactConfidence
  • PredicateShape
  • ImpactEstimate
  • AlterColumnChange
  • AlterColumn
  • AlterIndex
  • Alter
  • DML
  • 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.

  • 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
  • TableSnapshot includes convenience lookups for case-insensitive column/index existence checks so future rules do not need to duplicate iteration logic.

  • DML.Tables preserves the parser-neutral set of mutation target tables so denylist and future metadata-aware DML rules do not need to rediscover them from AST nodes.

  • 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.Operation now distinguishes create_table, create_view, alter_table, drop_table, drop_index, drop_view, and truncate_table 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
    • 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 for rules 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 for domain rule processing pos: domain specification model for all auditable SQL statements note: if this file changes, update this header and module README.md.

Index

Constants

This section is empty.

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"`
	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"`
}

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"
	DDLOperationAlterTable    DDLOperation = "alter_table"
	DDLOperationDropTable     DDLOperation = "drop_table"
	DDLOperationDropIndex     DDLOperation = "drop_index"
	DDLOperationCreateIndex   DDLOperation = "create_index"
	DDLOperationDropView      DDLOperation = "drop_view"
	DDLOperationTruncateTable DDLOperation = "truncate_table"
)

Supported DDL operations.

type DML

type DML struct {
	Operation      DMLOperation    `json:"operation"`
	Tables         []Table         `json:"tables,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"`
	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.

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 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"`
}

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"`
}

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

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