'Check if MSSQL transaction is uncommittable in SQLALchemy?

There is a a way to detect this using xact_state in pure SQL (using sqlcmd):

1> BEGIN TRANSACTION;
2> BEGIN TRY
3>   SELECT CAST('A' AS INT);
4> END TRY
5> BEGIN CATCH
6>   PRINT XACT_STATE();
7> END CATCH
8> GO
           
-----------

(0 rows affected)
-1

But how to get this result in SQLAlchemy? A try-catch similar to above is not giving any result:

qry = """
BEGIN TRY
  SELECT CAST('A' AS INT);
END TRY
BEGIN CATCH
  SELECT XACT_STATE();
END CATCH
"""

# How to detect xact_state = -1 and raise out?
res = session.execute("qry").fetchall();


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source