class documentation

class TextClause(roles.DDLConstraintColumnRole, roles.DDLExpressionRole, roles.StatementOptionRole, roles.WhereHavingRole, roles.OrderByRole, roles.FromClauseRole, roles.SelectStatementRole, roles.BinaryElementRole, roles.InElementRole, Executable, ClauseElement):

View In Hierarchy

Represent a literal SQL text fragment.

E.g.:

from sqlalchemy import text

t = text("SELECT * FROM users")
result = connection.execute(t)

The _expression.TextClause construct is produced using the _expression.text function; see that function for full documentation.

See Also

_expression.text

Class Method ​_create​_text Construct a new _expression.TextClause clause, representing a textual SQL string directly.
Method __and__ Undocumented
Method __init__ Undocumented
Method bindparams Establish the values and/or types of bound parameters within this _expression.TextClause construct.
Method columns No summary
Method self​_group Apply a 'grouping' to this _expression.ClauseElement.
Class Variable __visit​_name__ Undocumented
Class Variable ​_allow​_label​_resolve Undocumented
Class Variable ​_bind​_params​_regex Undocumented
Class Variable ​_execution​_options Undocumented
Class Variable ​_hide​_froms Undocumented
Class Variable ​_is​_implicitly​_boolean Undocumented
Class Variable ​_is​_text​_clause Undocumented
Class Variable ​_is​_textual Undocumented
Class Variable ​_label Undocumented
Class Variable ​_render​_label​_in​_columns​_clause Undocumented
Class Variable ​_traverse​_internals Undocumented
Class Variable key Undocumented
Instance Variable ​_bind Undocumented
Instance Variable ​_bindparams Undocumented
Instance Variable text Undocumented
Property ​_select​_iterable Undocumented
Property comparator Undocumented
Property type Undocumented

Inherited from DDLConstraintColumnRole:

Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via DDLConstraintColumnRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from DDLExpressionRole:

Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via DDLExpressionRole, StructuralRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from StatementOptionRole:

Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via StatementOptionRole, StructuralRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from WhereHavingRole:

Class Variable ​_role​_name Undocumented

Inherited from AllowsLambdaRole (via WhereHavingRole, OnClauseRole):

Class Variable allows​_lambda Undocumented

