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

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

134 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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 and PostgreSQL.

Delivered as both a Go library and a standalone CLI binary (sql-gunyu), 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 syntax defects and structural anti-patterns (such as functions wrapping predicate columns, leading wildcard LIKE, missing WHERE clauses on DML, and NULL comparison pitfalls) in milliseconds without database access via the sql-gunyu lint CLI or Go SDK.
  • 🔍 Slow Query Diagnosis & Governance: Gathers native EXPLAIN execution plans and schema metadata via database connection to confirm physical access paths (such as full-table scans and actual index usage), recommending optimal composite and covering indexes with estimated 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)
  • CLI Binary (Precompiled):
    • Linux (amd64, arm64) and macOS (amd64, arm64).
    • Standalone executable with zero external runtime dependencies — no Go toolchain or C compiler required.
  • Go Library (SDK):
    • 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 & Getting Started

Option 1: Standalone CLI (Recommended for CI/CD & Batch)

Download the precompiled archive and its .sha256 checksum file for your OS and architecture from the Releases page (tags starting with cli-v*). Verify and extract:

shasum -a 256 -c sql-gunyu-<platform>.tar.gz.sha256
tar -xzf sql-gunyu-<platform>.tar.gz
./sql-gunyu --version

Alternatively, build from source in a Go environment (requires Go 1.22+ and a C compiler for the PostgreSQL parser):

go build -o ./bin/sql-gunyu ./cmd/sql-gunyu

Option 2: Go Library

If you are developing a Go application, install the adapter in your module:

go get github.com/mgtv-tech/sql-gunyu/pkg/mysql@v0.4.1

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.

Command-Line Tool (CLI)

The sql-gunyu executable operates on both MySQL and PostgreSQL dialects without external runtime dependencies.

Core Subcommands

# 1. Offline static rule audit (lint)
./sql-gunyu lint --dialect mysql --in queries.sql --out audit.html --fail-on WARNING

# 2. Online slow query analysis with database connection (analyze)
./sql-gunyu analyze --dialect postgresql --in slow.sql --out slow.json --dsn-env SQL_GUNYU_POSTGRES_DSN

CLI Options

Flag Description Default / Allowed Values
--dialect Database dialect (required) mysql | postgresql
--in Input UTF-8 SQL file path, or - for stdin (required) e.g. queries.sql or -
--out Output report path (required) e.g. audit.html, slow.json
--format Output report format html | json (inferred from --out extension by default)
--fail-on Severity threshold triggering gate failure INFO | NOTICE | WARNING | ERROR | CRITICAL | none (default: ERROR)
--lang Report display language en | zh (default: en)
--dsn Direct database connection DSN (analyze only) Visible in process arguments
--dsn-env Environment variable holding database DSN (analyze only) Default: SQL_GUNYU_MYSQL_DSN or SQL_GUNYU_POSTGRES_DSN
--timeout Initial connection and per-statement deadline (analyze only) 15s

Exit Codes & CI Quality Gate

The CLI signals execution outcome via process exit codes:

  • 0: Passed. Analysis succeeded and no findings met or exceeded the --fail-on threshold.
  • 1: Blocked. Findings at or above the --fail-on threshold were detected (gate tripped).
  • 2: Incomplete / Error. Invalid arguments, syntax/lexing failure, connection failure, or report generation error.

CI/CD Integration (GitHub Actions)

A GitHub Actions step can run static auditing as a PR gate, enforcing code quality and archiving the HTML or JSON audit report:

steps:
  - uses: actions/checkout@v4

  # Build locally in Go workflows, or download the precompiled binary from Releases
  - uses: actions/setup-go@v5
    with:
      go-version: '1.22.x'
  - run: go build -o "$RUNNER_TEMP/sql-gunyu" ./cmd/sql-gunyu

  - name: Audit SQL Quality Gate
    run: '"$RUNNER_TEMP/sql-gunyu" lint --dialect mysql --in queries.sql --out "$RUNNER_TEMP/audit.json" --fail-on WARNING'

  - uses: actions/upload-artifact@v4
    if: always()
    with:
      name: sql-audit
      path: ${{ runner.temp }}/audit.json
      if-no-files-found: ignore

Operational & Security Notes

Note

  • Independent SQL Statements: Input files are split into independent statements based on standard quotes and PostgreSQL standard-conforming strings (including explicit E'…' escapes). Session-altering directives (such as USE, SET, BEGIN, COMMIT, LOCK) immediately halt remaining batch processing to avoid unexpected session state contamination.
  • Report Data Sensitivity: Generated HTML reports embed original SQL text. JSON reports (sql-gunyu-cli/v1) may include database identifiers, table/column names, and query literal values within rule evidence. Handle generated reports in accordance with your organization's data protection policies.

30-Second Quick Start (Go Library)

Save this offline MySQL audit as main.go.

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)
	}
}

Run go run . in the same directory. The example prints

[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 predicate columns (inhibiting indexing), deep pagination, and more.
  • Entry points:
    • Standalone CLI (Recommended for CI/CD pipelines & Git hooks):
      ./sql-gunyu lint --dialect mysql --in queries.sql --out audit.html --fail-on WARNING
    • Go Library (For embedded Go services & custom tooling): 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"
	"os"

	"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(),
		os.Getenv("SQL_GUNYU_MYSQL_DSN"),
		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

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages