### Format SQL with CASE Expressions Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt This Python example shows how sqlvalidator correctly indents and formats SQL queries containing `CASE WHEN` statements, improving readability. ```python import sqlvalidator sql = """ select id, case status when 'A' then 'Active' when 'I' then 'Inactive' else 'Unknown' end status_name, case when score >= 90 then 'A' when score >= 80 then 'B' else 'C' end grade from records """ print(sqlvalidator.format_sql(sql)) ``` -------------------------------- ### Format SQL using Python API Source: https://github.com/david-wobrock/sqlvalidator/blob/main/README.md Demonstrates how to use the sqlvalidator library to programmatically format a SQL query string. ```python import sqlvalidator formatted_sql = sqlvalidator.format_sql("SELECT * FROM table") ``` -------------------------------- ### Configure pre-commit hook Source: https://github.com/david-wobrock/sqlvalidator/blob/main/README.md Configuration snippet for integrating sqlvalidator into a .pre-commit-config.yaml file. ```yaml - repo: https://github.com/David-Wobrock/sqlvalidator rev: hooks: - id: sqlvalidator ``` -------------------------------- ### Validate SQL using Python API Source: https://github.com/david-wobrock/sqlvalidator/blob/main/README.md Shows how to parse a SQL query and check for validity, accessing error details if the query is invalid. ```python import sqlvalidator sql_query = sqlvalidator.parse("SELECT * from table") if not sql_query.is_valid(): print(sql_query.errors) ``` -------------------------------- ### Format SQL via Command Line Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt The command-line interface allows for batch processing of Python files to format embedded SQL strings. It supports individual files, multiple files, or entire directories. ```bash # Format a single file sqlvalidator --format queries.py # Format multiple files sqlvalidator --format models.py views.py # Format all Python files in a directory sqlvalidator --format ./src/ ``` -------------------------------- ### Format SQL with Window Functions and Analytics Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt This Python snippet demonstrates how sqlvalidator can format complex SQL queries involving window functions, including `PARTITION BY`, `ORDER BY`, and frame clauses. ```python import sqlvalidator sql = """ select employee_id, department, row_number() over (partition by department order by salary desc) rank, sum(salary) over (partition by department rows between unbounded preceding and current row) running_total from employees """ print(sqlvalidator.format_sql(sql)) ``` -------------------------------- ### Configure Pre-commit Hook for SQL Formatting Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt Integrate sqlvalidator into your project's pre-commit hooks by adding it to the `.pre-commit-config.yaml` file. This automates SQL formatting checks and application on each commit, ensuring consistent code style. ```yaml # .pre-commit-config.yaml repos: - repo: https://github.com/David-Wobrock/sqlvalidator rev: v0.0.20 # Use latest version hooks: - id: sqlvalidator # Optional: specify arguments args: ['--format'] # Optional: limit to specific files files: '\.py$' ``` ```bash # Install pre-commit hooks pre-commit install # Run manually on all files pre-commit run sqlvalidator --all-files # Runs automatically on git commit git add queries.py git commit -m "Update queries" # Output: sqlvalidator...........................................................Passed ``` -------------------------------- ### Using the SQLQuery Class Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt The SQLQuery class provides an object-oriented interface to encapsulate parsing, formatting, and validation logic for SQL statements. ```python from sqlvalidator.sql_validator import SQLQuery # Create SQLQuery directly query = SQLQuery("select count(*) from users group by status having count(*) > 10") # Format and Validate formatted = query.format() is_valid = query.is_valid() print(f"Formatted: {formatted}, Valid: {is_valid}") ``` -------------------------------- ### Format SQL Queries with Python Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt The format_sql function standardizes SQL strings by adjusting capitalization, indentation, and line breaks. It supports complex queries including joins and subqueries. ```python import sqlvalidator # Basic SELECT formatting sql = "select col1, col2, col3 from users where active = true" formatted = sqlvalidator.format_sql(sql) print(formatted) # Complex query with joins and subqueries complex_sql = """ select a.id, b.name, sum(c.amount) from orders a join customers b on a.customer_id = b.id join (select order_id, amount from line_items where qty > 0) c using (order_id) where a.status = 'completed' group by a.id, b.name order by sum(c.amount) desc limit 10 """ print(sqlvalidator.format_sql(complex_sql)) ``` -------------------------------- ### Format SQL with WITH Statements (CTEs) Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt This Python code illustrates the formatting capabilities of sqlvalidator for SQL queries that utilize Common Table Expressions (CTEs) and nested queries. ```python import sqlvalidator sql = """ with monthly_sales as ( select date_trunc('month', sale_date) month, sum(amount) total from sales group by 1 ), top_months as ( select month from monthly_sales where total > 10000 ) select * from sales where date_trunc('month', sale_date) in (select month from top_months) """ print(sqlvalidator.format_sql(sql)) ``` -------------------------------- ### Format BigQuery SQL with Python Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt Formats SQL queries that include BigQuery-specific syntax such as UNNEST, ARRAY_AGG, and STRUCT using the sqlvalidator library. This function takes a raw SQL string as input and returns a formatted SQL string. ```python import sqlvalidator sql = """ select user_id, array_agg(distinct event_name ignore nulls order by timestamp limit 10) recent_events, struct(count(*) as total, max(timestamp) as last_seen) stats from events, unnest(event_data) as data with offset pos where data.type = 'click' group by user_id """ print(sqlvalidator.format_sql(sql)) ``` -------------------------------- ### Skip SQL Formatting with Comments Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt Specific SQL strings within code can be excluded from formatting by adding the `nosqlformat` comment. This allows for preserving the original formatting of critical or complex SQL statements. ```python # In your Python file: def get_legacy_query(): # This SQL will not be reformatted return "select * from old_table" # nosqlformat def get_modern_query(): # This SQL will be formatted return "select * from new_table" ``` ```bash sqlvalidator --format myfile.py # Only formats queries without nosqlformat comment ``` -------------------------------- ### Check SQL Formatting without Modifying Files Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt The `--check-format` flag verifies if SQL files require formatting without altering them. It returns an exit code of 0 if no changes are needed and 1 if modifications would occur. This is useful for CI/CD pipelines to ensure code style consistency. ```bash # Check formatting without modifying filessqlvalidator --check-format queries.py # Output: would reformat queries.py (2 changed SQL) # 1 file would be reformatted (2 changed SQL queries). # Exit code: 1 # After formattingsqlvalidator --format queries.py sqlvalidator --check-format queries.py # Output: No file would be reformatted. # Exit code: 0 # Useful in CI/CD pipelines sqlvalidator --check-format ./src/ || echo "SQL formatting check failed!" ``` -------------------------------- ### Parse and Validate SQL Queries Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt The parse function creates an SQLQuery object used to check for syntactic and semantic errors. It provides an is_valid() method and an errors list for debugging invalid queries. ```python import sqlvalidator # Valid query validation sql_query = sqlvalidator.parse("SELECT id, name FROM users WHERE active = true") if sql_query.is_valid(): print("Query is valid!") # Invalid query - missing column in subquery invalid_sql = """ SELECT field2 FROM (SELECT field1 FROM table) """ sql_query = sqlvalidator.parse(invalid_sql) if not sql_query.is_valid(): print(f"Validation errors: {sql_query.errors}") ``` -------------------------------- ### Validate SQL Queries for Semantic Errors Source: https://context7.com/david-wobrock/sqlvalidator/llms.txt The `--validate` flag checks SQL queries for semantic errors without modifying the files. The `--verbose-validate` option provides detailed error messages, including line numbers and specific issues. This functionality can be applied to individual files or entire directories. ```bash # Basic validationsqlvalidator --validate queries.py # Output: invalid queries in queries.py (1 invalid SQL) # 1 file detected with invalid SQL (1 invalid SQL queries). # Verbose validation with error details sqlvalidator --verbose-validate queries.py # Output: invalid queries in queries.py (2 invalid SQL) # L15 - The column user_id was not found # L42 - Unknown column at position 3. SELECT has 2 columns # 1 file detected with invalid SQL (2 invalid SQL queries). # Validate entire directory sqlvalidator --validate ./src/ # Output: invalid queries in ./src/reports.py (1 invalid SQL) # 1 file detected with invalid SQL (1 invalid SQL queries). ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.