]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
fixup: try_cast: restore mssql implementation
authorNick Crews <nicholas.b.crews@gmail.com>
Mon, 15 May 2023 19:21:22 +0000 (11:21 -0800)
committerNick Crews <nicholas.b.crews@gmail.com>
Mon, 15 May 2023 19:21:22 +0000 (11:21 -0800)
From comments at
https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/4605

lib/sqlalchemy/dialects/mssql/base.py
test/dialect/mssql/test_compiler.py

index acab87f2b968e907227e2cfe519412b348cb80ae..344a9bd1aaa4bd308f85ba29ccb9acab8c189c37 100644 (file)
@@ -2145,6 +2145,12 @@ class MSSQLCompiler(compiler.SQLCompiler):
         else:
             return ""
 
+    def visit_try_cast(self, element, **kw):
+        return "TRY_CAST (%s AS %s)" % (
+            self.process(element.clause, **kw),
+            self.process(element.typeclause, **kw),
+        )
+
     def translate_select_structure(self, select_stmt, **kwargs):
         """Look for ``LIMIT`` and OFFSET in a select statement, and if
         so tries to wrap it in a subquery with ``row_number()`` criterion.
index 4afcbfd97a8295456cef83abd99b187348b58b9e..3cccac6a8a752082d2352dfe9541f203d70d0e85 100644 (file)
@@ -20,6 +20,7 @@ from sqlalchemy import String
 from sqlalchemy import Table
 from sqlalchemy import testing
 from sqlalchemy import text
+from sqlalchemy import try_cast
 from sqlalchemy import union
 from sqlalchemy import UniqueConstraint
 from sqlalchemy import update
@@ -1472,6 +1473,13 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
             "CREATE INDEX foo ON test (x) INCLUDE (y) WHERE y > 1",
         )
 
+    def test_try_cast(self):
+        t1 = Table("t1", MetaData(), Column("id", Integer, primary_key=True))
+        self.assert_compile(
+            select(try_cast(t1.c.id, Integer)),
+            "SELECT TRY_CAST (t1.id AS INTEGER) AS id FROM t1",
+        )
+
     @testing.combinations(
         ("no_persisted", "", "ignore"),
         ("persisted_none", "", None),