Column INSERT/UPDATE Defaults

Column INSERT and UPDATE defaults refer to functions that create a defaultvalue for a particular column in a row as an INSERT or UPDATE statement isproceeding against that row, in the case where no value was provided to theINSERT or UPDATE statement for that column. That is, if a table has a columncalled “timestamp”, and an INSERT statement proceeds which does not include avalue for this column, an INSERT default would create a new value, such asthe current time, that is used as the value to be INSERTed into the “timestamp”column. If the statement does include a value for this column, then thedefault does not take place.

Column defaults can be server-side functions or constant values which aredefined in the database along with the schema in DDL, or as SQLexpressions which are rendered directly within an INSERT or UPDATE statementemitted by SQLAlchemy; they may also be client-side Python functions orconstant values which are invoked by SQLAlchemy before data is passed to thedatabase.

Note

A column default handler should not be confused with a construct thatintercepts and modifies incoming values for INSERT and UPDATE statementswhich are provided to the statement as it is invoked. This is knownas data marshalling, where a column value is modified in some wayby the application before being sent to the database. SQLAlchemy providesa few means of achieving this which include using custom datatypes, SQL execution events andin the ORM custom validators as well asattribute events. Column defaults are onlyinvoked when there is no value present for a column in a SQLDML statement.

SQLAlchemy provides an array of features regarding default generationfunctions which take place for non-present values during INSERT and UPDATEstatements. Options include:

  • Scalar values used as defaults during INSERT and UPDATE operations

  • Python functions which execute upon INSERT and UPDATE operations

  • SQL expressions which are embedded in INSERT statements (or in some cases execute beforehand)

  • SQL expressions which are embedded in UPDATE statements

  • Server side default values used during INSERT

  • Markers for server-side triggers used during UPDATE

The general rule for all insert/update defaults is that they only take effectif no value for a particular column is passed as an execute() parameter;otherwise, the given value is used.

Scalar Defaults

The simplest kind of default is a scalar value used as the default value of a column:

  1. Table("mytable", meta,
  2. Column("somecolumn", Integer, default=12)
  3. )

Above, the value “12” will be bound as the column value during an INSERT if noother value is supplied.

A scalar value may also be associated with an UPDATE statement, though this isnot very common (as UPDATE statements are usually looking for dynamicdefaults):

  1. Table("mytable", meta,
  2. Column("somecolumn", Integer, onupdate=25)
  3. )

Python-Executed Functions

The Column.default and Column.onupdate keyword arguments also accept Pythonfunctions. These functions are invoked at the time of insert or update if noother value for that column is supplied, and the value returned is used forthe column’s value. Below illustrates a crude “sequence” that assigns anincrementing counter to a primary key column:

  1. # a function which counts upwards
  2. i = 0
  3. def mydefault():
  4. global i
  5. i += 1
  6. return i
  7.  
  8. t = Table("mytable", meta,
  9. Column('id', Integer, primary_key=True, default=mydefault),
  10. )

It should be noted that for real “incrementing sequence” behavior, thebuilt-in capabilities of the database should normally be used, which mayinclude sequence objects or other autoincrementing capabilities. For primarykey columns, SQLAlchemy will in most cases use these capabilitiesautomatically. See the API documentation forColumn including the Column.autoincrement flag, aswell as the section on Sequence later in thischapter for background on standard primary key generation techniques.

To illustrate onupdate, we assign the Python datetime function now tothe Column.onupdate attribute:

  1. import datetime
  2.  
  3. t = Table("mytable", meta,
  4. Column('id', Integer, primary_key=True),
  5.  
  6. # define 'last_updated' to be populated with datetime.now()
  7. Column('last_updated', DateTime, onupdate=datetime.datetime.now),
  8. )

When an update statement executes and no value is passed for last_updated,the datetime.datetime.now() Python function is executed and its returnvalue used as the value for last_updated. Notice that we provide nowas the function itself without calling it (i.e. there are no parenthesisfollowing) - SQLAlchemy will execute the function at the time the statementexecutes.

Context-Sensitive Default Functions

The Python functions used by Column.default andColumn.onupdate may also make use of the current statement’scontext in order to determine a value. The context of a statement is aninternal SQLAlchemy object which contains all information about the statementbeing executed, including its source expression, the parameters associated withit and the cursor. The typical use case for this context with regards todefault generation is to have access to the other values being inserted orupdated on the row. To access the context, provide a function that accepts asingle context argument:

  1. def mydefault(context):
  2. return context.get_current_parameters()['counter'] + 12
  3.  
  4. t = Table('mytable', meta,
  5. Column('counter', Integer),
  6. Column('counter_plus_twelve', Integer, default=mydefault, onupdate=mydefault)
  7. )

