Skip to content
mgtv-techPublic

About

A high-performance Go library for SQL auditing, static AST linting, and smart index advice for MySQL & PostgreSQL with native EXPLAIN and cost-based what-if analysis.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

131 Commits

Folders and files

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.

Q2: Why do some issues have no recommended SQL action?

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.

Q3: Can recommended CREATE INDEX statements be run automatically?

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.

About

A high-performance Go library for SQL auditing, static AST linting, and smart index advice for MySQL & PostgreSQL with native EXPLAIN and cost-based what-if analysis.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages