Skip to content

Commit 886d6db

Browse files
committed
New changes
1 parent 1ddefbc commit 886d6db

File tree

4 files changed

+109
-59
lines changed

4 files changed

+109
-59
lines changed

β€Ž.github/workflows/validate-queries.ymlβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,10 @@ jobs:
7272
env:
7373
SUMO_LOGIC_ACCESS_ID: ${{ secrets.SUMO_LOGIC_ACCESS_ID }}
7474
SUMO_LOGIC_ACCESS_KEY: ${{ secrets.SUMO_LOGIC_ACCESS_KEY }}
75+
BASE_COMMIT: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
76+
CURRENT_COMMIT: ${{ github.sha }}
7577
run: |
78+
echo "Validating only changed SQL queries between $BASE_COMMIT and $CURRENT_COMMIT"
7679
python validate_queries.py
7780
7881
- name: Skip validation

β€Ždocs/metrics/metrics-operators/where.mdβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ where [VALUE BOOLEAN EXPRESSION | REDUCER BOOLEAN EXPRESSION]
1414
```
1515
## Checking my PR:
1616
```sql
17-
_collector="ABC2" | where type="web"
17+
_collector="ABC3" | where type="web"
1818
```
1919
Where:
2020

β€Žscripts/sumologic_client.pyβ€Ž

Lines changed: 0 additions & 47 deletions
This file was deleted.

β€Žscripts/validate_queries.pyβ€Ž

Lines changed: 105 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import sys
44
import os
55
import json
6+
import subprocess
67
import requests
78
from pathlib import Path
89
from datetime import datetime, timedelta
@@ -66,8 +67,66 @@ def get_changed_files(repo_root):
6667
print("::error::No Markdown files found in docs/ directory")
6768
return []
6869

70+
def extract_changed_sql_queries(file_path, base_commit, current_commit):
71+
"""Extract only the SQL code blocks that were added/modified in the git diff"""
72+
try:
73+
# Get the git diff for this specific file
74+
diff_cmd = ["git", "diff", f"{base_commit}...{current_commit}", "--", file_path]
75+
result = subprocess.run(diff_cmd, capture_output=True, text=True, cwd=get_repo_root())
76+
77+
if result.returncode != 0:
78+
print(f"::warning::Could not get git diff for {file_path}")
79+
return []
80+
81+
diff_content = result.stdout
82+
83+
# Extract added SQL blocks from the diff
84+
added_sql_queries = []
85+
86+
# Look for lines that start with + and contain SQL code blocks
87+
lines = diff_content.split('\n')
88+
i = 0
89+
while i < len(lines):
90+
line = lines[i]
91+
92+
# Check if this is an added line with SQL code block start
93+
if line.startswith('+') and ('```sql' in line.lower() or '```sumo' in line.lower()):
94+
# Found start of an added SQL block
95+
sql_lines = []
96+
i += 1
97+
98+
# Collect all lines until we find the closing ```
99+
while i < len(lines):
100+
current_line = lines[i]
101+
102+
# If it's a closing ``` on an added line, we're done
103+
if current_line.startswith('+') and '```' in current_line and current_line.strip() == '+```':
104+
break
105+
106+
# If it's an added line with SQL content, add it
107+
if current_line.startswith('+'):
108+
# Remove the + prefix and add to SQL content
109+
sql_content = current_line[1:] # Remove the '+' prefix
110+
sql_lines.append(sql_content)
111+
112+
i += 1
113+
114+
# Join the SQL lines and clean up
115+
if sql_lines:
116+
sql_query = '\n'.join(sql_lines).strip()
117+
if sql_query and not sql_query.startswith('#') and not sql_query.startswith('//'):
118+
added_sql_queries.append(sql_query)
119+
120+
i += 1
121+
122+
return added_sql_queries
123+
124+
except Exception as e:
125+
print(f"::error::Error extracting changed SQL queries from {file_path}: {e}")
126+
return []
127+
69128
def extract_sql_queries(file_path):
70-
"""Extract SQL code blocks from markdown files"""
129+
"""Extract SQL code blocks from markdown files (fallback method)"""
71130
try:
72131
with open(file_path, 'r', encoding='utf-8') as f:
73132
content = f.read()
@@ -131,16 +190,35 @@ def validate_query_syntax(query):
131190

132191
return errors
133192

134-
def validate_file(file_path):
135-
"""Validate all SQL queries in a markdown file"""
193+
def get_git_commits():
194+
"""Get base and current commit from environment variables"""
195+
base_commit = os.getenv('BASE_COMMIT', '')
196+
current_commit = os.getenv('CURRENT_COMMIT', '')
197+
198+
if not base_commit or not current_commit:
199+
print("::warning::Git commit information not available, falling back to all queries validation")
200+
return None, None
201+
202+
return base_commit, current_commit
203+
204+
def validate_file(file_path, base_commit=None, current_commit=None):
205+
"""Validate SQL queries in a markdown file"""
136206
print(f"πŸ” Validating: {file_path}")
137207

138-
queries = extract_sql_queries(file_path)
208+
# Try to get only changed queries if git info is available
209+
if base_commit and current_commit:
210+
queries = extract_changed_sql_queries(file_path, base_commit, current_commit)
211+
query_type = "changed SQL queries"
212+
else:
213+
# Fallback to all queries in the file
214+
queries = extract_sql_queries(file_path)
215+
query_type = "SQL queries"
216+
139217
if not queries:
140-
print(f" ℹ️ No SQL queries found")
218+
print(f" ℹ️ No {query_type} found")
141219
return True
142220

143-
print(f" πŸ“Š Found {len(queries)} SQL queries")
221+
print(f" πŸ“Š Found {len(queries)} {query_type}")
144222

145223
all_valid = True
146224
for i, query in enumerate(queries, 1):
@@ -164,18 +242,28 @@ def main():
164242
print("::warning::No Markdown files to validate")
165243
sys.exit(0)
166244

167-
print(f"πŸ“‹ Validating {len(changed_files)} files...")
245+
# Get git commit information for diff-based validation
246+
base_commit, current_commit = get_git_commits()
247+
248+
if base_commit and current_commit:
249+
print(f"οΏ½ Using git diff mode: {base_commit}...{current_commit}")
250+
print("οΏ½πŸ“‹ Validating only added/modified SQL queries...")
251+
else:
252+
print("πŸ“‹ Validating all SQL queries in changed files...")
168253

169254
validation_results = []
170255
total_queries = 0
171256

172257
for file_path in changed_files:
173258
if os.path.exists(file_path):
174-
result = validate_file(file_path)
259+
result = validate_file(file_path, base_commit, current_commit)
175260
validation_results.append((file_path, result))
176261

177262
# Count queries for summary
178-
queries = extract_sql_queries(file_path)
263+
if base_commit and current_commit:
264+
queries = extract_changed_sql_queries(file_path, base_commit, current_commit)
265+
else:
266+
queries = extract_sql_queries(file_path)
179267
total_queries += len(queries)
180268
else:
181269
print(f"::warning::File not found: {file_path}")
@@ -189,7 +277,10 @@ def main():
189277
failed_files = len(validation_results) - passed_files
190278

191279
print(f"πŸ“ Files processed: {len(validation_results)}")
192-
print(f"πŸ“Š Total SQL queries: {total_queries}")
280+
if base_commit and current_commit:
281+
print(f"πŸ“Š Changed SQL queries: {total_queries}")
282+
else:
283+
print(f"πŸ“Š Total SQL queries: {total_queries}")
193284
print(f"βœ… Files passed: {passed_files}")
194285
print(f"❌ Files failed: {failed_files}")
195286

@@ -202,7 +293,10 @@ def main():
202293
print("\n::error::SQL query validation failed!")
203294
sys.exit(1)
204295
else:
205-
print("\nπŸŽ‰ All SQL queries passed validation!")
296+
if base_commit and current_commit:
297+
print("\nπŸŽ‰ All changed SQL queries passed validation!")
298+
else:
299+
print("\nπŸŽ‰ All SQL queries passed validation!")
206300
sys.exit(0)
207301

208302
if __name__ == "__main__":

0 commit comments

Comments
Β (0)