Jason Baker wrote:
> Here's what I'd like to do.  Suppose I have some class Foo in
> some_module.py:
>
>     class Foo(Entity):
>         def all_foos(self):
>             return self.session.query(Foo).all()
>
> ...sqlalchemy by default will log this to sqlalchemy.engine.  However,
> this makes it a bit difficult to narrow down what query is coming from
> where.  What I would like to have happen is that this is logged to the
> name some_module.Foo (or some_other_module.Bar if it comes from a
> different class).
>
> The best approach that I've come up with involves a query option and a
> decorator:
>
>
> class LoggerOption(MapperOption):
>     """
>     This is an option that may be passed in to sqlalchemy's
>     Query.options.  This will make the query be logged to
>     any arbitrary namespace. Example::
>
>         session.query(Mbr).options(LoggerOption('foo')
>
>     The above query will be logged on the logger returned
>     by logging.getLogger('foo').
>     """
>     def __init__(self, name):
>         self.name = name
>
>     propagate_to_loaders = True
>
>     def process_query(self, query):
>         logger = logging.getLogger(self.name)
>         statement = query.statement
>         logger.debug(str(statement))
>         logger.debug(str(statement.compile().params))
>
> def query(attr_name):
>     def _query(func):
>         def _run_query(self, *args, **kwargs):
>             query = func(self, *args, **kwargs)
>             query =
> query.options(LoggerOption(self.__class__.__module__ + '.' +
>
> self.__class__.__name__))
>             attr = getattr(query, attr_name)
>             return attr()
>         _run_query.__doc__ = func.__doc__
>         return _run_query
>     return _query
>
> ...so I could rewrite Foo like this:
>
>     class Foo(Entity):
>         @query('all')
>         def all_foos(self):
>             return self.session.query(Foo)
>
> This works, but it feels like there should be a better way than having
> to attach a decorator to every method and having to return a query
> from that method.  Is there any better way to do this?

I'm unclear on what usage you'd like to see.   Are you looking for all
queries to do this (use Session with query_cls)?


>
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To post to this group, send email to sqlalch...@googlegroups.com.
> To unsubscribe from this group, send email to
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/sqlalchemy?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to