queryopt 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- queryopt/__init__.py +64 -0
- queryopt/analyzer.py +130 -0
- queryopt/mcp_server.py +22 -0
- queryopt/ml_model.py +145 -0
- queryopt/schemas.py +19 -0
- queryopt/version.py +1 -0
- queryopt-1.0.0.dist-info/METADATA +127 -0
- queryopt-1.0.0.dist-info/RECORD +10 -0
- queryopt-1.0.0.dist-info/WHEEL +5 -0
- queryopt-1.0.0.dist-info/top_level.txt +1 -0
queryopt/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""QueryOpt — SQL slow query risk estimator and index advisor."""
|
|
2
|
+
from .version import __version__
|
|
3
|
+
from .schemas import QueryAnalysis, OptimizationTip
|
|
4
|
+
from .analyzer import rule_analyze, extract_features
|
|
5
|
+
from .ml_model import SlowQueryModelLoader
|
|
6
|
+
|
|
7
|
+
__all__ = ["__version__", "QueryOptimizer", "SQLAnalyzer", "IndexAdvisor", "QueryAnalysis", "OptimizationTip"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SQLAnalyzer:
|
|
11
|
+
"""Extract features from SQL queries."""
|
|
12
|
+
|
|
13
|
+
def analyze(self, sql: str) -> dict:
|
|
14
|
+
return extract_features(sql)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class IndexAdvisor:
|
|
18
|
+
"""Suggest indexes based on query patterns."""
|
|
19
|
+
|
|
20
|
+
def suggest(self, sql: str) -> list:
|
|
21
|
+
import re
|
|
22
|
+
suggestions = []
|
|
23
|
+
where_cols = re.findall(r"WHERE\s+(\w+)\s*=", sql, re.I)
|
|
24
|
+
join_cols = re.findall(r"ON\s+\w+\.(\w+)\s*=", sql, re.I)
|
|
25
|
+
for col in where_cols:
|
|
26
|
+
suggestions.append(f"CREATE INDEX idx_{col} ON <table>({col})")
|
|
27
|
+
for col in join_cols:
|
|
28
|
+
suggestions.append(f"CREATE INDEX idx_{col}_join ON <table>({col})")
|
|
29
|
+
return list(dict.fromkeys(suggestions))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class QueryOptimizer:
|
|
33
|
+
"""Main interface: analyze SQL queries for performance issues."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, use_ml: bool = True):
|
|
36
|
+
self._loader = SlowQueryModelLoader() if use_ml else None
|
|
37
|
+
self._advisor = IndexAdvisor()
|
|
38
|
+
self._use_ml = use_ml
|
|
39
|
+
|
|
40
|
+
def analyze(self, sql: str) -> dict:
|
|
41
|
+
rule_result = rule_analyze(sql)
|
|
42
|
+
features = extract_features(sql)
|
|
43
|
+
|
|
44
|
+
ml_risk = None
|
|
45
|
+
if self._use_ml and self._loader is not None:
|
|
46
|
+
ml_result = self._loader.predict(features)
|
|
47
|
+
ml_risk = ml_result.get("slow_risk", rule_result.slow_risk)
|
|
48
|
+
|
|
49
|
+
slow_risk = ml_risk or rule_result.slow_risk
|
|
50
|
+
index_suggestions = self._advisor.suggest(sql)
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
"slow_risk": slow_risk,
|
|
54
|
+
"n_plus_one": rule_result.n_plus_one,
|
|
55
|
+
"missing_index": rule_result.missing_index,
|
|
56
|
+
"estimated_cost": rule_result.estimated_cost,
|
|
57
|
+
"tips": [{"category": t.category, "message": t.message, "severity": t.severity}
|
|
58
|
+
for t in rule_result.tips],
|
|
59
|
+
"index_suggestions": index_suggestions,
|
|
60
|
+
"features": features,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
def is_risky(self, sql: str) -> bool:
|
|
64
|
+
return self.analyze(sql)["slow_risk"] in ("medium", "high")
|
queryopt/analyzer.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""SQL query analyzer — rule-based extraction of features and tips."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import re
|
|
4
|
+
from .schemas import QueryAnalysis, OptimizationTip
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _count_joins(sql: str) -> int:
|
|
8
|
+
return len(re.findall(r"\bJOIN\b", sql, re.I))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _count_tables(sql: str) -> int:
|
|
12
|
+
from_matches = re.findall(r"\bFROM\b\s+([\w.,\s]+?)(?:\bWHERE\b|\bJOIN\b|\bGROUP\b|\bORDER\b|$)", sql, re.I)
|
|
13
|
+
join_matches = re.findall(r"\bJOIN\b\s+(\w+)", sql, re.I)
|
|
14
|
+
tables = set()
|
|
15
|
+
for m in from_matches:
|
|
16
|
+
for t in re.split(r"[,\s]+", m.strip()):
|
|
17
|
+
t = t.strip().rstrip(",")
|
|
18
|
+
if t and re.match(r"^\w+$", t):
|
|
19
|
+
tables.add(t)
|
|
20
|
+
tables.update(join_matches)
|
|
21
|
+
return max(1, len(tables))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _has_select_star(sql: str) -> bool:
|
|
25
|
+
return bool(re.search(r"SELECT\s+\*", sql, re.I))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _subquery_depth(sql: str) -> int:
|
|
29
|
+
max_depth = depth = 0
|
|
30
|
+
for ch in sql:
|
|
31
|
+
if ch == "(":
|
|
32
|
+
depth += 1
|
|
33
|
+
max_depth = max(max_depth, depth)
|
|
34
|
+
elif ch == ")":
|
|
35
|
+
depth = max(0, depth - 1)
|
|
36
|
+
return max_depth
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _where_complexity(sql: str) -> int:
|
|
40
|
+
where_match = re.search(r"\bWHERE\b(.+?)(?:\bGROUP\b|\bORDER\b|\bHAVING\b|\bLIMIT\b|$)", sql, re.I | re.S)
|
|
41
|
+
if not where_match:
|
|
42
|
+
return 0
|
|
43
|
+
where_clause = where_match.group(1)
|
|
44
|
+
return len(re.findall(r"\bAND\b|\bOR\b", where_clause, re.I)) + 1
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _has_no_index_hint(sql: str) -> bool:
|
|
48
|
+
return bool(re.search(r"LIKE\s+'%|function\(.*column|LOWER\(|UPPER\(", sql, re.I))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _group_by_count(sql: str) -> int:
|
|
52
|
+
gb_match = re.search(r"\bGROUP\s+BY\b(.+?)(?:\bHAVING\b|\bORDER\b|\bLIMIT\b|$)", sql, re.I | re.S)
|
|
53
|
+
if not gb_match:
|
|
54
|
+
return 0
|
|
55
|
+
return len(re.split(r",", gb_match.group(1)))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def extract_features(sql: str) -> dict:
|
|
59
|
+
sql = sql.strip()
|
|
60
|
+
return {
|
|
61
|
+
"query_length": len(sql),
|
|
62
|
+
"table_count": _count_tables(sql),
|
|
63
|
+
"join_count": _count_joins(sql),
|
|
64
|
+
"has_select_star": int(_has_select_star(sql)),
|
|
65
|
+
"subquery_depth": _subquery_depth(sql),
|
|
66
|
+
"where_complexity": _where_complexity(sql),
|
|
67
|
+
"group_by_count": _group_by_count(sql),
|
|
68
|
+
"has_no_index_hint": int(_has_no_index_hint(sql)),
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def rule_analyze(sql: str) -> QueryAnalysis:
|
|
73
|
+
f = extract_features(sql)
|
|
74
|
+
tips = []
|
|
75
|
+
score = 0.0
|
|
76
|
+
|
|
77
|
+
if f["has_select_star"]:
|
|
78
|
+
tips.append(OptimizationTip("performance", "Avoid SELECT * — specify columns explicitly", "warning"))
|
|
79
|
+
score += 0.15
|
|
80
|
+
|
|
81
|
+
if f["join_count"] >= 4:
|
|
82
|
+
tips.append(OptimizationTip("complexity", f"{f['join_count']} JOINs detected — consider denormalization or materialized view", "critical"))
|
|
83
|
+
score += 0.3
|
|
84
|
+
elif f["join_count"] >= 2:
|
|
85
|
+
score += 0.1
|
|
86
|
+
|
|
87
|
+
if f["subquery_depth"] >= 3:
|
|
88
|
+
tips.append(OptimizationTip("complexity", "Deep nesting detected — consider CTEs for readability and performance", "warning"))
|
|
89
|
+
score += 0.2
|
|
90
|
+
|
|
91
|
+
if f["has_no_index_hint"]:
|
|
92
|
+
tips.append(OptimizationTip("index", "Function call or LIKE '%...' prevents index use", "critical"))
|
|
93
|
+
score += 0.25
|
|
94
|
+
|
|
95
|
+
if f["table_count"] >= 5:
|
|
96
|
+
score += 0.2
|
|
97
|
+
|
|
98
|
+
if f["query_length"] > 2000:
|
|
99
|
+
tips.append(OptimizationTip("complexity", "Very long query — split into CTEs or views", "info"))
|
|
100
|
+
score += 0.1
|
|
101
|
+
|
|
102
|
+
n_plus_one = f["join_count"] == 0 and f["table_count"] == 1 and "WHERE" in sql.upper() and f["query_length"] < 200
|
|
103
|
+
missing_index = f["has_no_index_hint"] or (f["where_complexity"] >= 3 and f["join_count"] >= 2)
|
|
104
|
+
|
|
105
|
+
if n_plus_one:
|
|
106
|
+
tips.append(OptimizationTip("n+1", "Possible N+1 pattern — consider bulk fetch or JOIN", "critical"))
|
|
107
|
+
score += 0.3
|
|
108
|
+
|
|
109
|
+
score = min(1.0, score)
|
|
110
|
+
if score >= 0.6:
|
|
111
|
+
slow_risk = "high"
|
|
112
|
+
cost = "expensive (>100ms)"
|
|
113
|
+
elif score >= 0.3:
|
|
114
|
+
slow_risk = "medium"
|
|
115
|
+
cost = "moderate (10-100ms)"
|
|
116
|
+
else:
|
|
117
|
+
slow_risk = "low"
|
|
118
|
+
cost = "fast (<10ms)"
|
|
119
|
+
|
|
120
|
+
if not tips:
|
|
121
|
+
tips.append(OptimizationTip("info", "Query looks well-structured", "info"))
|
|
122
|
+
|
|
123
|
+
return QueryAnalysis(
|
|
124
|
+
slow_risk=slow_risk,
|
|
125
|
+
n_plus_one=n_plus_one,
|
|
126
|
+
missing_index=missing_index,
|
|
127
|
+
estimated_cost=cost,
|
|
128
|
+
tips=tips,
|
|
129
|
+
score=round(score, 3),
|
|
130
|
+
)
|
queryopt/mcp_server.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""MCP server for QueryOpt — SQL query analysis tool."""
|
|
2
|
+
from mcp.server.fastmcp import FastMCP
|
|
3
|
+
from . import QueryOptimizer
|
|
4
|
+
|
|
5
|
+
mcp = FastMCP("queryopt")
|
|
6
|
+
_optimizer = QueryOptimizer()
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@mcp.tool()
|
|
10
|
+
def analyze_sql(query: str) -> dict:
|
|
11
|
+
"""Analyze a SQL query for slow query risk, N+1, missing indexes, and optimization tips."""
|
|
12
|
+
return _optimizer.analyze(query)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@mcp.tool()
|
|
16
|
+
def is_risky_query(query: str) -> bool:
|
|
17
|
+
"""Quick check: does this SQL query have medium or high slow-query risk?"""
|
|
18
|
+
return _optimizer.is_risky(query)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
if __name__ == "__main__":
|
|
22
|
+
mcp.run(transport="stdio")
|
queryopt/ml_model.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""SQL slow-query risk ML model — GBM → ONNX, lazy-load from HF Hub."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import os
|
|
4
|
+
import json
|
|
5
|
+
import numpy as np
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
HF_REPO = "teyfikoz/queryopt-sql-model"
|
|
10
|
+
CACHE_DIR = Path.home() / ".cache" / "queryopt"
|
|
11
|
+
FEATURE_NAMES = ["query_length", "table_count", "join_count", "has_select_star",
|
|
12
|
+
"subquery_depth", "where_complexity", "group_by_count", "has_no_index_hint"]
|
|
13
|
+
N_FEATURES = len(FEATURE_NAMES)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SlowQueryModelLoader:
|
|
17
|
+
_instance: Optional["SlowQueryModelLoader"] = None
|
|
18
|
+
_session = None
|
|
19
|
+
_metadata: dict = {}
|
|
20
|
+
|
|
21
|
+
def __new__(cls):
|
|
22
|
+
if cls._instance is None:
|
|
23
|
+
cls._instance = super().__new__(cls)
|
|
24
|
+
return cls._instance
|
|
25
|
+
|
|
26
|
+
def _ensure_loaded(self):
|
|
27
|
+
if self._session is not None:
|
|
28
|
+
return
|
|
29
|
+
try:
|
|
30
|
+
from huggingface_hub import hf_hub_download
|
|
31
|
+
import onnxruntime as ort
|
|
32
|
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
model_path = hf_hub_download(repo_id=HF_REPO, filename="slow_query_classifier.onnx",
|
|
34
|
+
cache_dir=str(CACHE_DIR))
|
|
35
|
+
meta_path = hf_hub_download(repo_id=HF_REPO, filename="metadata.json",
|
|
36
|
+
cache_dir=str(CACHE_DIR))
|
|
37
|
+
self._session = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])
|
|
38
|
+
self._metadata = json.loads(Path(meta_path).read_text())
|
|
39
|
+
except Exception:
|
|
40
|
+
self._session = None
|
|
41
|
+
|
|
42
|
+
def predict(self, features: dict) -> dict:
|
|
43
|
+
self._ensure_loaded()
|
|
44
|
+
feat_array = np.array([[features.get(f, 0) for f in FEATURE_NAMES]], dtype=np.float32)
|
|
45
|
+
|
|
46
|
+
if self._session is not None:
|
|
47
|
+
try:
|
|
48
|
+
input_name = self._session.get_inputs()[0].name
|
|
49
|
+
proba = self._session.run(None, {input_name: feat_array})[1][0]
|
|
50
|
+
score = float(proba[1]) if len(proba) > 1 else float(proba[0])
|
|
51
|
+
slow_risk = "high" if score >= 0.65 else ("medium" if score >= 0.35 else "low")
|
|
52
|
+
return {"slow_risk": slow_risk, "risk_score": round(score, 4), "model": "onnx_v1.0"}
|
|
53
|
+
except Exception:
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
return self._rule_fallback(features)
|
|
57
|
+
|
|
58
|
+
def _rule_fallback(self, features: dict) -> dict:
|
|
59
|
+
score = (
|
|
60
|
+
features.get("join_count", 0) * 0.1 +
|
|
61
|
+
features.get("subquery_depth", 0) * 0.15 +
|
|
62
|
+
features.get("has_select_star", 0) * 0.1 +
|
|
63
|
+
features.get("has_no_index_hint", 0) * 0.2 +
|
|
64
|
+
min(features.get("query_length", 0) / 5000, 0.2)
|
|
65
|
+
)
|
|
66
|
+
score = min(1.0, score)
|
|
67
|
+
slow_risk = "high" if score >= 0.65 else ("medium" if score >= 0.35 else "low")
|
|
68
|
+
return {"slow_risk": slow_risk, "risk_score": round(score, 4), "model": "rule_fallback"}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def train_and_push(hf_token: Optional[str] = None):
|
|
72
|
+
"""Train on synthetic SQL query data and push ONNX model to HF Hub."""
|
|
73
|
+
import tempfile
|
|
74
|
+
from sklearn.ensemble import GradientBoostingClassifier
|
|
75
|
+
from sklearn.model_selection import train_test_split
|
|
76
|
+
from sklearn.metrics import roc_auc_score
|
|
77
|
+
from skl2onnx import convert_sklearn
|
|
78
|
+
from skl2onnx.common.data_types import FloatTensorType
|
|
79
|
+
from huggingface_hub import HfApi
|
|
80
|
+
|
|
81
|
+
rng = np.random.default_rng(42)
|
|
82
|
+
n = 10_000
|
|
83
|
+
|
|
84
|
+
query_length = rng.integers(20, 3000, n)
|
|
85
|
+
table_count = rng.integers(1, 10, n)
|
|
86
|
+
join_count = rng.integers(0, 8, n)
|
|
87
|
+
has_select_star = rng.binomial(1, 0.3, n)
|
|
88
|
+
subquery_depth = rng.integers(0, 5, n)
|
|
89
|
+
where_complexity = rng.integers(0, 8, n)
|
|
90
|
+
group_by_count = rng.integers(0, 5, n)
|
|
91
|
+
has_no_index_hint = rng.binomial(1, 0.25, n)
|
|
92
|
+
|
|
93
|
+
X = np.stack([query_length, table_count, join_count, has_select_star,
|
|
94
|
+
subquery_depth, where_complexity, group_by_count, has_no_index_hint], axis=1).astype(np.float32)
|
|
95
|
+
|
|
96
|
+
y = (
|
|
97
|
+
(join_count >= 4) |
|
|
98
|
+
(subquery_depth >= 3) |
|
|
99
|
+
(has_no_index_hint == 1) |
|
|
100
|
+
((has_select_star == 1) & (table_count >= 3)) |
|
|
101
|
+
(query_length > 1500)
|
|
102
|
+
).astype(int)
|
|
103
|
+
|
|
104
|
+
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42)
|
|
105
|
+
clf = GradientBoostingClassifier(n_estimators=120, max_depth=4, learning_rate=0.1, random_state=42)
|
|
106
|
+
clf.fit(X_tr, y_tr)
|
|
107
|
+
auc = roc_auc_score(y_te, clf.predict_proba(X_te)[:, 1])
|
|
108
|
+
print(f" AUC: {auc:.4f}")
|
|
109
|
+
|
|
110
|
+
onnx_model = convert_sklearn(clf, initial_types=[("float_input", FloatTensorType([None, N_FEATURES]))],
|
|
111
|
+
target_opset=17)
|
|
112
|
+
|
|
113
|
+
token = hf_token or os.environ.get("HF_TOKEN", "")
|
|
114
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
115
|
+
tmpdir = Path(tmp)
|
|
116
|
+
(tmpdir / "slow_query_classifier.onnx").write_bytes(onnx_model.SerializeToString())
|
|
117
|
+
meta = {"version": "1.0.0", "auc": round(auc, 4), "n_train": len(X_tr),
|
|
118
|
+
"features": FEATURE_NAMES, "data": "10K synthetic SQL queries"}
|
|
119
|
+
(tmpdir / "metadata.json").write_text(json.dumps(meta, indent=2))
|
|
120
|
+
card = f"""---
|
|
121
|
+
library_name: queryopt
|
|
122
|
+
tags: [sql, query-optimization, slow-query, onnx, tabular]
|
|
123
|
+
license: mit
|
|
124
|
+
---
|
|
125
|
+
# QueryOpt SQL Model v1.0.0
|
|
126
|
+
|
|
127
|
+
GradientBoosting classifier for SQL slow query risk prediction.
|
|
128
|
+
|
|
129
|
+
- **AUC:** {auc:.4f}
|
|
130
|
+
- **Data:** 10K synthetic SQL queries with realistic JOIN/subquery distributions
|
|
131
|
+
- **Features:** {', '.join(FEATURE_NAMES)}
|
|
132
|
+
|
|
133
|
+
## Usage
|
|
134
|
+
```python
|
|
135
|
+
from queryopt import QueryOptimizer
|
|
136
|
+
qo = QueryOptimizer()
|
|
137
|
+
result = qo.analyze("SELECT * FROM users JOIN orders ON ...")
|
|
138
|
+
```
|
|
139
|
+
"""
|
|
140
|
+
(tmpdir / "README.md").write_text(card)
|
|
141
|
+
api = HfApi(token=token)
|
|
142
|
+
api.create_repo(HF_REPO, exist_ok=True, private=False)
|
|
143
|
+
api.upload_folder(folder_path=tmp, repo_id=HF_REPO, commit_message="v1.0.0 initial release")
|
|
144
|
+
print(f" Pushed → https://huggingface.co/{HF_REPO}")
|
|
145
|
+
return auc
|
queryopt/schemas.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import List
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class OptimizationTip:
|
|
7
|
+
category: str
|
|
8
|
+
message: str
|
|
9
|
+
severity: str # "critical", "warning", "info"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class QueryAnalysis:
|
|
14
|
+
slow_risk: str # "low", "medium", "high"
|
|
15
|
+
n_plus_one: bool
|
|
16
|
+
missing_index: bool
|
|
17
|
+
estimated_cost: str
|
|
18
|
+
tips: List[OptimizationTip]
|
|
19
|
+
score: float
|
queryopt/version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: queryopt
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: SQL slow query risk estimator and index advisor — ONNX model, MCP server, zero config
|
|
5
|
+
Author-email: Teyfik Öz <teyfikoz@yahoo.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/teyfikoz/queryopt
|
|
8
|
+
Project-URL: Repository, https://github.com/teyfikoz/queryopt
|
|
9
|
+
Keywords: sql,query-optimization,database,performance,onnx,index
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Database
|
|
15
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
Requires-Dist: numpy>=1.24
|
|
19
|
+
Requires-Dist: scikit-learn>=1.3
|
|
20
|
+
Requires-Dist: onnxruntime>=1.16
|
|
21
|
+
Requires-Dist: huggingface-hub>=0.19
|
|
22
|
+
Provides-Extra: ml
|
|
23
|
+
Requires-Dist: skl2onnx>=1.16; extra == "ml"
|
|
24
|
+
Provides-Extra: mcp
|
|
25
|
+
Requires-Dist: mcp>=1.0; extra == "mcp"
|
|
26
|
+
Provides-Extra: all
|
|
27
|
+
Requires-Dist: queryopt[mcp,ml]; extra == "all"
|
|
28
|
+
|
|
29
|
+
# QueryOpt
|
|
30
|
+
|
|
31
|
+
**SQL slow query risk estimator and index advisor** — detects N+1 patterns, missing indexes, expensive JOINs, and slow query risks using rule-based analysis + GBM ONNX model. MCP-ready for AI coding agents.
|
|
32
|
+
|
|
33
|
+
[](https://pypi.org/project/queryopt/)
|
|
34
|
+
[](https://www.python.org/)
|
|
35
|
+
[](https://opensource.org/licenses/MIT)
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install queryopt
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Quick Start
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from queryopt import QueryOptimizer
|
|
47
|
+
|
|
48
|
+
qo = QueryOptimizer()
|
|
49
|
+
|
|
50
|
+
# Analyze a query
|
|
51
|
+
result = qo.analyze("SELECT * FROM users WHERE email = 'x@example.com'")
|
|
52
|
+
print(result["slow_risk"]) # "low"
|
|
53
|
+
print(result["tips"]) # [{"category": "performance", "message": "Avoid SELECT *..."}]
|
|
54
|
+
|
|
55
|
+
# Complex query
|
|
56
|
+
result = qo.analyze("""
|
|
57
|
+
SELECT * FROM orders o
|
|
58
|
+
JOIN users u ON o.user_id = u.id
|
|
59
|
+
JOIN products p ON o.product_id = p.id
|
|
60
|
+
JOIN categories c ON p.category_id = c.id
|
|
61
|
+
WHERE LOWER(u.email) LIKE '%test%'
|
|
62
|
+
""")
|
|
63
|
+
print(result["slow_risk"]) # "high"
|
|
64
|
+
print(result["n_plus_one"]) # False
|
|
65
|
+
print(result["missing_index"]) # True
|
|
66
|
+
print(result["estimated_cost"]) # "expensive (>100ms)"
|
|
67
|
+
print(result["index_suggestions"]) # ["CREATE INDEX idx_..."]
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Features
|
|
71
|
+
|
|
72
|
+
| Feature | Description |
|
|
73
|
+
|---------|-------------|
|
|
74
|
+
| **Slow Query Risk** | low / medium / high — GBM ONNX model |
|
|
75
|
+
| **N+1 Detection** | Identify N+1 query patterns |
|
|
76
|
+
| **Index Advisor** | Suggest missing indexes from WHERE/JOIN columns |
|
|
77
|
+
| **Cost Estimation** | fast (<10ms) / moderate (10-100ms) / expensive (>100ms) |
|
|
78
|
+
| **Tips** | Actionable optimization suggestions |
|
|
79
|
+
| **MCP Tool** | Ready for AI coding agent integration |
|
|
80
|
+
|
|
81
|
+
## 🤖 ML Model (v1.0 — GBM + ONNX)
|
|
82
|
+
|
|
83
|
+
GradientBoosting trained on 10K synthetic SQL queries with realistic JOIN/subquery distributions.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from queryopt.ml_model import SlowQueryModelLoader
|
|
87
|
+
|
|
88
|
+
loader = SlowQueryModelLoader()
|
|
89
|
+
result = loader.predict({
|
|
90
|
+
"query_length": 450, "join_count": 5, "subquery_depth": 2,
|
|
91
|
+
"has_select_star": 1, "has_no_index_hint": 1,
|
|
92
|
+
"where_complexity": 3, "table_count": 4, "group_by_count": 1
|
|
93
|
+
})
|
|
94
|
+
# {"slow_risk": "high", "risk_score": 0.84, "model": "onnx_v1.0"}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**Model details:**
|
|
98
|
+
- Training: 10K synthetic SQL queries
|
|
99
|
+
- Features: query_length, table_count, join_count, has_select_star, subquery_depth, where_complexity, group_by_count, has_no_index_hint
|
|
100
|
+
- Architecture: GradientBoostingClassifier → ONNX (skl2onnx)
|
|
101
|
+
- Model: [`teyfikoz/queryopt-sql-model`](https://huggingface.co/teyfikoz/queryopt-sql-model)
|
|
102
|
+
- Lazy-loaded on first call → cached at `~/.cache/queryopt/`
|
|
103
|
+
|
|
104
|
+
## Index Advisor
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from queryopt import IndexAdvisor
|
|
108
|
+
|
|
109
|
+
adv = IndexAdvisor()
|
|
110
|
+
sql = "SELECT * FROM orders o JOIN users u ON o.user_id = u.id WHERE o.status = 'pending'"
|
|
111
|
+
for suggestion in adv.suggest(sql):
|
|
112
|
+
print(suggestion)
|
|
113
|
+
# CREATE INDEX idx_status ON <table>(status)
|
|
114
|
+
# CREATE INDEX idx_user_id_join ON <table>(user_id)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## MCP Usage
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
pip install "queryopt[mcp]"
|
|
121
|
+
# Add to your MCP config:
|
|
122
|
+
# {"command": "python", "args": ["-m", "queryopt.mcp_server"]}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## License
|
|
126
|
+
|
|
127
|
+
MIT — [Teyfik Öz](https://github.com/teyfikoz)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
queryopt/__init__.py,sha256=fiGp4HB6o1cG0vb1Rnw6S8YagtIJGf39NOTnPXNrvY8,2339
|
|
2
|
+
queryopt/analyzer.py,sha256=SVS8EKVVmyQ2NVYs9Ilos0o6C_yq2j72afS5U2p1J2E,4270
|
|
3
|
+
queryopt/mcp_server.py,sha256=WypD0v5Wrm-wo8BuRA2kwVv68ej6WVvf0AGGtk6SW14,600
|
|
4
|
+
queryopt/ml_model.py,sha256=XKAFkvxv4jvorfksdh3-oAcQSwf79ibCp3KD5kEu8-k,5891
|
|
5
|
+
queryopt/schemas.py,sha256=TI_0-uFTudcirAZ5BVNxVNBV2q-PLmImyx467aWYUdY,385
|
|
6
|
+
queryopt/version.py,sha256=J-j-u0itpEFT6irdmWmixQqYMadNl1X91TxUmoiLHMI,22
|
|
7
|
+
queryopt-1.0.0.dist-info/METADATA,sha256=oyaXLQugt412GvdbDF74rz7_BSvmu4XG5aMxwwDSsGY,4351
|
|
8
|
+
queryopt-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
9
|
+
queryopt-1.0.0.dist-info/top_level.txt,sha256=AEPugQJVNnQVPJI6_X3vL1DBxsuAJKG5utr0BHCI_ew,9
|
|
10
|
+
queryopt-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
queryopt
|