The above default generation function is applied so that it will execute forall INSERT and UPDATE statements where a value for counter_plus_twelve wasotherwise not provided, and the value will be that of whatever value is presentin the execution for the counter column, plus the number 12.

For a single statement that is being executed using “executemany” style, e.g.with multiple parameter sets passed to Connection.execute(), the user-defined function is called once for each set of parameters. For the use case ofa multi-valued Insert construct (e.g. with more than one VALUESclause set up via the Insert.values() method), the user-defined functionis also called once for each set of parameters.

When the function is invoked, the special methodDefaultExecutionContext.get_current_parameters() is available fromthe context object (an subclass of DefaultExecutionContext). Thismethod returns a dictionary of column-key to values that represents thefull set of values for the INSERT or UPDATE statement. In the case of amulti-valued INSERT construct, the subset of parameters that corresponds tothe individual VALUES clause is isolated from the full parameter dictionaryand returned alone.

New in version 1.2: Added DefaultExecutionContext.get_current_parameters() method,which improves upon the still-presentDefaultExecutionContext.current_parameters attributeby offering the service of organizing multiple VALUES clausesinto individual parameter dictionaries.

Client-Invoked SQL Expressions

The Column.default and Column.onupdate keywords mayalso be passed SQL expressions, which are in most cases rendered inline within theINSERT or UPDATE statement:

  1. t = Table("mytable", meta,
  2. Column('id', Integer, primary_key=True),
  3.  
  4. # define 'create_date' to default to now()
  5. Column('create_date', DateTime, default=func.now()),
  6.  
  7. # define 'key' to pull its default from the 'keyvalues' table
  8. Column('key', String(20), default=select([keyvalues.c.key]).where(keyvalues.c.type='type1')),
  9.  
  10. # define 'last_modified' to use the current_timestamp SQL function on update
  11. Column('last_modified', DateTime, onupdate=func.utc_timestamp())
  12. )

Above, the create_date column will be populated with the result of thenow() SQL function (which, depending on backend, compiles into NOW()or CURRENT_TIMESTAMP in most cases) during an INSERT statement, and thekey column with the result of a SELECT subquery from another table. Thelast_modified column will be populated with the value ofthe SQL UTC_TIMESTAMP() MySQL function when an UPDATE statement isemitted for this table.

Note

When using SQL functions with the func construct, we “call” thenamed function, e.g. with parenthesis as in func.now(). This differsfrom when we specify a Python callable as a default such asdatetime.datetime, where we pass the function itself, but we don’tinvoke it ourselves. In the case of a SQL function, invokingfunc.now() returns the SQL expression object that will render the“NOW” function into the SQL being emitted.

Default and update SQL expressions specified by Column.default andColumn.onupdate are invoked explicitly by SQLAlchemy when anINSERT or UPDATE statement occurs, typically rendered inline within the DMLstatement except in certain cases listed below. This is different than a“server side” default, which is part of the table’s DDL definition, e.g. aspart of the “CREATE TABLE” statement, which are likely more common. Forserver side defaults, see the next section Server-invoked DDL-Explicit Default Expressions.

When a SQL expression indicated by Column.default is used withprimary key columns, there are some cases where SQLAlchemy must “pre-execute”the default generation SQL function, meaning it is invoked in a separate SELECTstatement, and the resulting value is passed as a parameter to the INSERT.This only occurs for primary key columns for an INSERT statement that is beingasked to return this primary key value, where RETURNING or cursor.lastrowidmay not be used. An Insert construct that specifies theinline flag will always render default expressionsinline.

When the statement is executed with a single set of parameters (that is, it isnot an “executemany” style execution), the returnedResultProxy will contain a collection accessiblevia ResultProxy.postfetch_cols() which contains a list of allColumn objects which had an inline-executeddefault. Similarly, all parameters which were bound to the statement, includingall Python and SQL expressions which were pre-executed, are present in theResultProxy.last_inserted_params() orResultProxy.last_updated_params() collections onResultProxy. TheResultProxy.inserted_primary_key collection contains a list of primarykey values for the row inserted (a list so that single-column and composite-column primary keys are represented in the same format).

