sqlnbfmt 0.1.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.
sqlnbfmt/__init__.py ADDED
File without changes
sqlnbfmt/formatter.py ADDED
@@ -0,0 +1,409 @@
1
+ import ast
2
+ import logging
3
+ import re
4
+ import sys
5
+ import uuid
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Set, Optional, Dict, Union, Tuple, List
9
+
10
+ import nbformat
11
+ import yaml
12
+ from sqlglot import parse_one, parse, errors
13
+ from sqlglot.errors import TokenError
14
+
15
+
16
+ @dataclass
17
+ class FormattingConfig:
18
+ """Configuration for SQL formatting."""
19
+
20
+ sql_keywords: Set[str]
21
+ function_names: Set[str]
22
+ sql_decorators: Set[str]
23
+ single_line_threshold: int = 80
24
+ indent_width: int = 4
25
+
26
+
27
+ class SQLFormattingError(Exception):
28
+ """Custom exception for SQL formatting errors."""
29
+ pass
30
+
31
+
32
+ def setup_logging(level: str = "INFO") -> logging.Logger:
33
+ """Sets up logging with the specified level."""
34
+ logger = logging.getLogger('formatter')
35
+ logger.setLevel(level.upper())
36
+ if not logger.handlers:
37
+ handler = logging.StreamHandler(sys.stdout)
38
+ formatter = logging.Formatter("[%(levelname)s] %(message)s")
39
+ handler.setFormatter(formatter)
40
+ logger.addHandler(handler)
41
+ return logger
42
+
43
+
44
+ def load_config(config_path: Union[str, Path] = "config.yaml") -> FormattingConfig:
45
+ """Loads configuration from a YAML file."""
46
+ config_file = Path(config_path)
47
+ if not config_file.is_file():
48
+ raise FileNotFoundError(f"Configuration file '{config_file}' not found.")
49
+
50
+ try:
51
+ with open(config_file) as file:
52
+ config = yaml.safe_load(file)
53
+ return FormattingConfig(
54
+ sql_keywords=set(config.get("sql_keywords", [])),
55
+ function_names=set(config.get("function_names", [])),
56
+ sql_decorators=set(config.get("sql_decorators", [])),
57
+ single_line_threshold=config.get("formatting_options", {}).get(
58
+ "single_line_threshold", 80
59
+ ),
60
+ indent_width=config.get("formatting_options", {}).get(
61
+ "indent_width", 4
62
+ ),
63
+ )
64
+ except yaml.YAMLError as e:
65
+ raise yaml.YAMLError(f"Error parsing the configuration file: {e}")
66
+
67
+
68
+ def format_sql_code(
69
+ sql_code: str,
70
+ dialect: Optional[str],
71
+ config: FormattingConfig,
72
+ placeholders: Optional[Dict[str, str]] = None,
73
+ force_single_line: bool = False,
74
+ ignore_placeholders: bool = False,
75
+ ) -> str:
76
+ """Formats SQL code using sqlglot's native formatting capabilities while preserving placeholders."""
77
+ try:
78
+ logger = logging.getLogger('formatter')
79
+
80
+ if not sql_code.strip():
81
+ return sql_code
82
+
83
+ temp_sql = sql_code
84
+ placeholder_mapping = {}
85
+
86
+ # Handle placeholders for expressions
87
+ if placeholders and not ignore_placeholders:
88
+ for expr_placeholder, expr in placeholders.items():
89
+ marker = f"'__EXPR_PLACEHOLDER_{uuid.uuid4()}__'"
90
+ temp_sql = temp_sql.replace(expr_placeholder, marker)
91
+ placeholder_mapping[marker.strip("'")] = expr_placeholder
92
+ logger.debug(f"Replaced placeholder {expr_placeholder} with marker {marker}")
93
+
94
+ # Automatically replace common placeholders (%s and ?) with unique markers
95
+ if not ignore_placeholders:
96
+ auto_placeholders = {'%s', '?'}
97
+ for placeholder in auto_placeholders:
98
+ unique_id = str(uuid.uuid4())
99
+ marker = f"'__AUTO_PLACEHOLDER_{unique_id}__'"
100
+ temp_sql = temp_sql.replace(placeholder, marker)
101
+ placeholder_mapping[marker.strip("'")] = placeholder
102
+ logger.debug(f"Auto-replaced placeholder {placeholder} with marker {marker}")
103
+
104
+ temp_sql = temp_sql.strip()
105
+
106
+ # Prevent multiple statements
107
+ statements = parse(temp_sql, read=dialect)
108
+ if len(statements) > 1:
109
+ raise SQLFormattingError("Multiple SQL statements are not supported.")
110
+
111
+ # Parse SQL
112
+ parsed = statements[0]
113
+
114
+ # Generate formatted SQL with uppercase keywords and proper quoting
115
+ formatted_sql = parsed.sql(
116
+ pretty=not force_single_line,
117
+ indent=config.indent_width,
118
+ dialect=dialect,
119
+ )
120
+
121
+ # Condense to single line if necessary
122
+ if force_single_line or (
123
+ config.single_line_threshold
124
+ and len(formatted_sql.replace('\n', ' ')) <= config.single_line_threshold
125
+ ):
126
+ formatted_sql = " ".join(formatted_sql.split())
127
+
128
+ # Restore placeholders
129
+ if placeholder_mapping:
130
+ for marker, original_placeholder in placeholder_mapping.items():
131
+ formatted_sql = formatted_sql.replace(f"'{marker}'", original_placeholder)
132
+ logger.debug(f"Restored marker '{marker}' to placeholder {original_placeholder}")
133
+
134
+ # Logging
135
+ logger.debug(f"Original SQL:\n{sql_code}")
136
+ logger.debug(f"Formatted SQL:\n{formatted_sql}")
137
+
138
+ return formatted_sql
139
+
140
+ except errors.ParseError as e:
141
+ logger.warning(f"SQL parsing failed: {e}. Returning original SQL code.")
142
+ return sql_code # Return the original SQL code unmodified
143
+ except TokenError as te:
144
+ logger.warning(f"Tokenization failed: {te}. Returning original SQL code.")
145
+ return sql_code # Return the original SQL code unmodified
146
+ except Exception as e:
147
+ raise SQLFormattingError(f"Unexpected error during SQL formatting: {e}") from e
148
+
149
+
150
+ class SQLStringFormatter(ast.NodeTransformer):
151
+ """AST NodeTransformer that formats SQL strings."""
152
+
153
+ def __init__(
154
+ self, config: FormattingConfig, dialect: Optional[str], logger: logging.Logger
155
+ ):
156
+ super().__init__()
157
+ self.config = config
158
+ self.dialect = dialect
159
+ self.logger = logger
160
+ self.changed = False
161
+
162
+ def is_likely_sql(self, code: str) -> bool:
163
+ """Enhanced SQL detection with better heuristics."""
164
+ if not code or len(code.strip()) < 10:
165
+ return False
166
+
167
+ if re.match(r"^\s*(/|[a-zA-Z]:\\|https?://|<!DOCTYPE|<html)", code.strip()):
168
+ return False
169
+
170
+ upper_code = code.upper()
171
+ keyword_count = sum(
172
+ 1
173
+ for keyword in self.config.sql_keywords
174
+ if re.search(rf"\b{re.escape(keyword)}\b", upper_code)
175
+ )
176
+
177
+ has_sql_pattern = bool(
178
+ re.search(
179
+ r"\bSELECT\b.*\bFROM\b|\bUPDATE\b.*\bSET\b|\bINSERT\b.*\bINTO\b|\bDELETE\b.*\bFROM\b",
180
+ upper_code,
181
+ re.DOTALL,
182
+ )
183
+ )
184
+
185
+ return keyword_count >= 2 or has_sql_pattern
186
+
187
+ def extract_fstring_parts(self, node: ast.JoinedStr) -> Tuple[str, Dict[str, str]]:
188
+ """Extracts parts of an f-string, preserving expressions."""
189
+ sql_parts = []
190
+ placeholders = {}
191
+
192
+ for value in node.values:
193
+ if isinstance(value, ast.Constant):
194
+ sql_parts.append(value.value)
195
+ elif isinstance(value, ast.FormattedValue):
196
+ expr = ast.unparse(value.value).strip()
197
+ placeholder = f"__EXPR_PLACEHOLDER_{uuid.uuid4()}__"
198
+ sql_parts.append(placeholder)
199
+ placeholders[placeholder] = f"{{{expr}}}"
200
+
201
+ return "".join(sql_parts), placeholders
202
+
203
+ def format_sql_node(
204
+ self, node: Union[ast.Constant, ast.JoinedStr], force_single_line: bool = False
205
+ ) -> Optional[ast.AST]:
206
+ """Formats SQL code in AST nodes."""
207
+ try:
208
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
209
+ if not self.is_likely_sql(node.value):
210
+ return None
211
+ formatted_sql = format_sql_code(
212
+ node.value,
213
+ self.dialect,
214
+ self.config,
215
+ force_single_line=force_single_line,
216
+ )
217
+ if formatted_sql != node.value:
218
+ self.changed = True
219
+ return ast.Constant(value=formatted_sql)
220
+
221
+ elif isinstance(node, ast.JoinedStr):
222
+ sql_str, placeholders = self.extract_fstring_parts(node)
223
+ if not self.is_likely_sql(sql_str):
224
+ return None
225
+ formatted_sql = format_sql_code(
226
+ sql_str,
227
+ self.dialect,
228
+ self.config,
229
+ placeholders=placeholders,
230
+ force_single_line=force_single_line,
231
+ )
232
+ if formatted_sql != sql_str:
233
+ self.changed = True
234
+ # Reconstruct the f-string
235
+ new_values = []
236
+ pattern = re.compile('|'.join(re.escape(k) for k in placeholders.keys()))
237
+ idx = 0
238
+ while idx < len(formatted_sql):
239
+ match = pattern.search(formatted_sql, idx)
240
+ if match:
241
+ if match.start() > idx:
242
+ new_values.append(ast.Constant(value=formatted_sql[idx:match.start()]))
243
+ expr_placeholder = match.group()
244
+ expr_str = placeholders[expr_placeholder]
245
+ expr_ast = ast.parse(expr_str).body[0].value
246
+ new_values.append(ast.FormattedValue(
247
+ value=expr_ast,
248
+ conversion=-1,
249
+ format_spec=None
250
+ ))
251
+ idx = match.end()
252
+ else:
253
+ new_values.append(ast.Constant(value=formatted_sql[idx:]))
254
+ break
255
+ return ast.JoinedStr(values=new_values)
256
+ return None
257
+ except SQLFormattingError as e:
258
+ self.logger.warning(f"SQL formatting skipped: {e}")
259
+ return None
260
+
261
+ def visit_Constant(self, node: ast.Constant) -> ast.AST:
262
+ """Handles string constants."""
263
+ formatted_node = self.format_sql_node(node)
264
+ return formatted_node or node
265
+
266
+ def visit_JoinedStr(self, node: ast.JoinedStr) -> ast.AST:
267
+ """Handles f-strings."""
268
+ formatted_node = self.format_sql_node(node)
269
+ return formatted_node or node
270
+
271
+ def visit_Assign(self, node: ast.Assign) -> ast.AST:
272
+ """Handles assignments."""
273
+ self.generic_visit(node)
274
+ return node
275
+
276
+ def visit_Call(self, node: ast.Call) -> ast.AST:
277
+ """Handles function calls."""
278
+ func_name = self.get_full_func_name(node.func)
279
+ if any(name in func_name for name in self.config.function_names):
280
+ for idx, arg in enumerate(node.args):
281
+ if isinstance(arg, (ast.Constant, ast.JoinedStr)):
282
+ formatted_node = self.format_sql_node(arg)
283
+ if formatted_node:
284
+ node.args[idx] = formatted_node
285
+ for keyword in node.keywords:
286
+ if isinstance(keyword.value, (ast.Constant, ast.JoinedStr)):
287
+ formatted_node = self.format_sql_node(keyword.value)
288
+ if formatted_node:
289
+ keyword.value = formatted_node
290
+ self.generic_visit(node)
291
+ return node
292
+
293
+ @staticmethod
294
+ def get_full_func_name(node: ast.AST) -> str:
295
+ """Gets the full function name from an AST node."""
296
+ parts = []
297
+ while isinstance(node, ast.Attribute):
298
+ parts.append(node.attr)
299
+ node = node.value
300
+ if isinstance(node, ast.Name):
301
+ parts.append(node.id)
302
+ return ".".join(reversed(parts))
303
+
304
+
305
+ def process_notebook(
306
+ notebook_path: Path,
307
+ config: FormattingConfig,
308
+ dialect: Optional[str],
309
+ logger: logging.Logger
310
+ ) -> bool:
311
+ """Processes a Jupyter notebook, formatting SQL code within code cells."""
312
+ try:
313
+ nb = nbformat.read(notebook_path, as_version=4)
314
+ changed = False
315
+ failed = False # Flag to track failures
316
+
317
+ for idx, cell in enumerate(nb.cells):
318
+ if cell.cell_type != "code":
319
+ continue
320
+
321
+ original_source = cell.source
322
+
323
+ # Handle magic SQL cells
324
+ if cell.source.lstrip().startswith("%%sql"):
325
+ stripped_source = cell.source.lstrip()
326
+ lines = stripped_source.split('\n', 1)
327
+ magic_command = lines[0]
328
+ sql_code = lines[1] if len(lines) > 1 else ''
329
+ try:
330
+ formatted_sql = format_sql_code(
331
+ sql_code, dialect, config, ignore_placeholders=True
332
+ )
333
+ cell.source = f"{magic_command}\n{formatted_sql}"
334
+ if cell.source != original_source:
335
+ changed = True
336
+ except SQLFormattingError as e:
337
+ logger.warning(f"Failed to format magic SQL in cell {idx}: {e}")
338
+ failed = True
339
+ continue
340
+
341
+ # Process regular code cells
342
+ try:
343
+ tree = ast.parse(cell.source)
344
+ formatter = SQLStringFormatter(config, dialect, logger)
345
+ new_tree = formatter.visit(tree)
346
+ if formatter.changed:
347
+ cell.source = ast.unparse(new_tree)
348
+ changed = True
349
+ except SyntaxError as e:
350
+ logger.warning(f"Syntax error in cell {idx}: {e}")
351
+ failed = True
352
+ except Exception as e:
353
+ logger.error(f"Error processing cell {idx}: {e}")
354
+ failed = True
355
+
356
+ if changed and not failed:
357
+ nbformat.write(nb, notebook_path)
358
+ logger.info(f"Updated notebook: {notebook_path}")
359
+ return True
360
+ elif failed:
361
+ logger.error(f"Notebook processing failed for: {notebook_path}")
362
+ return False
363
+ else:
364
+ logger.info(f"No changes made to notebook: {notebook_path}")
365
+ return True
366
+
367
+ except Exception as e:
368
+ logger.error(f"Error processing notebook {notebook_path}: {e}")
369
+ return False
370
+
371
+
372
+ def main():
373
+ """Main entry point for the SQL formatter."""
374
+ import argparse
375
+
376
+ parser = argparse.ArgumentParser(description="Format SQL code in Jupyter notebooks")
377
+ parser.add_argument(
378
+ "notebooks", nargs="+", type=Path, help="Notebook paths to process"
379
+ )
380
+ parser.add_argument(
381
+ "--config", type=Path, default="config.yaml", help="Configuration file path"
382
+ )
383
+ parser.add_argument(
384
+ "--dialect", type=str, help="SQL dialect (e.g., mysql, postgres)"
385
+ )
386
+ parser.add_argument(
387
+ "--log-level",
388
+ choices=["DEBUG", "INFO", "WARNING", "ERROR"],
389
+ default="INFO",
390
+ help="Logging level",
391
+ )
392
+
393
+ args = parser.parse_args()
394
+ logger = setup_logging(args.log_level)
395
+
396
+ try:
397
+ config = load_config(args.config)
398
+ all_succeeded = True
399
+
400
+ for notebook in args.notebooks:
401
+ success = process_notebook(notebook, config, args.dialect, logger)
402
+ if not success:
403
+ all_succeeded = False
404
+
405
+ sys.exit(0 if all_succeeded else 1)
406
+
407
+ except Exception as e:
408
+ logger.error(f"Fatal error: {e}")
409
+ sys.exit(1)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Qing Ye
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.1
2
+ Name: sqlnbfmt
3
+ Version: 0.1.0
4
+ Summary: A tool to format SQL code in Jupyter notebooks.
5
+ Author-email: Qing <qingye779@gmail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.12
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: astor>=0.8.1
11
+ Requires-Dist: nbformat>=5.10.4
12
+ Requires-Dist: pyyaml>=6.0.2
13
+ Requires-Dist: sqlglot>=25.27.0
14
+
15
+ # sqlnbfmt
16
+ A SQL formatter for Jupyter Notebooks
@@ -0,0 +1,8 @@
1
+ sqlnbfmt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ sqlnbfmt/formatter.py,sha256=KSCM42mRI5PzXvP9UKxjc31zy0VVq-5VGwralELtoqg,15249
3
+ sqlnbfmt-0.1.0.dist-info/LICENSE,sha256=BrKXQOe5lGnEFNJnzTAdeApTMe0cwOa6jDvz5cwxjhc,1064
4
+ sqlnbfmt-0.1.0.dist-info/METADATA,sha256=RC9t0QrtNTl101ubyRWatByYTSJbt1YAzpqNAtdNqcE,420
5
+ sqlnbfmt-0.1.0.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
6
+ sqlnbfmt-0.1.0.dist-info/entry_points.txt,sha256=y01fLZxACmxE-XtPqiP-uvI9gHx4dYtclAO7yVk5u80,53
7
+ sqlnbfmt-0.1.0.dist-info/top_level.txt,sha256=DOJA_VGRv4FJRstit8bQ5Ru_n-AMqaN_uFG8D1c2aL8,9
8
+ sqlnbfmt-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.2.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sqlnbfmt = sqlnbfmt.formatter:main
@@ -0,0 +1 @@
1
+ sqlnbfmt