]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
document the crap out of text(), Session.execute()
authorMike Bayer <mike_mp@zzzcomputing.com>
Tue, 20 Jul 2010 15:54:58 +0000 (11:54 -0400)
committerMike Bayer <mike_mp@zzzcomputing.com>
Tue, 20 Jul 2010 15:54:58 +0000 (11:54 -0400)
doc/build/reference/orm/sessions.rst
doc/build/reference/sqlalchemy/connections.rst
lib/sqlalchemy/engine/base.py
lib/sqlalchemy/orm/session.py
lib/sqlalchemy/sql/expression.py

index 7b2195fcf0be5fe50ecd2053ac4bdb59f0a744c9..1272e051c5d4321f88abc17f16c23a74eeb71dae 100644 (file)
@@ -1,14 +1,13 @@
 Sessions
 ========
 
-.. module:: sqlalchemy.orm
+.. module:: sqlalchemy.orm.session
 
-
-.. autofunction:: create_session
+.. autofunction:: sqlalchemy.orm.create_session
 
 .. autofunction:: make_transient
 
-.. autofunction:: scoped_session
+.. autofunction:: sqlalchemy.orm.scoped_session
 
 .. autofunction:: sessionmaker
 
index f1bb1a5124a0c9bc1e332dbf60e981f433ee0866..c5ffcb48c99aae9e3fb53367d6512da53ecbd4a1 100644 (file)
@@ -18,9 +18,11 @@ Connectables
 
 .. autoclass:: Engine
    :members:
+   :undoc-members:
 
 .. autoclass:: Connection
    :members:
+   :undoc-members:
 
 .. autoclass:: Connectable
    :members:
index 81ef6a32955fa79b7e88441e1ac215d92fb447aa..cf459f9e65fa51744a6096b033a9e9126605d3e7 100644 (file)
@@ -1667,7 +1667,14 @@ class Engine(Connectable, log.Identified):
         return expression._FunctionGenerator(bind=self)
 
     def text(self, text, *args, **kwargs):
-        """Return a sql.text() object for performing literal queries."""
+        """Return a :func:`~sqlalchemy.sql.expression.text` construct, 
+        bound to this engine.
+        
+        This is equivalent to::
+        
+            text("SELECT * FROM table", bind=engine)
+            
+        """
 
         return expression.text(text, bind=self, *args, **kwargs)
 
@@ -1711,6 +1718,8 @@ class Engine(Connectable, log.Identified):
             conn.close()
 
     def execute(self, statement, *multiparams, **params):
+        """Executes and returns a ResultProxy."""
+
         connection = self.contextual_connect(close_with_result=True)
         return connection.execute(statement, *multiparams, **params)
 
index ead860ebd3fadc1095983dbe1839dda6bd937b06..d092375a690c60249922500b049c20ed8ec1b2d8 100644 (file)
@@ -703,28 +703,52 @@ class Session(object):
     def execute(self, clause, params=None, mapper=None, **kw):
         """Execute a clause within the current transaction.
 
-        Returns a ``ResultProxy`` of execution results.  `autocommit` Sessions
-        will create a transaction on the fly.
-
-        Connection ambiguity in multi-bind or unbound Sessions will be
-        resolved by inspecting the clause for binds.  The 'mapper' and
-        'instance' keyword arguments may be used if this is insufficient, See
-        ``get_bind()`` for more information.
-
-        clause
+        Returns a :class:`~sqlalchemy.engine.base.ResultProxy` representing
+        results of the statement execution, in the same manner as that of an
+        :class:`~sqlalchemy.engine.base.Engine` or
+        :class:`~sqlalchemy.engine.base.Connection`.
+
+        :meth:`Session.execute` accepts any executable clause construct, such
+        as :func:`~sqlalchemy.sql.expression.select`,
+        :func:`~sqlalchemy.sql.expression.insert`,
+        :func:`~sqlalchemy.sql.expression.update`,
+        :func:`~sqlalchemy.sql.expression.delete`, and
+        :func:`~sqlalchemy.sql.expression.text`, and additionally accepts
+        plain strings that represent SQL statements. If a plain string is
+        passed, it is first converted to a
+        :func:`~sqlalchemy.sql.expression.text` construct, which here means
+        that bind parameters should be specified using the format ``:param``.
+
+        The statement is executed within the current transactional context of
+        this :class:`Session`. If this :class:`Session` is set for
+        "autocommit", and no transaction is in progress, an ad-hoc transaction
+        will be created for the life of the result (i.e., a connection is
+        checked out from the connection pool, which is returned when the
+        result object is closed).
+        
+        If the :class:`Session` is not bound to an
+        :class:`~sqlalchemy.engine.base.Engine` or
+        :class:`~sqlalchemy.engine.base.Connection`, the given clause will be
+        inspected for binds (i.e., looking for "bound metadata"). If the
+        session is bound to multiple connectables, the ``mapper`` keyword
+        argument is typically passed in to specify which bind should be used
+        (since the :class:`Session` keys multiple bind sources to a series of
+        :func:`mapper` objects). See :meth:`get_bind` for further details on
+        bind resolution.
+        
+        :param clause:
             A ClauseElement (i.e. select(), text(), etc.) or
             string SQL statement to be executed
 
-        params
+        :param params:
             Optional, a dictionary of bind parameters.
 
-        mapper
+        :param mapper:
           Optional, a ``mapper`` or mapped class
 
-        \**kw
+        :param \**kw:
           Additional keyword arguments are sent to :meth:`get_bind()`
           which locates a connectable to use for the execution.
-          Subclasses of :class:`Session` may override this.
           
         """
         clause = expression._literal_as_text(clause)
index 5084495c32c5f3c57c94f060098f06f13b0b658c..050b5c05b98641dcb47f6f9b92affe0a79c9420a 100644 (file)
@@ -781,40 +781,97 @@ def outparam(key, type_=None):
                 key, None, type_=type_, unique=False, isoutparam=True)
 
 def text(text, bind=None, *args, **kwargs):
-    """Create literal text to be inserted into a query.
-
-    When constructing a query from a :func:`select()`, :func:`update()`,
-    :func:`insert()` or :func:`delete()`, using plain strings for argument
-    values will usually result in text objects being created
-    automatically.  Use this function when creating textual clauses
-    outside of other :class:`ClauseElement` objects, or optionally wherever
-    plain text is to be used.
+    """Create a SQL construct that is represented by a literal string.
+    
+    E.g.::
+    
+        t = text("SELECT * FROM users")
+        result = connection.execute(t)
+        
+    The advantages :func:`text` provides over a plain string are
+    backend-neutral support for bind parameters, per-statement
+    execution options, as well as 
+    bind parameter and result-column typing behavior, allowing 
+    SQLAlchemy type constructs to play a role when executing
+    a statement that is specified literally.
+    
+    Bind parameters are specified by name, using the format ``:name``.
+    E.g.::
+    
+        t = text("SELECT * FROM users WHERE id=:user_id")
+        result = connection.execute(t, user_id=12)
+        
+    To invoke SQLAlchemy typing logic for bind parameters, the 
+    ``bindparams`` list allows specification of :func:`bindparam`
+    constructs which specify the type for a given name::
+    
+        t = text("SELECT id FROM users WHERE updated_at>:updated",
+                    bindparams=[bindparam('updated', DateTime())]
+                )
+                
+    Typing during result row processing is also an important concern.   
+    Result column types
+    are specified using the ``typemap`` dictionary, where the keys
+    match the names of columns.  These names are taken from what
+    the DBAPI returns as ``cursor.description``::
+    
+        t = text("SELECT id, name FROM users",
+                typemap={
+                    'id':Integer,
+                    'name':Unicode
+                }
+        )
+    
+    The :func:`text` construct is used internally for most cases when
+    a literal string is specified for part of a larger query, such as
+    within :func:`select()`, :func:`update()`,
+    :func:`insert()` or :func:`delete()`.   In those cases, the same
+    bind parameter syntax is applied::
+    
+        s = select([users.c.id, users.c.name]).where("id=:user_id")
+        result = connection.execute(s, user_id=12)
+    
+    Using :func:`text` explicitly usually implies the construction
+    of a full, standalone statement.   As such, SQLAlchemy refers
+    to it as an :class:`Executable` object, and it supports
+    the :meth:`Executable.execution_options` method.  For example,
+    a :func:`text` construct that should be subject to "autocommit"
+    can be set explicitly so using the ``autocommit`` option::
+    
+        t = text("EXEC my_procedural_thing()").\\
+                execution_options(autocommit=True)
+                
+    Note that SQLAlchemy's usual "autocommit" behavior applies to
+    :func:`text` constructs - that is, statements which begin
+    with a phrase such as ``INSERT``, ``UPDATE``, ``DELETE``, 
+    or a variety of other phrases specific to certain backends, will 
+    be eligible for autocommit if no transaction is in progress.
 
-    text
+    :param text:
       the text of the SQL statement to be created.  use ``:<param>``
       to specify bind parameters; they will be compiled to their
       engine-specific format.
 
-    bind
-      an optional connection or engine to be used for this text query.
-
-    autocommit=True
+    :param autocommit:
       Deprecated.  Use .execution_options(autocommit=<True|False>)
       to set the autocommit option.
 
-    bindparams
+    :param bind:
+      an optional connection or engine to be used for this text query.
+
+    :param bindparams:
       a list of :func:`bindparam()` instances which can be used to define
       the types and/or initial values for the bind parameters within
       the textual statement; the keynames of the bindparams must match
       those within the text of the statement.  The types will be used
       for pre-processing on bind values.
 
-    typemap
+    :param typemap:
       a dictionary mapping the names of columns represented in the
-      ``SELECT`` clause of the textual statement to type objects,
+      columns clause of a ``SELECT`` statement  to type objects,
       which will be used to perform post-processing on columns within
-      the result set (for textual statements that produce result
-      sets).
+      the result set.   This argument applies to any expression 
+      that returns result sets.
 
     """
     return _TextClause(text, bind=bind, *args, **kwargs)