Server-invoked DDL-Explicit Default Expressions

A variant on the SQL expression default is the Column.server_default, which getsplaced in the CREATE TABLE statement during a Table.create() operation:

  1. t = Table('test', meta,
  2. Column('abc', String(20), server_default='abc'),
  3. Column('created_at', DateTime, server_default=func.sysdate()),
  4. Column('index_value', Integer, server_default=text("0"))
  5. )

A create call for the above table will produce:

  1. CREATE TABLE test (
  2. abc varchar(20) default 'abc',
  3. created_at datetime default sysdate,
  4. index_value integer default 0
  5. )

The above example illustrates the two typical use cases for Column.server_default,that of the SQL function (SYSDATE in the above example) as well as a server-side constantvalue (the integer “0” in the above example). It is advisable to use thetext() construct for any literal SQL values as opposed to passing theraw value, as SQLAlchemy does not typically perform any quoting or escaping onthese values.

Like client-generated expressions, Column.server_default can accommodateSQL expressions in general, however it is expected that these will usually be simplefunctions and expressions, and not the more complex cases like an embedded SELECT.

Marking Implicitly Generated Values, timestamps, and Triggered Columns

Columns which generate a new value on INSERT or UPDATE based on otherserver-side database mechanisms, such as database-specific auto-generatingbehaviors such as seen with TIMESTAMP columns on some platforms, as well ascustom triggers that invoke upon INSERT or UPDATE to generate a new value,may be called out using FetchedValue as a marker:

  1. t = Table('test', meta,
  2. Column('id', Integer, primary_key=True),
  3. Column('abc', TIMESTAMP, server_default=FetchedValue()),
  4. Column('def', String(20), server_onupdate=FetchedValue())
  5. )

The FetchedValue indicator does not affect the rendered DDL for theCREATE TABLE. Instead, it marks the column as one that will have a new valuepopulated by the database during the process of an INSERT or UPDATE statement,and for supporting databases may be used to indicate that the column should bepart of a RETURNING or OUTPUT clause for the statement. Tools such as theSQLAlchemy ORM then make use of this marker in order to know how to get at thevalue of the column after such an operation. In particular, theValuesBase.return_defaults() method can be used with an Insertor Update construct to indicate that these values should bereturned.

For details on using FetchedValue with the ORM, seeFetching Server-Generated Defaults.

See also

Fetching Server-Generated Defaults

Defining Sequences

SQLAlchemy represents database sequences using theSequence object, which is considered to be aspecial case of “column default”. It only has an effect on databases whichhave explicit support for sequences, which currently includes PostgreSQL,Oracle, and Firebird. The Sequence object isotherwise ignored.

The Sequence may be placed on any column as a“default” generator to be used during INSERT operations, and can also beconfigured to fire off during UPDATE operations if desired. It is mostcommonly used in conjunction with a single integer primary key column:

  1. table = Table("cartitems", meta,
  2. Column(
  3. "cart_id",
  4. Integer,
  5. Sequence('cart_id_seq', metadata=meta), primary_key=True),
  6. Column("description", String(40)),
  7. Column("createdate", DateTime())
  8. )

Where above, the table “cartitems” is associated with a sequence named“cart_id_seq”. When INSERT statements take place for “cartitems”, and no valueis passed for the “cart_id” column, the “cart_id_seq” sequence will be used togenerate a value. Typically, the sequence function is embedded in theINSERT statement, which is combined with RETURNING so that the newly generatedvalue can be returned to the Python code:

  1. INSERT INTO cartitems (cart_id, description, createdate)
  2. VALUES (next_val(cart_id_seq), 'some description', '2015-10-15 12:00:15')
  3. RETURNING cart_id

When the Sequence is associated with aColumn as its Python-side default generator, theSequence will also be subject to “CREATE SEQUENCE” and “DROPSEQUENCE” DDL when similar DDL is emitted for the owning Table.This is a limited scope convenience feature that does not accommodate forinheritance of other aspects of the MetaData, such as the defaultschema. Therefore, it is best practice that for a Sequence whichis local to a certain Column / Table, that it beexplicitly associated with the MetaData using theSequence.metadata parameter. See the sectionAssociating a Sequence with the MetaData for more background on this.

Associating a Sequence on a SERIAL column

