sqlgunyu

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

SQL GunYu

English | 简体中文

CI PostgreSQL Integration Go Reference Go Report Card Latest Release Go Version License

sql-gunyu is a high-performance SQL auditing and optimization analysis engine for MySQL.

Integrated as a Go library, it combines AST parsing, native execution plans (EXPLAIN), and an internal cost model to provide production-ready rule auditing, defect diagnosis, and index recommendations:

  • 🚀 CI/CD Quality Gate: Pure offline AST static analysis that detects anti-patterns (such as full-table scans, implicit type conversions, and unindexed predicates) in milliseconds.
  • 🔍 Slow Query Diagnosis & Governance: Combines native EXPLAIN plans with a whole-query cost model to recommend optimal composite and covering indexes, estimating relative cost reductions.
  • 📊 Standardized Structured Report: Supports multilingual internationalization (i18n), staged execution status, and structured diagnostics for seamless integration with web platforms and monitoring/alerting systems.
  • 🛡️ Production-Safe Operation: Executes only read-only metadata queries and read-only EXPLAIN without ANALYZE. Never runs caller DML/DDL and never applies recommended SQL automatically.

Try the MySQL Demo

The Docker demo bundles MySQL, sample data, and a web page in one image. Build the demo image from this checkout once:

docker build -f examples/docker_mysql/Dockerfile -t sql-gunyu-demo:local .

Then start it with one command:

docker run --rm -p 127.0.0.1:8080:8080 sql-gunyu-demo:local

Open localhost:8080 and click Analyze to see findings, the native execution plan, and index advice for the prefilled SQL.

Supported Environment

  • Database:
    • MySQL 5.7+
    • PostgreSQL 16 and 17 (supported via pkg/postgresql)
  • Go Version: Go 1.22+
    • MySQL Adapter: Pure Go, zero CGO dependencies.
    • PostgreSQL Adapter: Requires CGO (gcc/clang) for PostgreSQL native parser (libpg_query).

Table of Contents


Installation

Add the library to your Go module:

go get github.com/mgtv-tech/sql-gunyu

Requirements:

  • Go 1.22 or later.
  • CGO is optional: pure Go with zero CGO dependencies for MySQL; CGO (gcc/clang) is required when using the PostgreSQL adapter.

30-Second Quick Start (Static Audit)

No database connection needed. Audit SQL syntax and anti-patterns in 10 lines of code:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mgtv-tech/sql-gunyu/pkg/analysis"
	"github.com/mgtv-tech/sql-gunyu/pkg/mysql"
)

func main() {
	// An empty DSN creates an offline agent without connecting to a database
	agent, err := mysql.NewAgent(context.Background(), "")
	if err != nil {
		log.Fatal(err)
	}
	defer agent.Close()

	res, err := agent.AnalyzeStatic(context.Background(),
		"SELECT id FROM users WHERE id = NULL",
		analysis.WithLanguage("en"),
	)
	if err != nil {
		log.Fatal(err)
	}

	for _, issue := range res.Issues {
		fmt.Printf("[%s] %s: %s\n", issue.Severity, issue.Code, issue.Description.Text)
	}
}

Output:

[CRITICAL] WHERE_COMPARE_NULL: NULL comparison with = or != always returns NULL, use IS NULL or IS NOT NULL instead

Input and Output Showcase

Given a slow query:

SELECT id, title, created_at FROM orders
WHERE tenant_id = 1001 AND status = 'PAID'
ORDER BY created_at DESC LIMIT 20;

This illustrative excerpt shows selected fields from a connected analysis report (agent.Analyze).

