SQL GunYu Examples
This directory contains executable examples demonstrating how to integrate and use sql-gunyu in your Go applications.
Example Directory Overview
| Directory |
Mode |
Description |
docker_mysql/ |
Single Docker container |
Starts MySQL, seeds a disposable database, and serves an interactive query analysis page. |
static_audit/ |
Offline (Zero DB) |
Demonstrates AST-based offline static rule auditing for MySQL and PostgreSQL with multilingual output (Chinese/English). |
connected_mysql/ |
Connected (Online) |
Demonstrates connected MySQL analysis, including native EXPLAIN retrieval and cost-driven composite/covering index recommendation. |
postgresql_analysis/ |
Offline & Connected |
Demonstrates PostgreSQL 16/17 analysis, native parsing via pg_query_go, and structured report inspection. |
1. Quick Start: Offline Static Audit
Static audit runs purely in-memory via AST parsing without requiring a database connection or credentials.
go run ./examples/static_audit/main.go
Key features demonstrated:
- Initializing
mysql.NewAgent and postgresql.NewAnalysisAgent with empty DSNs ("").
- Calling
AnalyzeStatic(ctx, sql, options...).
- Requesting localized diagnostics (
analysis.WithLanguage("zh") or "en").
- Inspecting detected issues, severity levels, and actionable suggestions.
2. Connected MySQL Analysis & Index Advisor
Connected analysis combines AST parsing with database metadata and native EXPLAIN plans to produce candidate index evaluations and whole-query cost recommendations.
Production Security Best Practice
Always create and use a dedicated READ-ONLY audit user:
CREATE USER 'sql_audit'@'%' IDENTIFIED BY 'StrongPassword123!';
GRANT SELECT, PROCESS, SHOW VIEW ON *.* TO 'sql_audit'@'%';
-- Never grant INSERT, UPDATE, DELETE, DROP, or ALTER privileges!
Running the Example
# Provide a connection string to a disposable or read-only test MySQL instance:
export SQL_GUNYU_MYSQL_DSN="sql_audit:StrongPassword123!@tcp(127.0.0.1:3306)/demo_db"
go run ./examples/connected_mysql/main.go
If SQL_GUNYU_MYSQL_DSN is not provided, the example demonstrates graceful degradation when database connections are unreachable.
3. PostgreSQL 16/17 Analysis
The PostgreSQL adapter provides native SQL parsing (via pg_query_go), semantic binding, and compatibility with the unified analysis.AnalyzeResult report model.
Note: The PostgreSQL adapter requires CGO enabled (with gcc or clang installed) because it compiles PostgreSQL's native parser.
# Run in offline mode:
go run ./examples/postgresql_analysis/main.go
# Or run against a real PostgreSQL instance:
export SQL_GUNYU_POSTGRES_DSN="postgres://readonly_user:password@127.0.0.1:5432/demo_db?sslmode=disable"
go run ./examples/postgresql_analysis/main.go