PostgreSQL’s SERIAL datatype is an auto-incrementing type that impliesthe implicit creation of a PostgreSQL sequence when CREATE TABLE is emitted.If a Column specifies an explicit Sequence objectwhich also specifies a true value for the Sequence.optionalboolean flag, the Sequence will not take effect under PostgreSQL,and the SERIAL datatype will proceed normally. Instead, the Sequencewill only take effect when used against other sequence-supportingdatabases, currently Oracle and Firebird.

Executing a Sequence Standalone

A SEQUENCE is a first class schema object in SQL and can be used to generatevalues independently in the database. If you have a Sequenceobject, it can be invoked with its “next value” instruction bypassing it directly to a SQL execution method:

  1. with my_engine.connect() as conn:
  2. seq = Sequence('some_sequence')
  3. nextid = conn.execute(seq)

In order to embed the “next value” function of a Sequenceinside of a SQL statement like a SELECT or INSERT, use the Sequence.next_value()method, which will render at statement compilation time a SQL function that isappropriate for the target backend:

  1. >>> my_seq = Sequence('some_sequence')
  2. >>> stmt = select([my_seq.next_value()])
  3. >>> print stmt.compile(dialect=postgresql.dialect())
  4. SELECT nextval('some_sequence') AS next_value_1

Associating a Sequence with the MetaData

For many years, the SQLAlchemy documentation referred to theexample of associating a Sequence with a table as follows:

  1. table = Table("cartitems", meta,
  2. Column("cart_id", Integer, Sequence('cart_id_seq'),
  3. primary_key=True),
  4. Column("description", String(40)),
  5. Column("createdate", DateTime())
  6. )

While the above is a prominent idiomatic pattern, it is recommended thatthe Sequence in most cases be explicitly associated with theMetaData, using the Sequence.metadata parameter:

  1. table = Table("cartitems", meta,
  2. Column(
  3. "cart_id",
  4. Integer,
  5. Sequence('cart_id_seq', metadata=meta), primary_key=True),
  6. Column("description", String(40)),
  7. Column("createdate", DateTime())
  8. )

The Sequence object is a first classschema construct that can exist independently of any table in a database, andcan also be shared among tables. Therefore SQLAlchemy does not implicitlymodify the Sequence when it is associated with a Columnobject as either the Python-side or server-side default generator. While theCREATE SEQUENCE / DROP SEQUENCE DDL is emitted for a Sequencedefined as a Python side generator at the same time the table itself is subjectto CREATE or DROP, this is a convenience feature that does not imply that theSequence is fully associated with the MetaData object.

Explicitly associating the Sequence with MetaDataallows for the following behaviors:

Since the vast majority of cases that deal with Sequence expectthat Sequence to be fully “owned” by the associated Tableand that options like default schema are propagated, setting theSequence.metadata parameter should be considered a best practice.

Associating a Sequence as the Server Side Default

Note

The following technique is known to work only with the PostgreSQLdatabase. It does not work with Oracle.

The preceding sections illustrate how to associate a Sequence with aColumn as the Python side default generator:

  1. Column(
  2. "cart_id", Integer, Sequence('cart_id_seq', metadata=meta),
  3. primary_key=True)

In the above case, the Sequence will automatically be subjectto CREATE SEQUENCE / DROP SEQUENCE DDL when the related Tableis subject to CREATE / DROP. However, the sequence will not be presentas the server-side default for the column when CREATE TABLE is emitted.

If we want the sequence to be used as a server-side default,meaning it takes place even if we emit INSERT commands to the table fromthe SQL command line, we can use the Column.server_defaultparameter in conjunction with the value-generation function of thesequence, available from the Sequence.next_value() method. Belowwe illustrate the same Sequence being associated with theColumn both as the Python-side default generator as well asthe server-side default generator:

  1. cart_id_seq = Sequence('cart_id_seq', metadata=meta)
  2. table = Table("cartitems", meta,
  3. Column(
  4. "cart_id", Integer, cart_id_seq,
  5. server_default=cart_id_seq.next_value(), primary_key=True),
  6. Column("description", String(40)),
  7. Column("createdate", DateTime())
  8. )

or with the ORM:

  1. class CartItem(Base):
  2. __tablename__ = 'cartitems'
  3.  
  4. cart_id_seq = Sequence('cart_id_seq', metadata=Base.metadata)
  5. cart_id = Column(
  6. Integer, cart_id_seq,
  7. server_default=cart_id_seq.next_value(), primary_key=True)
  8. description = Column(String(40))
  9. createdate = Column(DateTime)

