|
| 1 | +# Query.Farm SQL Manipulation |
| 2 | + |
| 3 | +A Python library for intelligent SQL predicate manipulation using [SQLGlot](https://sqlglot.com/sqlglot.html). This library provides tools to safely remove specific predicates from `SQL WHERE` clauses and filter SQL statements based on column availability. |
| 4 | + |
| 5 | +## Features |
| 6 | + |
| 7 | +- **Predicate Removal**: Safely remove specific predicates from complex `SQL WHERE` clauses while preserving logical structure |
| 8 | +- **Column Filtering**: Filter SQL statements to only include predicates referencing allowed columns |
| 9 | +- **Intelligent Logic Handling**: Properly handles `AND/OR` logic, nested expressions, `CASE` statements, and parentheses |
| 10 | +- **SQLGlot Integration**: Built on top of [SQLGlot](https://sqlglot.com/sqlglot.html) for robust SQL parsing and manipulation |
| 11 | +- **Multiple Dialect Support**: Works with various SQL dialects (default: DuckDB) |
| 12 | + |
| 13 | +## Installation |
| 14 | + |
| 15 | +```bash |
| 16 | +pip install query-farm-sql-manipulation |
| 17 | +``` |
| 18 | + |
| 19 | +## Requirements |
| 20 | + |
| 21 | +- Python >= 3.12 |
| 22 | +- SQLGlot >= 26.33.0 |
| 23 | + |
| 24 | +## Quick Start |
| 25 | + |
| 26 | +### Basic Predicate Removal |
| 27 | + |
| 28 | +```python |
| 29 | +import sqlglot |
| 30 | +from query_farm_sql_manipulation import transforms |
| 31 | + |
| 32 | +# Parse a SQL statement |
| 33 | +sql = 'SELECT * FROM data WHERE x = 1 AND y = 2' |
| 34 | +statement = sqlglot.parse_one(sql, dialect="duckdb") |
| 35 | + |
| 36 | +# Find the predicate you want to remove |
| 37 | +predicates = list(statement.find_all(sqlglot.expressions.Predicate)) |
| 38 | +target_predicate = predicates[0] # x = 1 |
| 39 | + |
| 40 | +# Remove the predicate |
| 41 | +transforms.remove_expression_part(target_predicate) |
| 42 | + |
| 43 | +# Result: SELECT * FROM data WHERE y = 2 |
| 44 | +print(statement.sql()) |
| 45 | +``` |
| 46 | + |
| 47 | +### Column-Based Filtering |
| 48 | + |
| 49 | +```python |
| 50 | +from query_farm_sql_manipulation import transforms |
| 51 | + |
| 52 | +# Filter SQL to only include predicates with allowed columns |
| 53 | +sql = 'SELECT * FROM data WHERE color = "red" AND size > 10 AND type = "car"' |
| 54 | +allowed_columns = {"color", "type"} |
| 55 | + |
| 56 | +filtered = transforms.filter_column_references_statement( |
| 57 | + sql=sql, |
| 58 | + allowed_column_names=allowed_columns, |
| 59 | + dialect="duckdb" |
| 60 | +) |
| 61 | + |
| 62 | +# Result: SELECT * FROM data WHERE color = "red" AND type = "car" |
| 63 | +print(filtered.sql()) |
| 64 | +``` |
| 65 | + |
| 66 | +## API Reference |
| 67 | + |
| 68 | +### `remove_expression_part(child: sqlglot.Expression) -> None` |
| 69 | + |
| 70 | +Removes the specified expression from its parent, respecting logical structure. |
| 71 | + |
| 72 | +**Parameters:** |
| 73 | +- `child`: The SQLGlot expression to remove |
| 74 | + |
| 75 | +**Raises:** |
| 76 | +- `ValueError`: If the expression cannot be safely removed |
| 77 | + |
| 78 | +**Supported Parent Types:** |
| 79 | +- `AND`/`OR` expressions: Replaces parent with the remaining operand |
| 80 | +- `WHERE` clauses: Removes the entire WHERE clause if it becomes empty |
| 81 | +- `Parentheses`: Recursively removes the parent |
| 82 | +- `NOT` expressions: Removes the entire NOT expression |
| 83 | +- `CASE` statements: Removes conditional branches |
| 84 | + |
| 85 | +### `filter_column_references_statement(*, sql: str, allowed_column_names: Container[str], dialect: str = "duckdb") -> sqlglot.Expression` |
| 86 | + |
| 87 | +Filters a SQL statement to remove predicates containing columns not in the allowed set. |
| 88 | + |
| 89 | +**Parameters:** |
| 90 | +- `sql`: The SQL statement to filter |
| 91 | +- `allowed_column_names`: Container of column names that should be preserved |
| 92 | +- `dialect`: SQL dialect for parsing (default: "duckdb") |
| 93 | + |
| 94 | +**Returns:** |
| 95 | +- Filtered SQLGlot expression with non-allowed columns removed |
| 96 | + |
| 97 | +**Raises:** |
| 98 | +- `ValueError`: If a column can't be cleanly removed due to interactions with allowed columns |
| 99 | + |
| 100 | +## Examples |
| 101 | + |
| 102 | +### Complex Logic Handling |
| 103 | + |
| 104 | +The library intelligently handles complex logical expressions: |
| 105 | + |
| 106 | +```python |
| 107 | +# Original: (x = 1 AND y = 2) OR z = 3 |
| 108 | +# Remove y = 2: x = 1 OR z = 3 |
| 109 | + |
| 110 | +# Original: NOT (x = 1 AND y = 2) |
| 111 | +# Remove x = 1: NOT y = 2 (which becomes y <> 2) |
| 112 | + |
| 113 | +# Original: CASE WHEN x = 1 THEN 'yes' WHEN x = 2 THEN 'maybe' ELSE 'no' END |
| 114 | +# Remove x = 1: CASE WHEN x = 2 THEN 'maybe' ELSE 'no' END |
| 115 | +``` |
| 116 | + |
| 117 | +### Column Filtering with Complex Expressions |
| 118 | + |
| 119 | +```python |
| 120 | +sql = ''' |
| 121 | +SELECT * FROM users |
| 122 | +WHERE age > 18 |
| 123 | + AND (status = 'active' OR role = 'admin') |
| 124 | + AND department IN ('engineering', 'sales') |
| 125 | +''' |
| 126 | + |
| 127 | +# Only keep predicates involving 'age' and 'role' |
| 128 | +allowed_columns = {'age', 'role'} |
| 129 | + |
| 130 | +result = transforms.filter_column_references_statement( |
| 131 | + sql=sql, |
| 132 | + allowed_column_names=allowed_columns |
| 133 | +) |
| 134 | + |
| 135 | +# Result: SELECT * FROM users WHERE age > 18 AND role = 'admin' |
| 136 | +``` |
| 137 | + |
| 138 | +### Error Handling |
| 139 | + |
| 140 | +The library will raise `ValueError` when predicates cannot be safely removed: |
| 141 | + |
| 142 | +```python |
| 143 | +# This will raise ValueError because x = 1 is part of a larger expression |
| 144 | +sql = "SELECT * FROM data WHERE result = (x = 1)" |
| 145 | +# Cannot remove x = 1 because it's used as a value, not a predicate |
| 146 | +``` |
| 147 | + |
| 148 | +## Supported SQL Constructs |
| 149 | + |
| 150 | +- **Logical Operators**: AND, OR, NOT |
| 151 | +- **Comparison Operators**: =, <>, <, >, <=, >=, LIKE, IN, IS NULL, etc. |
| 152 | +- **Complex Expressions**: CASE statements, subqueries, function calls |
| 153 | +- **Nested Logic**: Parentheses and nested boolean expressions |
| 154 | +- **Multiple Dialects**: DuckDB, PostgreSQL, MySQL, SQLite, and more via SQLGlot |
| 155 | + |
| 156 | +## Testing |
| 157 | + |
| 158 | +Run the test suite: |
| 159 | + |
| 160 | +```bash |
| 161 | +pytest src/query_farm_sql_manipulation/test_transforms.py |
| 162 | +``` |
| 163 | + |
| 164 | +The test suite includes comprehensive examples of: |
| 165 | +- Basic predicate removal scenarios |
| 166 | +- Complex logical expression handling |
| 167 | +- Error cases and edge conditions |
| 168 | +- Column filtering with various SQL constructs |
| 169 | + |
| 170 | +## Contributing |
| 171 | + |
| 172 | +This project uses: |
| 173 | +- **Rye** for dependency management |
| 174 | +- **pytest** for testing |
| 175 | +- **mypy** for type checking |
| 176 | +- **ruff** for linting |
| 177 | + |
| 178 | + |
| 179 | +## Author |
| 180 | + |
| 181 | +This Python module was created by [Query.Farm](https://query.farm). |
| 182 | + |
| 183 | +# License |
| 184 | + |
| 185 | +MIT Licensed. |
0 commit comments