class TextClause(roles.DDLConstraintColumnRole, roles.DDLExpressionRole, roles.StatementOptionRole, roles.WhereHavingRole, roles.OrderByRole, roles.FromClauseRole, roles.SelectStatementRole, roles.BinaryElementRole, roles.InElementRole, Executable, ClauseElement):
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 |
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)
See Also
:ref:`sqlexpression_text` - in the Core tutorial
Parameters | |
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. |
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
_expression.text
constructs.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))
_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 | |
*cols | A 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. |
**types | A 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. |
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.