When the “CREATE TABLE” statement is emitted, on PostgreSQL it would beemitted as:

  1. CREATE TABLE cartitems (
  2. cart_id INTEGER DEFAULT nextval('cart_id_seq') NOT NULL,
  3. description VARCHAR(40),
  4. createdate TIMESTAMP WITHOUT TIME ZONE,
  5. PRIMARY KEY (cart_id)
  6. )

Placement of the Sequence in both the Python-side and server-sidedefault generation contexts ensures that the “primary key fetch” logicworks in all cases. Typically, sequence-enabled databases also supportRETURNING for INSERT statements, which is used automatically by SQLAlchemywhen emitting this statement. However if RETURNING is not used for a particularinsert, then SQLAlchemy would prefer to “pre-execute” the sequence outsideof the INSERT statement itself, which only works if the sequence isincluded as the Python-side default generator function.

The example also associates the Sequence with the enclosingMetaData directly, which again ensures that the Sequenceis fully associated with the parameters of the MetaData collectionincluding the default schema, if any.

See also

Sequences/SERIAL/IDENTITY - in the PostgreSQL dialect documentation

RETURNING Support - in the Oracle dialect documentation

Default Objects API

A plain default value on a column.

This could correspond to a constant, a callable function,or a SQL clause.

ColumnDefault is generated automaticallywhenever the default, onupdate arguments ofColumn are used. A ColumnDefaultcan be passed positionally as well.

For example, the following:

  1. Column('foo', Integer, default=50)

Is equivalent to:

  1. Column('foo', Integer, ColumnDefault(50))

A DDL-specified DEFAULT column value.

DefaultClause is a FetchedValuethat also generates a “DEFAULT” clause when“CREATE TABLE” is emitted.

DefaultClause is generated automaticallywhenever the server_default, server_onupdate arguments ofColumn are used. A DefaultClausecan be passed positionally as well.

For example, the following:

  1. Column('foo', Integer, server_default="50")

Is equivalent to:

  1. Column('foo', Integer, DefaultClause("50"))

Base class for column default values.

  • class sqlalchemy.schema.FetchedValue(for_update=False)
  • Bases: sqlalchemy.schema._NotAColumnExpr, sqlalchemy.sql.expression.SchemaEventTarget

A marker for a transparent database-side default.

Use FetchedValue when the database is configuredto provide some automatic default for a column.

E.g.:

  1. Column('foo', Integer, FetchedValue())

Would indicate that some trigger or default generatorwill create a new value for the foo column during anINSERT.

See also

Marking Implicitly Generated Values, timestamps, and Triggered Columns

A DDL-specified DEFAULT column value.

Deprecated since version 0.6: PassiveDefault is deprecated and will be removed in a future release. Please refer to DefaultClause.

  • class sqlalchemy.schema.Sequence(name, start=None, increment=None, minvalue=None, maxvalue=None, nominvalue=None, nomaxvalue=None, cycle=None, schema=None, cache=None, order=None, optional=False, quote=None, metadata=None, quote_schema=None, for_update=False)
  • Bases: sqlalchemy.schema.DefaultGenerator

Represents a named database sequence.

The Sequence object represents the name and configurationalparameters of a database sequence. It also representsa construct that can be “executed” by a SQLAlchemy Engineor Connection, rendering the appropriate “next value” functionfor the target database and returning a result.

The Sequence is typically associated with a primary key column:

  1. some_table = Table(
  2. 'some_table', metadata,
  3. Column('id', Integer, Sequence('some_table_seq'),
  4. primary_key=True)
  5. )

When CREATE TABLE is emitted for the above Table, if thetarget platform supports sequences, a CREATE SEQUENCE statement willbe emitted as well. For platforms that don’t support sequences,the Sequence construct is ignored.

See also

CreateSequence

DropSequence

  • init(name, start=None, increment=None, minvalue=None, maxvalue=None, nominvalue=None, nomaxvalue=None, cycle=None, schema=None, cache=None, order=None, optional=False, quote=None, metadata=None, quote_schema=None, for_update=False)
  • Construct a Sequence object.

    • Parameters
      • name – The name of the sequence.

      • start – the starting index of the sequence. This value isused when the CREATE SEQUENCE command is emitted to the databaseas the value of the “START WITH” clause. If None, theclause is omitted, which on most platforms indicates a startingvalue of 1.

      • increment – the increment value of the sequence. Thisvalue is used when the CREATE SEQUENCE command is emitted tothe database as the value of the “INCREMENT BY” clause. If None,the clause is omitted, which on most platforms indicates anincrement of 1.

      • minvalue

