Skip to content

A powerful SQL query analyzer and optimizer supporting MySQL, PostgreSQL, SQL Server, SQLite, and Oracle

Notifications You must be signed in to change notification settings

Chahine-tech/sqlens

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

38 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SQL Parser Go

A powerful multi-dialect SQL query analysis tool written in Go that provides comprehensive parsing, analysis, and optimization suggestions for SQL queries and log files.

Go Version License Performance

✨ Key Features

  • πŸ—„οΈ Multi-Dialect Support: MySQL, PostgreSQL, SQL Server, SQLite, Oracle
  • ⚑ Sub-Microsecond Parsing: Parse queries in <1ΞΌs (SQL Server: 375ns!)
  • πŸ” Schema-Aware Validation: Validate SQL against database schemas
  • πŸ“Š Execution Plan Analysis: Analyze EXPLAIN output and detect bottlenecks
  • πŸ’‘ Smart Optimizations: Dialect-specific optimization suggestions
  • πŸš€ Production-Ready Performance: Zero-allocation paths, object pooling, intelligent caching

πŸ“¦ Installation

Prerequisites

  • Go 1.21 or higher

Build from Source

# Clone the repository
git clone https://github.com/Chahine-tech/sql-parser-go.git
cd sql-parser-go

# Install dependencies
make deps

# Build the application
make build

# Run tests
make test

πŸš€ Quick Start

Basic Usage

# Analyze query from file
./bin/sqlparser -query examples/queries/complex_query.sql -output table

# Analyze query from string
./bin/sqlparser -sql "SELECT * FROM users WHERE id > 100" -dialect mysql

# Get optimization suggestions
./bin/sqlparser -sql "SELECT * FROM users" -dialect postgresql -output table

Multi-Dialect Examples

# MySQL with backticks
./bin/sqlparser -sql "SELECT \`user_id\` FROM \`users\`" -dialect mysql

# PostgreSQL with double quotes
./bin/sqlparser -sql "SELECT \"user_id\" FROM \"users\"" -dialect postgresql

# SQL Server with brackets
./bin/sqlparser -sql "SELECT [user_id] FROM [users]" -dialect sqlserver

See docs/EXAMPLES.md for comprehensive usage examples.

πŸ“š Supported SQL Features

Core SQL Statements

  • βœ… SELECT - Complex joins, subqueries, aggregations, window functions
  • βœ… INSERT - VALUES, multiple rows, INSERT...SELECT
  • βœ… UPDATE - Multiple columns, WHERE, ORDER BY/LIMIT (MySQL/SQLite)
  • βœ… DELETE - WHERE clause, ORDER BY/LIMIT (MySQL/SQLite)
  • βœ… EXPLAIN - Full support for EXPLAIN and EXPLAIN ANALYZE

DDL (Data Definition Language)

  • βœ… CREATE TABLE - Columns, constraints, foreign keys, IF NOT EXISTS
  • βœ… DROP - TABLE/DATABASE/INDEX/VIEW/TRIGGER with IF EXISTS and CASCADE
  • βœ… ALTER TABLE - ADD/DROP/MODIFY/CHANGE columns and constraints
  • βœ… CREATE INDEX - Simple and unique indexes with IF NOT EXISTS
  • βœ… CREATE VIEW - Views and materialized views with OR REPLACE, IF NOT EXISTS, WITH CHECK OPTION
  • βœ… CREATE TRIGGER - BEFORE/AFTER/INSTEAD OF triggers, multiple events, FOR EACH ROW/STATEMENT, WHEN conditions

Transaction Control

  • βœ… BEGIN/START TRANSACTION - Start transactions (dialect-aware)
  • βœ… COMMIT/ROLLBACK - Commit or rollback transactions
  • βœ… SAVEPOINT - Create and manage savepoints

Advanced Features

  • βœ… CTEs (WITH clause) - Common Table Expressions with recursive support
  • βœ… Window Functions - ROW_NUMBER, RANK, PARTITION BY, window frames
  • βœ… Set Operations - UNION, INTERSECT, EXCEPT
  • βœ… Comprehensive Subqueries - Scalar, EXISTS, IN, derived tables, correlated
  • βœ… Stored Procedures & Functions - CREATE PROCEDURE/FUNCTION with parameters

Schema & Plan Analysis

  • βœ… Schema-Aware Parsing - Validate SQL against database schemas (JSON/YAML)
  • βœ… Execution Plan Analysis - Parse and analyze EXPLAIN output
  • βœ… Bottleneck Detection - Automatic performance issue identification
  • βœ… Type Checking - Data type compatibility validation

🎯 Command Line Options

./bin/sqlparser [options]

Options:
  -query FILE          Analyze SQL query from file
  -sql STRING          Analyze SQL query from string
  -log FILE            Parse SQL Server log file
  -output FORMAT       Output format: json, table (default: json)
  -dialect DIALECT     SQL dialect: mysql, postgresql, sqlserver, sqlite, oracle (default: sqlserver)
  -verbose             Enable verbose output
  -config FILE         Configuration file path
  -help                Show help

πŸ“Š Example Output

Query Analysis (Table Format)

=== SQL Query Analysis ===
Query Type: SELECT
Complexity: 4

