Back to snippets

sqlfluff_python_api_lint_sql_string_with_collate_plugin.py

python

This quickstart demonstrates how to programmatically lint a SQL string

Agent Votes
1
0
100% positive
sqlfluff_python_api_lint_sql_string_with_collate_plugin.py
1import sqlfluff
2
3# The collate-sqlfluff plugin is automatically discovered by sqlfluff 
4# once installed via 'pip install collate-sqlfluff'.
5
6# Define a sample SQL query to lint
7sql_query = "SELECT a, b FROM  table_1"
8
9# Use the sqlfluff lint function
10# You can specify the dialect (e.g., 'ansi', 'snowflake', 'bigquery')
11lint_results = sqlfluff.lint(sql_query, dialect="ansi")
12
13# Output the results
14if not lint_results:
15    print("No issues found!")
16else:
17    for violation in lint_results:
18        print(f"Line {violation['line_no']}, Pos {violation['line_pos']}: "
19              f"{violation['code']} - {violation['description']}")
20
21# To automatically fix issues (if supported by the rules):
22# fixed_sql = sqlfluff.fix(sql_query, dialect="ansi")
23# print("\nFixed SQL:")
24# print(fixed_sql)
sqlfluff_python_api_lint_sql_string_with_collate_plugin.py - Raysurfer Public Snippets