models

package
v0.0.0-...-b8497f2 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package models contains the core domain models for the SQLTraceBench application.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BenchmarkResult

type BenchmarkResult struct {
	Latencies []time.Duration
	QPS       float64
}

type BenchmarkWorkload

type BenchmarkWorkload struct {
	// Queries is a list of all the SQL queries and their arguments for the workload.
	Queries []QueryWithArgs `json:"queries"`
}

BenchmarkWorkload represents a set of queries to be executed by the benchmark.

type ColumnSchema

type ColumnSchema struct {
	Name         string `json:"name"`
	DataType     string `json:"data_type"`
	IsNullable   bool   `json:"is_nullable"`
	IsPrimaryKey bool   `json:"is_primary_key"`
	Default      string `json:"default"`
}

ColumnSchema represents a single column in a database table.

type Config

type Config struct {
	TracePath       string `json:"trace_path"`
	SchemaPath      string `json:"schema_path"`
	WorkloadPath    string `json:"workload_path"`
	BaseMetricsPath string `json:"base_metrics_path"`
	CandMetricsPath string `json:"cand_metrics_path"`
	ReportPath      string `json:"report_path"`
	Executor        string `json:"executor"`
	Target          string `json:"target"`
}

Config holds the configuration for a benchmark job. This is a simplified version of the main application config.

type DatabaseSchema

type DatabaseSchema struct {
	Name   string         `json:"name"`
	Tables []*TableSchema `json:"tables"`
}

DatabaseSchema represents the schema of an entire database.

type DistributionType

type DistributionType string

DistributionType defines the type of statistical distribution.

const (
	DistUniform   DistributionType = "uniform"
	DistZipfian   DistributionType = "zipfian"
	DistNormal    DistributionType = "normal"
	DistEmpirical DistributionType = "empirical" // Fallback for arbitrary distribution
)

type IndexSchema

type IndexSchema struct {
	Name     string   `json:"name"`
	Columns  []string `json:"columns"`
	IsUnique bool     `json:"is_unique"`
}

IndexSchema represents a database index.

type Job