Inherited from SQLRole (via WhereHavingRole, OnClauseRole, StructuralRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from OrderByRole:

Class Variable ​_role​_name Undocumented

Inherited from AllowsLambdaRole (via OrderByRole):

Class Variable allows​_lambda Undocumented

Inherited from SQLRole (via OrderByRole, ByOfRole, ColumnListRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from FromClauseRole:

Class Variable ​_is​_subquery Undocumented
Class Variable ​_role​_name Undocumented

Inherited from AllowsLambdaRole (via FromClauseRole, ColumnsClauseRole):

Class Variable allows​_lambda Undocumented

Inherited from UsesInspection (via FromClauseRole, ColumnsClauseRole):

Class Variable ​_post​_inspect Undocumented
Class Variable uses​_inspection Undocumented

Inherited from SQLRole (via FromClauseRole, ColumnsClauseRole, ColumnListRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from AllowsLambdaRole (via FromClauseRole, JoinTargetRole):

Class Variable allows​_lambda Undocumented

Inherited from UsesInspection (via FromClauseRole, JoinTargetRole):

Class Variable ​_post​_inspect Undocumented
Class Variable uses​_inspection Undocumented

Inherited from SQLRole (via FromClauseRole, JoinTargetRole, StructuralRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from SelectStatementRole:

Method subquery Undocumented
Class Variable ​_role​_name Undocumented

Inherited from StatementRole (via SelectStatementRole):

Class Variable ​_propagate​_attrs Undocumented

Inherited from SQLRole (via SelectStatementRole, StatementRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from SQLRole (via SelectStatementRole, ReturnsRowsRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from BinaryElementRole:

Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via BinaryElementRole, ExpressionElementRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from InElementRole:

Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via InElementRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from Executable:

Method ​_add​_context​_option Add a context option to this statement.
Method ​_set​_compile​_options Assign the compile options to a new value.
Method ​_update​_compile​_options update the _compile_options with new keys.
Method execute Compile and execute this .Executable.
Method execution​_options Set non-SQL options for the statement which take effect during execution.
Method get​_execution​_options Get the non-SQL options which will take effect during execution.
Method options Apply options to this statement.
Method scalar Compile and execute this .Executable, returning the result's scalar representation.
Class Variable ​_executable​_traverse​_internals Undocumented
Class Variable ​_with​_context​_options Undocumented
Class Variable ​_with​_options Undocumented
Class Variable is​_delete Undocumented
Class Variable is​_dml Undocumented
Class Variable is​_insert Undocumented
Class Variable is​_select Undocumented
Class Variable is​_text Undocumented
Class Variable is​_update Undocumented
Class Variable supports​_execution Undocumented
Instance Variable ​_compile​_options Undocumented
Property ​_effective​_plugin​_target Undocumented
Property bind Returns the _engine.Engine or _engine.Connection to which this .Executable is bound, or None if none found.

Inherited from StatementRole (via Executable):

Class Variable ​_propagate​_attrs Undocumented
Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via Executable, StatementRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from Generative (via Executable):

Method ​_generate Undocumented

Inherited from ClauseElement:

Method compare Compare this _expression.ClauseElement to the given _expression.ClauseElement.
Method compile Compile this SQL expression.
Method params Return a copy with _expression.bindparam elements replaced.
Method unique​_params Return a copy with _expression.bindparam elements replaced.
Method __bool__ Undocumented
Method __getstate__ Undocumented
Method __invert__ Undocumented
Method __repr__ Undocumented
Method __str__ Undocumented
Method ​_clone Create a shallow copy of this ClauseElement.
Method ​_cloned​_set Return the set consisting all cloned ancestors of this ClauseElement.
Method ​_compile​_w​_cache Undocumented
Method ​_compiler Return a compiler appropriate for this ClauseElement, given a Dialect.
Method ​_execute​_on​_connection Undocumented
Method ​_negate Undocumented
Method ​_negate​_in​_binary a hook to allow the right side of a binary expression to respond to a negation of the binary expression.
Method ​_replace​_params Undocumented
Method ​_set​_propagate​_attrs Undocumented
Method ​_ungroup Return this _expression.ClauseElement without any groupings.
Method ​_with​_binary​_element​_type in the context of binary expression, convert the type of this object to the one given.
Class Variable ​_cache​_key​_traversal Undocumented
Class Variable ​_from​_objects Undocumented
Class Variable ​_is​_bind​_parameter Undocumented
Class Variable ​_is​_clause​_list Undocumented
Class Variable ​_is​_clone​_of Undocumented
Class Variable ​_is​_from​_clause Undocumented
Class Variable ​_is​_from​_container Undocumented
Class Variable ​_is​_immutable Undocumented
Class Variable ​_is​_lambda​_element Undocumented
Class Variable ​_is​_returns​_rows Undocumented
Class Variable ​_is​_select​_container Undocumented
Class Variable ​_is​_select​_statement Undocumented
Class Variable ​_is​_singleton​_constant Undocumented
Class Variable ​_order​_by​_label​_element Undocumented
Class Variable bind Undocumented
Class Variable description Undocumented
Class Variable is​_clause​_element Undocumented
Class Variable is​_selectable Undocumented
Class Variable stringify​_dialect Undocumented
Class Variable supports​_execution Undocumented
Instance Variable ​_propagate​_attrs like annotations, however these propagate outwards liberally as SQL constructs are built, and are set up at construction time.
Property ​_constructor return the 'constructor' for this ClauseElement.
Property entity​_namespace Undocumented

Inherited from SQLRole (via ClauseElement):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from SupportsWrappingAnnotations (via ClauseElement):

Method ​_annotate return a copy of this ClauseElement with annotations updated by the given dictionary.
Method ​_deannotate return a copy of this _expression.ClauseElement with annotations removed.
Method ​_with​_annotations return a copy of this ClauseElement with annotations replaced by the given dictionary.

Inherited from SupportsAnnotations (via ClauseElement, SupportsWrappingAnnotations):

Property ​_annotations​_cache​_key Undocumented

Inherited from MemoizedHasCacheKey (via ClauseElement):

Method ​_generate​_cache​_key return a cache key.

Inherited from HasCacheKey (via ClauseElement, MemoizedHasCacheKey):

Class Variable inherit​_cache Indicate if this .HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.
Class Method ​_generate​_cache​_attrs generate cache key dispatcher for a new class.
Class Method ​_generate​_cache​_key​_for​_object Undocumented
Method ​_gen​_cache​_key return an optional cache key.
Class Variable __slots__ Undocumented
Class Variable ​_hierarchy​_supports​_caching private attribute which may be set to False to prevent the inherit_cache warning from being emitted for a hierarchy of subclasses.
Class Variable ​_is​_has​_cache​_key Undocumented

Inherited from HasCopyInternals (via ClauseElement):

Method ​_copy​_internals Reassign internal elements to be clones of themselves.

Inherited from Traversible (via ClauseElement):

Method get​_children Return immediate child .visitors.Traversible elements of this .visitors.Traversible.
Method __class​_getitem__ Undocumented
@classmethod
@_document_text_coercion('text', ':func:`.text`', ':paramref:`.text.text`')
@util.deprecated_params(bind=('2.0', 'The :paramref:`_sql.text.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.'))
def _create_text(cls, text, bind=None):

Construct a new _expression.TextClause clause, representing a textual SQL string directly.

E.g.:

from sqlalchemy import text

t = text("SELECT * FROM users")
result = connection.execute(t)

The advantages _expression.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. The construct can also be provided with a .c collection of column elements, allowing it to be embedded in other SQL expression constructs as a subquery.

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)

For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape:

t = text("SELECT * FROM users WHERE name='\:username'")

The _expression.TextClause construct includes methods which can provide information about the bound parameters as well as the column values which would be returned from the textual statement, assuming it's an executable SELECT type of statement. The _expression.TextClause.bindparams method is used to provide bound parameter detail, and _expression.TextClause.columns method allows specification of return columns including names and types:

t = text("SELECT * FROM users WHERE id=:user_id").\
        bindparams(user_id=7).\
        columns(id=Integer, name=String)

for id, name in connection.execute(t):
    print(id, name)

The _expression.text construct is used in cases when a literal string SQL fragment is specified as part of a larger query, such as for the WHERE clause of a SELECT statement:

s = select(users.c.id, users.c.name).where(text("id=:user_id"))
result = connection.execute(s, user_id=12)

_expression.text is also used for the construction of a full, standalone statement using plain text. As such, SQLAlchemy refers to it as an .Executable object, and it supports the Executable.execution_options method. For example, a _expression.text construct that should be subject to "autocommit" can be set explicitly so using the :paramref:`.Connection.execution_options.autocommit` option:

t = text("EXEC my_procedural_thing()").\
        execution_options(autocommit=True)
Deprecated since version 1.4: The "autocommit" execution option is deprecated and will be removed in SQLAlchemy 2.0. See :ref:`migration_20_autocommit` for discussion.

See Also

:ref:`sqlexpression_text` - in the Core tutorial

Parameters
textthe text of the SQL statement to be created. Use :<param> to specify bind parameters; they will be compiled to their engine-specific format.
bindan optional connection or engine to be used for this text query.
def __and__(self, other):

Undocumented

def __init__(self, text, bind=None):

Undocumented

@_generative
def bindparams(self, *binds, **names_to_values):

Establish the values and/or types of bound parameters within this _expression.TextClause construct.

Given a text construct such as:

from sqlalchemy import text
stmt = text("SELECT id, name FROM user WHERE name=:name "
            "AND timestamp=:timestamp")

the _expression.TextClause.bindparams method can be used to establish the initial value of :name and :timestamp, using simple keyword arguments:

stmt = stmt.bindparams(name='jack',
            timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))

Where above, new .BindParameter objects will be generated with the names name and timestamp, and values of jack and datetime.datetime(2012, 10, 8, 15, 12, 5), respectively. The types will be inferred from the values given, in this case .String and .DateTime.

When specific typing behavior is needed, the positional *binds argument can be used in which to specify .bindparam constructs directly. These constructs must include at least the key argument, then an optional value and type:

from sqlalchemy import bindparam
stmt = stmt.bindparams(
                bindparam('name', value='jack', type_=String),
                bindparam('timestamp', type_=DateTime)
            )

Above, we specified the type of .DateTime for the timestamp bind, and the type of .String for the name bind. In the case of name we also set the default value of "jack".

Additional bound parameters can be supplied at statement execution time, e.g.:

result = connection.execute(stmt,
            timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))

The _expression.TextClause.bindparams method can be called repeatedly, where it will re-use existing .BindParameter objects to add new information. For example, we can call _expression.TextClause.bindparams first with typing information, and a second time with value information, and it will be combined:

stmt = text("SELECT id, name FROM user WHERE name=:name "
            "AND timestamp=:timestamp")
stmt = stmt.bindparams(
    bindparam('name', type_=String),
    bindparam('timestamp', type_=DateTime)
)
stmt = stmt.bindparams(
    name='jack',
    timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
)

The _expression.TextClause.bindparams method also supports the concept of unique bound parameters. These are parameters that are "uniquified" on name at statement compilation time, so that multiple _expression.text constructs may be combined together without the names conflicting. To use this feature, specify the :paramref:`.BindParameter.unique` flag on each .bindparam object:

stmt1 = text("select id from table where name=:name").bindparams(
    bindparam("name", value='name1', unique=True)
)
stmt2 = text("select id from table where name=:name").bindparams(
    bindparam("name", value='name2', unique=True)
)

union = union_all(
    stmt1.columns(column("id")),
    stmt2.columns(column("id"))
)

The above statement will render as:

select id from table where name=:name_1
UNION ALL select id from table where name=:name_2
New in version 1.3.11: Added support for the :paramref:`.BindParameter.unique` flag to work with _expression.text constructs.
@util.preload_module('sqlalchemy.sql.selectable')
def columns(self, *cols, **types):

Turn this _expression.TextClause object into a _expression.TextualSelect object that serves the same role as a SELECT statement.

The _expression.TextualSelect is part of the _expression.SelectBase hierarchy and can be embedded into another statement by using the _expression.TextualSelect.subquery method to produce a .Subquery object, which can then be SELECTed from.

This function essentially bridges the gap between an entirely textual SELECT statement and the SQL expression language concept of a "selectable":

from sqlalchemy.sql import column, text

stmt = text("SELECT id, name FROM some_table")
stmt = stmt.columns(column('id'), column('name')).subquery('st')

stmt = select(mytable).\
        select_from(
            mytable.join(stmt, mytable.c.name == stmt.c.name)
        ).where(stmt.c.id > 5)

Above, we pass a series of _expression.column elements to the _expression.TextClause.columns method positionally. These _expression.column elements now become first class elements upon the _expression.TextualSelect.selected_columns column collection, which then become part of the .Subquery.c collection after _expression.TextualSelect.subquery is invoked.

The column expressions we pass to _expression.TextClause.columns may also be typed; when we do so, these .TypeEngine objects become the effective return type of the column, so that SQLAlchemy's result-set-processing systems may be used on the return values. This is often needed for types such as date or boolean types, as well as for unicode processing on some dialect configurations:

stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
            column('id', Integer),
            column('name', Unicode),
            column('timestamp', DateTime)
        )

for id, name, timestamp in connection.execute(stmt):
    print(id, name, timestamp)

As a shortcut to the above syntax, keyword arguments referring to types alone may be used, if only type conversion is needed:

stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
            id=Integer,
            name=Unicode,
            timestamp=DateTime
        )

for id, name, timestamp in connection.execute(stmt):
    print(id, name, timestamp)

The positional form of _expression.TextClause.columns also provides the unique feature of positional column targeting, which is particularly useful when using the ORM with complex textual queries. If we specify the columns from our model to _expression.TextClause.columns, the result set will match to those columns positionally, meaning the name or origin of the column in the textual SQL doesn't matter:

stmt = text("SELECT users.id, addresses.id, users.id, "
     "users.name, addresses.email_address AS email "
     "FROM users JOIN addresses ON users.id=addresses.user_id "
     "WHERE users.id = 1").columns(
        User.id,
        Address.id,
        Address.user_id,
        User.name,
        Address.email_address
     )

query = session.query(User).from_statement(stmt).options(
    contains_eager(User.addresses))
New in version 1.1: the _expression.TextClause.columns method now offers positional column targeting in the result set when the column expressions are passed purely positionally.

The _expression.TextClause.columns method provides a direct route to calling _expression.FromClause.subquery as well as _expression.SelectBase.cte against a textual SELECT statement:

stmt = stmt.columns(id=Integer, name=String).cte('st')

stmt = select(sometable).where(sometable.c.id == stmt.c.id)
Parameters
*colsA series of _expression.ColumnElement objects, typically _schema.Column objects from a _schema.Table or ORM level column-mapped attributes, representing a set of columns that this textual string will SELECT from.
**typesA mapping of string names to .TypeEngine type objects indicating the datatypes to use for names that are SELECTed from the textual string. Prefer to use the *cols argument as it also indicates positional ordering.
def self_group(self, against=None):

Apply a 'grouping' to this _expression.ClauseElement.

This method is overridden by subclasses to return a "grouping" construct, i.e. parenthesis. In particular it's used by "binary" expressions to provide a grouping around themselves when placed into a larger expression, as well as by _expression.select constructs when placed into the FROM clause of another _expression.select. (Note that subqueries should be normally created using the _expression.Select.alias method, as many platforms require nested SELECT statements to be named).

As expressions are composed together, the application of self_group is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy's clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like x OR (y AND z) - AND takes precedence over OR.

The base self_group method of _expression.ClauseElement just returns self.

__visit_name__: str =
_allow_label_resolve: bool =

Undocumented

_bind_params_regex =

Undocumented

_execution_options =
_hide_froms: tuple =
_is_implicitly_boolean: bool =

Undocumented

_is_text_clause: bool =
_is_textual: bool =
_label =

Undocumented

_render_label_in_columns_clause: bool =

Undocumented

_traverse_internals =

Undocumented

key =

Undocumented

_bind =

Undocumented

_bindparams =

Undocumented

text =

Undocumented

@property
_select_iterable =
@property
comparator =

Undocumented

@property
type =

Undocumented