On Mar 31, 2011, at 7:18 AM, bool wrote:
>
> I want to set some context and would like sqlalchemy to respect that
> context. For Eg., I want to set a context where all my select queries
> should have an additional condition "t.c.from_date > 20110301" if the
> table has a column named from_date.
>
>
>
> with fromDateContext(from_date = "20110301"):
>
> s1 = select([t, t1])
> conn.execute(s1)
>
> s2 = select([t])
> conn.execute(s2)
>
> u1 = t.update.where(a = '1')
> conn.execute(u1)
>
>
>
> So in the above examples I would like to append the additional
> condtion "t.c.from_date > 20110301" for all select/update queries with
> in the context before executing them.
>
> Is this possible ?
its quite easy to do with a @compiles that augments the compilation of the
select() construct.
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Select, Join
import threading
_global_context = threading.local()
class DateContext(object):
def __init__(self, **crit):
self.crit = crit
def __enter__(self):
_global_context.select_crit = self.crit
return self
def __exit__(self, type, value, traceback):
del _global_context.select_crit
def find_tables(select):
for table in select.froms:
if isinstance(table, Join):
yield table.left
yield table.right
else:
yield table
@compiles(Select)
def contextual_select_thing(select, compiler, **kw):
if getattr(_global_context, 'select_crit', None):
newselect = select
for table in set(find_tables(select)):
for k, v in _global_context.select_crit.items():
if k in table.c:
newselect = newselect.where(table.c[k] == v)
return compiler.visit_select(newselect, **kw)
else:
return compiler.visit_select(select, **kw)
from sqlalchemy.sql import table, column, select
t1 = table('t1', column('a'), column('b'), column('c'))
t2 = table('t2', column('a'), column('b'), column('c'))
print select([t1])
print select([t1]).select_from(t1.join(t2, t1.c.a==t2.c.c))
with DateContext(b=12):
print select([t1])
print select([t1]).select_from(t1.join(t2, t1.c.a==t2.c.c))
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.