summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/ext
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2007-02-25 22:44:52 +0000
committerMike Bayer <mike_mp@zzzcomputing.com>2007-02-25 22:44:52 +0000
commit962c22c9eda7d2ab7dc0b41bd1c7a52cf0c9d008 (patch)
treef0ab113c7947c80dfea42d4a1bef52217bf6ed96 /lib/sqlalchemy/ext
parent8fa3becd5fac57bb898a0090bafaac377b60f070 (diff)
downloadsqlalchemy-962c22c9eda7d2ab7dc0b41bd1c7a52cf0c9d008.tar.gz
migrated (most) docstrings to pep-257 format, docstring generator using straight <pre> + trim() func
for now. applies most of [ticket:214], compliemnts of Lele Gaifax
Diffstat (limited to 'lib/sqlalchemy/ext')
-rw-r--r--lib/sqlalchemy/ext/associationproxy.py64
-rw-r--r--lib/sqlalchemy/ext/proxy.py46
-rw-r--r--lib/sqlalchemy/ext/selectresults.py130
-rw-r--r--lib/sqlalchemy/ext/sessioncontext.py47
-rw-r--r--lib/sqlalchemy/ext/sqlsoup.py214
5 files changed, 314 insertions, 187 deletions
diff --git a/lib/sqlalchemy/ext/associationproxy.py b/lib/sqlalchemy/ext/associationproxy.py
index c9160ded4..907ef19dc 100644
--- a/lib/sqlalchemy/ext/associationproxy.py
+++ b/lib/sqlalchemy/ext/associationproxy.py
@@ -1,47 +1,60 @@
-"""contains the AssociationProxy class, a Python property object which
-provides transparent proxied access to the endpoint of an association object.
+"""Contain the ``AssociationProxy`` class.
-See the example examples/association/proxied_association.py.
+The ``AssociationProxy`` is a Python property object which provides
+transparent proxied access to the endpoint of an association object.
+
+See the example ``examples/association/proxied_association.py``.
"""
from sqlalchemy.orm import class_mapper
class AssociationProxy(object):
- """a property object that automatically sets up AssociationLists on a parent object."""
+ """A property object that automatically sets up ``AssociationLists`` on a parent object."""
+
def __init__(self, targetcollection, attr, creator=None):
- """create a new association property.
-
- targetcollection - the attribute name which stores the collection of Associations
-
- attr - name of the attribute on the Association in which to get/set target values
-
- creator - optional callable which is used to create a new association object. this
- callable is given a single argument which is an instance of the "proxied" object.
- if creator is not given, the association object is created using the class associated
- with the targetcollection attribute, using its __init__() constructor and setting
- the proxied attribute.
+ """Create a new association property.
+
+ targetcollection
+ The attribute name which stores the collection of Associations.
+
+ attr
+ Name of the attribute on the Association in which to get/set target values.
+
+ creator
+ Optional callable which is used to create a new association
+ object. This callable is given a single argument which is
+ an instance of the *proxied* object. If creator is not
+ given, the association object is created using the class
+ associated with the targetcollection attribute, using its
+ ``__init__()`` constructor and setting the proxied
+ attribute.
"""
self.targetcollection = targetcollection
self.attr = attr
self.creator = creator
+
def __init_deferred(self):
prop = class_mapper(self._owner_class).props[self.targetcollection]
self._cls = prop.mapper.class_
self._uselist = prop.uselist
+
def _get_class(self):
try:
return self._cls
except AttributeError:
self.__init_deferred()
return self._cls
+
def _get_uselist(self):
try:
return self._uselist
except AttributeError:
self.__init_deferred()
return self._uselist
+
cls = property(_get_class)
uselist = property(_get_uselist)
+
def create(self, target, **kw):
if self.creator is not None:
return self.creator(target, **kw)
@@ -49,6 +62,7 @@ class AssociationProxy(object):
assoc = self.cls(**kw)
setattr(assoc, self.attr, target)
return assoc
+
def __get__(self, obj, owner):
self._owner_class = owner
if obj is None:
@@ -63,34 +77,44 @@ class AssociationProxy(object):
return a
else:
return getattr(getattr(obj, self.targetcollection), self.attr)
+
def __set__(self, obj, value):
if self.uselist:
setattr(obj, self.targetcollection, [self.create(x) for x in value])
else:
setattr(obj, self.targetcollection, self.create(value))
+
def __del__(self, obj):
delattr(obj, self.targetcollection)
class _AssociationList(object):
- """generic proxying list which proxies list operations to a different
- list-holding attribute of the parent object, converting Association objects
- to and from a target attribute on each Association object."""
+ """Generic proxying list which proxies list operations to a
+ different list-holding attribute of the parent object, converting
+ Association objects to and from a target attribute on each
+ Association object.
+ """
+
def __init__(self, proxy, parent):
- """create a new AssociationList."""
+ """Create a new ``AssociationList``."""
self.proxy = proxy
self.parent = parent
+
def append(self, item, **kw):
a = self.proxy.create(item, **kw)
getattr(self.parent, self.proxy.targetcollection).append(a)
+
def __iter__(self):
return iter([getattr(x, self.proxy.attr) for x in getattr(self.parent, self.proxy.targetcollection)])
+
def __repr__(self):
return repr([getattr(x, self.proxy.attr) for x in getattr(self.parent, self.proxy.targetcollection)])
+
def __len__(self):
return len(getattr(self.parent, self.proxy.targetcollection))
+
def __getitem__(self, index):
return getattr(getattr(self.parent, self.proxy.targetcollection)[index], self.proxy.attr)
+
def __setitem__(self, index, value):
a = self.proxy.create(item)
getattr(self.parent, self.proxy.targetcollection)[index] = a
-
diff --git a/lib/sqlalchemy/ext/proxy.py b/lib/sqlalchemy/ext/proxy.py
index c7e707f8d..b81702fc4 100644
--- a/lib/sqlalchemy/ext/proxy.py
+++ b/lib/sqlalchemy/ext/proxy.py
@@ -10,26 +10,41 @@ __all__ = ['BaseProxyEngine', 'AutoConnectEngine', 'ProxyEngine']
class BaseProxyEngine(sql.Executor):
"""Basis for all proxy engines."""
-
+
def get_engine(self):
raise NotImplementedError
def set_engine(self, engine):
raise NotImplementedError
-
+
engine = property(lambda s:s.get_engine(), lambda s,e:s.set_engine(e))
-
+
def execute_compiled(self, *args, **kwargs):
- """this method is required to be present as it overrides the execute_compiled present in sql.Engine"""
- return self.get_engine().execute_compiled(*args, **kwargs)
- def compiler(self, *args, **kwargs):
- """this method is required to be present as it overrides the compiler method present in sql.Engine"""
- return self.get_engine().compiler(*args, **kwargs)
+ """Override superclass behaviour.
+
+ This method is required to be present as it overrides the
+ `execute_compiled` present in ``sql.Engine``.
+ """
+
+ return self.get_engine().execute_compiled(*args, **kwargs)
+
+ def compiler(self, *args, **kwargs):
+ """Override superclass behaviour.
+
+ This method is required to be present as it overrides the
+ `compiler` method present in ``sql.Engine``.
+ """
+
+ return self.get_engine().compiler(*args, **kwargs)
def __getattr__(self, attr):
- """provides proxying for methods that are not otherwise present on this BaseProxyEngine. Note
- that methods which are present on the base class sql.Engine will *not* be proxied through this,
- and must be explicit on this class."""
+ """Provide proxying for methods that are not otherwise present on this ``BaseProxyEngine``.
+
+ Note that methods which are present on the base class
+ ``sql.Engine`` will **not** be proxied through this, and must
+ be explicit on this class.
+ """
+
# call get_engine() to give subclasses a chance to change
# connection establishment behavior
e = self.get_engine()
@@ -38,16 +53,15 @@ class BaseProxyEngine(sql.Executor):
raise AttributeError("No connection established in ProxyEngine: "
" no access to %s" % attr)
-
class AutoConnectEngine(BaseProxyEngine):
"""An SQLEngine proxy that automatically connects when necessary."""
-
+
def __init__(self, dburi, **kwargs):
BaseProxyEngine.__init__(self)
self.dburi = dburi
self.kwargs = kwargs
self._engine = None
-
+
def get_engine(self):
if self._engine is None:
if callable(self.dburi):
@@ -60,7 +74,7 @@ class AutoConnectEngine(BaseProxyEngine):
class ProxyEngine(BaseProxyEngine):
"""Engine proxy for lazy and late initialization.
-
+
This engine will delegate access to a real engine set with connect().
"""
@@ -89,7 +103,7 @@ class ProxyEngine(BaseProxyEngine):
except KeyError:
map[key] = create_engine(*args, **kwargs)
self.storage.engine = map[key]
-
+
def get_engine(self):
if not hasattr(self.storage, 'engine') or self.storage.engine is None:
raise AttributeError("No connection established")
diff --git a/lib/sqlalchemy/ext/selectresults.py b/lib/sqlalchemy/ext/selectresults.py
index eab2aa688..d65a02f01 100644
--- a/lib/sqlalchemy/ext/selectresults.py
+++ b/lib/sqlalchemy/ext/selectresults.py
@@ -2,7 +2,7 @@ import sqlalchemy.sql as sql
import sqlalchemy.orm as orm
class SelectResultsExt(orm.MapperExtension):
- """a MapperExtension that provides SelectResults functionality for the
+ """a MapperExtension that provides SelectResults functionality for the
results of query.select_by() and query.select()"""
def select_by(self, query, *args, **params):
return SelectResults(query, query.join_by(*args, **params))
@@ -13,14 +13,19 @@ class SelectResultsExt(orm.MapperExtension):
return SelectResults(query, arg, ops=kwargs)
class SelectResults(object):
- """Builds a query one component at a time via separate method calls,
- each call transforming the previous SelectResults instance into a new SelectResults
- instance with further limiting criterion added. When interpreted
- in an iterator context (such as via calling list(selectresults)), executes the query."""
-
+ """Build a query one component at a time via separate method
+ calls, each call transforming the previous ``SelectResults``
+ instance into a new ``SelectResults`` instance with further
+ limiting criterion added. When interpreted in an iterator context
+ (such as via calling ``list(selectresults)``), executes the query.
+ """
+
def __init__(self, query, clause=None, ops={}, joinpoint=None):
- """constructs a new SelectResults using the given Query object and optional WHERE
- clause. ops is an optional dictionary of bind parameter values."""
+ """Construct a new ``SelectResults`` using the given ``Query``
+ object and optional ``WHERE`` clause. `ops` is an optional
+ dictionary of bind parameter values.
+ """
+
self._query = query
self._clause = clause
self._ops = {}
@@ -28,23 +33,24 @@ class SelectResults(object):
self._joinpoint = joinpoint or (self._query.table, self._query.mapper)
def options(self,*args, **kwargs):
- """transform the original mapper query form to an alternate form
-
- See also Query.options
+ """Transform the original mapper query form to an alternate form
+ See also ``Query.options``.
"""
+
self._query = self._query.options(*args, **kwargs)
def count(self):
- """executes the SQL count() function against the SelectResults criterion."""
+ """Execute the SQL ``count()`` function against the ``SelectResults`` criterion."""
+
return self._query.count(self._clause, **self._ops)
def _col_aggregate(self, col, func):
- """executes func() function against the given column
+ """Execute ``func()`` function against the given column.
- For performance, only use subselect if order_by attribute is set.
-
+ For performance, only use subselect if `order_by` attribute is set.
"""
+
if self._ops.get('order_by'):
s1 = sql.select([col], self._clause, **self._ops).alias('u')
return sql.select([func(s1.corresponding_column(col))]).scalar()
@@ -52,95 +58,115 @@ class SelectResults(object):
return sql.select([func(col)], self._clause, **self._ops).scalar()
def min(self, col):
- """executes the SQL min() function against the given column"""
+ """Execute the SQL ``min()`` function against the given column."""
+
return self._col_aggregate(col, sql.func.min)
def max(self, col):
- """executes the SQL max() function against the given column"""
+ """Execute the SQL ``max()`` function against the given column."""
+
return self._col_aggregate(col, sql.func.max)
def sum(self, col):
- """executes the SQL sum() function against the given column"""
+ """Execute the SQL ``sum``() function against the given column."""
+
return self._col_aggregate(col, sql.func.sum)
def avg(self, col):
- """executes the SQL avg() function against the given column"""
+ """Execute the SQL ``avg()`` function against the given column."""
+
return self._col_aggregate(col, sql.func.avg)
def clone(self):
- """creates a copy of this SelectResults."""
+ """Create a copy of this ``SelectResults``."""
+
return SelectResults(self._query, self._clause, self._ops.copy(), self._joinpoint)
-
+
def filter(self, clause):
- """applies an additional WHERE clause against the query."""
+ """Apply an additional ``WHERE`` clause against the query."""
+
new = self.clone()
new._clause = sql.and_(self._clause, clause)
return new
def select(self, clause):
return self.filter(clause)
-
+
def select_by(self, *args, **kwargs):
return self.filter(self._query._join_by(args, kwargs, start=self._joinpoint[1]))
-
+
def order_by(self, order_by):
- """apply an ORDER BY to the query."""
+ """Apply an ``ORDER BY`` to the query."""
+
new = self.clone()
new._ops['order_by'] = order_by
return new
def limit(self, limit):
- """apply a LIMIT to the query."""
+ """Apply a ``LIMIT`` to the query."""
+
return self[:limit]
def offset(self, offset):
- """apply an OFFSET to the query."""
+ """Apply an ``OFFSET`` to the query."""
+
return self[offset:]
def distinct(self):
- """applies a DISTINCT to the query"""
+ """Apply a ``DISTINCT`` to the query."""
+
new = self.clone()
new._ops['distinct'] = True
return new
-
+
def list(self):
- """return the results represented by this SelectResults as a list.
-
- this results in an execution of the underlying query."""
+ """Return the results represented by this ``SelectResults`` as a list.
+
+ This results in an execution of the underlying query.
+ """
+
return list(self)
-
+
def select_from(self, from_obj):
- """set the from_obj parameter of the query to a specific table or set of tables.
-
- from_obj is a list."""
+ """Set the `from_obj` parameter of the query.
+
+ `from_obj` is a list of one or more tables.
+ """
+
new = self.clone()
new._ops['from_obj'] = from_obj
return new
-
+
def join_to(self, prop):
- """join the table of this SelectResults to the table located against the given property name.
-
- subsequent calls to join_to or outerjoin_to will join against the rightmost table located from the
- previous join_to or outerjoin_to call, searching for the property starting with the rightmost mapper
- last located."""
+ """Join the table of this ``SelectResults`` to the table located against the given property name.
+
+ Subsequent calls to join_to or outerjoin_to will join against
+ the rightmost table located from the previous `join_to` or
+ `outerjoin_to` call, searching for the property starting with
+ the rightmost mapper last located.
+ """
+
new = self.clone()
(clause, mapper) = self._join_to(prop, outerjoin=False)
new._ops['from_obj'] = [clause]
new._joinpoint = (clause, mapper)
return new
-
+
def outerjoin_to(self, prop):
- """outer join the table of this SelectResults to the table located against the given property name.
-
- subsequent calls to join_to or outerjoin_to will join against the rightmost table located from the
- previous join_to or outerjoin_to call, searching for the property starting with the rightmost mapper
- last located."""
+ """Outer join the table of this ``SelectResults`` to the table located against the given property name.
+
+ Subsequent calls to join_to or outerjoin_to will join against
+ the rightmost table located from the previous ``join_to` or
+ `outerjoin_to` call, searching for the property starting with
+ the rightmost mapper last located.
+ """
+
new = self.clone()
(clause, mapper) = self._join_to(prop, outerjoin=True)
new._ops['from_obj'] = [clause]
new._joinpoint = (clause, mapper)
return new
-
+
def _join_to(self, prop, outerjoin=False):
[keys,p] = self._query._locate_prop(prop, start=self._joinpoint[1])
clause = self._joinpoint[0]
@@ -153,10 +179,10 @@ class SelectResults(object):
clause = clause.join(prop.select_table, prop.get_join(mapper))
mapper = prop.mapper
return (clause, mapper)
-
+
def compile(self):
return self._query.compile(self._clause, **self._ops)
-
+
def __getitem__(self, item):
if isinstance(item, slice):
start = item.start
@@ -178,6 +204,6 @@ class SelectResults(object):
return res
else:
return list(self[item:item+1])[0]
-
+
def __iter__(self):
return iter(self._query.select_whereclause(self._clause, **self._ops))
diff --git a/lib/sqlalchemy/ext/sessioncontext.py b/lib/sqlalchemy/ext/sessioncontext.py
index f431f87c7..2f81e55d2 100644
--- a/lib/sqlalchemy/ext/sessioncontext.py
+++ b/lib/sqlalchemy/ext/sessioncontext.py
@@ -4,35 +4,41 @@ from sqlalchemy.orm.mapper import MapperExtension
__all__ = ['SessionContext', 'SessionContextExt']
class SessionContext(object):
- """A simple wrapper for ScopedRegistry that provides a "current" property
- which can be used to get, set, or remove the session in the current scope.
-
- By default this object provides thread-local scoping, which is the default
- scope provided by sqlalchemy.util.ScopedRegistry.
-
- Usage:
- engine = create_engine(...)
- def session_factory():
- return Session(bind_to=engine)
- context = SessionContext(session_factory)
-
- s = context.current # get thread-local session
- context.current = Session(bind_to=other_engine) # set current session
- del context.current # discard the thread-local session (a new one will
- # be created on the next call to context.current)
+ """A simple wrapper for ``ScopedRegistry`` that provides a
+ `current` property which can be used to get, set, or remove the
+ session in the current scope.
+
+ By default this object provides thread-local scoping, which is the
+ default scope provided by sqlalchemy.util.ScopedRegistry.
+
+ Usage::
+
+ engine = create_engine(...)
+ def session_factory():
+ return Session(bind_to=engine)
+ context = SessionContext(session_factory)
+
+ s = context.current # get thread-local session
+ context.current = Session(bind_to=other_engine) # set current session
+ del context.current # discard the thread-local session (a new one will
+ # be created on the next call to context.current)
"""
+
def __init__(self, session_factory, scopefunc=None):
self.registry = ScopedRegistry(session_factory, scopefunc)
super(SessionContext, self).__init__()
def get_current(self):
return self.registry()
+
def set_current(self, session):
self.registry.set(session)
+
def del_current(self):
self.registry.clear()
+
current = property(get_current, set_current, del_current,
- """Property used to get/set/del the session in the current scope""")
+ """Property used to get/set/del the session in the current scope.""")
def _get_mapper_extension(self):
try:
@@ -40,16 +46,17 @@ class SessionContext(object):
except AttributeError:
self._extension = ext = SessionContextExt(self)
return ext
+
mapper_extension = property(_get_mapper_extension,
- doc="""get a mapper extension that implements get_session using this context""")
+ doc="""Get a mapper extension that implements `get_session` using this context.""")
class SessionContextExt(MapperExtension):
- """a mapper extionsion that provides sessions to a mapper using SessionContext"""
+ """A mapper extension that provides sessions to a mapper using ``SessionContext``."""
def __init__(self, context):
MapperExtension.__init__(self)
self.context = context
-
+
def get_session(self):
return self.context.current
diff --git a/lib/sqlalchemy/ext/sqlsoup.py b/lib/sqlalchemy/ext/sqlsoup.py
index 5fb42df23..b899c043d 100644
--- a/lib/sqlalchemy/ext/sqlsoup.py
+++ b/lib/sqlalchemy/ext/sqlsoup.py
@@ -2,28 +2,30 @@
Introduction
============
-SqlSoup provides a convenient way to access database tables without having
-to declare table or mapper classes ahead of time.
+SqlSoup provides a convenient way to access database tables without
+having to declare table or mapper classes ahead of time.
Suppose we have a database with users, books, and loans tables
-(corresponding to the PyWebOff dataset, if you're curious).
-For testing purposes, we'll create this db as follows:
+(corresponding to the PyWebOff dataset, if you're curious). For
+testing purposes, we'll create this db as follows::
>>> from sqlalchemy import create_engine
>>> e = create_engine('sqlite:///:memory:')
>>> for sql in _testsql: e.execute(sql) #doctest: +ELLIPSIS
<...
-Creating a SqlSoup gateway is just like creating an SqlAlchemy engine:
+Creating a SqlSoup gateway is just like creating an SQLAlchemy
+engine::
>>> from sqlalchemy.ext.sqlsoup import SqlSoup
>>> db = SqlSoup('sqlite:///:memory:')
-or, you can re-use an existing metadata:
+or, you can re-use an existing metadata::
>>> db = SqlSoup(BoundMetaData(e))
-You can optionally specify a schema within the database for your SqlSoup:
+You can optionally specify a schema within the database for your
+SqlSoup::
# >>> db.schema = myschemaname
@@ -31,33 +33,34 @@ You can optionally specify a schema within the database for your SqlSoup:
Loading objects
===============
-Loading objects is as easy as this:
+Loading objects is as easy as this::
>>> users = db.users.select()
>>> users.sort()
>>> users
[MappedUsers(name='Joe Student',email='student@example.edu',password='student',classname=None,admin=0), MappedUsers(name='Bhargan Basepair',email='basepair@example.edu',password='basepair',classname=None,admin=1)]
-Of course, letting the database do the sort is better (".c" is short for ".columns"):
+Of course, letting the database do the sort is better (".c" is short for ".columns")::
>>> db.users.select(order_by=[db.users.c.name])
[MappedUsers(name='Bhargan Basepair',email='basepair@example.edu',password='basepair',classname=None,admin=1), MappedUsers(name='Joe Student',email='student@example.edu',password='student',classname=None,admin=0)]
-Field access is intuitive:
+Field access is intuitive::
>>> users[0].email
u'student@example.edu'
-Of course, you don't want to load all users very often. Let's add a WHERE clause.
-Let's also switch the order_by to DESC while we're at it.
+Of course, you don't want to load all users very often. Let's add a
+WHERE clause. Let's also switch the order_by to DESC while we're at
+it::
>>> from sqlalchemy import or_, and_, desc
>>> where = or_(db.users.c.name=='Bhargan Basepair', db.users.c.email=='student@example.edu')
>>> db.users.select(where, order_by=[desc(db.users.c.name)])
[MappedUsers(name='Joe Student',email='student@example.edu',password='student',classname=None,admin=0), MappedUsers(name='Bhargan Basepair',email='basepair@example.edu',password='basepair',classname=None,admin=1)]
-You can also use the select...by methods if you're querying on a single column.
-This allows using keyword arguments as column names:
+You can also use the select...by methods if you're querying on a
+single column. This allows using keyword arguments as column names::
>>> db.users.selectone_by(name='Bhargan Basepair')
MappedUsers(name='Bhargan Basepair',email='basepair@example.edu',password='basepair',classname=None,admin=1)
@@ -66,36 +69,56 @@ This allows using keyword arguments as column names:
Select variants
---------------
-All the SqlAlchemy Query select variants are available.
-Here's a quick summary of these methods:
+All the SQLAlchemy Query select variants are available. Here's a
+quick summary of these methods::
-- get(PK): load a single object identified by its primary key (either a scalar, or a tuple)
-- select(Clause, \*\*kwargs): perform a select restricted by the Clause argument; returns a list of objects. The most common clause argument takes the form "db.tablename.c.columname == value." The most common optional argument is order_by.
-- select_by(\*\*params): select methods ending with _by allow using bare column names. (columname=value) This feels more natural to most Python programmers; the downside is you can't specify order_by or other select options.
-- selectfirst, selectfirst_by: returns only the first object found; equivalent to select(...)[0] or select_by(...)[0], except None is returned if no rows are selected.
-- selectone, selectone_by: like selectfirst or selectfirst_by, but raises if less or more than one object is selected.
-- count, count_by: returns an integer count of the rows selected.
+- ``get(PK)``: load a single object identified by its primary key
+ (either a scalar, or a tuple)
-See the SqlAlchemy documentation for details:
+- ``select(Clause, **kwargs)``: perform a select restricted by the
+ `Clause` argument; returns a list of objects. The most common clause
+ argument takes the form ``db.tablename.c.columname == value``. The
+ most common optional argument is `order_by`.
-- http://www.sqlalchemy.org/docs/datamapping.myt#datamapping_query for general info and examples,
-- http://www.sqlalchemy.org/docs/sqlconstruction.myt for details on constructing WHERE clauses.
+- ``select_by(**params)``: select methods ending with ``_by`` allow
+ using bare column names (``columname=value``). This feels more
+ natural to most Python programmers; the downside is you can't
+ specify ``order_by`` or other select options.
+
+- ``selectfirst``, ``selectfirst_by``: returns only the first object
+ found; equivalent to ``select(...)[0]`` or ``select_by(...)[0]``,
+ except None is returned if no rows are selected.
+
+- ``selectone``, ``selectone_by``: like ``selectfirst`` or
+ ``selectfirst_by``, but raises if less or more than one object is
+ selected.
+
+- ``count``, ``count_by``: returns an integer count of the rows
+ selected.
+
+See the SQLAlchemy documentation for details, `datamapping query`__
+for general info and examples, `sql construction`__ for details on
+constructing ``WHERE`` clauses.
+
+__ http://www.sqlalchemy.org/docs/datamapping.myt#datamapping_query
+__http://www.sqlalchemy.org/docs/sqlconstruction.myt
Modifying objects
=================
-Modifying objects is intuitive:
+Modifying objects is intuitive::
>>> user = _
>>> user.email = 'basepair+nospam@example.edu'
>>> db.flush()
-(SqlSoup leverages the sophisticated SqlAlchemy unit-of-work code, so
-multiple updates to a single object will be turned into a single UPDATE
-statement when you flush.)
+(SqlSoup leverages the sophisticated SQLAlchemy unit-of-work code, so
+multiple updates to a single object will be turned into a single
+``UPDATE`` statement when you flush.)
-To finish covering the basics, let's insert a new loan, then delete it:
+To finish covering the basics, let's insert a new loan, then delete
+it::
>>> book_id = db.books.selectfirst(db.books.c.title=='Regional Variation in Moss').id
>>> db.loans.insert(book_id=book_id, user_name=user.name)
@@ -106,34 +129,39 @@ To finish covering the basics, let's insert a new loan, then delete it:
>>> db.delete(loan)
>>> db.flush()
-You can also delete rows that have not been loaded as objects. Let's do our
-insert/delete cycle once more, this time using the loans table's delete
-method. (For SQLAlchemy experts: note that no flush() call is required since
-this delete acts at the SQL level, not at the Mapper level.) The same
-where-clause construction rules apply here as to the select methods.
+You can also delete rows that have not been loaded as objects. Let's
+do our insert/delete cycle once more, this time using the loans
+table's delete method. (For SQLAlchemy experts: note that no flush()
+call is required since this delete acts at the SQL level, not at the
+Mapper level.) The same where-clause construction rules apply here as
+to the select methods.
+
+::
>>> db.loans.insert(book_id=book_id, user_name=user.name)
MappedLoans(book_id=2,user_name='Bhargan Basepair',loan_date=None)
>>> db.flush()
>>> db.loans.delete(db.loans.c.book_id==2)
-You can similarly update multiple rows at once. This will change the book_id
-to 1 in all loans whose book_id is 2:
+You can similarly update multiple rows at once. This will change the
+book_id to 1 in all loans whose book_id is 2::
>>> db.loans.update(db.loans.c.book_id==2, book_id=1)
>>> db.loans.select_by(db.loans.c.book_id==1)
[MappedLoans(book_id=1,user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0))]
-
+
Joins
=====
-Occasionally, you will want to pull out a lot of data from related tables all at
-once. In this situation, it is far
-more efficient to have the database perform the necessary join. (Here
-we do not have "a lot of data," but hopefully the concept is still clear.)
-SQLAlchemy is smart enough to recognize that loans has a foreign key
-to users, and uses that as the join condition automatically.
+Occasionally, you will want to pull out a lot of data from related
+tables all at once. In this situation, it is far more efficient to
+have the database perform the necessary join. (Here we do not have *a
+lot of data* but hopefully the concept is still clear.) SQLAlchemy is
+smart enough to recognize that loans has a foreign key to users, and
+uses that as the join condition automatically.
+
+::
>>> join1 = db.join(db.users, db.loans, isouter=True)
>>> join1.select_by(name='Joe Student')
@@ -142,25 +170,26 @@ to users, and uses that as the join condition automatically.
If you're unfortunate enough to be using MySQL with the default MyISAM
storage engine, you'll have to specify the join condition manually,
since MyISAM does not store foreign keys. Here's the same join again,
-with the join condition explicitly specified:
+with the join condition explicitly specified::
>>> db.join(db.users, db.loans, db.users.c.name==db.loans.c.user_name, isouter=True)
<class 'sqlalchemy.ext.sqlsoup.MappedJoin'>
-You can compose arbitrarily complex joins by combining Join objects with
-tables or other joins. Here we combine our first join with the books table:
+You can compose arbitrarily complex joins by combining Join objects
+with tables or other joins. Here we combine our first join with the
+books table::
>>> join2 = db.join(join1, db.books)
>>> join2.select()
[MappedJoin(name='Joe Student',email='student@example.edu',password='student',classname=None,admin=0,book_id=1,user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0),id=1,title='Mustards I Have Known',published_year='1989',authors='Jones')]
-If you join tables that have an identical column name, wrap your join with "with_labels",
-to disambiguate columns with their table name:
+If you join tables that have an identical column name, wrap your join
+with `with_labels`, to disambiguate columns with their table name::
>>> db.with_labels(join1).c.keys()
['users_name', 'users_email', 'users_password', 'users_classname', 'users_admin', 'loans_book_id', 'loans_user_name', 'loans_loan_date']
-You can also join directly to a labeled object:
+You can also join directly to a labeled object::
>>> labeled_loans = db.with_labels(db.loans)
>>> db.join(db.users, labeled_loans, isouter=True).c.keys()
@@ -173,27 +202,30 @@ Advanced Use
Accessing the Session
---------------------
-SqlSoup uses a SessionContext to provide thread-local sessions. You can
-get a reference to the current one like this:
+SqlSoup uses a SessionContext to provide thread-local sessions. You
+can get a reference to the current one like this::
>>> from sqlalchemy.ext.sqlsoup import objectstore
>>> session = objectstore.current
-Now you have access to all the standard session-based SA features, such
-as transactions. (SqlSoup's flush() is normally transactionalized, but
-you can perform manual transaction management if you need a transaction
-to span multiple flushes.)
+Now you have access to all the standard session-based SA features,
+such as transactions. (SqlSoup's ``flush()`` is normally
+transactionalized, but you can perform manual transaction management
+if you need a transaction to span multiple flushes.)
Mapping arbitrary Selectables
-----------------------------
-SqlSoup can map any SQLAlchemy Selectable with the map method. Let's map a
-Select object that uses an aggregate function; we'll use the SQLAlchemy Table
-that SqlSoup introspected as the basis. (Since we're not mapping to a simple
-table or join, we need to tell SQLAlchemy how to find the "primary key," which
-just needs to be unique within the select, and not necessarily correspond to a
-"real" PK in the database.)
+SqlSoup can map any SQLAlchemy ``Selectable`` with the map
+method. Let's map a ``Select`` object that uses an aggregate function;
+we'll use the SQLAlchemy ``Table`` that SqlSoup introspected as the
+basis. (Since we're not mapping to a simple table or join, we need to
+tell SQLAlchemy how to find the *primary key* which just needs to be
+unique within the select, and not necessarily correspond to a *real*
+PK in the database.)
+
+::
>>> from sqlalchemy import select, func
>>> b = db.books._table
@@ -202,20 +234,21 @@ just needs to be unique within the select, and not necessarily correspond to a
>>> years_with_count = db.map(s, primary_key=[s.c.published_year])
>>> years_with_count.select_by(published_year='1989')
[MappedBooks(published_year='1989',n=1)]
-
-Obviously if we just wanted to get a list of counts associated with book years
-once, raw SQL is going to be less work. The advantage of mapping a Select is
-reusability, both standalone and in Joins. (And if you go to full SQLAlchemy,
-you can perform mappings like this directly to your object models.)
+
+Obviously if we just wanted to get a list of counts associated with
+book years once, raw SQL is going to be less work. The advantage of
+mapping a Select is reusability, both standalone and in Joins. (And if
+you go to full SQLAlchemy, you can perform mappings like this directly
+to your object models.)
Raw SQL
-------
-You can access the SqlSoup's ``engine`` attribute to compose SQL directly.
-The engine's ``execute`` method corresponds
-to the one of a DBAPI cursor, and returns a ``ResultProxy`` that has ``fetch`` methods
-you would also see on a cursor.
+You can access the SqlSoup's `engine` attribute to compose SQL
+directly. The engine's ``execute`` method corresponds to the one of a
+DBAPI cursor, and returns a ``ResultProxy`` that has ``fetch`` methods
+you would also see on a cursor::
>>> rp = db.engine.execute('select name, email from users order by name')
>>> for name, email in rp.fetchall(): print name, email
@@ -230,14 +263,16 @@ Extra tests
Boring tests here. Nothing of real expository value.
+::
+
>>> db.users.select(db.users.c.classname==None, order_by=[db.users.c.name])
[MappedUsers(name='Bhargan Basepair',email='basepair+nospam@example.edu',password='basepair',classname=None,admin=1), MappedUsers(name='Joe Student',email='student@example.edu',password='student',classname=None,admin=0)]
-
+
>>> db.nopk
Traceback (most recent call last):
...
PKNotFoundError: table 'nopk' does not have a primary key defined
-
+
>>> db.nosuchtable
Traceback (most recent call last):
...
@@ -282,7 +317,7 @@ CREATE TABLE users (
CREATE TABLE loans (
book_id int PRIMARY KEY REFERENCES books(id),
- user_name varchar(32) references users(name)
+ user_name varchar(32) references users(name)
ON DELETE SET NULL ON UPDATE CASCADE,
loan_date datetime DEFAULT current_timestamp
);
@@ -299,7 +334,7 @@ values('Regional Variation in Moss', '1971', 'Flim and Flam');
insert into loans(book_id, user_name, loan_date)
values (
- (select min(id) from books),
+ (select min(id) from books),
(select name from users where name like 'Joe%'),
'2006-07-12 0:0:0')
;
@@ -330,30 +365,37 @@ def _ddl_error(cls):
msg = 'SQLSoup can only modify mapped Tables (found: %s)' \
% cls._table.__class__.__name__
raise InvalidRequestError(msg)
+
class SelectableClassType(type):
def insert(cls, **kwargs):
_ddl_error(cls)
+
def delete(cls, *args, **kwargs):
_ddl_error(cls)
+
def update(cls, whereclause=None, values=None, **kwargs):
_ddl_error(cls)
+
def _selectable(cls):
return cls._table
+
def __getattr__(cls, attr):
if attr == '_query':
# called during mapper init
raise AttributeError()
return getattr(cls._query, attr)
+
class TableClassType(SelectableClassType):
def insert(cls, **kwargs):
o = cls()
o.__dict__.update(kwargs)
return o
+
def delete(cls, *args, **kwargs):
cls._table.delete(*args, **kwargs).execute()
+
def update(cls, whereclause=None, values=None, **kwargs):
cls._table.update(whereclause, values).execute(**kwargs)
-
def _is_outer_join(selectable):
if not isinstance(selectable, sql.Join):
@@ -384,6 +426,7 @@ def class_for_table(selectable, **mapper_kwargs):
klass = TableClassType(mapname, (object,), {})
else:
klass = SelectableClassType(mapname, (object,), {})
+
def __cmp__(self, o):
L = self.__class__.c.keys()
L.sort()
@@ -393,6 +436,7 @@ def class_for_table(selectable, **mapper_kwargs):
except AttributeError:
raise TypeError('unable to compare with %s' % o.__class__)
return cmp(t1, t2)
+
def __repr__(self):
import locale
encoding = locale.getdefaultlocale()[1] or 'ascii'
@@ -403,6 +447,7 @@ def class_for_table(selectable, **mapper_kwargs):
value = value.encode(encoding)
L.append("%s=%r" % (k, value))
return '%s(%s)' % (self.__class__.__name__, ','.join(L))
+
for m in ['__cmp__', '__repr__']:
setattr(klass, m, eval(m))
klass._table = selectable
@@ -416,10 +461,12 @@ def class_for_table(selectable, **mapper_kwargs):
class SqlSoup:
def __init__(self, *args, **kwargs):
+ """Initialize a new ``SqlSoup``.
+
+ `args` may either be an ``SQLEngine`` or a set of arguments
+ suitable for passing to ``create_engine``.
"""
- args may either be an SQLEngine or a set of arguments suitable
- for passing to create_engine
- """
+
# meh, sometimes having method overloading instead of kwargs would be easier
if isinstance(args[0], MetaData):
args = list(args)
@@ -431,15 +478,21 @@ class SqlSoup:
self._metadata = metadata
self._cache = {}
self.schema = None
+
def engine(self):
return self._metadata._engine
+
engine = property(engine)
+
def delete(self, *args, **kwargs):
objectstore.delete(*args, **kwargs)
+
def flush(self):
objectstore.get_session().flush()
+
def clear(self):
objectstore.clear()
+
def map(self, selectable, **kwargs):
try:
t = self._cache[selectable]
@@ -447,12 +500,15 @@ class SqlSoup:
t = class_for_table(selectable, **kwargs)
self._cache[selectable] = t
return t
+
def with_labels(self, item):
# TODO give meaningful aliases
return self.map(item._selectable().select(use_labels=True).alias('foo'))
+
def join(self, *args, **kwargs):
j = join(*args, **kwargs)
return self.map(j)
+
def __getattr__(self, attr):
try:
t = self._cache[attr]