From: Mike Bayer Date: Tue, 20 Jul 2010 15:54:58 +0000 (-0400) Subject: document the crap out of text(), Session.execute() X-Git-Tag: rel_0_6_4~84 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=199fb1dd3822001503c13de673fd2db1150a6d4b;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git document the crap out of text(), Session.execute() --- diff --git a/doc/build/reference/orm/sessions.rst b/doc/build/reference/orm/sessions.rst index 7b2195fcf0..1272e051c5 100644 --- a/doc/build/reference/orm/sessions.rst +++ b/doc/build/reference/orm/sessions.rst @@ -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 diff --git a/doc/build/reference/sqlalchemy/connections.rst b/doc/build/reference/sqlalchemy/connections.rst index f1bb1a5124..c5ffcb48c9 100644 --- a/doc/build/reference/sqlalchemy/connections.rst +++ b/doc/build/reference/sqlalchemy/connections.rst @@ -18,9 +18,11 @@ Connectables .. autoclass:: Engine :members: + :undoc-members: .. autoclass:: Connection :members: + :undoc-members: .. autoclass:: Connectable :members: diff --git a/lib/sqlalchemy/engine/base.py b/lib/sqlalchemy/engine/base.py index 81ef6a3295..cf459f9e65 100644 --- a/lib/sqlalchemy/engine/base.py +++ b/lib/sqlalchemy/engine/base.py @@ -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) diff --git a/lib/sqlalchemy/orm/session.py b/lib/sqlalchemy/orm/session.py index ead860ebd3..d092375a69 100644 --- a/lib/sqlalchemy/orm/session.py +++ b/lib/sqlalchemy/orm/session.py @@ -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) diff --git a/lib/sqlalchemy/sql/expression.py b/lib/sqlalchemy/sql/expression.py index 5084495c32..050b5c05b9 100644 --- a/lib/sqlalchemy/sql/expression.py +++ b/lib/sqlalchemy/sql/expression.py @@ -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 ``:`` 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=) 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)