Repository: sqlfluff/sqlfluff

Issue:
Lint API breaks if no violations

Just a quick test of the new API reveals an edge case we did not consider!

```python
from sqlfluff.api import lint

sql = """
select * from t
"""

print(lint(sql, dialect="ansi"))

# IndexError: list index out of range

```


This is on the brand new 0.4.0, and is due to this line in simple.py: https://github.com/sqlfluff/sqlfluff/blob/9f3bcdc91037157a2ea4ae988ff04922eea66b21/src/sqlfluff/api/simple.py#L36

When there are no errors, the records is an empty list and thus accessing [0] is a problem. I will fix this!

Discussion:

Patch:
diff --git a/src/sqlfluff/api/simple.py b/src/sqlfluff/api/simple.py
index bfa1aad4c..4b143db8e 100644
--- a/src/sqlfluff/api/simple.py
+++ b/src/sqlfluff/api/simple.py
@@ -33,7 +33,7 @@ def lint(sql, dialect="ansi", rules=None):
     result = linter.lint_string_wrapped(sql)
     result_records = result.as_records()
     # Return just the violations for this file
-    return result_records[0]["violations"]
+    return [] if not result_records else result_records[0]["violations"]
 
 
 def fix(sql, dialect="ansi", rules=None):


Test patch:
diff --git a/test/api/simple_test.py b/test/api/simple_test.py
index a47e90465..9d370b65a 100644
--- a/test/api/simple_test.py
+++ b/test/api/simple_test.py
@@ -3,7 +3,6 @@
 import io
 
 import sqlfluff
-
 from sqlfluff.core.linter import ParsedString
 
 my_bad_query = "SeLEct  *, 1, blah as  fOO  from myTable"
@@ -66,6 +65,12 @@ lint_result = [
 ]
 
 
+def test__api__lint_string_without_violations():
+    """Check lint functionality when there is no violation."""
+    result = sqlfluff.lint("select column from table\n")
+    assert result == []
+
+
 def test__api__lint_string():
     """Basic checking of lint functionality."""
     result = sqlfluff.lint(my_bad_query)