Commits

Mike Bayer  committed 6d93eff

- Added explicit true()/false() constructs to expression
lib - coercion rules will intercept "False"/"True"
into these constructs. In 0.6, the constructs were
typically converted straight to string, which was
no longer accepted in 0.7. [ticket:2117]

  • Participants
  • Parent commits 32ab578

Comments (0)

Files changed (5)

     now function, tests added for before/after events
     on all constraint types.  [ticket:2105]
 
+  - Added explicit true()/false() constructs to expression
+    lib - coercion rules will intercept "False"/"True"
+    into these constructs.  In 0.6, the constructs were
+    typically converted straight to string, which was 
+    no longer accepted in 0.7.  [ticket:2117]
+
 - engine
   - The C extension is now enabled by default on CPython
     2.x with a fallback to pure python if it fails to

File doc/build/core/expression_api.rst

 
 .. autofunction:: extract
 
+.. autofunction:: false
+
 .. autodata:: func
 
 .. autofunction:: insert
 
 .. autofunction:: text
 
+.. autofunction:: true
+
 .. autofunction:: tuple_
 
 .. autofunction:: type_coerce

File lib/sqlalchemy/sql/compiler.py

              self.post_process_text(textclause.text))
         )
 
-    def visit_null(self, null, **kwargs):
+    def visit_null(self, expr, **kw):
         return 'NULL'
 
+    def visit_true(self, expr, **kw):
+        return 'true'
+
+    def visit_false(self, expr, **kw):
+        return 'false'
+
     def visit_clauselist(self, clauselist, **kwargs):
         sep = clauselist.operator
         if sep is None:

File lib/sqlalchemy/sql/expression.py

     return _Over(func, partition_by=partition_by, order_by=order_by)
 
 def null():
-    """Return a :class:`_Null` object, which compiles to ``NULL`` in a sql
-    statement.
+    """Return a :class:`_Null` object, which compiles to ``NULL``.
 
     """
     return _Null()
 
+def true():
+    """Return a :class:`_True` object, which compiles to ``true``, or the 
+    boolean equivalent for the target dialect.
+
+    """
+    return _True()
+
+def false():
+    """Return a :class:`_False` object, which compiles to ``false``, or the 
+    boolean equivalent for the target dialect.
+
+    """
+    return _False()
+
 class _FunctionGenerator(object):
     """Generate :class:`.Function` objects based on getattr calls."""
 
         return element.__clause_element__()
     elif isinstance(element, basestring):
         return _TextClause(unicode(element))
+    elif isinstance(element, (util.NoneType, bool)):
+        return _const_expr(element)
     else:
         raise exc.ArgumentError(
             "SQL expression object or string expected."
         )
 
+def _const_expr(element):
+    if element is None:
+        return null()
+    elif element is False:
+        return false()
+    elif element is True:
+        return true()
+    else:
+        raise exc.ArgumentError(
+            "Expected None, False, or True"
+        )
+
 def _clause_element_as_expr(element):
     if hasattr(element, '__clause_element__'):
         return element.__clause_element__()
     """
 
     __visit_name__ = 'null'
-
     def __init__(self):
         self.type = sqltypes.NULLTYPE
 
+class _False(ColumnElement):
+    """Represent the ``false`` keyword in a SQL statement.
+
+    Public constructor is the :func:`false()` function.
+
+    """
+
+    __visit_name__ = 'false'
+    def __init__(self):
+        self.type = sqltypes.BOOLEANTYPE
+
+class _True(ColumnElement):
+    """Represent the ``true`` keyword in a SQL statement.
+
+    Public constructor is the :func:`true()` function.
+
+    """
+
+    __visit_name__ = 'true'
+    def __init__(self):
+        self.type = sqltypes.BOOLEANTYPE
+
 
 class ClauseList(ClauseElement):
     """Describe a list of clauses, separated by an operator.

File test/sql/test_compiler.py

 from sqlalchemy import *
 from sqlalchemy import exc, sql, util
 from sqlalchemy.sql import table, column, label, compiler
-from sqlalchemy.sql.expression import ClauseList
+from sqlalchemy.sql.expression import ClauseList, _literal_as_text
 from sqlalchemy.engine import default
 from sqlalchemy.databases import *
 from test.lib import *
                     "INSERT INTO remote_owner.remotetable (rem_id, datatype_id, value) VALUES "
                     "(:rem_id, :datatype_id, :value)")
 
+
+class CoercionTest(fixtures.TestBase, AssertsCompiledSQL):
+    __dialect__ = 'default'
+
+    def _fixture(self):
+        m = MetaData()
+        return Table('foo', m,
+            Column('id', Integer))
+
+    def test_null_constant(self):
+        t = self._fixture()
+        self.assert_compile(_literal_as_text(None), "NULL")
+
+    def test_false_constant(self):
+        t = self._fixture()
+        self.assert_compile(_literal_as_text(False), "false")
+
+    def test_true_constant(self):
+        t = self._fixture()
+        self.assert_compile(_literal_as_text(True), "true")
+
+    def test_val_and_false(self):
+        t = self._fixture()
+        self.assert_compile(and_(t.c.id == 1, False),
+                            "foo.id = :id_1 AND false")
+
+    def test_val_and_true_coerced(self):
+        t = self._fixture()
+        self.assert_compile(and_(t.c.id == 1, True),
+                            "foo.id = :id_1 AND true")
+
+    def test_val_is_null_coerced(self):
+        t = self._fixture()
+        self.assert_compile(and_(t.c.id == None),
+                            "foo.id IS NULL")
+
+    def test_val_and_None(self):
+        # current convention is None in and_() or
+        # other clauselist is ignored.  May want
+        # to revise this at some point.
+        t = self._fixture()
+        self.assert_compile(and_(t.c.id == 1, None),
+                            "foo.id = :id_1")
+
+    def test_None_and_val(self):
+        # current convention is None in and_() or
+        # other clauselist is ignored.  May want
+        # to revise this at some point.
+        t = self._fixture()
+        self.assert_compile(and_(t.c.id == 1, None),
+                            "foo.id = :id_1")
+
+    def test_None_and_nothing(self):
+        # current convention is None in and_()
+        # returns None May want
+        # to revise this at some point.
+        assert and_(None) is None
+
+    def test_val_and_null(self):
+        t = self._fixture()
+        self.assert_compile(and_(t.c.id == 1, null()),
+                            "foo.id = :id_1 AND NULL")
+