Skip to content

Instantly share code, notes, and snippets.

@sheilatron
Last active August 29, 2015 14:24
Show Gist options
  • Save sheilatron/a88a9b035d80ce303ea6 to your computer and use it in GitHub Desktop.
Save sheilatron/a88a9b035d80ce303ea6 to your computer and use it in GitHub Desktop.
test for isnull FunctionElement with concatenation
from sqlalchemy import select, Boolean, String
from sqlalchemy.sql.expression import FunctionElement
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import column
from sqlalchemy.testing import fixtures, AssertsCompiledSQL
from sqlalchemy.sql.functions import ReturnTypeFromArgs
class isnull(ReturnTypeFromArgs):
"""
Provide MSSQL's and Oracle's `isnull` function for use within SQLAlchemy
queries. Registered by a compiler directive within this module.
Usage:
>>> from jivacore.db.custom_handlers import isnull
>>> session.query(isnull(None, 100)).first()
>>> (100,)
"""
name = 'isnull'
def add_mssql_isnull_handler():
"Enable SQLAlchemy expression compilation for MSSQL ISNULL"
@compiles(isnull, 'mssql')
def compile(element, compiler, **kw):
"""
MSSQL has a built-in "ISNULL" function designed to provide a default value.
The first arg must be a column or expression; the second arg is the default
to be used if the first arg evaluates to a NULL value.
"""
if len(element.clauses) > 2:
raise TypeError("isnull only supports two arguments on MS-SQL")
return "isnull(%s)" % compiler.process(element.clauses)
class UserDefinedTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'mssql+mxodbc'
def test_null_concat(self):
add_mssql_isnull_handler()
self.assert_compile(select([isnull(column('spam'), '') +
isnull(column('spamspam'), '').label("bothcols"), ]),
'SELECT isnull(spam, :param_1) + isnull(spamspam, :param_2) AS anon_1')
@sheilatron
Copy link
Author

Ok, after fixes based on help from @zzzeek this test is now passing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment