Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Raise SQLError on empty select expressions and a dangling AS (#1147)

Andrew Chen46467a3453fe
diff --git a/src/python/txtai/database/sql/expression.py b/src/python/txtai/database/sql/expression.py
index 85b3304b..2f8a9b47 100644
--- a/src/python/txtai/database/sql/expression.py
+++ b/src/python/txtai/database/sql/expression.py
@@ -186,6 +186,10 @@ class Expression:
if x not in aliases.values():
alias = tokens[x]
+ # An empty expression (e.g. a stray comma in the select clause) has no alias
+ if not alias:
+ raise SQLError("Empty expression in SQL clause")
+
# Strip leading/trailing brackets from alias name that doesn't have operators
if not any(Token.isoperator(t) for t in alias) and alias[0] in ("[", "(") and alias[-1] in ("]", ")"):
alias = alias[1:-1]
@@ -337,6 +341,10 @@ class Expression:
if token in Token.ALIAS:
x, token = next(iterator, (None, None))
+ # A trailing AS with no alias name exhausts the stream
+ if x is None:
+ raise SQLError("Missing alias name in SQL expression")
+
# Consume tokens until end of stream or a separator is found. Evaluate next token to prevent consuming here.
while x + 1 < len(tokens) and not Token.isseparator(Token.get(tokens, x + 1)):
x, token = next(iterator, (None, None))
diff --git a/test/python/testdatabase/testsql.py b/test/python/testdatabase/testsql.py
index dcd92a6b..cd9690cd 100644
--- a/test/python/testdatabase/testsql.py
+++ b/test/python/testdatabase/testsql.py
@@ -282,6 +282,22 @@ class TestSQL(unittest.TestCase):
with self.assertRaises(SQLError):
self.db.search("select * from txtai where similar('abc'")
+ def testMalformedExpression(self):
+ """
+ Test malformed select expressions raise a SQLError instead of an internal exception
+ """
+
+ # Empty select components (stray commas) raised IndexError
+ with self.assertRaises(SQLError):
+ self.db.search("select a,,b from txtai")
+
+ with self.assertRaises(SQLError):
+ self.db.search("select ,a from txtai")
+
+ # A trailing AS with no alias name raised TypeError
+ with self.assertRaises(SQLError):
+ self.db.search("select a as from txtai")
+
def testUpper(self):
"""
Test SQL statements are case insensitive.