INSERT, UPDATE and DELETE statements build on a hierarchy starting
with UpdateBase
. The Insert
and Update
constructs build on the intermediary ValuesBase
.
sqlalchemy.sql.expression.
delete
(table, whereclause=None, **kwargs)¶Represent a DELETE
statement via the Delete
SQL
construct.
Similar functionality is available via the
delete()
method on
Table
.
Parameters: |
|
---|
See also
Deletes - SQL Expression Tutorial
sqlalchemy.sql.expression.
insert
(table, values=None, inline=False, **kwargs)¶Represent an INSERT
statement via the Insert
SQL
construct.
Similar functionality is available via the
insert()
method on
Table
.
Parameters: |
|
---|
If both values and compile-time bind parameters are present, the compile-time bind parameters override the information specified within values on a per-key basis.
The keys within values can be either Column
objects or their string identifiers. Each key may reference one of:
If a SELECT
statement is specified which references this
INSERT
statement’s table, the statement will be correlated
against the INSERT
statement.
See also
Insert Expressions - SQL Expression Tutorial
Inserts, Updates and Deletes - SQL Expression Tutorial
sqlalchemy.sql.expression.
update
(table, whereclause=None, values=None, inline=False, **kwargs)¶Represent an UPDATE
statement via the Update
SQL
construct.
E.g.:
from sqlalchemy import update
stmt = update(users).where(users.c.id==5).\
values(name='user #5')
Similar functionality is available via the
update()
method on
Table
:
stmt = users.update().\
where(users.c.id==5).\
values(name='user #5')
Parameters: |
|
---|
If both values
and compile-time bind parameters are present, the
compile-time bind parameters override the information specified
within values
on a per-key basis.
The keys within values
can be either Column
objects or their string identifiers (specifically the “key” of the
Column
, normally but not necessarily equivalent to
its “name”). Normally, the
Column
objects used here are expected to be
part of the target Table
that is the table
to be updated. However when using MySQL, a multiple-table
UPDATE statement can refer to columns from any of
the tables referred to in the WHERE clause.
The values referred to in values
are typically:
Column
,
a scalar-returning select()
construct,
etc.When combining select()
constructs within the values
clause of an update()
construct,
the subquery represented by the select()
should be
correlated to the parent table, that is, providing criterion
which links the table inside the subquery to the outer table
being updated:
users.update().values(
name=select([addresses.c.email_address]).\
where(addresses.c.user_id==users.c.id).\
as_scalar()
)
See also
Inserts, Updates and Deletes - SQL Expression Language Tutorial
sqlalchemy.sql.expression.
Delete
(table, whereclause, bind=None, returning=None, prefixes=None, **kwargs)¶Bases: sqlalchemy.sql.expression.UpdateBase
Represent a DELETE construct.
The Delete
object is created using the delete()
function.
bind
¶bind
attribute of UpdateBase
Return a ‘bind’ linked to this UpdateBase
or a Table
associated with it.
compare
(other, **kw)¶compare()
method of ClauseElement
Compare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and
may be used to modify the criteria for comparison.
(see ColumnElement
)
compile
(bind=None, dialect=None, **kw)¶compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
Parameters: |
|
---|
execute
(*multiparams, **params)¶execute()
method of Executable
Compile and execute this Executable
.
execution_options
(**kw)¶execution_options()
method of Executable
Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or
per Connection
basis. Additionally, the
Engine
and ORM Query
objects provide
access to execution options which they in turn configure upon
connections.
The execution_options()
method is generative. A new
instance of this statement is returned that contains the options:
statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be applied
to a statement - these include “autocommit” and “stream_results”,
but not “isolation_level” or “compiled_cache”.
See Connection.execution_options()
for a full list of
possible options.
params
(*arg, **kw)¶params()
method of UpdateBase
Set the parameters for the statement.
This method raises NotImplementedError
on the base class,
and is overridden by ValuesBase
to provide the
SET/VALUES clause of UPDATE and INSERT.
prefix_with
(*expr, **kw)¶prefix_with()
method of HasPrefixes
Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.
This is used to support backend-specific prefix keywords such as those provided by MySQL.
E.g.:
stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
Multiple prefixes can be specified by multiple calls
to prefix_with()
.
Parameters: |
|
---|
returning
(*cols)¶returning()
method of UpdateBase
Add a RETURNING or equivalent clause to this statement.
The given list of columns represent columns within the table that is
the target of the INSERT, UPDATE, or DELETE. Each element can be any
column expression. Table
objects will be
expanded into their individual columns.
Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted.
Upon execution, the values of the columns to be returned
are made available via the result set and can be iterated
using fetchone()
and similar. For DBAPIs which do not
natively support returning values (i.e. cx_oracle),
SQLAlchemy will approximate this behavior at the result level
so that a reasonable amount of behavioral neutrality is
provided.
Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING.
scalar
(*multiparams, **params)¶scalar()
method of Executable
Compile and execute this Executable
, returning the
result’s scalar representation.
self_group
(against=None)¶self_group()
method of ClauseElement
Apply a ‘grouping’ to this 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 select()
constructs when placed into
the FROM clause of another select()
. (Note that
subqueries should be normally created using the
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 ClauseElement
just returns self.
unique_params
(*optionaldict, **kwargs)¶unique_params()
method of ClauseElement
Return a copy with bindparam()
elements replaced.
Same functionality as params()
, except adds unique=True
to affected bind parameters so that multiple statements can be
used.
where
(whereclause)¶Add the given WHERE clause to a newly returned delete construct.
with_hint
(text, selectable=None, dialect_name='*')¶with_hint()
method of UpdateBase
Add a table hint for a single table to this INSERT/UPDATE/DELETE statement.
Note
UpdateBase.with_hint()
currently applies only to
Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
UpdateBase.prefix_with()
.
The text of the hint is rendered in the appropriate
location for the database backend in use, relative
to the Table
that is the subject of this
statement, or optionally to that of the given
Table
passed as the selectable
argument.
The dialect_name
option will limit the rendering of a particular
hint to a particular backend. Such as, to add a hint
that only takes effect for SQL Server:
mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
New in version 0.7.6.
Parameters: |
|
---|
sqlalchemy.sql.expression.
Insert
(table, values=None, inline=False, bind=None, prefixes=None, returning=None, **kwargs)¶Bases: sqlalchemy.sql.expression.ValuesBase
Represent an INSERT construct.
The Insert
object is created using the
insert()
function.
See also
bind
¶bind
attribute of UpdateBase
Return a ‘bind’ linked to this UpdateBase
or a Table
associated with it.
compare
(other, **kw)¶compare()
method of ClauseElement
Compare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and
may be used to modify the criteria for comparison.
(see ColumnElement
)
compile
(bind=None, dialect=None, **kw)¶compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
Parameters: |
|
---|
execute
(*multiparams, **params)¶execute()
method of Executable
Compile and execute this Executable
.
execution_options
(**kw)¶execution_options()
method of Executable
Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or
per Connection
basis. Additionally, the
Engine
and ORM Query
objects provide
access to execution options which they in turn configure upon
connections.
The execution_options()
method is generative. A new
instance of this statement is returned that contains the options:
statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be applied
to a statement - these include “autocommit” and “stream_results”,
but not “isolation_level” or “compiled_cache”.
See Connection.execution_options()
for a full list of
possible options.
from_select
(names, select)¶Return a new Insert
construct which represents
an INSERT...FROM SELECT
statement.
e.g.:
sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5)
ins = table2.insert().from_select(['a', 'b'], sel)
Parameters: |
|
---|
Note
Depending on backend, it may be necessary for the Insert
statement to be constructed using the inline=True
flag; this
flag will prevent the implicit usage of RETURNING
when the
INSERT
statement is rendered, which isn’t supported on a backend
such as Oracle in conjunction with an INSERT..SELECT
combination:
sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5)
ins = table2.insert(inline=True).from_select(['a', 'b'], sel)
New in version 0.8.3.
params
(*arg, **kw)¶params()
method of UpdateBase
Set the parameters for the statement.
This method raises NotImplementedError
on the base class,
and is overridden by ValuesBase
to provide the
SET/VALUES clause of UPDATE and INSERT.
prefix_with
(*expr, **kw)¶prefix_with()
method of HasPrefixes
Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.
This is used to support backend-specific prefix keywords such as those provided by MySQL.
E.g.:
stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
Multiple prefixes can be specified by multiple calls
to prefix_with()
.
Parameters: |
|
---|
returning
(*cols)¶returning()
method of UpdateBase
Add a RETURNING or equivalent clause to this statement.
The given list of columns represent columns within the table that is
the target of the INSERT, UPDATE, or DELETE. Each element can be any
column expression. Table
objects will be
expanded into their individual columns.
Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted.
Upon execution, the values of the columns to be returned
are made available via the result set and can be iterated
using fetchone()
and similar. For DBAPIs which do not
natively support returning values (i.e. cx_oracle),
SQLAlchemy will approximate this behavior at the result level
so that a reasonable amount of behavioral neutrality is
provided.
Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING.
scalar
(*multiparams, **params)¶scalar()
method of Executable
Compile and execute this Executable
, returning the
result’s scalar representation.
self_group
(against=None)¶self_group()
method of ClauseElement
Apply a ‘grouping’ to this 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 select()
constructs when placed into
the FROM clause of another select()
. (Note that
subqueries should be normally created using the
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 ClauseElement
just returns self.
unique_params
(*optionaldict, **kwargs)¶unique_params()
method of ClauseElement
Return a copy with bindparam()
elements replaced.
Same functionality as params()
, except adds unique=True
to affected bind parameters so that multiple statements can be
used.
values
(*args, **kwargs)¶values()
method of ValuesBase
specify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE.
Note that the Insert
and Update
constructs support
per-execution time formatting of the VALUES and/or SET clauses,
based on the arguments passed to Connection.execute()
. However,
the ValuesBase.values()
method can be used to “fix” a particular
set of parameters into the statement.
Multiple calls to ValuesBase.values()
will produce a new
construct, each one with the parameter list modified to include
the new parameters sent. In the typical case of a single
dictionary of parameters, the newly passed keys will replace
the same keys in the previous construct. In the case of a list-based
“multiple values” construct, each new list of values is extended
onto the existing list of values.
Parameters: |
|
---|
See also
Inserts, Updates and Deletes - SQL Expression Language Tutorial
insert()
- produce an INSERT
statement
update()
- produce an UPDATE
statement
with_hint
(text, selectable=None, dialect_name='*')¶with_hint()
method of UpdateBase
Add a table hint for a single table to this INSERT/UPDATE/DELETE statement.
Note
UpdateBase.with_hint()
currently applies only to
Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
UpdateBase.prefix_with()
.
The text of the hint is rendered in the appropriate
location for the database backend in use, relative
to the Table
that is the subject of this
statement, or optionally to that of the given
Table
passed as the selectable
argument.
The dialect_name
option will limit the rendering of a particular
hint to a particular backend. Such as, to add a hint
that only takes effect for SQL Server:
mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
New in version 0.7.6.
Parameters: |
|
---|
sqlalchemy.sql.expression.
Update
(table, whereclause, values=None, inline=False, bind=None, prefixes=None, returning=None, **kwargs)¶Bases: sqlalchemy.sql.expression.ValuesBase
Represent an Update construct.
The Update
object is created using the update()
function.
bind
¶bind
attribute of UpdateBase
Return a ‘bind’ linked to this UpdateBase
or a Table
associated with it.
compare
(other, **kw)¶compare()
method of ClauseElement
Compare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and
may be used to modify the criteria for comparison.
(see ColumnElement
)
compile
(bind=None, dialect=None, **kw)¶compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
Parameters: |
|
---|
execute
(*multiparams, **params)¶execute()
method of Executable
Compile and execute this Executable
.
execution_options
(**kw)¶execution_options()
method of Executable
Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or
per Connection
basis. Additionally, the
Engine
and ORM Query
objects provide
access to execution options which they in turn configure upon
connections.
The execution_options()
method is generative. A new
instance of this statement is returned that contains the options:
statement = select([table.c.x, table.c.y])
statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be applied
to a statement - these include “autocommit” and “stream_results”,
but not “isolation_level” or “compiled_cache”.
See Connection.execution_options()
for a full list of
possible options.
params
(*arg, **kw)¶params()
method of UpdateBase
Set the parameters for the statement.
This method raises NotImplementedError
on the base class,
and is overridden by ValuesBase
to provide the
SET/VALUES clause of UPDATE and INSERT.
prefix_with
(*expr, **kw)¶prefix_with()
method of HasPrefixes
Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.
This is used to support backend-specific prefix keywords such as those provided by MySQL.
E.g.:
stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
Multiple prefixes can be specified by multiple calls
to prefix_with()
.
Parameters: |
|
---|
returning
(*cols)¶returning()
method of UpdateBase
Add a RETURNING or equivalent clause to this statement.
The given list of columns represent columns within the table that is
the target of the INSERT, UPDATE, or DELETE. Each element can be any
column expression. Table
objects will be
expanded into their individual columns.
Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted.
Upon execution, the values of the columns to be returned
are made available via the result set and can be iterated
using fetchone()
and similar. For DBAPIs which do not
natively support returning values (i.e. cx_oracle),
SQLAlchemy will approximate this behavior at the result level
so that a reasonable amount of behavioral neutrality is
provided.
Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING.
scalar
(*multiparams, **params)¶scalar()
method of Executable
Compile and execute this Executable
, returning the
result’s scalar representation.
self_group
(against=None)¶self_group()
method of ClauseElement
Apply a ‘grouping’ to this 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 select()
constructs when placed into
the FROM clause of another select()
. (Note that
subqueries should be normally created using the
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 ClauseElement
just returns self.
unique_params
(*optionaldict, **kwargs)¶unique_params()
method of ClauseElement
Return a copy with bindparam()
elements replaced.
Same functionality as params()
, except adds unique=True
to affected bind parameters so that multiple statements can be
used.
values
(*args, **kwargs)¶values()
method of ValuesBase
specify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE.
Note that the Insert
and Update
constructs support
per-execution time formatting of the VALUES and/or SET clauses,
based on the arguments passed to Connection.execute()
. However,
the ValuesBase.values()
method can be used to “fix” a particular
set of parameters into the statement.
Multiple calls to ValuesBase.values()
will produce a new
construct, each one with the parameter list modified to include
the new parameters sent. In the typical case of a single
dictionary of parameters, the newly passed keys will replace
the same keys in the previous construct. In the case of a list-based
“multiple values” construct, each new list of values is extended
onto the existing list of values.
Parameters: |
|
---|
See also
Inserts, Updates and Deletes - SQL Expression Language Tutorial
insert()
- produce an INSERT
statement
update()
- produce an UPDATE
statement
where
(whereclause)¶return a new update() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.
with_hint
(text, selectable=None, dialect_name='*')¶with_hint()
method of UpdateBase
Add a table hint for a single table to this INSERT/UPDATE/DELETE statement.
Note
UpdateBase.with_hint()
currently applies only to
Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
UpdateBase.prefix_with()
.
The text of the hint is rendered in the appropriate
location for the database backend in use, relative
to the Table
that is the subject of this
statement, or optionally to that of the given
Table
passed as the selectable
argument.
The dialect_name
option will limit the rendering of a particular
hint to a particular backend. Such as, to add a hint
that only takes effect for SQL Server:
mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
New in version 0.7.6.
Parameters: |
|
---|
sqlalchemy.sql.expression.
UpdateBase
¶Bases: sqlalchemy.sql.expression.HasPrefixes
, sqlalchemy.sql.expression.Executable
, sqlalchemy.sql.expression.ClauseElement
Form the base for INSERT
, UPDATE
, and DELETE
statements.
bind
¶Return a ‘bind’ linked to this UpdateBase
or a Table
associated with it.
params
(*arg, **kw)¶Set the parameters for the statement.
This method raises NotImplementedError
on the base class,
and is overridden by ValuesBase
to provide the
SET/VALUES clause of UPDATE and INSERT.
returning
(*cols)¶Add a RETURNING or equivalent clause to this statement.
The given list of columns represent columns within the table that is
the target of the INSERT, UPDATE, or DELETE. Each element can be any
column expression. Table
objects will be
expanded into their individual columns.
Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted.
Upon execution, the values of the columns to be returned
are made available via the result set and can be iterated
using fetchone()
and similar. For DBAPIs which do not
natively support returning values (i.e. cx_oracle),
SQLAlchemy will approximate this behavior at the result level
so that a reasonable amount of behavioral neutrality is
provided.
Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING.
with_hint
(text, selectable=None, dialect_name='*')¶Add a table hint for a single table to this INSERT/UPDATE/DELETE statement.
Note
UpdateBase.with_hint()
currently applies only to
Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use
UpdateBase.prefix_with()
.
The text of the hint is rendered in the appropriate
location for the database backend in use, relative
to the Table
that is the subject of this
statement, or optionally to that of the given
Table
passed as the selectable
argument.
The dialect_name
option will limit the rendering of a particular
hint to a particular backend. Such as, to add a hint
that only takes effect for SQL Server:
mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql")
New in version 0.7.6.
Parameters: |
|
---|
sqlalchemy.sql.expression.
ValuesBase
(table, values, prefixes)¶Bases: sqlalchemy.sql.expression.UpdateBase
Supplies support for ValuesBase.values()
to
INSERT and UPDATE constructs.
values
(*args, **kwargs)¶specify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE.
Note that the Insert
and Update
constructs support
per-execution time formatting of the VALUES and/or SET clauses,
based on the arguments passed to Connection.execute()
. However,
the ValuesBase.values()
method can be used to “fix” a particular
set of parameters into the statement.
Multiple calls to ValuesBase.values()
will produce a new
construct, each one with the parameter list modified to include
the new parameters sent. In the typical case of a single
dictionary of parameters, the newly passed keys will replace
the same keys in the previous construct. In the case of a list-based
“multiple values” construct, each new list of values is extended
onto the existing list of values.
Parameters: |
|
---|
See also
Inserts, Updates and Deletes - SQL Expression Language Tutorial
insert()
- produce an INSERT
statement
update()
- produce an UPDATE
statement