Tables:
Name                 Schema     Alias      Usage
------------------------------------------------------------
users                           u          SELECT
orders                          o          SELECT

Columns:
Name                 Table      Usage
----------------------------------------
name                 u          SELECT
total                o          SELECT

Joins:
Type       Left Table      Right Table     Condition
------------------------------------------------------------
INNER                      orders          (u.id = o.user_id)

=== Optimization Suggestions ===
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TYPE                    β”‚ SEVERITY β”‚ DESCRIPTION                    β”‚ SUGGESTION              β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ πŸ” SELECT_STAR          β”‚ WARNING  β”‚ Avoid SELECT * for performance β”‚ Specify explicit columnsβ”‚
β”‚ ⚑ MISSING_INDEX        β”‚ INFO     β”‚ Consider adding index          β”‚ CREATE INDEX ON users(id)β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ—οΈ Architecture

sql-parser-go/
β”œβ”€β”€ cmd/sqlparser/          # CLI application
β”œβ”€β”€ pkg/
β”‚   β”œβ”€β”€ lexer/             # SQL tokenization
β”‚   β”œβ”€β”€ parser/            # SQL parsing and AST
β”‚   β”œβ”€β”€ analyzer/          # Query analysis and optimization
β”‚   β”œβ”€β”€ dialect/           # Dialect-specific support
β”‚   β”œβ”€β”€ schema/            # Schema definitions and validation
β”‚   β”œβ”€β”€ plan/              # Execution plan analysis
β”‚   └── logger/            # Log parsing
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ config/            # Configuration management
β”‚   └── performance/       # Performance monitoring
β”œβ”€β”€ tests/                 # Comprehensive test suite
└── examples/              # Example queries, logs, schemas

Key Components

  1. Lexer - Tokenizes SQL text into tokens (~1826 ns/op)
  2. Parser - Builds Abstract Syntax Tree (~1141 ns/op, sub-microsecond!)
  3. Analyzer - Extracts metadata and optimization suggestions (1786 ns/op cold, 26 ns/op cached - 67x speedup!)
  4. Dialect - Handles dialect-specific syntax and features
  5. Schema - Schema loading and validation (7.2ΞΌs load, 155-264ns validation)
  6. Plan - Execution plan analysis (46ns analysis, 117ns bottleneck detection)

πŸš€ Performance Highlights

Tested on Apple M2 Pro - See docs/PERFORMANCE.md for complete benchmarks.

Parsing Performance

Dialect Time (ns/op) Throughput (MB/s)
SQL Server 375.9 1327.54
Oracle 1,315 379.61
SQLite 1,248 379.77
PostgreSQL 2,753 178.71
MySQL 4,887 97.60

Advanced Features Performance

Feature Time Notes
Scalar Subqueries 8-10 ΞΌs Sub-10 microseconds!
Window Functions 12-32 ΞΌs ROW_NUMBER, PARTITION BY
CTEs (WITH clause) 14-80 ΞΌs Single/Multiple CTEs
Schema Validation 155-264 ns Zero-allocation!
Plan Analysis 46 ns Ultra-fast
Transaction COMMIT 149 ns Lightning-fast

This is production-ready performance that matches or exceeds commercial SQL parsers!

πŸ› οΈ Development

Build & Test

# Build
make build

# Run tests
make test

# Run benchmarks
make bench

# Format code
make fmt

# Run all checks (deps, fmt, lint, test, build)
make all

Example Development Commands

# Analyze complex query
make dev-query

# Analyze simple query
make dev-simple

# Parse log file
make dev-log

πŸ“– Documentation

  • docs/ - Complete documentation (examples, performance, guides)
    • EXAMPLES.md - Comprehensive usage examples for all features
    • PERFORMANCE.md - Detailed performance benchmarks and optimizations
  • DIALECT_SUPPORT.md - Complete dialect-specific documentation
  • CLAUDE.md - Developer guide for working with Claude Code
  • examples/ - Example queries, logs, and schemas

πŸ—ΊοΈ Roadmap

βœ… Completed Features

  • Multi-dialect support (5 dialects)
  • Full SQL statement support (SELECT, INSERT, UPDATE, DELETE)
  • DDL support (CREATE, DROP, ALTER, INDEX)
  • Transaction control (BEGIN, COMMIT, ROLLBACK, SAVEPOINT)
  • Advanced SQL features (CTEs, Window Functions, Set Operations)
  • Comprehensive subquery support
  • Schema-aware parsing and validation
  • Query execution plan analysis
  • Stored procedures and functions
  • View definitions (CREATE VIEW, CREATE MATERIALIZED VIEW)
  • Trigger parsing (CREATE TRIGGER, DROP TRIGGER)
  • Performance benchmarking
  • Dialect-specific optimizations

🚧 Planned Features

  • Real-time log monitoring
  • Integration with monitoring tools

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Run make all to ensure code quality
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Inspired by various SQL parsing libraries
  • Built with Go's excellent standard library
  • Uses minimal external dependencies for better maintainability

πŸ“ž Support


Built with ❀️ using Go | Sub-microsecond performance | Production-ready

About

A powerful SQL query analyzer and optimizer supporting MySQL, PostgreSQL, SQL Server, SQLite, and Oracle

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •