Metadata-Version: 2.4
Name: multi-dialect-sql-parser
Version: 0.2.0
Summary: Multi-dialect SQL parser supporting MySQL, PostgreSQL, Oracle, TiDB, OceanBase
Project-URL: Homepage, https://github.com/your-org/multi-dialect-sql-parser
Project-URL: Repository, https://github.com/your-org/multi-dialect-sql-parser
Project-URL: Documentation, https://github.com/your-org/multi-dialect-sql-parser#readme
Author-email: DylanYang <1223880534@qq.com>
License: MIT
License-File: LICENSE
Keywords: mysql,oceanbase,oracle,parser,postgresql,sql,sqlglot,tidb
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Requires-Dist: pydantic>=2.0.0
Requires-Dist: sqlglot>=20.0.0
Provides-Extra: dev
Requires-Dist: memory-profiler>=0.61.0; extra == 'dev'
Requires-Dist: pytest-benchmark>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Description-Content-Type: text/markdown

# SQL Parser

Multi-dialect SQL parser supporting MySQL, PostgreSQL, Oracle, TiDB, OceanBase.

## Features

- 支持 6 种数据库方言：MySQL、PostgreSQL、Oracle、TiDB、OceanBase-MySQL、OceanBase-Oracle
- 多进程批量解析，流式返回结果
- 精确错误位置定位
- 预处理 SQLGlot 不支持的方言特有语法
- 支持存储过程、函数、触发器等过程化对象解析

## Installation

```bash
pip install multi-dialect-sql-parser
```

或从源码安装：

```bash
pip install -e .
```

## Quick Start

```python
from sql_parser import SQLParser

# 创建解析器
parser = SQLParser(dialect="mysql")

# 解析单条 SQL
result = parser.parse("SELECT * FROM users WHERE id = 1")

if result.success:
    print(f"语句类型: {result.statement_type}")
    print(f"涉及表: {[t.name for t in result.tables]}")
    print(f"涉及列: {[c.name for c in result.columns]}")
```

## Batch Parsing

```python
sqls = [
    "SELECT * FROM users",
    "INSERT INTO orders (user_id) VALUES (1)",
    "UPDATE products SET price = 99 WHERE id = 1",
]

# 流式返回（推荐，内存友好）
for result in parser.parse_batch(sqls):
    print(f"{result.statement_type}: {result.success}")

# 返回汇总结果
batch = parser.parse_batch_all(sqls)
print(f"成功: {batch.successful}/{batch.total_statements}")
```

## Supported Dialects

| 方言 | 标识符 | 说明 |
|------|--------|------|
| MySQL | `mysql` | MySQL 5.7+ |
| PostgreSQL | `postgresql` | PostgreSQL 10+ |
| Oracle | `oracle` | Oracle 11g+，支持 PL/SQL |
| TiDB | `tidb` | TiDB 4.0+，支持 AUTO_RANDOM、Hint |
| OceanBase MySQL | `oceanbase-mysql` | OceanBase MySQL 模式 |
| OceanBase Oracle | `oceanbase-oracle` | OceanBase Oracle 模式 |

## Performance Benchmark

测试环境：Windows 11, Python 3.11, Intel Core i7

### 单条 SQL 解析性能

| SQL 类型 | 平均耗时 | 吞吐量 |
|----------|----------|--------|
| 简单查询 | 0.14 ms | 7,130 ops/s |
| 复杂查询（多表 JOIN） | 1.35 ms | 741 ops/s |

### 批量解析性能

| SQL 数量 | 总耗时 | 平均耗时 | 吞吐量 |
|----------|--------|----------|--------|
| 100 | 0.06s | 0.59ms | 1,697 ops/s |
| 1,000 | 0.59s | 0.59ms | 1,682 ops/s |
| 5,000 | 1.78s | 0.36ms | 2,811 ops/s |
| 10,000 | 2.88s | 0.29ms | 3,471 ops/s |

### 内存使用

| SQL 数量 | 峰值内存 | 每条 SQL |
|----------|----------|----------|
| 1,000 | 8.6 MB | 8.8 KB |
| 5,000 | 54 MB | 11.0 KB |
| 10,000 | 107 MB | 11.0 KB |

### 方言性能对比

| 方言 | 吞吐量 | 成功率 |
|------|--------|--------|
| PostgreSQL | 1,638 ops/s | 100% |
| TiDB | 1,626 ops/s | 100% |
| MySQL | 1,616 ops/s | 100% |
| OceanBase-MySQL | 1,536 ops/s | 100% |
| Oracle | 973 ops/s | 100% |

### 流式解析 vs 全量解析（10000 条 SQL）

| 模式 | 耗时 | 峰值内存 |
|------|------|----------|
| 流式 (`parse_batch`) | 3.5s | 15 MB |
| 全量 (`parse_batch_all`) | 3.6s | 54 MB |

**结论**：流式解析节省 72% 内存，推荐用于大批量场景。

## API Reference

### SQLParser

```python
class SQLParser:
    def __init__(
        self,
        dialect: str = "mysql",      # 数据库方言
        max_workers: int = None,     # 最大进程数（默认 CPU 核心数）
        batch_size: int = 1000,      # 批量大小
        enable_cache: bool = False,  # 启用 LRU 缓存
        cache_size: int = 1000,      # 缓存最大条目数
    ): ...
    
    def parse(self, sql: str) -> ParseResult:
        """解析单条 SQL"""
    
    def parse_batch(self, sqls: List[str]) -> Iterator[ParseResult]:
        """批量解析，流式返回"""
    
    def parse_batch_all(self, sqls: List[str]) -> BatchParseResult:
        """批量解析，返回汇总结果"""
    
    def cache_info(self) -> CacheInfo | None:
        """获取缓存统计信息"""
    
    def clear_cache(self) -> None:
        """清空缓存"""
```

### ParseResult

```python
class ParseResult:
    sql: str                    # 原始 SQL
    dialect: str                # 方言
    statement_type: str         # 语句类型
    success: bool               # 是否成功
    tables: List[TableReference]    # 表列表
    columns: List[ColumnReference]  # 列列表
    conditions: List[ConditionNode] # WHERE 条件
    joins: List[JoinInfo]           # JOIN 信息
    group_by: List[str]             # GROUP BY
    order_by: List[OrderByItem]     # ORDER BY
    limit: int | None               # LIMIT
    offset_value: int | None        # OFFSET
    errors: List[ParseError]        # 错误列表
    warnings: List[ParseError]      # 警告列表
    
    # 方言特有信息
    mysql_info: MySQLSpecificInfo | None
    postgresql_info: PostgreSQLSpecificInfo | None
    oracle_info: OracleSpecificInfo | None
    tidb_info: TiDBSpecificInfo | None
    oceanbase_info: OceanBaseSpecificInfo | None
```

## Run Benchmark

```bash
python benchmark.py
```

## License

MIT
