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)
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)