the minimum value of the sequence. Thisvalue is used when the CREATE SEQUENCE command is emitted tothe database as the value of the “MINVALUE” clause. If None,the clause is omitted, which on most platforms indicates aminvalue of 1 and -2^63-1 for ascending and descending sequences,respectively.

New in version 1.0.7.

  1. -

maxvalue

the maximum value of the sequence. Thisvalue is used when the CREATE SEQUENCE command is emitted tothe database as the value of the “MAXVALUE” clause. If None,the clause is omitted, which on most platforms indicates amaxvalue of 2^63-1 and -1 for ascending and descending sequences,respectively.

New in version 1.0.7.

  1. -

nominvalue

no minimum value of the sequence. Thisvalue is used when the CREATE SEQUENCE command is emitted tothe database as the value of the “NO MINVALUE” clause. If None,the clause is omitted, which on most platforms indicates aminvalue of 1 and -2^63-1 for ascending and descending sequences,respectively.

New in version 1.0.7.

  1. -

nomaxvalue

no maximum value of the sequence. Thisvalue is used when the CREATE SEQUENCE command is emitted tothe database as the value of the “NO MAXVALUE” clause. If None,the clause is omitted, which on most platforms indicates amaxvalue of 2^63-1 and -1 for ascending and descending sequences,respectively.

New in version 1.0.7.

  1. -

cycle

allows the sequence to wrap around when the maxvalueor minvalue has been reached by an ascending or descending sequencerespectively. This value is used when the CREATE SEQUENCE commandis emitted to the database as the “CYCLE” clause. If the limit isreached, the next number generated will be the minvalue or maxvalue,respectively. If cycle=False (the default) any calls to nextvalafter the sequence has reached its maximum value will return anerror.

New in version 1.0.7.

  1. -

schema – Optional schema name for the sequence, if locatedin a schema other than the default. The rules for selecting theschema name when a MetaData is also present are the sameas that of Table.schema.

  1. -

cache

optional integer value; number of future values in thesequence which are calculated in advance. Renders the CACHE keywordunderstood by Oracle and PostgreSQL.

New in version 1.1.12.

  1. -

order

optional boolean value; if true, renders theORDER keyword, understood by Oracle, indicating the sequence isdefinitively ordered. May be necessary to provide deterministicordering using Oracle RAC.

New in version 1.1.12.

  1. -

optional – boolean value, when True, indicates that thisSequence object only needs to be explicitly generatedon backends that don’t provide another way to generate primarykey identifiers. Currently, it essentially means, “don’t createthis sequence on the PostgreSQL backend, where the SERIAL keywordcreates a sequence for us automatically”.

  1. -

quote – boolean value, when True or False, explicitlyforces quoting of the schema name on or off. When left at itsdefault of None, normal quoting rules based on casing andreserved words take place.

  1. -

quote_schema – set the quoting preferences for the schemaname.

  1. -

metadata

optional MetaData object which thisSequence will be associated with. A Sequencethat is associated with a MetaData gains the followingcapabilities:

  1. -

The Sequence will inherit the MetaData.schemaparameter specified to the target MetaData, whichaffects the production of CREATE / DROP DDL, if any.

  1. -

The Sequence.create() and Sequence.drop() methodsautomatically use the engine bound to the MetaDataobject, if any.

  1. -

The MetaData.create_all() and MetaData.drop_all()methods will emit CREATE / DROP for this Sequence,even if the Sequence is not associated with anyTable / Column that’s a member of thisMetaData.

The above behaviors can only occur if the Sequence isexplicitly associated with the MetaData via this parameter.

See also

Associating a Sequence with the MetaData - full discussion of theSequence.metadata parameter.

  1. -

for_update – Indicates this Sequence, when associatedwith a Column, should be invoked for UPDATE statementson that column’s table, rather than for INSERT statements, whenno value is otherwise present for that column in the statement.

  • property bind
  • Return the connectable associated with this default.

  • create(bind=None, checkfirst=True)

  • Creates this sequence in the database.

  • drop(bind=None, checkfirst=True)

  • Drops this sequence from the database.

  • nextvalue(_func)

  • Return a next_value function elementwhich will render the appropriate increment functionfor this Sequence within any SQL expression.