Case condition
PostgreSQL supports
case command. The case command can be
written as an ordinary python function which is later automatically
transformed into SQL case. Because
case is just a general
if..elif..else command, there is one requirement: in the function
every
if <sql_condition> must contain a return.
The
macrotranslate module currently does not support
exceptions, do not use any try:except block inside the case function.
from sqlabstr import Case
foo = db.foo()
def casefunc():
if today() < tommorrow(): # - this is not <sql_condition>
do_something
if foo.age > 25: # this is SQL condition
if foo.city == 'alabama':
return 'blue'
return 'yellow
return None
foo.AddCol(Case(casefunc) >> 'color')
## This function is incorrect!!!
def casefunc():
if foo.x > foo.y:
if foo.x > 5:
return foo.x
#### -> The (foo.x > foo.y) condition exits here without return
if foo.z > 5:
return 1
return None
The
Case class acts as a macro preprocessor. Every
if
statement, that has as an argument general SQL condition is automatically
translated into an appropriate
case SQL command. The python function
is evaluated before the SQL command execution, or before the output
of the
repr function.