{
  "summary": {
    "status": "COMPLETE",
    "issue_count": 1,
    "recommendation_count": 1,
    "conclusion": {
      "text": "The model estimates that a composite index on orders can avoid the full table scan and filesort."
    }
  },
  "issues": [
    {
      "code": "FULL_TABLE_SCAN",
      "severity": "ERROR",
      "title": { "text": "Full Table Scan" },
      "description": { "text": "Table orders lacks a suitable index; the execution plan uses an ALL scan." }
    }
  ],
  "recommendations": [
    {
      "title": { "text": "Add composite index to orders" },
      "actions": [
        {
          "kind": "INDEX",
          "execution": {
            "availability": "AVAILABLE",
            "sql": "CREATE INDEX idx_tenant_status_created ON orders (tenant_id, status, created_at)"
          }
        }
      ],
      "benefit": {
        "status": "QUANTIFIED",
        "summary": {
          "text": "The model estimates a query cost reduction of about 84.5% for this proposal, about a 6.45x improvement. Validate actual performance in a test environment."
        },
        "assessments": [
          {
            "basis": "INTERNAL_MODEL",
            "metrics": [
              {
                "metric": "MODEL_COST",
                "baseline": 1250.0,
                "candidate": 193.75,
                "reduction_percent": 84.5
              },
              {
                "metric": "ESTIMATED_ROWS_EXAMINED",
                "baseline": 100000.0,
                "candidate": 20.0,
                "reduction_percent": 99.98
              }
            ],
            "plan_changes": [
              {
                "kind": "ACCESS_METHOD",
                "access_method": {
                  "before": "ALL",
                  "after": "ref"
                }
              },
              {
                "kind": "USED_INDEXES",
                "used_indexes": {
                  "before": [],
                  "after": [
                    "idx_tenant_status_created"
                  ]
                }
              }
            ]
          }
        ]
      }
    }
  ]
}

💡 Cost & Benefit Breakdown:

  • Query Cost Comparison: Baseline cost drops from 1250.0 to 193.75 (an ~84.5% reduction).
  • Rows Examined: Baseline scan drops from 100,000 rows to 20 index-filtered rows (a 99.98% reduction).
  • Plan Evolution: Access method upgrades from full table scan (ALL) to indexed lookup (ref), with the candidate plan actively using the recommended composite index.

Core Usage Scenarios

Scenario 1: Local & CI/CD Static Audit (No Database Required)

Use pure AST analysis in pre-commit hooks or PR pipelines without deploying disposable test databases:

  • What it checks: SELECT *, UPDATE/DELETE without WHERE, comparisons with NULL, functions wrapping index columns, deep pagination, and more.
  • Entry point: Pass an empty DSN to mysql.NewAgent() and call agent.AnalyzeStatic().
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mgtv-tech/sql-gunyu/pkg/analysis"
	"github.com/mgtv-tech/sql-gunyu/pkg/mysql"
)

func main() {
	agent, err := mysql.NewAgent(context.Background(), "")
	if err != nil {
		log.Fatal(err)
	}
	defer agent.Close()

	sql := "SELECT * FROM orders WHERE DATE(created_at) = '2026-11-01'"
	result, err := agent.AnalyzeStatic(context.Background(), sql, analysis.WithLanguage("en"))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Detected %d static issue(s):\n", len(result.Issues))
	for _, issue := range result.Issues {
		fmt.Printf("- [%s] %s: %s\n", issue.Severity, issue.Code, issue.Description.Text)
	}
}

Scenario 2: Connected MySQL Analysis & Index Recommendation

Connect to a live MySQL instance to evaluate actual row counts, cardinality, existing indexes, and native EXPLAIN FORMAT=JSON, producing candidate designs and estimating whole-query cost improvements:

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/mgtv-tech/sql-gunyu/pkg/analysis"
	"github.com/mgtv-tech/sql-gunyu/pkg/mysql"
)

func main() {
	dsn := os.Getenv("SQL_GUNYU_MYSQL_DSN")
	if dsn == "" {
		log.Fatal("set SQL_GUNYU_MYSQL_DSN before running this example")
	}

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	// 1. Create Agent (validates local config; connection is established lazily)
	agent, err := mysql.NewAgent(ctx, dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer agent.Close()

	sql := "SELECT id FROM users WHERE city = 'York' ORDER BY created_at DESC LIMIT 100"

	// 2. Run comprehensive analysis (static rules + native EXPLAIN + cost modeling)
	result, analyzeErr := agent.Analyze(ctx, sql, analysis.WithLanguage("en"))

	// 3. Inspect result before handling error: partial static findings and plan evidence
	// are preserved even if online stages encounter permissions or timeout issues.
	if result != nil && result.Execution != nil {
		fmt.Printf("Report Status: %s (Execution: %s)\n",
			result.Execution.ReportStatus, result.Execution.Status)

		if result.Execution.ReportStatus == analysis.ReportStatusAvailable {
			// Print detected issues
			for _, issue := range result.Issues {
				fmt.Printf("[%s] %s: %s\n", issue.Severity, issue.Code, issue.Description.Text)
			}

			// Print recommendations and candidate SQL
			for _, rec := range result.Recommendations {
				fmt.Println("Recommendation:", rec.Title.Text)
				for _, action := range rec.Actions {
					if action.Execution.Availability == "AVAILABLE" && action.Execution.SQL != "" {
						fmt.Println("  Action SQL:", action.Execution.SQL)
					}
				}
			}
		}
	}

	if analyzeErr != nil {
		log.Printf("Analysis incomplete (partial result preserved): %v", analyzeErr)
	}
}

Key Operational Notes:

  1. All-in-One Data Retrieval: agent.Analyze() already includes both static rules and native plan collection in a single pipeline. The returned result.Issues contains all static audit findings, and result.Explain contains the native EXPLAIN table rows. Calling it once delivers the complete diagnostic report without needing to invoke Explain() or AnalyzeStatic() separately for manual assembly.
  2. Agent Lifecycle: Reuse Agent instances across requests in long-running services. NewAgent() validates configuration locally without blocking network I/O; supply a bounded context.Context per request.

Reading the Analysis Report

The *analysis.AnalyzeResult returned by Analyze is a self-contained tree structure. Consumers typically read:

Field Path Type Usage & Integration
result.Issues []*Issue Detected problems. Use issue.Code for programmatic decisions and display issue.Description.Text to users.
result.Recommendations []Recommendation Optimization advice. Access suggested SQL via rec.Actions[].Execution.SQL when availability is AVAILABLE.
result.Assessment.Evaluations []EvaluationReport Cost-scenario evaluations. comparison.cost.model_cost_reduction_percent records relative model benefit.
result.Execution *ExecutionReport Staged execution progress. execution.status indicates whether all stages are COMPLETED or PARTIAL.
result.Explain *ExplainResult Traditional EXPLAIN table rows collected during the same call. Iterate over result.Explain.Rows for tabular display.

MySQL prices existing and hypothetical indexes using distinct-value estimates for each index prefix. Wide prefixes can fall back to catalog statistics or a shorter prefix. Sampled index cardinality

MySQL keeps independent what-if comparisons when a nested FirstMatch lacks conditional probe evidence. A selected design with this limitation is advisory only and omits quantified benefit and index DDL.

For ordered nested MySQL EXISTS, a request can use observed prefix hits, empty lookups and optional materialization build counts from the same immutable data. Request-scoped probe observations

⚠️ Safe Interpretation of Cost Estimates:

  1. Relative Model Cost: Cost reduction percentages (e.g. 80% reduction) are internal model comparisons to guide optimization decisions. They do not guarantee that real-world wall-clock latency will decrease by the exact same ratio.
  2. Whole-Plan Attribution: If a recommendation combines multiple indexes, the estimated benefit belongs to the complete action set; do not sum independent candidate gains.
  3. Safety First: Suggested SQL statements are provided for review. The library never executes DDL/DML automatically.

Common Configuration Examples

PostgreSQL requests can set RequestOptions.RuleNames in a request option (nil uses defaults; an empty list selects none). An explicit connected selection includes index design only when it names PG.INDEX_RECOMMENDATION; disabled rules and advice remain disabled after report merging. See request options for the static, runtime-plan and DDL boundaries.

Configure rule policies, thresholds, and optimization limits cleanly with mysql.DefaultAgentConfig():

package main

import (
	"context"
	"log"

	"github.com/mgtv-tech/sql-gunyu/pkg/analysis"
	"github.com/mgtv-tech/sql-gunyu/pkg/mysql"
)

func main() {
	config := mysql.DefaultAgentConfig()

	// 1. Disable specific rules (e.g. allow SELECT *)
	config.RulePolicy.DisabledRules = map[string]bool{
		"sql_style.select_star": true,
	}

	// 2. Adjust large table & large scan row thresholds (inclusive lower bounds)
	config.DiagnosticPolicy.Thresholds.LargeTableRows = 100_000
	config.DiagnosticPolicy.Thresholds.LargeScanRows = 10_000

	// 3. Override severity for specific issues
	config.DiagnosticPolicy.Severity.Overrides["FULL_TABLE_SCAN"] = analysis.SeverityCritical

	// 4. Build Agent with resolved configuration
	agent, err := mysql.NewAgent(
		context.Background(),
		"root:secret@tcp(127.0.0.1:3306)/test",
		mysql.WithResolvedAgentConfig(config),
		mysql.WithDefaultLanguage("en"),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer agent.Close()
}

Multi-Database Support (PostgreSQL 16 and 17)

While this guide highlights MySQL, sql-gunyu also provides an independent adapter for PostgreSQL 16 and 17 via postgresql.NewAnalysisAgent:

  • Implements the unified pkg/analysis.Agent contract, including staged failure reports that retain completed evidence.
  • Construction is local; online methods connect on demand, or call Connect(ctx) explicitly. Static/dynamic rule profiles and opt-in metadata caching are described in the API reference.
  • Requires CGO for the PostgreSQL AST parser (pg_query_go).
  • PostgreSQL retains completed diagnostics and catalog facts across permission errors, missing statistics, cancellation and deadlines, with explicit stage reasons and no execution of caller DML.
  • HypoPG is the sole PostgreSQL what-if provider and uses a dedicated session on the configured database. HypoPG is disabled by default, so analysis keeps native EXPLAIN and diagnostics and skips what-if.
  • HypoPG reports link submitted index designs to their evaluations and show each hypothetical or physical index use at its candidate EXPLAIN path.
  • PostgreSQL expression diagnostics distinguish self-join operands and expose proven Boolean-branch sources. Ambiguous native ownership keeps independent diagnostics.
  • Each HypoPG scenario records adoption, native cost direction, or why it could not be evaluated. Recoverable errors can leave completed comparisons available after session cleanup.
  • A pair that uses both hypothetical indexes and beats the baseline and comparable individual designs can produce one advisory recommendation with quantified whole-query planner cost.
  • HypoPG can compare narrow and covering designs and alternative equality or range key orders. For joins, self-joins, and subqueries, the report preserves the source aliases and query blocks and identifies designs left unevaluated by the search budget.
  • Dedicated integration tests run against SQL_GUNYU_POSTGRES_TEST_DSN.
  • For details and governance extensions (AnalyzeDDL, AnalyzeDDLBatch, AnalyzeRuntimePlan), see the API Reference.

Architecture & In-Depth Documentation

For optimizer internals, custom rule development, or platform integration, refer to the focused documentation:


Frequently Asked Questions (FAQ)

Q1: Is a database connection required?

No. Creating an agent with an empty DSN mysql.NewAgent(ctx, "") and calling agent.AnalyzeStatic(ctx, sql) runs pure AST static analysis with zero network I/O, sub-millisecond latency, and no database setup required.

The library adheres strictly to semantic equivalence and database safety:

  • Many defects (such as missing join conditions, implicit type conversions, or functions wrapping indexed columns) represent application logic risks where automated rewrites cannot guarantee equivalent result sets. These provide explanatory guidance only.
  • Index recommendations are emitted only when evidence proves a clear whole-query benefit without causing excessive index redundancy.

Do not run them automatically in production without review.

  • Recommended actions are designed for developer and DBA evaluation.
  • Adding indexes introduces write amplification, storage overhead, and optimizer plan shifts. Always review them in staging before applying them in production.
Q4: Can one Agent instance be shared across concurrent requests?

Yes, and reuse is strongly recommended.

  • The Agent maintains concurrent-safe caches for table statistics and plan evaluations. On MySQL 5.7, the default table cache can retain up to 40,000 raw sample rows per table.
  • In web servers or background workers, pass a request-specific context.Context (with an appropriate timeout) to Analyze() / AnalyzeStatic(). Do not re-instantiate agents per request.

Documentation

Overview

Package sqlgunyu provides SQL parsing, analysis, and optimization capabilities with internationalization support for different SQL dialects.

This package serves as the main entry point for the sql-gunyu library, offering functionality for: - SQL parsing and analysis - Query optimization - Cost estimation - Internationalization (i18n) support for different SQL dialects

Example usage:

// Create a custom catalog for one dialect (recommended for runtime isolation)
catalog, err := sqlgunyu.NewCatalog(
    sqlgunyu.WithDialects(sqlgunyu.DialectMySQL),
    sqlgunyu.WithLanguages("zh", "en"),
)
if err != nil {
    log.Fatal(err)
}

// Optional: initialize the shared default catalog.
// Prefer explicit dialect/language scopes to avoid loading unnecessary locales.
if err := sqlgunyu.Init(
    sqlgunyu.WithDialects(sqlgunyu.DialectMySQL),
    sqlgunyu.WithLanguages("zh", "en"),
); err != nil {
    log.Fatal(err)
}

Supported dialects:

  • MySQL
  • PostgreSQL 16 and 17

Supported languages:

  • English (en)
  • Chinese (zh)

Note: This package embeds locale files for built-in dialects and languages. Custom translation files can be loaded using the WithFiles option. For multi-dialect applications, prefer catalog-per-dialect to avoid key collisions.

Index

Constants

This section is empty.

Variables

View Source
var ErrExplainUnsupported = errors.New("statement does not support EXPLAIN analysis")

ErrExplainUnsupported indicates that a valid statement is outside the connected EXPLAIN analysis pipeline's supported statement types.

Functions

func Init

func Init(opts ...InitOption) error

Init loads embedded/custom locale files into the default shared catalog.

Types

type Catalog

type Catalog = sqli18n.Catalog

Catalog is the locale catalog used for message localization.

func DefaultCatalog

func DefaultCatalog() *Catalog

DefaultCatalog returns the process-wide shared i18n catalog.

func NewCatalog

func NewCatalog(opts ...InitOption) (*Catalog, error)

NewCatalog creates a new catalog and loads embedded/custom locale files into it.

type Dialect

type Dialect string

Dialect identifies a SQL engine family for loading dialect-specific locales.

const (
	// DialectMySQL is the MySQL dialect.
	DialectMySQL Dialect = "mysql"
	// DialectPostgreSQL is the PostgreSQL dialect.
	DialectPostgreSQL Dialect = "postgresql"
)

type InitOption

type InitOption func(*initConfig)

InitOption configures catalog initialization behavior.

func WithAllDialects

func WithAllDialects() InitOption

WithAllDialects enables loading locales for all built-in dialects.

func WithAllLanguages

func WithAllLanguages() InitOption

WithAllLanguages enables loading all discovered built-in languages.

func WithCatalog

func WithCatalog(catalog *Catalog) InitOption

WithCatalog sets the target catalog to load locale files into.

func WithDialects

func WithDialects(dialects ...Dialect) InitOption

WithDialects limits embedded locale loading to the specified dialects.

func WithFiles

func WithFiles(files ...string) InitOption

WithFiles appends custom translation files to load after embedded locales.

func WithLanguages

func WithLanguages(langs ...string) InitOption

WithLanguages limits embedded locale loading to the specified languages.

Directories

Path Synopsis
examples
connected_mysql command
docker_mysql command
Command docker_mysql serves the SQL GunYu demo with a disposable MySQL instance.
Command docker_mysql serves the SQL GunYu demo with a disposable MySQL instance.
static_audit command
internal
analysisinput
Package analysisinput holds engine computation inputs before report assembly.
Package analysisinput holds engine computation inputs before report assembly.
analysisreport
Package analysisreport assembles reports from engine-owned computation facts.
Package analysisreport assembles reports from engine-owned computation facts.
cache
Package cache provides bounded, concurrent LRU storage.
Package cache provides bounded, concurrent LRU storage.
mysqltestenv
Package mysqltestenv centralizes environment-variable names used by optional MySQL integration tests and test utilities.
Package mysqltestenv centralizes environment-variable names used by optional MySQL integration tests and test utilities.
mysqltestworkload
Package mysqltestworkload defines the shared, versioned SQL workload used by MySQL integration tests, offline replay, and physical-plan benchmarks.
Package mysqltestworkload defines the shared, versioned SQL workload used by MySQL integration tests, offline replay, and physical-plan benchmarks.
postgresqltestenv
Package postgresqltestenv centralizes environment variables and destructive PostgreSQL test safety checks.
Package postgresqltestenv centralizes environment variables and destructive PostgreSQL test safety checks.
postgresqltestworkload
Package postgresqltestworkload defines the shared, versioned SQL workload used by PostgreSQL integration tests, offline replay, and physical-plan benchmarks.
Package postgresqltestworkload defines the shared, versioned SQL workload used by PostgreSQL integration tests, offline replay, and physical-plan benchmarks.
testdbversion
Package testdbversion provides strict database-version selection for test fixtures and expectations.
Package testdbversion provides strict database-version selection for test fixtures and expectations.
pkg
analysis
Package analysis defines the stable, engine-neutral API contract for SQL analysis.
Package analysis defines the stable, engine-neutral API contract for SQL analysis.
analysis/logicalir
Package logicalir contains the experimental logical SQL IR and rewrite evaluation API.
Package logicalir contains the experimental logical SQL IR and rewrite evaluation API.
mysql/optimizer
result_model.go defines the public boundary between native EXPLAIN facts and internal whole-query what-if predictions.
result_model.go defines the public boundary between native EXPLAIN facts and internal whole-query what-if predictions.
mysql/parser
Package parser converts TiDB parser nodes into sql-gunyu's MySQL AST.
Package parser converts TiDB parser nodes into sql-gunyu's MySQL AST.
mysql/relation
Package relation defines canonical MySQL physical-relation identities.
Package relation defines canonical MySQL physical-relation identities.
postgresql
Package postgresql provides an analysis.Agent implementation for PostgreSQL.
Package postgresql provides an analysis.Agent implementation for PostgreSQL.
postgresql/cost/native_hypopg
Package native_hypopg implements the explicitly enabled PostgreSQL-native HypoPG what-if provider.
Package native_hypopg implements the explicitly enabled PostgreSQL-native HypoPG what-if provider.
postgresql/db
Package db implements PostgreSQL-only connections, planning-context identity, catalog metadata, statistics, and caches.
Package db implements PostgreSQL-only connections, planning-context identity, catalog metadata, statistics, and caches.
postgresql/explain
Package explain decodes and safely executes PostgreSQL JSON EXPLAIN.
Package explain decodes and safely executes PostgreSQL JSON EXPLAIN.
postgresql/locale
Package locale provides PostgreSQL-scoped message catalogs.
Package locale provides PostgreSQL-scoped message catalogs.
postgresql/profile
Package profile defines PostgreSQL-major version profiles and effective capability calculation.
Package profile defines PostgreSQL-major version profiles and effective capability calculation.
tests
mysql/indexmatrix
Package indexmatrix contains only synthetic input and independent data oracles for the offline MySQL index recommendation tests.
Package indexmatrix contains only synthetic input and independent data oracles for the offline MySQL index recommendation tests.
mysql/mysqlfixture
Package mysqlfixture adapts shared evidence at MySQL's external I/O boundary.
Package mysqlfixture adapts shared evidence at MySQL's external I/O boundary.
mysql/testkit
Package testkit loads engine-neutral offline acceptance inputs and assertions.
Package testkit loads engine-neutral offline acceptance inputs and assertions.
postgresql/bulkload command
Command bulkload destructively rebuilds an explicitly selected PostgreSQL test schema with deterministic, type-rich canonical data.
Command bulkload destructively rebuilds an explicitly selected PostgreSQL test schema with deterministic, type-rich canonical data.

Jump to

Keyboard shortcuts

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