Skip to content

armgit / txtai

Public Imported from GitHub
0

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

fix(sql): keep the type name in cast() out of column resolution (#1520)

Serhii Zghamae32d9940c778
diff --git a/src/python/txtai/database/sql/expression.py b/src/python/txtai/database/sql/expression.py
index 2f8a9b47..fddc9f9f 100644
--- a/src/python/txtai/database/sql/expression.py
+++ b/src/python/txtai/database/sql/expression.py
@@ -294,12 +294,20 @@ class Expression:
similar: list where similar function call parameters are stored
"""
+ # Only cast functions take a type name after AS
+ cast = token.lower() in Token.CAST
+
# Consume function parameters
while token and token != ")":
x, token = self.readtoken(iterator)
+ # Check if token starts a cast type, i.e. cast(a as integer)
+ if cast and token and token.lower() in Token.ALIAS:
+ # Skip type name, it's not a column
+ self.casttype(iterator, tokens, x)
+
# Check if token is a square bracket
- if Token.isbracket(token):
+ elif Token.isbracket(token):
# Resolve bracket expression
self.bracket(iterator, tokens, x)
@@ -323,6 +331,28 @@ class Expression:
# Resolve compound expressions
self.compound(iterator, tokens, x, aliases, similar)
+ def casttype(self, iterator, tokens, x):
+ """
+ Consumes the type name of a cast expression without resolving it. Type names can have
+ multiple words or parameters, i.e. double precision, decimal(10, 2).
+
+ Args:
+ iterator: tokens iterator
+ tokens: input tokens
+ x: current position
+ """
+
+ # Read until the closing paren of the cast function
+ parens = 0
+ while Token.get(tokens, x + 1) and (Token.get(tokens, x + 1) != ")" or parens):
+ x, token = self.readtoken(iterator)
+
+ # Track type parameter parens
+ if token == "(":
+ parens += 1
+ elif token == ")":
+ parens -= 1
+
def alias(self, iterator, tokens, x, aliases, index):
"""
Reads an alias clause and stores it in aliases.
diff --git a/src/python/txtai/database/sql/token.py b/src/python/txtai/database/sql/token.py
index 0d817c56..7bf8186f 100644
--- a/src/python/txtai/database/sql/token.py
+++ b/src/python/txtai/database/sql/token.py
@@ -19,6 +19,9 @@ class Token:
# Default alias token
ALIAS = ["as"]
+ # Functions that take a type name after an alias token, i.e. cast(a as integer)
+ CAST = ["cast", "try_cast"]
+
# Default list of comparison operators
OPERATORS = ["=", "!=", "<>", ">", ">=", "<", "<=", "+", "-", "*", "/", "%", "||", "not", "between", "like", "is", "null"]
diff --git a/test/python/testdatabase/testrdbms.py b/test/python/testdatabase/testrdbms.py
index 98148ba8..86152473 100644
--- a/test/python/testdatabase/testrdbms.py
+++ b/test/python/testdatabase/testrdbms.py
@@ -97,6 +97,22 @@ class Common:
result = embeddings.search(self.data[4], 1)[0]
self.assertEqual(len(result["id"]), 36)
+ def testCast(self):
+ """
+ Test casting a JSON field in select, where and order by clauses
+ """
+
+ embeddings = Embeddings({"keyword": True, "content": self.backend})
+ embeddings.index([{"text": text, "n": n} for text, n in zip(self.data[:3], ["10", "9", "100"])])
+
+ # Numeric order instead of text order
+ result = embeddings.search("select id, cast(n as integer) as n from txtai order by cast(n as integer)")
+ self.assertEqual([(x["id"], x["n"]) for x in result], [("1", 9), ("0", 10), ("2", 100)])
+
+ # Numeric comparison
+ result = embeddings.search("select id from txtai where cast(n as integer) > 9 order by id")
+ self.assertEqual([x["id"] for x in result], ["0", "2"])
+
def testCheckpoint(self):
"""
Test embeddings index checkpoints
diff --git a/test/python/testdatabase/testsql.py b/test/python/testdatabase/testsql.py
index 0ed7a9a4..5f06ddaf 100644
--- a/test/python/testdatabase/testsql.py
+++ b/test/python/testdatabase/testsql.py
@@ -241,6 +241,26 @@ class TestSQL(unittest.TestCase):
self.assertSql("groupby", "select * from txtai group by [a]", "json_extract(data, '$.a')")
self.assertSql("orderby", "select * from txtai where order by [a]", "json_extract(data, '$.a')")
+ def testCast(self):
+ """
+ Test cast expressions don't resolve the type name as a column
+ """
+
+ self.assertSql("select", "select cast(a as integer) from txtai", "cast(json_extract(data, '$.a') as integer) as \"cast(a as integer)\"")
+ self.assertSql("select", "select CAST(id AS TEXT) a from txtai", "CAST(s.id AS TEXT) a")
+ self.assertSql("select", "select try_cast(a as integer) b from txtai", "try_cast(json_extract(data, '$.a') as integer) b")
+ self.assertSql("where", "select * from txtai where cast(a as decimal(10, 2)) > 5", "cast(json_extract(data, '$.a') as decimal(10, 2)) > 5")
+ self.assertSql(
+ "where",
+ "select * from txtai where cast(a as double precision) > b",
+ "cast(json_extract(data, '$.a') as double precision) > json_extract(data, '$.b')",
+ )
+ self.assertSql(
+ "orderby",
+ "select * from txtai order by func(cast(a as integer), b)",
+ "func(cast(json_extract(data, '$.a') as integer), json_extract(data, '$.b'))",
+ )
+
def testDistinct(self):
"""
Test distinct expressions