type Job struct {
	ID        string    `json:"id"`
	Status    JobStatus `json:"status"`
	Config    *Config   `json:"config"`
	Report    *Report   `json:"report,omitempty"`
	Error     string    `json:"error,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Job represents a benchmark job.

type JobStatus

type JobStatus string

JobStatus represents the status of a benchmark job.

const (
	JobStatusPending   JobStatus = "pending"
	JobStatusRunning   JobStatus = "running"
	JobStatusCompleted JobStatus = "completed"
	JobStatusFailed    JobStatus = "failed"
)

type ParameterModel

type ParameterModel struct {
	ParamName string           `json:"param_name"`
	DataType  string           `json:"data_type"` // e.g., "INT", "VARCHAR"
	DistType  DistributionType `json:"dist_type"` // Detected distribution

	// Zipf specific
	ZipfS float64 `json:"zipf_s,omitempty"` // Skewness parameter
	ZipfV float64 `json:"zipf_v,omitempty"` // Value range parameter (usually 1)

	// Stats
	Cardinality  int     `json:"cardinality"`
	HotspotRatio float64 `json:"hotspot_ratio"` // e.g., 0.8 means 20% items get 80% traffic

	// Sample Values (for reproduction)
	// We store TopValues and TopFrequencies to support empirical sampling of hotspots.
	TopValues      []interface{} `json:"top_values"`
	TopFrequencies []int         `json:"top_frequencies"`
}

ParameterModel holds the detailed statistical model for a single parameter.

type PerformanceMetrics

type PerformanceMetrics struct {
	// QueriesExecuted is the total number of queries run during the benchmark.
	QueriesExecuted int64 `json:"queries_executed"`
	// Errors is the total number of errors that occurred during the benchmark.
	Errors int64 `json:"errors"`
	// Duration is the total time taken for the benchmark to complete.
	Duration time.Duration `json:"duration"`
	// Latencies is a slice of all the individual query latencies.
	Latencies []time.Duration `json:"-"` // Exclude from JSON report for brevity
	// P50 is the 50th percentile latency.
	P50 time.Duration `json:"p50"`
	// P90 is the 90th percentile latency.
	P90 time.Duration `json:"p90"`
	// P99 is the 99th percentile latency.
	P99 time.Duration `json:"p99"`
	// SlowQueries is the number of queries that exceeded the slow query threshold.
	SlowQueries int64 `json:"slow_queries"`
}

PerformanceMetrics holds the key performance indicators from a benchmark run.

func (*PerformanceMetrics) CalculatePercentiles

func (pm *PerformanceMetrics) CalculatePercentiles()

CalculatePercentiles computes the P50, P90, and P99 latencies from the collected latency data.

func (*PerformanceMetrics) ErrorRate

func (pm *PerformanceMetrics) ErrorRate() float64

ErrorRate calculates the percentage of queries that resulted in an error.

func (*PerformanceMetrics) QPS

func (pm *PerformanceMetrics) QPS() float64

QPS calculates the average queries per second.

type QueryExecutionResult

type QueryExecutionResult struct {
	Duration time.Duration
	Error    error
}

type QueryWithArgs

type QueryWithArgs struct {
	// Query is the SQL statement with '?' placeholders for parameters.
	Query string `json:"query"`
	// Args is a slice of arguments to be bound to the query's placeholders.
	Args []interface{} `json:"args"`
}

QueryWithArgs represents a single query to be executed, with its parameters separated to allow for safe execution using prepared statements.

type Report

type Report struct {
	Version   string            `json:"version"`
	Timestamp time.Time         `json:"timestamp"`
	Metadata  *ReportMetadata   `json:"metadata"`
	Result    *ValidationResult `json:"result"`
}

Report is the top-level structure for the benchmark report. It includes metadata and the validation results.

type ReportMetadata

type ReportMetadata struct {
	BaseTarget      string         `json:"base_target"`
	CandidateTarget string         `json:"candidate_target"`
	Threshold       float64        `json:"threshold"`
	TemplateSummary []*SQLTemplate `json:"template_summary"`
}

ReportMetadata contains contextual information about the benchmark run.

type SQLTemplate

type SQLTemplate struct {
	RawSQL     string
	GroupKey   string
	Weight     int
	Parameters []string
}

SQLTemplate represents a normalized SQL query with its parameters extracted.

func (*SQLTemplate) ExtractParameters

func (t *SQLTemplate) ExtractParameters()

ExtractParameters finds all named parameters in the RawSQL query.

func (*SQLTemplate) GenerateQuery

func (t *SQLTemplate) GenerateQuery(params map[string]interface{}) (QueryWithArgs, error)

GenerateQuery creates a QueryWithArgs struct from the template. It replaces named parameters with '?' placeholders and populates the args slice.

type SQLTrace

type SQLTrace struct {
	Query      string
	Timestamp  time.Time
	Latency    time.Duration
	Parameters map[string]interface{}
}

SQLTrace represents a single SQL query event captured from a trace.

type Schema

type Schema struct {
	Databases []DatabaseSchema `json:"databases"`
}

Schema represents the entire database schema, containing multiple databases.

type TableSchema

type TableSchema struct {
	Name      string                  `json:"name"`
	Columns   []*ColumnSchema         `json:"columns"`
	PK        []string                `json:"pk"` // Primary Key columns
	Indexes   map[string]*IndexSchema `json:"indexes"`
	Engine    string                  `json:"engine,omitempty"` // e.g., "MergeTree() ORDER BY ..."
	CreateSQL string                  `json:"create_sql,omitempty"`
}

TableSchema represents the schema of a single database table.

type TraceCollection

type TraceCollection struct {
	Traces []SQLTrace
}

TraceCollection holds a collection of SQLTraces.

func (*TraceCollection) Add

func (tc *TraceCollection) Add(trace SQLTrace)

Add appends a new SQLTrace to the collection.

func (*TraceCollection) Len

func (tc *TraceCollection) Len() int

Len returns the number of traces in the collection.

type ValidationReport

type ValidationReport struct {
	Status         string
	QPSDeviation   float64
	LatencyP99Diff float64
}

type ValidationResult

type ValidationResult struct {
	BaseMetrics      *PerformanceMetrics `json:"base_metrics"`
	CandidateMetrics *PerformanceMetrics `json:"candidate_metrics"`
	Pass             bool                `json:"pass"`
	Reason           string              `json:"reason"`
}

ValidationResult contains the comparison of the two benchmark runs.

type ValueDistribution

type ValueDistribution struct {
	// Values is a slice of unique parameter values.
	Values []interface{}
	// Frequencies is a slice of corresponding frequencies for each value.
	Frequencies []int
	// Total is the total number of observations for this parameter.
	Total int
}

ValueDistribution holds the observed values and their frequencies for a single parameter. Deprecated: This struct is kept for temporary compatibility but should be replaced by ParameterModel. Or we use this to accumulate data before converting to ParameterModel.

func NewValueDistribution

func NewValueDistribution() *ValueDistribution

NewValueDistribution creates an empty value distribution.

func (*ValueDistribution) AddObservation

func (vd *ValueDistribution) AddObservation(value interface{})

AddObservation records an observation of a parameter value. If the value has been seen before, its frequency is incremented. Otherwise, the new value is added with a frequency of 1.

type WorkloadParameterModel

type WorkloadParameterModel struct {
	// TemplateParameters maps a template's GroupKey to a map of its parameters.
	// Each parameter is then mapped to its parameter model.
	TemplateParameters map[string]map[string]*ParameterModel
}

WorkloadParameterModel holds the statistical model of parameters for a set of SQL templates. It maps each template (by its GroupKey) to a model of its parameters.

func NewWorkloadParameterModel

func NewWorkloadParameterModel() *WorkloadParameterModel

NewWorkloadParameterModel creates an empty workload parameter model.

Jump to

Keyboard shortcuts

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