The core of SQLAlchemy’s query and object mapping operations are supported by database metadata, which is comprised of Python objects that describe tables and other schema-level objects. These objects are at the core of three major types of operations - issuing CREATE and DROP statements (known as DDL), constructing SQL queries, and expressing information about structures that already exist within the database.
Database metadata can be expressed by explicitly naming the various components and their properties, using constructs such as Table, Column, ForeignKey and Sequence, all of which are imported from the sqlalchemy.schema package. It can also be generated by SQLAlchemy using a process called reflection, which means you start with a single object such as Table, assign it a name, and then instruct SQLAlchemy to load all the additional information related to that name from a particular engine source.
A key feature of SQLAlchemy’s database metadata constructs is that they are designed to be used in a declarative style which closely resembles that of real DDL. They are therefore most intuitive to those who have some background in creating real schema generation scripts.
A collection of metadata entities is stored in an object aptly named MetaData:
from sqlalchemy import *
metadata = MetaData()
MetaData is a container object that keeps together many different features of a database (or multiple databases) being described.
To represent a table, use the Table class. Its two primary arguments are the table name, then the MetaData object which it will be associated with. The remaining positional arguments are mostly Column objects describing each column:
user = Table('user', metadata,
Column('user_id', Integer, primary_key = True),
Column('user_name', String(16), nullable = False),
Column('email_address', String(60)),
Column('password', String(20), nullable = False)
)
Above, a table called user is described, which contains four columns. The primary key of the table consists of the user_id column. Multiple columns may be assigned the primary_key=True flag which denotes a multi-column primary key, known as a composite primary key.
Note also that each column describes its datatype using objects corresponding to genericized types, such as Integer and String. SQLAlchemy features dozens of types of varying levels of specificity as well as the ability to create custom types. Documentation on the type system can be found at types.
The MetaData object contains all of the schema constructs we’ve associated with it. It supports a few methods of accessing these table objects, such as the sorted_tables accessor which returns a list of each Table object in order of foreign key dependency (that is, each table is preceded by all tables which it references):
>>> for t in metadata.sorted_tables:
... print t.name
user
user_preference
invoice
invoice_item
In most cases, individual Table objects have been explicitly declared, and these objects are typically accessed directly as module-level variables in an application. Once a Table has been defined, it has a full set of accessors which allow inspection of its properties. Given the following Table definition:
employees = Table('employees', metadata,
Column('employee_id', Integer, primary_key=True),
Column('employee_name', String(60), nullable=False),
Column('employee_dept', Integer, ForeignKey("departments.department_id"))
)
Note the ForeignKey object used in this table - this construct defines a reference to a remote table, and is fully described in Defining Foreign Keys. Methods of accessing information about this table include:
# access the column "EMPLOYEE_ID":
employees.columns.employee_id
# or just
employees.c.employee_id
# via string
employees.c['employee_id']
# iterate through all columns
for c in employees.c:
print c
# get the table's primary key columns
for primary_key in employees.primary_key:
print primary_key
# get the table's foreign key objects:
for fkey in employees.foreign_keys:
print fkey
# access the table's MetaData:
employees.metadata
# access the table's bound Engine or Connection, if its MetaData is bound:
employees.bind
# access a column's name, type, nullable, primary key, foreign key
employees.c.employee_id.name
employees.c.employee_id.type
employees.c.employee_id.nullable
employees.c.employee_id.primary_key
employees.c.employee_dept.foreign_keys
# get the "key" of a column, which defaults to its name, but can
# be any user-defined string:
employees.c.employee_name.key
# access a column's table:
employees.c.employee_id.table is employees
# get the table related by a foreign key
list(employees.c.employee_dept.foreign_keys)[0].column.table
Once you’ve defined some Table objects, assuming you’re working with a brand new database one thing you might want to do is issue CREATE statements for those tables and their related constructs (as an aside, it’s also quite possible that you don’t want to do this, if you already have some preferred methodology such as tools included with your database or an existing scripting system - if that’s the case, feel free to skip this section - SQLAlchemy has no requirement that it be used to create your tables).
The usual way to issue CREATE is to use create_all() on the MetaData object. This method will issue queries that first check for the existence of each individual table, and if not found will issue the CREATE statements:
engine = create_engine('sqlite:///:memory:') metadata = MetaData() user = Table('user', metadata, Column('user_id', Integer, primary_key = True), Column('user_name', String(16), nullable = False), Column('email_address', String(60), key='email'), Column('password', String(20), nullable = False) ) user_prefs = Table('user_prefs', metadata, Column('pref_id', Integer, primary_key=True), Column('user_id', Integer, ForeignKey("user.user_id"), nullable=False), Column('pref_name', String(40), nullable=False), Column('pref_value', String(100)) ) sqlmetadata.create_all(engine)PRAGMA table_info(user){} CREATE TABLE user( user_id INTEGER NOT NULL PRIMARY KEY, user_name VARCHAR(16) NOT NULL, email_address VARCHAR(60), password VARCHAR(20) NOT NULL ) PRAGMA table_info(user_prefs){} CREATE TABLE user_prefs( pref_id INTEGER NOT NULL PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES user(user_id), pref_name VARCHAR(40) NOT NULL, pref_value VARCHAR(100) )
create_all() creates foreign key constraints between tables usually inline with the table definition itself, and for this reason it also generates the tables in order of their dependency. There are options to change this behavior such that ALTER TABLE is used instead.
Dropping all tables is similarly achieved using the drop_all() method. This method does the exact opposite of create_all() - the presence of each table is checked first, and tables are dropped in reverse order of dependency.
Creating and dropping individual tables can be done via the create() and drop() methods of Table. These methods by default issue the CREATE or DROP regardless of the table being present:
engine = create_engine('sqlite:///:memory:')
meta = MetaData()
employees = Table('employees', meta,
Column('employee_id', Integer, primary_key=True),
Column('employee_name', String(60), nullable=False, key='name'),
Column('employee_dept', Integer, ForeignKey("departments.department_id"))
)
sqlemployees.create(engine)
CREATE TABLE employees(
employee_id SERIAL NOT NULL PRIMARY KEY,
employee_name VARCHAR(60) NOT NULL,
employee_dept INTEGER REFERENCES departments(department_id)
)
drop() method:
sqlemployees.drop(engine)
DROP TABLE employee
To enable the “check first for the table existing” logic, add the checkfirst=True argument to create() or drop():
employees.create(engine, checkfirst=True)
employees.drop(engine, checkfirst=False)
While SQLAlchemy directly supports emitting CREATE and DROP statements for schema constructs, the ability to alter those constructs, usually via the ALTER statement as well as other database-specific constructs, is outside of the scope of SQLAlchemy itself. While it’s easy enough to emit ALTER statements and similar by hand, such as by passing a string to Connection.execute() or by using the DDL construct, it’s a common practice to automate the maintenance of database schemas in relation to application code using schema migration tools.
There are two major migration tools available for SQLAlchemy:
Some databases support the concept of multiple schemas. A Table can reference this by specifying the schema keyword argument:
financial_info = Table('financial_info', meta,
Column('id', Integer, primary_key=True),
Column('value', String(100), nullable=False),
schema='remote_banks'
)
Within the MetaData collection, this table will be identified by the combination of financial_info and remote_banks. If another table called financial_info is referenced without the remote_banks schema, it will refer to a different Table. ForeignKey objects can specify references to columns in this table using the form remote_banks.financial_info.id.
The schema argument should be used for any name qualifiers required, including Oracle’s “owner” attribute and similar. It also can accommodate a dotted name for longer schemes:
schema="dbo.scott"
Table supports database-specific options. For example, MySQL has different table backend types, including “MyISAM” and “InnoDB”. This can be expressed with Table using mysql_engine:
addresses = Table('engine_email_addresses', meta,
Column('address_id', Integer, primary_key = True),
Column('remote_user_id', Integer, ForeignKey(users.c.user_id)),
Column('email_address', String(20)),
mysql_engine='InnoDB'
)
Other backends may support table-level options as well - these would be described in the individual documentation sections for each dialect.
Bases: sqlalchemy.schema.SchemaItem, sqlalchemy.sql.expression.ColumnClause
Represents a column in a database table.
Implement the == operator.
In a column context, produces the clause a = b. If the target is None, produces a IS NULL.
Construct a new Column object.
| Parameters: |
|
|---|
Implement the <= operator.
In a column context, produces the clause a <= b.
Implement the < operator.
In a column context, produces the clause a < b.
Implement the != operator.
In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.
provides a constant ‘anonymous label’ for this ColumnElement.
This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.
the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.
Produce a asc() clause against the parent object.
Produce a between() clause against the parent object, given the lower and upper range.
Produce a collate() clause against the parent object, given the collation string.
Compare this ColumnElement to another.
Special arguments understood:
| Parameters: |
|
|---|
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: |
|
|---|
Implement the ‘concat’ operator.
In a column context, produces the clause a || b, or uses the concat() operator on MySQL.
Implement the ‘contains’ operator.
In a column context, produces the clause LIKE '%<other>%'
Create a copy of this Column, unitialized.
This is used in Table.tometadata.
Produce a desc() clause against the parent object.
alias of DDLEventsDispatch
Produce a distinct() clause against the parent object.
Implement the ‘endswith’ operator.
In a column context, produces the clause LIKE '%<other>'
Return a column expression.
Part of the inspection interface; returns self.
Implement the ilike operator.
In a column context, produces the clause a ILIKE other.
E.g.:
select([sometable]).where(sometable.c.column.ilike("%foobar%"))
| Parameters: |
|
|---|
See also
Implement the in operator.
In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.
Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.
The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.
Implement the IS operator.
Normally, IS is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS may be desirable if comparing to boolean values on certain platforms.
New in version 0.7.9.
See also
Implement the IS NOT operator.
Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.
New in version 0.7.9.
See also
Produce a column label, i.e. <columnname> AS <name>.
This is a shortcut to the label() function.
if ‘name’ is None, an anonymous label name will be generated.
Implement the like operator.
In a column context, produces the clause a LIKE other.
E.g.:
select([sometable]).where(sometable.c.column.like("%foobar%"))
| Parameters: |
|
|---|
See also
Implements the ‘match’ operator.
In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.
implement the NOT ILIKE operator.
This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).
New in version 0.8.
See also
implement the NOT IN operator.
This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).
New in version 0.8.
See also
implement the NOT LIKE operator.
This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).
New in version 0.8.
See also
Produce a nullsfirst() clause against the parent object.
Produce a nullslast() clause against the parent object.
produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
This function can also be used to make bitwise operators explicit. For example:
somecolumn.op('&')(0xff)
is a bitwise AND of the value in somecolumn.
| Parameters: |
|
|---|
Return True if this Column references the given column via foreign key.
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.
Return True if the given ColumnElement has a common ancestor to this ColumnElement.
Implement the startwith operator.
In a column context, produces the clause LIKE '<other>%'
Bases: sqlalchemy.schema.SchemaItem
A collection of Table objects and their associated schema constructs.
Holds a collection of Table objects as well as an optional binding to an Engine or Connection. If bound, the Table objects in the collection and their columns may participate in implicit SQL execution.
The Table objects themselves are stored in the metadata.tables dictionary.
The bind property may be assigned to dynamically. A common pattern is to start unbound and then bind later when an engine is available:
metadata = MetaData()
# define tables
Table('mytable', metadata, ...)
# connect to an engine later, perhaps after loading a URL from a
# configuration file
metadata.bind = an_engine
MetaData is a thread-safe object after tables have been explicitly defined or loaded via reflection.
See also:
Describing Databases with MetaData - Introduction to database metadata
Create a new MetaData object.
| Parameters: |
|
|---|
New in version 0.7.4: schema and quote_schema parameters.
Append a DDL event listener to this MetaData.
Deprecated. See DDLEvents.
An Engine or Connection to which this MetaData is bound.
Typically, a Engine is assigned to this attribute so that “implicit execution” may be used, or alternatively as a means of providing engine binding information to an ORM Session object:
engine = create_engine("someurl://")
metadata.bind = engine
See also
Connectionless Execution, Implicit Execution - background on “bound metadata”
Clear all Table objects from this MetaData.
Create all tables stored in this metadata.
Conditional by default, will not attempt to recreate tables already present in the target database.
| Parameters: |
|
|---|
Drop all tables stored in this metadata.
Conditional by default, will not attempt to drop tables not present in the target database.
| Parameters: |
|
|---|
True if this MetaData is bound to an Engine or Connection.
Load all available table definitions from the database.
Automatically creates Table entries in this MetaData for any table available in the database but not yet present in the MetaData. May be called multiple times to pick up tables recently added to the database, however no special action is taken if a table in this MetaData no longer exists in the database.
| Parameters: |
|
|---|
Remove the given Table object from this MetaData.
Returns a list of Table objects sorted in order of foreign key dependency.
The sorting will place Table objects that have dependencies first, before the dependencies themselves, representing the order in which they can be created. To get the order in which the tables would be dropped, use the reversed() Python built-in.
See also
Inspector.sorted_tables()
Bases: sqlalchemy.events.SchemaEventTarget, sqlalchemy.sql.visitors.Visitable
Base class for items that define a database schema.
used to allow SchemaVisitor access
Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.
The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.
Bases: sqlalchemy.schema.SchemaItem, sqlalchemy.sql.expression.TableClause
Represent a table in a database.
e.g.:
mytable = Table("mytable", metadata,
Column('mytable_id', Integer, primary_key=True),
Column('value', String(50))
)
The Table object constructs a unique instance of itself based on its name and optional schema name within the given MetaData object. Calling the Table constructor with the same name and same MetaData argument a second time will return the same Table object - in this way the Table constructor acts as a registry function.
See also:
Describing Databases with MetaData - Introduction to database metadata
Constructor arguments are as follows:
| Parameters: |
|
|---|
Constructor for Table.
This method is a no-op. See the top-level documentation for Table for constructor arguments.
Add a ‘dependency’ for this Table.
This is another Table object which must be created first before this one can, or dropped after this one.
Usually, dependencies between tables are determined via ForeignKey objects. However, for other situations that create dependencies outside of foreign keys (rules, inheriting), this method can manually establish such a link.
return an alias of this FromClause.
This is shorthand for calling:
from sqlalchemy import alias
a = alias(self, name=name)
See alias() for details.
Append a Column to this Table.
The “key” of the newly added Column, i.e. the value of its .key attribute, will then be available in the .c collection of this Table, and the column definition will be included in any CREATE TABLE, SELECT, UPDATE, etc. statements generated from this Table construct.
Note that this does not change the definition of the table as it exists within any underlying database, assuming that table has already been created in the database. Relational databases support the addition of columns to existing tables using the SQL ALTER command, which would need to be emitted for an already-existing table that doesn’t contain the newly added column.
Append a Constraint to this Table.
This has the effect of the constraint being included in any future CREATE TABLE statement, assuming specific DDL creation events have not been associated with the given Constraint object.
Note that this does not produce the constraint within the relational database automatically, for a table that already exists in the database. To add a constraint to an existing relational database table, the SQL ALTER command must be used. SQLAlchemy also provides the AddConstraint construct which can produce this SQL when invoked as an executable clause.
Append a DDL event listener to this Table.
Deprecated. See DDLEvents.
Return the connectable associated with this Table.
An alias for the columns attribute.
A named-based collection of ColumnElement objects maintained by this FromClause.
The columns, or c collection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
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 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: |
|
|---|
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
Given a ColumnElement, return the exported ColumnElement object from this Selectable which corresponds to that original Column via a common ancestor column.
| Parameters: |
|
|---|
the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this FromClause.
return a SELECT COUNT generated against this TableClause.
Issue a CREATE statement for this Table, using the given Connectable for connectivity.
See also MetaData.create_all().
Generate a delete() construct against this TableClause.
E.g.:
table.delete().where(table.c.id==7)
See delete() for argument and usage information.
alias of DDLEventsDispatch
Issue a DROP statement for this Table, using the given Connectable for connectivity.
See also MetaData.drop_all().
Return True if this table exists.
Return the collection of ForeignKey objects which this FromClause references.
Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.
The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.
Generate an insert() construct against this TableClause.
E.g.:
table.insert().values(name='foo')
See insert() for argument and usage information.
Return True if this FromClause is ‘derived’ from the given FromClause.
An example would be an Alias of a Table is derived from that Table.
return a join of this FromClause against another FromClause.
return an outer join of this FromClause against another FromClause.
Return the collection of Column objects which comprise the primary key of this FromClause.
replace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this FromClause.
return a SELECT of this FromClause.
See also
select() - general purpose method which allows for arbitrary column lists.
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.
Return a copy of this Table associated with a different MetaData.
E.g.:
some_engine = create_engine("sqlite:///some.db")
# create two metadata
meta1 = MetaData()
meta2 = MetaData()
# load 'users' from the sqlite engine
users_table = Table('users', meta1, autoload=True,
autoload_with=some_engine)
# create the same Table object for the plain metadata
users_table_2 = users_table.tometadata(meta2)
| Parameters: |
|---|
Generate an update() construct against this TableClause.
E.g.:
table.update().where(table.c.id==7).values(name='foo')
See update() for argument and usage information.
Bases: sqlalchemy.schema.MetaData
A MetaData variant that presents a different bind in every thread.
Makes the bind property of the MetaData a thread-local value, allowing this collection of tables to be bound to different Engine implementations or connections in each thread.
The ThreadLocalMetaData starts off bound to None in each thread. Binds must be made explicitly by assigning to the bind property or using connect(). You can also re-bind dynamically multiple times per thread, just like a regular MetaData.
Construct a ThreadLocalMetaData.
The bound Engine or Connection for this thread.
This property may be assigned an Engine or Connection, or assigned a string or URL to automatically create a basic Engine for this bind with create_engine().
Dispose all bound engines, in all thread contexts.
True if there is a bind for this thread.
A Table object can be instructed to load information about itself from the corresponding database schema object already existing within the database. This process is called reflection. In the most simple case you need only specify the table name, a MetaData object, and the autoload=True flag. If the MetaData is not persistently bound, also add the autoload_with argument:
>>> messages = Table('messages', meta, autoload=True, autoload_with=engine)
>>> [c.name for c in messages.columns]
['message_id', 'message_name', 'date']
The above operation will use the given engine to query the database for information about the messages table, and will then generate Column, ForeignKey, and other objects corresponding to this information as though the Table object were hand-constructed in Python.
When tables are reflected, if a given table references another one via foreign key, a second Table object is created within the MetaData object representing the connection. Below, assume the table shopping_cart_items references a table named shopping_carts. Reflecting the shopping_cart_items table has the effect such that the shopping_carts table will also be loaded:
>>> shopping_cart_items = Table('shopping_cart_items', meta, autoload=True, autoload_with=engine)
>>> 'shopping_carts' in meta.tables:
True
The MetaData has an interesting “singleton-like” behavior such that if you requested both tables individually, MetaData will ensure that exactly one Table object is created for each distinct table name. The Table constructor actually returns to you the already-existing Table object if one already exists with the given name. Such as below, we can access the already generated shopping_carts table just by naming it:
shopping_carts = Table('shopping_carts', meta)
Of course, it’s a good idea to use autoload=True with the above table regardless. This is so that the table’s attributes will be loaded if they have not been already. The autoload operation only occurs for the table if it hasn’t already been loaded; once loaded, new calls to Table with the same name will not re-issue any reflection queries.
Individual columns can be overridden with explicit values when reflecting tables; this is handy for specifying custom datatypes, constraints such as primary keys that may not be configured within the database, etc.:
>>> mytable = Table('mytable', meta,
... Column('id', Integer, primary_key=True), # override reflected 'id' to have primary key
... Column('mydata', Unicode(50)), # override reflected 'mydata' to be Unicode
... autoload=True)
The reflection system can also reflect views. Basic usage is the same as that of a table:
my_view = Table("some_view", metadata, autoload=True)
Above, my_view is a Table object with Column objects representing the names and types of each column within the view “some_view”.
Usually, it’s desired to have at least a primary key constraint when reflecting a view, if not foreign keys as well. View reflection doesn’t extrapolate these constraints.
Use the “override” technique for this, specifying explicitly those columns which are part of the primary key or have foreign key constraints:
my_view = Table("some_view", metadata,
Column("view_id", Integer, primary_key=True),
Column("related_thing", Integer, ForeignKey("othertable.thing_id")),
autoload=True
)
The MetaData object can also get a listing of tables and reflect the full set. This is achieved by using the reflect() method. After calling it, all located tables are present within the MetaData object’s dictionary of tables:
meta = MetaData()
meta.reflect(bind=someengine)
users_table = meta.tables['users']
addresses_table = meta.tables['addresses']
metadata.reflect() also provides a handy way to clear or delete all the rows in a database:
meta = MetaData()
meta.reflect(bind=someengine)
for table in reversed(meta.sorted_tables):
someengine.execute(table.delete())
A low level interface which provides a backend-agnostic system of loading lists of schema, table, column, and constraint descriptions from a given database is also available. This is known as the “Inspector”:
from sqlalchemy import create_engine
from sqlalchemy.engine import reflection
engine = create_engine('...')
insp = reflection.Inspector.from_engine(engine)
print insp.get_table_names()
Bases: object
Performs database schema inspection.
The Inspector acts as a proxy to the reflection methods of the Dialect, providing a consistent interface as well as caching support for previously fetched metadata.
A Inspector object is usually created via the inspect() function:
from sqlalchemy import inspect, create_engine
engine = create_engine('...')
insp = inspect(engine)
The inspection method above is equivalent to using the Inspector.from_engine() method, i.e.:
engine = create_engine('...')
insp = Inspector.from_engine(engine)
Where above, the Dialect may opt to return an Inspector subclass that provides additional methods specific to the dialect’s target database.
Initialize a new Inspector.
| Parameters: | bind – a Connectable, which is typically an instance of Engine or Connection. |
|---|
For a dialect-specific instance of Inspector, see Inspector.from_engine()
Return the default schema name presented by the dialect for the current engine’s database user.
E.g. this is typically public for Postgresql and dbo for SQL Server.
Construct a new dialect-specific Inspector object from the given engine or connection.
| Parameters: | bind – a Connectable, which is typically an instance of Engine or Connection. |
|---|
This method differs from direct a direct constructor call of Inspector in that the Dialect is given a chance to provide a dialect-specific Inspector instance, which may provide additional methods.
See the example at Inspector.
Return information about columns in table_name.
Given a string table_name and an optional string schema, return column information as a list of dicts with these keys:
Return information about foreign_keys in table_name.
Given a string table_name, and an optional string schema, return foreign key information as a list of dicts with these keys:
Return information about indexes in table_name.
Given a string table_name and an optional string schema, return index information as a list of dicts with these keys:
Return information about primary key constraint on table_name.
Given a string table_name, and an optional string schema, return primary key information as a dictionary with these keys:
Return information about primary keys in table_name.
Deprecated since version 0.7: Call to deprecated method get_primary_keys. Use get_pk_constraint instead.
Given a string table_name, and an optional string schema, return primary key information as a list of column names.
Return all schema names.
Return all table names in referred to within a particular schema.
The names are expected to be real tables only, not views. Views are instead returned using the get_view_names() method.
| Parameters: |
|
|---|
See also
Return a dictionary of options specified when the table of the given name was created.
This currently includes some options that apply to MySQL tables.
Return definition for view_name.
| Parameters: | schema – Optional, retrieve names from a non-default schema. |
|---|
Return all view names in schema.
| Parameters: | schema – Optional, retrieve names from a non-default schema. |
|---|
Given a Table object, load its internal constructs based on introspection.
This is the underlying method used by most dialects to produce table reflection. Direct usage is like:
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.engine import reflection
engine = create_engine('...')
meta = MetaData()
user_table = Table('user', meta)
insp = Inspector.from_engine(engine)
insp.reflecttable(user_table, None)
| Parameters: |
|
|---|
SQLAlchemy provides a very rich featureset regarding column level events which take place during INSERT and UPDATE statements. Options include:
The general rule for all insert/update defaults is that they only take effect if no value for a particular column is passed as an execute() parameter; otherwise, the given value is used.
The simplest kind of default is a scalar value used as the default value of a column:
Table("mytable", meta,
Column("somecolumn", Integer, default=12)
)
Above, the value “12” will be bound as the column value during an INSERT if no other value is supplied.
A scalar value may also be associated with an UPDATE statement, though this is not very common (as UPDATE statements are usually looking for dynamic defaults):
Table("mytable", meta,
Column("somecolumn", Integer, onupdate=25)
)
The default and onupdate keyword arguments also accept Python functions. These functions are invoked at the time of insert or update if no other value for that column is supplied, and the value returned is used for the column’s value. Below illustrates a crude “sequence” that assigns an incrementing counter to a primary key column:
# a function which counts upwards
i = 0
def mydefault():
global i
i += 1
return i
t = Table("mytable", meta,
Column('id', Integer, primary_key=True, default=mydefault),
)
It should be noted that for real “incrementing sequence” behavior, the built-in capabilities of the database should normally be used, which may include sequence objects or other autoincrementing capabilities. For primary key columns, SQLAlchemy will in most cases use these capabilities automatically. See the API documentation for Column including the autoincrement flag, as well as the section on Sequence later in this chapter for background on standard primary key generation techniques.
To illustrate onupdate, we assign the Python datetime function now to the onupdate attribute:
import datetime
t = Table("mytable", meta,
Column('id', Integer, primary_key=True),
# define 'last_updated' to be populated with datetime.now()
Column('last_updated', DateTime, onupdate=datetime.datetime.now),
)
When an update statement executes and no value is passed for last_updated, the datetime.datetime.now() Python function is executed and its return value used as the value for last_updated. Notice that we provide now as the function itself without calling it (i.e. there are no parenthesis following) - SQLAlchemy will execute the function at the time the statement executes.
The Python functions used by default and onupdate may also make use of the current statement’s context in order to determine a value. The context of a statement is an internal SQLAlchemy object which contains all information about the statement being executed, including its source expression, the parameters associated with it and the cursor. The typical use case for this context with regards to default generation is to have access to the other values being inserted or updated on the row. To access the context, provide a function that accepts a single context argument:
def mydefault(context):
return context.current_parameters['counter'] + 12
t = Table('mytable', meta,
Column('counter', Integer),
Column('counter_plus_twelve', Integer, default=mydefault, onupdate=mydefault)
)
Above we illustrate a default function which will execute for all INSERT and UPDATE statements where a value for counter_plus_twelve was otherwise not provided, and the value will be that of whatever value is present in the execution for the counter column, plus the number 12.
While the context object passed to the default function has many attributes, the current_parameters member is a special member provided only during the execution of a default function for the purposes of deriving defaults from its existing values. For a single statement that is executing many sets of bind parameters, the user-defined function is called for each set of parameters, and current_parameters will be provided with each individual parameter set for each execution.
The “default” and “onupdate” keywords may also be passed SQL expressions, including select statements or direct function calls:
t = Table("mytable", meta,
Column('id', Integer, primary_key=True),
# define 'create_date' to default to now()
Column('create_date', DateTime, default=func.now()),
# define 'key' to pull its default from the 'keyvalues' table
Column('key', String(20), default=keyvalues.select(keyvalues.c.type='type1', limit=1)),
# define 'last_modified' to use the current_timestamp SQL function on update
Column('last_modified', DateTime, onupdate=func.utc_timestamp())
)
Above, the create_date column will be populated with the result of the now() SQL function (which, depending on backend, compiles into NOW() or CURRENT_TIMESTAMP in most cases) during an INSERT statement, and the key column with the result of a SELECT subquery from another table. The last_modified column will be populated with the value of UTC_TIMESTAMP(), a function specific to MySQL, when an UPDATE statement is emitted for this table.
Note that when using func functions, unlike when using Python datetime functions we do call the function, i.e. with parenthesis “()” - this is because what we want in this case is the return value of the function, which is the SQL expression construct that will be rendered into the INSERT or UPDATE statement.
The above SQL functions are usually executed “inline” with the INSERT or UPDATE statement being executed, meaning, a single statement is executed which embeds the given expressions or subqueries within the VALUES or SET clause of the statement. Although in some cases, the function is “pre-executed” in a SELECT statement of its own beforehand. This happens when all of the following is true:
Whether or not the default generation clause “pre-executes” is not something that normally needs to be considered, unless it is being addressed for performance reasons.
When the statement is executed with a single set of parameters (that is, it is not an “executemany” style execution), the returned ResultProxy will contain a collection accessible via result.postfetch_cols() which contains a list of all Column objects which had an inline-executed default. Similarly, all parameters which were bound to the statement, including all Python and SQL expressions which were pre-executed, are present in the last_inserted_params() or last_updated_params() collections on ResultProxy. The inserted_primary_key collection contains a list of primary key values for the row inserted (a list so that single-column and composite-column primary keys are represented in the same format).
A variant on the SQL expression default is the server_default, which gets placed in the CREATE TABLE statement during a create() operation:
t = Table('test', meta,
Column('abc', String(20), server_default='abc'),
Column('created_at', DateTime, server_default=text("sysdate"))
)
A create call for the above table will produce:
CREATE TABLE test (
abc varchar(20) default 'abc',
created_at datetime default sysdate
)
The behavior of server_default is similar to that of a regular SQL default; if it’s placed on a primary key column for a database which doesn’t have a way to “postfetch” the ID, and the statement is not “inlined”, the SQL expression is pre-executed; otherwise, SQLAlchemy lets the default fire off on the database side normally.
Columns with values set by a database trigger or other external process may be called out using FetchedValue as a marker:
t = Table('test', meta,
Column('abc', String(20), server_default=FetchedValue()),
Column('def', String(20), server_onupdate=FetchedValue())
)
Changed in version 0.8.0b2,0.7.10: The for_update argument on FetchedValue is set automatically when specified as the server_onupdate argument. If using an older version, specify the onupdate above as server_onupdate=FetchedValue(for_update=True).
These markers do not emit a “default” clause when the table is created, however they do set the same internal flags as a static server_default clause, providing hints to higher-level tools that a “post-fetch” of these rows should be performed after an insert or update.
Note
It’s generally not appropriate to use FetchedValue in conjunction with a primary key column, particularly when using the ORM or any other scenario where the ResultProxy.inserted_primary_key attribute is required. This is becaue the “post-fetch” operation requires that the primary key value already be available, so that the row can be selected on its primary key.
For a server-generated primary key value, all databases provide special accessors or other techniques in order to acquire the “last inserted primary key” column of a table. These mechanisms aren’t affected by the presence of FetchedValue. For special situations where triggers are used to generate primary key values, and the database in use does not support the RETURNING clause, it may be necessary to forego the usage of the trigger and instead apply the SQL expression or function as a “pre execute” expression:
t = Table('test', meta,
Column('abc', MyType, default=func.generate_new_value(), primary_key=True)
)
Where above, when Table.insert() is used, the func.generate_new_value() expression will be pre-executed in the context of a scalar SELECT statement, and the new value will be applied to the subsequent INSERT, while at the same time being made available to the ResultProxy.inserted_primary_key attribute.
SQLAlchemy represents database sequences using the Sequence object, which is considered to be a special case of “column default”. It only has an effect on databases which have explicit support for sequences, which currently includes Postgresql, Oracle, and Firebird. The Sequence object is otherwise ignored.
The Sequence may be placed on any column as a “default” generator to be used during INSERT operations, and can also be configured to fire off during UPDATE operations if desired. It is most commonly used in conjunction with a single integer primary key column:
table = Table("cartitems", meta,
Column("cart_id", Integer, Sequence('cart_id_seq'), primary_key=True),
Column("description", String(40)),
Column("createdate", DateTime())
)
Where above, the table “cartitems” is associated with a sequence named “cart_id_seq”. When INSERT statements take place for “cartitems”, and no value is passed for the “cart_id” column, the “cart_id_seq” sequence will be used to generate a value.
When the Sequence is associated with a table, CREATE and DROP statements issued for that table will also issue CREATE/DROP for the sequence object as well, thus “bundling” the sequence object with its parent table.
The Sequence object also implements special functionality to accommodate Postgresql’s SERIAL datatype. The SERIAL type in PG automatically generates a sequence that is used implicitly during inserts. This means that if a Table object defines a Sequence on its primary key column so that it works with Oracle and Firebird, the Sequence would get in the way of the “implicit” sequence that PG would normally use. For this use case, add the flag optional=True to the Sequence object - this indicates that the Sequence should only be used if the database provides no other option for generating primary key identifiers.
The Sequence object also has the ability to be executed standalone like a SQL expression, which has the effect of calling its “next value” function:
seq = Sequence('some_sequence')
nextid = connection.execute(seq)
Bases: sqlalchemy.schema.DefaultGenerator
A plain default value on a column.
This could correspond to a constant, a callable function, or a SQL clause.
ColumnDefault is generated automatically whenever the default, onupdate arguments of Column are used. A ColumnDefault can be passed positionally as well.
For example, the following:
Column('foo', Integer, default=50)
Is equivalent to:
Column('foo', Integer, ColumnDefault(50))
Bases: sqlalchemy.schema.FetchedValue
A DDL-specified DEFAULT column value.
DefaultClause is a FetchedValue that also generates a “DEFAULT” clause when “CREATE TABLE” is emitted.
DefaultClause is generated automatically whenever the server_default, server_onupdate arguments of Column are used. A DefaultClause can be passed positionally as well.
For example, the following:
Column('foo', Integer, server_default="50")
Is equivalent to:
Column('foo', Integer, DefaultClause("50"))
Bases: sqlalchemy.schema._NotAColumnExpr, sqlalchemy.schema.SchemaItem
Base class for column default values.
Bases: sqlalchemy.schema._NotAColumnExpr, sqlalchemy.events.SchemaEventTarget
A marker for a transparent database-side default.
Use FetchedValue when the database is configured to provide some automatic default for a column.
E.g.:
Column('foo', Integer, FetchedValue())
Would indicate that some trigger or default generator will create a new value for the foo column during an INSERT.
See also
Bases: sqlalchemy.schema.DefaultClause
A DDL-specified DEFAULT column value.
Deprecated since version 0.6: PassiveDefault is deprecated. Use DefaultClause.
Bases: sqlalchemy.schema.DefaultGenerator
Represents a named database sequence.
The Sequence object represents the name and configurational parameters of a database sequence. It also represents a construct that can be “executed” by a SQLAlchemy Engine or Connection, rendering the appropriate “next value” function for the target database and returning a result.
The Sequence is typically associated with a primary key column:
some_table = Table('some_table', metadata,
Column('id', Integer, Sequence('some_table_seq'), primary_key=True)
)
When CREATE TABLE is emitted for the above Table, if the target platform supports sequences, a CREATE SEQUENCE statement will be emitted as well. For platforms that don’t support sequences, the Sequence construct is ignored.
See also: CreateSequence DropSequence
Construct a Sequence object.
| Parameters: |
|
|---|
Creates this sequence in the database.
Drops this sequence from the database.
Return a next_value function element which will render the appropriate increment function for this Sequence within any SQL expression.
A foreign key in SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table. We call the columns which are constrained the foreign key columns and the columns which they are constrained towards the referenced columns. The referenced columns almost always define the primary key for their owning table, though there are exceptions to this. The foreign key is the “joint” that connects together pairs of rows which have a relationship with each other, and SQLAlchemy assigns very deep importance to this concept in virtually every area of its operation.
In SQLAlchemy as well as in DDL, foreign key constraints can be defined as additional attributes within the table clause, or for single-column foreign keys they may optionally be specified within the definition of a single column. The single column foreign key is more common, and at the column level is specified by constructing a ForeignKey object as an argument to a Column object:
user_preference = Table('user_preference', metadata,
Column('pref_id', Integer, primary_key=True),
Column('user_id', Integer, ForeignKey("user.user_id"), nullable=False),
Column('pref_name', String(40), nullable=False),
Column('pref_value', String(100))
)
Above, we define a new table user_preference for which each row must contain a value in the user_id column that also exists in the user table’s user_id column.
The argument to ForeignKey is most commonly a string of the form <tablename>.<columnname>, or for a table in a remote schema or “owner” of the form <schemaname>.<tablename>.<columnname>. It may also be an actual Column object, which as we’ll see later is accessed from an existing Table object via its c collection:
ForeignKey(user.c.user_id)
The advantage to using a string is that the in-python linkage between user and user_preference is resolved only when first needed, so that table objects can be easily spread across multiple modules and defined in any order.
Foreign keys may also be defined at the table level, using the ForeignKeyConstraint object. This object can describe a single- or multi-column foreign key. A multi-column foreign key is known as a composite foreign key, and almost always references a table that has a composite primary key. Below we define a table invoice which has a composite primary key:
invoice = Table('invoice', metadata,
Column('invoice_id', Integer, primary_key=True),
Column('ref_num', Integer, primary_key=True),
Column('description', String(60), nullable=False)
)
And then a table invoice_item with a composite foreign key referencing invoice:
invoice_item = Table('invoice_item', metadata,
Column('item_id', Integer, primary_key=True),
Column('item_name', String(60), nullable=False),
Column('invoice_id', Integer, nullable=False),
Column('ref_num', Integer, nullable=False),
ForeignKeyConstraint(['invoice_id', 'ref_num'], ['invoice.invoice_id', 'invoice.ref_num'])
)
It’s important to note that the ForeignKeyConstraint is the only way to define a composite foreign key. While we could also have placed individual ForeignKey objects on both the invoice_item.invoice_id and invoice_item.ref_num columns, SQLAlchemy would not be aware that these two values should be paired together - it would be two individual foreign key constraints instead of a single composite foreign key referencing two columns.
In all the above examples, the ForeignKey object causes the “REFERENCES” keyword to be added inline to a column definition within a “CREATE TABLE” statement when create_all() is issued, and ForeignKeyConstraint invokes the “CONSTRAINT” keyword inline with “CREATE TABLE”. There are some cases where this is undesireable, particularly when two tables reference each other mutually, each with a foreign key referencing the other. In such a situation at least one of the foreign key constraints must be generated after both tables have been built. To support such a scheme, ForeignKey and ForeignKeyConstraint offer the flag use_alter=True. When using this flag, the constraint will be generated using a definition similar to “ALTER TABLE <tablename> ADD CONSTRAINT <name> ...”. Since a name is required, the name attribute must also be specified. For example:
node = Table('node', meta,
Column('node_id', Integer, primary_key=True),
Column('primary_element', Integer,
ForeignKey('element.element_id', use_alter=True, name='fk_node_element_id')
)
)
element = Table('element', meta,
Column('element_id', Integer, primary_key=True),
Column('parent_node_id', Integer),
ForeignKeyConstraint(
['parent_node_id'],
['node.node_id'],
use_alter=True,
name='fk_element_parent_node_id'
)
)
Most databases support cascading of foreign key values, that is the when a parent row is updated the new value is placed in child rows, or when the parent row is deleted all corresponding child rows are set to null or deleted. In data definition language these are specified using phrases like “ON UPDATE CASCADE”, “ON DELETE CASCADE”, and “ON DELETE SET NULL”, corresponding to foreign key constraints. The phrase after “ON UPDATE” or “ON DELETE” may also other allow other phrases that are specific to the database in use. The ForeignKey and ForeignKeyConstraint objects support the generation of this clause via the onupdate and ondelete keyword arguments. The value is any string which will be output after the appropriate “ON UPDATE” or “ON DELETE” phrase:
child = Table('child', meta,
Column('id', Integer,
ForeignKey('parent.id', onupdate="CASCADE", ondelete="CASCADE"),
primary_key=True
)
)
composite = Table('composite', meta,
Column('id', Integer, primary_key=True),
Column('rev_id', Integer),
Column('note_id', Integer),
ForeignKeyConstraint(
['rev_id', 'note_id'],
['revisions.id', 'revisions.note_id'],
onupdate="CASCADE", ondelete="SET NULL"
)
)
Note that these clauses are not supported on SQLite, and require InnoDB tables when used with MySQL. They may also not be supported on other databases.
Unique constraints can be created anonymously on a single column using the unique keyword on Column. Explicitly named unique constraints and/or those with multiple columns are created via the UniqueConstraint table-level construct.
meta = MetaData()
mytable = Table('mytable', meta,
# per-column anonymous unique constraint
Column('col1', Integer, unique=True),
Column('col2', Integer),
Column('col3', Integer),
# explicit/composite unique constraint. 'name' is optional.
UniqueConstraint('col2', 'col3', name='uix_1')
)
Check constraints can be named or unnamed and can be created at the Column or Table level, using the CheckConstraint construct. The text of the check constraint is passed directly through to the database, so there is limited “database independent” behavior. Column level check constraints generally should only refer to the column to which they are placed, while table level constraints can refer to any columns in the table.
Note that some databases do not actively support check constraints such as MySQL.
meta = MetaData()
mytable = Table('mytable', meta,
# per-column CHECK constraint
Column('col1', Integer, CheckConstraint('col1>5')),
Column('col2', Integer),
Column('col3', Integer),
# table level CHECK constraint. 'name' is optional.
CheckConstraint('col2 > col3 + 5', name='check1')
)
sqlmytable.create(engine)
CREATE TABLE mytable (
col1 INTEGER CHECK (col1>5),
col2 INTEGER,
col3 INTEGER,
CONSTRAINT check1 CHECK (col2 > col3 + 5)
)
The Table is the SQLAlchemy Core construct that allows one to define table metadata, which among other things can be used by the SQLAlchemy ORM as a target to map a class. The Declarative extension allows the Table object to be created automatically, given the contents of the table primarily as a mapping of Column objects.
To apply table-level constraint objects such as ForeignKeyConstraint to a table defined using Declarative, use the __table_args__ attribute, described at Table Configuration.
Bases: sqlalchemy.schema.SchemaItem
A table-level SQL constraint.
Bases: sqlalchemy.schema.Constraint
A table- or column-level CHECK constraint.
Can be included in the definition of a Table or Column.
Bases: sqlalchemy.schema.ColumnCollectionMixin, sqlalchemy.schema.Constraint
A constraint that proxies a ColumnCollection.
Bases: sqlalchemy.schema.SchemaItem
Defines a dependency between two columns.
ForeignKey is specified as an argument to a Column object, e.g.:
t = Table("remote_table", metadata,
Column("remote_id", ForeignKey("main_table.id"))
)
Note that ForeignKey is only a marker object that defines a dependency between two columns. The actual constraint is in all cases represented by the ForeignKeyConstraint object. This object will be generated automatically when a ForeignKey is associated with a Column which in turn is associated with a Table. Conversely, when ForeignKeyConstraint is applied to a Table, ForeignKey markers are automatically generated to be present on each associated Column, which are also associated with the constraint object.
Note that you cannot define a “composite” foreign key constraint, that is a constraint between a grouping of multiple parent/child columns, using ForeignKey objects. To define this grouping, the ForeignKeyConstraint object must be used, and applied to the Table. The associated ForeignKey objects are created automatically.
The ForeignKey objects associated with an individual Column object are available in the foreign_keys collection of that column.
Further examples of foreign key configuration are in Defining Foreign Keys.
Construct a column-level FOREIGN KEY.
The ForeignKey object when constructed generates a ForeignKeyConstraint which is associated with the parent Table object’s collection of constraints.
| Parameters: |
|
|---|
Return the target Column referenced by this ForeignKey.
If this ForeignKey was created using a string-based target column specification, this attribute will on first access initiate a resolution process to locate the referenced remote Column. The resolution process traverses to the parent Column, Table, and MetaData to proceed - if any of these aren’t yet present, an error is raised.
Produce a copy of this ForeignKey object.
The new ForeignKey will not be bound to any Column.
This method is usually used by the internal copy procedures of Column, Table, and MetaData.
| Parameters: | schema – The returned ForeignKey will reference the original table and column name, qualified by the given string schema name. |
|---|
Return the Column in the given Table referenced by this ForeignKey.
Returns None if this ForeignKey does not reference the given Table.
Return True if the given Table is referenced by this ForeignKey.
Return a string based ‘column specification’ for this ForeignKey.
This is usually the equivalent of the string-based “tablename.colname” argument first passed to the object’s constructor.
Bases: sqlalchemy.schema.Constraint
A table-level FOREIGN KEY constraint.
Defines a single column or composite FOREIGN KEY ... REFERENCES constraint. For a no-frills, single column foreign key, adding a ForeignKey to the definition of a Column is a shorthand equivalent for an unnamed, single column ForeignKeyConstraint.
Examples of foreign key configuration are in Defining Foreign Keys.
Construct a composite-capable FOREIGN KEY.
| Parameters: |
|
|---|
Bases: sqlalchemy.schema.ColumnCollectionConstraint
A table-level PRIMARY KEY constraint.
Defines a single column or composite PRIMARY KEY constraint. For a no-frills primary key, adding primary_key=True to one or more Column definitions is a shorthand equivalent for an unnamed single- or multiple-column PrimaryKeyConstraint.
Bases: sqlalchemy.schema.ColumnCollectionConstraint
A table-level UNIQUE constraint.
Defines a single column or composite UNIQUE constraint. For a no-frills, single column constraint, adding unique=True to the Column definition is a shorthand equivalent for an unnamed, single column UniqueConstraint.
Indexes can be created anonymously (using an auto-generated name ix_<column label>) for a single column using the inline index keyword on Column, which also modifies the usage of unique to apply the uniqueness to the index itself, instead of adding a separate UNIQUE constraint. For indexes with specific names or which encompass more than one column, use the Index construct, which requires a name.
Below we illustrate a Table with several Index objects associated. The DDL for “CREATE INDEX” is issued right after the create statements for the table:
meta = MetaData()
mytable = Table('mytable', meta,
# an indexed column, with index "ix_mytable_col1"
Column('col1', Integer, index=True),
# a uniquely indexed column with index "ix_mytable_col2"
Column('col2', Integer, index=True, unique=True),
Column('col3', Integer),
Column('col4', Integer),
Column('col5', Integer),
Column('col6', Integer),
)
# place an index on col3, col4
Index('idx_col34', mytable.c.col3, mytable.c.col4)
# place a unique index on col5, col6
Index('myindex', mytable.c.col5, mytable.c.col6, unique=True)
sqlmytable.create(engine)
CREATE TABLE mytable (
col1 INTEGER,
col2 INTEGER,
col3 INTEGER,
col4 INTEGER,
col5 INTEGER,
col6 INTEGER
)
CREATE INDEX ix_mytable_col1 ON mytable (col1)
CREATE UNIQUE INDEX ix_mytable_col2 ON mytable (col2)
CREATE UNIQUE INDEX myindex ON mytable (col5, col6)
CREATE INDEX idx_col34 ON mytable (col3, col4)
Note in the example above, the Index construct is created externally to the table which it corresponds, using Column objects directly. Index also supports “inline” definition inside the Table, using string names to identify columns:
meta = MetaData()
mytable = Table('mytable', meta,
Column('col1', Integer),
Column('col2', Integer),
Column('col3', Integer),
Column('col4', Integer),
# place an index on col1, col2
Index('idx_col12', 'col1', 'col2'),
# place a unique index on col3, col4
Index('idx_col34', 'col3', 'col4', unique=True)
)
New in version 0.7: Support of “inline” definition inside the Table for Index.
The Index object also supports its own create() method:
i = Index('someindex', mytable.c.col5)
sqli.create(engine)
CREATE INDEX someindex ON mytable (col5)
Index supports SQL and function expressions, as supported by the target backend. To create an index against a column using a descending value, the ColumnElement.desc() modifier may be used:
from sqlalchemy import Index
Index('someindex', mytable.c.somecol.desc())
Or with a backend that supports functional indexes such as Postgresql, a “case insensitive” index can be created using the lower() function:
from sqlalchemy import func, Index
Index('someindex', func.lower(mytable.c.somecol))
New in version 0.8: Index supports SQL expressions and functions as well as plain columns.
Bases: sqlalchemy.schema.ColumnCollectionMixin, sqlalchemy.schema.SchemaItem
A table-level INDEX.
Defines a composite (one or more column) INDEX. For a no-frills, single column index, adding index=True to the Column definition is a shorthand equivalent for an unnamed, single column Index.
See also
Indexes - General information on Index.
Postgresql-Specific Index Options - PostgreSQL-specific options available for the Index construct.
MySQL Specific Index Options - MySQL-specific options available for the Index construct.
MSSQL-Specific Index Options - MSSQL-specific options available for the Index construct.
Construct an index object.
| Parameters: |
|
|---|
Return the connectable associated with this Index.
Issue a CREATE statement for this Index, using the given Connectable for connectivity.
See also MetaData.create_all().
Issue a DROP statement for this Index, using the given Connectable for connectivity.
See also MetaData.drop_all().
In the preceding sections we’ve discussed a variety of schema constructs including Table, ForeignKeyConstraint, CheckConstraint, and Sequence. Throughout, we’ve relied upon the create() and create_all() methods of Table and MetaData in order to issue data definition language (DDL) for all constructs. When issued, a pre-determined order of operations is invoked, and DDL to create each table is created unconditionally including all constraints and other objects associated with it. For more complex scenarios where database-specific DDL is required, SQLAlchemy offers two techniques which can be used to add any DDL based on any condition, either accompanying the standard generation of tables or by itself.
The sqlalchemy.schema package contains SQL expression constructs that provide DDL expressions. For example, to produce a CREATE TABLE statement:
from sqlalchemy.schema import CreateTable
sqlengine.execute(CreateTable(mytable))
CREATE TABLE mytable (
col1 INTEGER,
col2 INTEGER,
col3 INTEGER,
col4 INTEGER,
col5 INTEGER,
col6 INTEGER
)
Above, the CreateTable construct works like any other expression construct (such as select(), table.insert(), etc.). A full reference of available constructs is in DDL Expression Constructs API.
The DDL constructs all extend a common base class which provides the capability to be associated with an individual Table or MetaData object, to be invoked upon create/drop events. Consider the example of a table which contains a CHECK constraint:
users = Table('users', metadata,
Column('user_id', Integer, primary_key=True),
Column('user_name', String(40), nullable=False),
CheckConstraint('length(user_name) >= 8',name="cst_user_name_length")
)
sqlusers.create(engine)
CREATE TABLE users (
user_id SERIAL NOT NULL,
user_name VARCHAR(40) NOT NULL,
PRIMARY KEY (user_id),
CONSTRAINT cst_user_name_length CHECK (length(user_name) >= 8)
)
The above table contains a column “user_name” which is subject to a CHECK constraint that validates that the length of the string is at least eight characters. When a create() is issued for this table, DDL for the CheckConstraint will also be issued inline within the table definition.
The CheckConstraint construct can also be constructed externally and associated with the Table afterwards:
constraint = CheckConstraint('length(user_name) >= 8',name="cst_user_name_length")
users.append_constraint(constraint)
So far, the effect is the same. However, if we create DDL elements corresponding to the creation and removal of this constraint, and associate them with the Table as events, these new events will take over the job of issuing DDL for the constraint. Additionally, the constraint will be added via ALTER:
from sqlalchemy import event
event.listen(
users,
"after_create",
AddConstraint(constraint)
)
event.listen(
users,
"before_drop",
DropConstraint(constraint)
)
sqlusers.create(engine)
CREATE TABLE users (
user_id SERIAL NOT NULL,
user_name VARCHAR(40) NOT NULL,
PRIMARY KEY (user_id)
)
ALTER TABLE users ADD CONSTRAINT cst_user_name_length CHECK (length(user_name) >= 8)
sqlusers.drop(engine)
ALTER TABLE users DROP CONSTRAINT cst_user_name_length
DROP TABLE user
The real usefulness of the above becomes clearer once we illustrate the DDLElement.execute_if() method. This method returns a modified form of the DDL callable which will filter on criteria before responding to a received event. It accepts a parameter dialect, which is the string name of a dialect or a tuple of such, which will limit the execution of the item to just those dialects. It also accepts a callable_ parameter which may reference a Python callable which will be invoked upon event reception, returning True or False indicating if the event should proceed.
If our CheckConstraint was only supported by Postgresql and not other databases, we could limit its usage to just that dialect:
event.listen(
users,
'after_create',
AddConstraint(constraint).execute_if(dialect='postgresql')
)
event.listen(
users,
'before_drop',
DropConstraint(constraint).execute_if(dialect='postgresql')
)
Or to any set of dialects:
event.listen(
users,
"after_create",
AddConstraint(constraint).execute_if(dialect=('postgresql', 'mysql'))
)
event.listen(
users,
"before_drop",
DropConstraint(constraint).execute_if(dialect=('postgresql', 'mysql'))
)
When using a callable, the callable is passed the ddl element, the Table or MetaData object whose “create” or “drop” event is in progress, and the Connection object being used for the operation, as well as additional information as keyword arguments. The callable can perform checks, such as whether or not a given item already exists. Below we define should_create() and should_drop() callables that check for the presence of our named constraint:
def should_create(ddl, target, connection, **kw):
row = connection.execute("select conname from pg_constraint where conname='%s'" % ddl.element.name).scalar()
return not bool(row)
def should_drop(ddl, target, connection, **kw):
return not should_create(ddl, target, connection, **kw)
event.listen(
users,
"after_create",
AddConstraint(constraint).execute_if(callable_=should_create)
)
event.listen(
users,
"before_drop",
DropConstraint(constraint).execute_if(callable_=should_drop)
)
sqlusers.create(engine)
CREATE TABLE users (
user_id SERIAL NOT NULL,
user_name VARCHAR(40) NOT NULL,
PRIMARY KEY (user_id)
)
select conname from pg_constraint where conname='cst_user_name_length'
ALTER TABLE users ADD CONSTRAINT cst_user_name_length CHECK (length(user_name) >= 8)
sqlusers.drop(engine)
select conname from pg_constraint where conname='cst_user_name_length'
ALTER TABLE users DROP CONSTRAINT cst_user_name_length
DROP TABLE user
Custom DDL phrases are most easily achieved using the DDL construct. This construct works like all the other DDL elements except it accepts a string which is the text to be emitted:
event.listen(
metadata,
"after_create",
DDL("ALTER TABLE users ADD CONSTRAINT "
"cst_user_name_length "
" CHECK (length(user_name) >= 8)")
)
A more comprehensive method of creating libraries of DDL constructs is to use custom compilation - see Custom SQL Constructs and Compilation Extension for details.
Bases: sqlalchemy.sql.expression.Executable, sqlalchemy.schema._DDLCompiles
Base class for DDL expression constructs.
This class is the base for the general purpose DDL class, as well as the various create/drop clause constructs such as CreateTable, DropTable, AddConstraint, etc.
DDLElement integrates closely with SQLAlchemy events, introduced in Events. An instance of one is itself an event receiving callable:
event.listen(
users,
'after_create',
AddConstraint(constraint).execute_if(dialect='postgresql')
)
See also:
Execute the DDL as a ddl_listener.
Return a copy of this DDL against a specific schema item.
Execute this DDL immediately.
Executes the DDL statement in isolation using the supplied Connectable or Connectable assigned to the .bind property, if not supplied. If the DDL has a conditional on criteria, it will be invoked with None as the event.
| Parameters: |
|
|---|
Link execution of this DDL to the DDL lifecycle of a SchemaItem.
Deprecated since version 0.7: See DDLEvents, as well as DDLElement.execute_if().
Links this DDLElement to a Table or MetaData instance, executing it when that schema item is created or dropped. The DDL statement will be executed using the same Connection and transactional context as the Table create/drop itself. The .bind property of this statement is ignored.
| Parameters: |
|
|---|
A DDLElement instance can be linked to any number of schema items.
execute_at builds on the append_ddl_listener interface of MetaData and Table objects.
Caveat: Creating or dropping a Table in isolation will also trigger any DDL set to execute_at that Table’s MetaData. This may change in a future release.
Return a callable that will execute this DDLElement conditionally.
Used to provide a wrapper for event listening:
event.listen(
metadata,
'before_create',
DDL("my_ddl").execute_if(dialect='postgresql')
)
| Parameters: |
|
|---|
See also:
Bases: sqlalchemy.schema.DDLElement
A literal DDL statement.
Specifies literal SQL DDL to be executed by the database. DDL objects function as DDL event listeners, and can be subscribed to those events listed in DDLEvents, using either Table or MetaData objects as targets. Basic templating support allows a single DDL instance to handle repetitive tasks for multiple tables.
Examples:
from sqlalchemy import event, DDL
tbl = Table('users', metadata, Column('uid', Integer))
event.listen(tbl, 'before_create', DDL('DROP TRIGGER users_trigger'))
spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE')
event.listen(tbl, 'after_create', spow.execute_if(dialect='somedb'))
drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE')
connection.execute(drop_spow)
When operating on Table events, the following statement string substitions are available:
%(table)s - the Table name, with any required quoting applied
%(schema)s - the schema name, with any required quoting applied
%(fullname)s - the Table name including schema, quoted if needed
The DDL’s “context”, if any, will be combined with the standard substutions noted above. Keys present in the context will override the standard substitutions.
Create a DDL statement.
| Parameters: |
|
|---|
See also:
DDLEvents sqlalchemy.event
Bases: sqlalchemy.schema._CreateDropBase
Represent a CREATE TABLE statement.
Create a CreateTable construct.
| Parameters: |
|---|
Bases: sqlalchemy.schema._CreateDropBase
Represent a DROP TABLE statement.
Bases: sqlalchemy.schema._DDLCompiles
Represent a Column as rendered in a CREATE TABLE statement, via the CreateTable construct.
This is provided to support custom column DDL within the generation of CREATE TABLE statements, by using the compiler extension documented in Custom SQL Constructs and Compilation Extension to extend CreateColumn.
Typical integration is to examine the incoming Column object, and to redirect compilation if a particular flag or condition is found:
from sqlalchemy import schema
from sqlalchemy.ext.compiler import compiles
@compiles(schema.CreateColumn)
def compile(element, compiler, **kw):
column = element.element
if "special" not in column.info:
return compiler.visit_create_column(element, **kw)
text = "%s SPECIAL DIRECTIVE %s" % (
column.name,
compiler.type_compiler.process(column.type)
)
default = compiler.get_column_default_string(column)
if default is not None:
text += " DEFAULT " + default
if not column.nullable:
text += " NOT NULL"
if column.constraints:
text += " ".join(
compiler.process(const)
for const in column.constraints)
return text
The above construct can be applied to a Table as follows:
from sqlalchemy import Table, Metadata, Column, Integer, String
from sqlalchemy import schema
metadata = MetaData()
table = Table('mytable', MetaData(),
Column('x', Integer, info={"special":True}, primary_key=True),
Column('y', String(50)),
Column('z', String(20), info={"special":True})
)
metadata.create_all(conn)
Above, the directives we’ve added to the Column.info collection will be detected by our custom compilation scheme:
CREATE TABLE mytable (
x SPECIAL DIRECTIVE INTEGER NOT NULL,
y VARCHAR(50),
z SPECIAL DIRECTIVE VARCHAR(20),
PRIMARY KEY (x)
)
New in version 0.8: The CreateColumn construct was added to support custom column creation styles.
Bases: sqlalchemy.schema._CreateDropBase
Represent a CREATE SEQUENCE statement.
Bases: sqlalchemy.schema._CreateDropBase
Represent a DROP SEQUENCE statement.
Bases: sqlalchemy.schema._CreateDropBase
Represent a CREATE INDEX statement.
Bases: sqlalchemy.schema._CreateDropBase
Represent a DROP INDEX statement.
Bases: sqlalchemy.schema._CreateDropBase
Represent an ALTER TABLE ADD CONSTRAINT statement.
Bases: sqlalchemy.schema._CreateDropBase
Represent an ALTER TABLE DROP CONSTRAINT statement.
Bases: sqlalchemy.schema._CreateDropBase
Represent a CREATE SCHEMA statement.
New in version 0.7.4.
The argument here is the string name of the schema.
Create a new CreateSchema construct.
Bases: sqlalchemy.schema._CreateDropBase
Represent a DROP SCHEMA statement.
The argument here is the string name of the schema.
New in version 0.7.4.
Create a new DropSchema construct.


Secured All India Rank 162 (out of 472,000 students) in IIT JEE (Indian Institute of Technology - Joint Entrance Examination) 2010.
Secured All India Rank 189 (out of 1 million students) in AIEEE (All India Engineering Entrance Examination) 2010.
Cleared Regional Maths Olympiad (RMO) to qualify for INMO (Indian National Mathematics Olympaid) 2010.
Certificate of merit for being in Nationwise Top 1% in NSEP (National Standard Examination in Physics) in November 2009.
Certificate of merit for being in Nationwise Top 1% in NSEA (National Standard Examination in Astronomy) in November 2007.
Selected for Orientation Cum Selection Camp (OCSC) for International Astronomy Olympiad 2008.
Secured AIR 6 in IMO (International Mathematics Olympiad) 2008 conducted by SOF (Science Olympiad Foundation).
Secured AIR 88 in NSO (National Science Olympaid) 2007 conducted by SOF (Science Olympiad Foundation).
Secured AIR 95 in NSTSE (National Level Science Talent Search Examination) 2008 conducted by Unified Council.


Device Abstraction layer header for USB MUSB device contoller driver. More...
Data Structures | |
| struct | usbMusbDcdDevice |
| Musb device object used by the MUSB driver. More... | |
Macros | |
| #define | USB_MAX_INTERFACES_PER_DEVICE 8 |
Typedefs | |
| typedef enum usbMusbDcdEp0State | tEP0State |
| This enum contains the possible values of state of endpoint 0. | |
| typedef struct usbMusbDcdDevice | usbMusbDcdDevice_t |
| Musb device object used by the MUSB driver. | |
Enumerations | |
| enum | usbMusbDcdEp0State |
| This enum contains the possible values of state of endpoint 0. | |
Functions | |
| uint32_t | USBMusbDcdInit (usbDcd_t *pDcdObject) |
| USB MUSB device controller driver core init API. More... | |
| uint32_t | USBMusbDcdIntrHandler (usbMusbDcdDevice_t *MUSB) |
| USB MUSB device interrupt handler. This will get all the device and endpoint events for all the endpoints. More... | |
| uint32_t | USBMusbDcdConfigDevChara (usbDcd_t *pDcdObject, usbDevChara_t *pDevCharacteristic) |
| This API sets the device characteristics. More... | |
| uint32_t | USBMusbDcdEp0Req (usbDcd_t *pDcdObject, usbEndpt0Request_t *req) |
| Endpoint 0 request for control endpoint. More... | |
| uint32_t | USBMusbDcdEpReq (usbDcd_t *pDcdObject, usbEndptRequest_t *req) |
| Endpoint request for control bulk and isoch transfers for all endpoints other than endpoint 0. More... | |
| void | usbMusbDcdEnableWrapperIntr (uint32_t baseAddr) |
| Enable all the wrapper interrupts. More... | |
Device Abstraction layer header for USB MUSB device contoller driver.
| #define USB_MAX_INTERFACES_PER_DEVICE 8 |
The maximum number of independent interfaces that any single device
implementation can support. Independent interfaces means interface
descriptors with different bInterfaceNumber values - several interface
descriptors offering different alternative settings but the same interface
number count as a single interface.
| uint32_t USBMusbDcdConfigDevChara | ( | usbDcd_t * | pDcdObject, |
| usbDevChara_t * | pDevCharacteristic | ||
| ) |
This API sets the device characteristics.
| pDcdObject | pointer to the USB device control object. |
| pDevCharacteristic | pointer to the device characteristics structure. |
| void usbMusbDcdEnableWrapperIntr | ( | uint32_t | baseAddr | ) |
Enable all the wrapper interrupts.
| baseAddr | Baseaddress of USB wrapper register |
| uint32_t USBMusbDcdEp0Req | ( | usbDcd_t * | pDcdObject, |
| usbEndpt0Request_t * | req | ||
| ) |
Endpoint 0 request for control endpoint.
| pDcdObject | pointer to the USB device control object. |
| req | USB request which needs to be handled for endpoint 0 |
| uint32_t USBMusbDcdEpReq | ( | usbDcd_t * | pDcdObject, |
| usbEndptRequest_t * | req | ||
| ) |
Endpoint request for control bulk and isoch transfers for all endpoints other than endpoint 0.
| pDcdObject | pointer to the USB device control object. |
| req | USB request which needs to be handled for endpoint other than endpoint 0. |
| uint32_t USBMusbDcdInit | ( | usbDcd_t * | pDcdObject | ) |
USB MUSB device controller driver core init API.
| pDcdObject | pointer to the USB device control driver object |
| uint32_t USBMusbDcdIntrHandler | ( | usbMusbDcdDevice_t * | MUSB | ) |
USB MUSB device interrupt handler. This will get all the device and endpoint events for all the endpoints.
| MUSB | pointer to the MUSB object |


Third update before MECSPE 2017, where we will be thanks to Confartigianato Padova. In this video Marco Pietrangelo, technical manager of combustion division, explains us what happens behind the team scenes during the single-seater production.
Enjoy!


--- title: "Timer" layout: project project-url: https://github.com/connyr/ios-projects/tree/master/Numbers/AlarmClock icon: icons_stopwatch.svg bgcolor: bgcolor-jade-green categories: - project tags: - ios - objc - games ---
Countdown timer and stopwatch similar to apple's included clock app.
Timer uses the UIDatePicker to set up the alarm time and counts down until it reaches zero. It also continues counting (for some time) when the app enters the background and uses a UILocalNotification to alert the user when the time has run out and plays a sound.
Stopwatch can recored lap times, and the usual play, pause, resume and reset functionalities. It also continues running for some time, after the app enters the background.


Create Custom Polls with Live Results!
Live graph shows your poll results immediately in an easy to understand format.
One graph will not provide whole picture thats why we provide multiple graph types.
This polling app works on tablets, smart-phones, noteboks and net books along with traditional desktops.
Our responsive designs take care of that.
Easy to integrate with social sites such as Github.
Sharing is also made easier.


{{ object }}
Original Paste
Posted {{ object.created|date }} ({{ object.created|timesince }} ago)
{{ object.paste }}
As WKT
As Extended WKT
As GeoJSON
As KML
Other formats
We were unable to parse this paste as WKT, EWKT, GeoJSON or KML.
Posted {{ object.created|date }} ({{ object.created|timesince }} ago)
{{ object.paste }}
We were unable to parse this paste as WKT, EWKT, GeoJSON or KML.


House Frey of the Twins is the former Great House of the Riverlands, having gained their position for their treachery against their former liege lords, House Tully, who were stripped of all their lands and titles for their rebellion against the Iron Throne; House Tully had supported the independence movement for the Kingdom of the North. The current head of the house is unknown following the assassinations of Lord Walder Frey and two of his sons, Lothar Frey and Walder Rivers, by the vengeful Arya Stark. This is made more complex by the subsequent assassination of all male Freys soon after. After the defeat of Cersei Lannister, Edmure Tully took back his title of Lord of the Riverlands and Riverrun became the Great House of the Riverlands again.
Their ancestral seat is known as the Twins for its two identical keeps on both sides of a river linked by a bridge, sometimes called the Stone Bridge. The Twins is one of the primary crossings over the Green Fork of the Trident River, and tolls from bridge crossings have made the Freys quite wealthy fairly quickly, elevating them from obscurity six centuries ago to being one of the most powerful noble houses in the Riverlands - though they are looked down upon by older aristocratic families. The construction of the Twins took the Freys for three centuries, and ever since they have grown wealthy by charging the travelers crossing the Twins.
The heraldry of House Frey represents their castle-seat of the Twins: it consists of two grey towers linked by a bridge, on a darker grey background, over an escutcheon of blue water.[1] Their house words are "We Stand Together," ironic considering the Freys' frequent infighting between family members[2], but it could also refer to their seat, the Twins, standing together.
House Frey was a noble house in the Riverlands that had emerged about six hundred years before the War of the Five Kings. Their seat is at The Twins, a castle consisting of two identical towers and a bridge intersecting the Green Fork of The Trident river. The Freys grew rich from exacting tolls on travelers crossing the Green Fork. For most of their history, the Freys have been vassals of House Tully, the paramount lords of the Trident since the Targaryen conquest. During Robert's Rebellion, Lord Walder Frey was late in marshaling forces to assist the forces of his liege lord Hoster Tully during the Battle of the Trident. For this insolence, Lord Hoster mockingly referred to Lord Frey as the "Late Walder Frey"; much to Walder's chagrin.[3]


SMConfiguration Class Reference
| Inherits from | NSObject |
|---|---|
| Declared in | SMConfiguration.h |
userName
Name value of the user.
@property (nonatomic, strong) NSString *userName
Availability
2.0.0
Discussion
Name value of the user.
Declared In
SMConfiguration.h
authorizationName
“Authorization Name” value of the user. It must be set when username and authorizationName are different Default value is nil
@property (nonatomic, strong) NSString *authorizationName
Availability
4.5.6
Discussion
“Authorization Name” value of the user. It must be set when username and authorizationName are different Default value is nil
Declared In
SMConfiguration.h
password
Password value of the user.
@property (nonatomic, strong) NSString *password
Availability
2.0.0
Discussion
Password value of the user.
Declared In
SMConfiguration.h
restServerPort
server port information of the baseUrl used for REST request.
@property (nonatomic, strong) NSString *restServerPort
Availability
2.0.0
Discussion
server port information of the baseUrl used for REST request.
Default value is 443.
Declared In
SMConfiguration.h
restServerIP
server ip information of the baseUrl used for REST request.
@property (nonatomic, strong) NSString *restServerIP
Availability
2.0.0
Discussion
server ip information of the baseUrl used for REST request.
Declared In
SMConfiguration.h
pushServerURL
Sets the push server URL.
@property (nonatomic, strong) NSURL *pushServerURL
Availability
4.6.0
Discussion
Sets the push server URL.
Declared In
SMConfiguration.h
webSocketServerPort
port information used in web socket connection creation.
@property (nonatomic, strong) NSString *webSocketServerPort
Availability
2.0.0
Discussion
port information used in web socket connection creation.
Default value is 443.
Declared In
SMConfiguration.h
webSocketServerIP
ip information used in web socket connection creation.
@property (nonatomic, strong) NSString *webSocketServerIP
Availability
2.0.0
Discussion
ip information used in web socket connection creation.
Declared In
SMConfiguration.h
webSocketCertificate
Web socket Self signed certificate file data. Can be fetched from a file or string @code NSString *cerPath = [[NSBundle mainBundle\ pathForResource:@“myOwnCertificate” ofType:@“der”\; [[Configuration getInstance] setWebSocketCertificate:[[NSData alloc\ initWithContentsOfFile:cerPath\\; @endcode
@property (nonatomic, strong) NSData *webSocketCertificate
Availability
3.0.3
Discussion
Web socket Self signed certificate file data. Can be fetched from a file or string @code NSString *cerPath = [[NSBundle mainBundle\ pathForResource:@“myOwnCertificate” ofType:@“der”\; [[Configuration getInstance] setWebSocketCertificate:[[NSData alloc\ initWithContentsOfFile:cerPath\\; @endcode
Declared In
SMConfiguration.h
logger
LoggingDelegate reference used by LogManager.
@property (nonatomic, strong) id<SMLoggingDelegate> _Nonnull logger
Availability
2.0.0
Discussion
LoggingDelegate reference used by LogManager.
Declared In
SMConfiguration.h
iceOption
Sets the ice options as ICE_VANILLA or ICE_TRICKLE. Default value is ICE_VANILLA MobileSDK will have same behavior in older versions, if “iceOption” is selected as Vanilla ICE or used default value.
@property (nonatomic) SMICEOptions iceOption
Availability
4.1.0
Discussion
Sets the ice options as ICE_VANILLA or ICE_TRICKLE. Default value is ICE_VANILLA MobileSDK will have same behavior in older versions, if “iceOption” is selected as Vanilla ICE or used default value.
Declared In
SMConfiguration.h
ICEServers
ICEServers stores ICE servers array (including stun & turn).
@property (nonatomic, strong) SMICEServers *ICEServers
Availability
3.0.3
Discussion
ICEServers stores ICE servers array (including stun & turn).
Declared In
SMConfiguration.h
defaultICEUsername
Default username of ICEServers.
@property (nonatomic, strong) NSString *defaultICEUsername
Availability
3.0.3
Discussion
Default username of ICEServers.
Declared In
SMConfiguration.h
defaultICEPassword
Default password of ICEServers.
@property (nonatomic, strong) NSString *defaultICEPassword
Availability
3.0.3
Discussion
Default password of ICEServers.
Declared In
SMConfiguration.h
videoResolution
Sets initial video resolution for video Value should be one of the AVCaptureSessionPreset strings.
If videoResolution value is to nil high resolution (720p) will be used by default.
@property (nonatomic, strong) NSString *videoResolution
Availability
2.0.0 @modified 4.0.2
Declared In
SMConfiguration.h
httpPersistentConnection
Configuration to set HTTP Connection header in rest request Default value is true true for Connection: keep alive false for Connection: close
@property (nonatomic) BOOL httpPersistentConnection
Availability
5.4.0
Discussion
Configuration to set HTTP Connection header in rest request Default value is true true for Connection: keep alive false for Connection: close
Declared In
SMConfiguration.h
subscriptionExpires
Subscription expire time
@property (nonatomic, strong) NSNumber *subscriptionExpires
Availability
2.0.0
Discussion
Subscription expire time
Declared In
SMConfiguration.h
serverCertificate
Server certificate to be used in HTTPS connection.Certificate must be .DER format @code NSString *cerPath = [[NSBundle mainBundle\ pathForResource:@“myOwnCertificate” ofType:@“der”\; [[Configuration getInstance] setWebSocketCertificate:[[NSData alloc\ initWithContentsOfFile:cerPath\\; @endcode
@property (nonatomic, strong) NSData *serverCertificate
Availability
2.0.0
Discussion
Server certificate to be used in HTTPS connection.Certificate must be .DER format @code NSString *cerPath = [[NSBundle mainBundle\ pathForResource:@“myOwnCertificate” ofType:@“der”\; [[Configuration getInstance] setWebSocketCertificate:[[NSData alloc\ initWithContentsOfFile:cerPath\\; @endcode
Declared In
SMConfiguration.h
auditFrequency
Sending audit message frequency (seconds)
@property (nonatomic) NSInteger auditFrequency
Availability
2.0.0
Discussion
Sending audit message frequency (seconds)
Default value is 30.
Declared In
SMConfiguration.h
forceDisableMediaOnHold
Forces to disable media transfer when media on hold is active. It helps to fix some MOH issues on PSTN calls
@property (nonatomic) BOOL forceDisableMediaOnHold
Availability
4.5.5
Discussion
Forces to disable media transfer when media on hold is active. It helps to fix some MOH issues on PSTN calls
Declared In
SMConfiguration.h
preferredCodecSet
codecSet stores available codecs for audio and video.
@property (nonatomic, strong) SMCodecSet *preferredCodecSet
Availability
3.0.5
Discussion
codecSet stores available codecs for audio and video.
Declared In
SMConfiguration.h
codecPayloadTypeSet
Sets codecPayloadTypeSet to modify payload numbers of audio and video codecs
@property (nonatomic, strong) NSArray<SMCodecToReplace*> *codecPayloadTypeSet
Availability
4.5.8
Discussion
Sets codecPayloadTypeSet to modify payload numbers of audio and video codecs
Declared In
SMConfiguration.h
orientationMode
Sets the camera orientation type of video capturer. Video orientation can be changed according to application status bar orientation or device orientation. Camera can be bind to this notifications or not to be bind anything.
@property (nonatomic) SMCameraOrientationMode orientationMode
Availability
2.0.0
Discussion
Sets the camera orientation type of video capturer. Video orientation can be changed according to application status bar orientation or device orientation. Camera can be bind to this notifications or not to be bind anything.
Declared In
SMConfiguration.h
scalingType
Scaling type parameter for local and remote video views.
@property (nonatomic) SMScalingType scalingType
Availability
5.20.0
Discussion
Scaling type parameter for local and remote video views.
Declared In
SMConfiguration.h
cameraPosition
Sets the default camera position mode
@property (nonatomic) AVCaptureDevicePosition cameraPosition
Availability
3.0.1
Discussion
Sets the default camera position mode
Declared In
SMConfiguration.h
fps
Sets fps value of the video source If invalid value is set, it will cause no video on call Default value is 30.
@property (nonatomic) NSUInteger fps
Availability
<IP_ADDRESS>
Discussion
Sets fps value of the video source If invalid value is set, it will cause no video on call Default value is 30.
Declared In
SMConfiguration.h
dtmfToneDuration
Sets duration value of DTMF tones im ms Default value is 600 and can be between 40 and 6000
@property (nonatomic) NSUInteger dtmfToneDuration
Availability
5.0.0
Discussion
Sets duration value of DTMF tones im ms Default value is 600 and can be between 40 and 6000
Declared In
SMConfiguration.h
logLevel
Sets log level of Mobile SDK
@property (nonatomic) SMLogLevel logLevel
Availability
3.0.2
Discussion
Sets log level of Mobile SDK
If not set, TRACE level is used as default.
See Also
Declared In
SMConfiguration.h
ICECollectionTimeout
Specifies timeout value of ICE Collection Default value is 10 and it means that waits 10 seconds for ice gathering. if it is set as 0, it means that waits until ice gathering completion.
@property (nonatomic) NSTimeInterval ICECollectionTimeout
Availability
3.1.3 @modified 5.6.0
Discussion
Specifies timeout value of ICE Collection Default value is 10 and it means that waits 10 seconds for ice gathering. if it is set as 0, it means that waits until ice gathering completion.
Declared In
SMConfiguration.h
audioSessionConfiguration
Sets audio session configuration
@property (nonatomic, strong) SMAudioSessionConfiguration *audioSessionConfiguration
Availability
4.2.0
Discussion
Sets audio session configuration
Declared In
SMConfiguration.h
audioCodecConfigurations
Sets the audio codec configurations. If parameter is null WebRTC defaults will be use. Warning: This is advance usage if you don’t have expertise on audio codecs, especially opus, don’t use it.
@property (nonatomic, strong) SMAudioCodecConfiguration *audioCodecConfigurations
Parameters
audioCodecConfigurations |
SMAudioCodecConfiguration object which will contains all audio codec configurations. |
|---|
Availability
4.2.0
Discussion
Sets the audio codec configurations. If parameter is null WebRTC defaults will be use. Warning: This is advance usage if you don’t have expertise on audio codecs, especially opus, don’t use it.
Declared In
SMConfiguration.h
slowStartCallPolicy
Specifies accept type for Slow Start Incoming Calls. Default value will be AudioSupported that means Slow Start Incoming Calls will be initiated by supporting only audio.
@property (nonatomic) SMSlowStartCallPolicy slowStartCallPolicy
Availability
4.5.4
Discussion
Specifies accept type for Slow Start Incoming Calls. Default value will be AudioSupported that means Slow Start Incoming Calls will be initiated by supporting only audio.
Declared In
SMConfiguration.h
receiveBandwidthLimit
Bandwidth limit of receiving media
@property (nonatomic, strong) SMCallReceiveBandwidthLimit *receiveBandwidthLimit
Availability
4.6.1
Discussion
Bandwidth limit of receiving media
Declared In
SMConfiguration.h
isPushEnabled
Push Notification Configuration Parameter
@property (nonatomic) BOOL isPushEnabled
Availability
5.0.0
Discussion
Push Notification Configuration Parameter
Declared In
SMConfiguration.h
bearerToken
Bearer Token Configuration Parameter
@property (nonatomic) NSString *bearerToken
Availability
5.7.0
Discussion
Bearer Token Configuration Parameter
Declared In
SMConfiguration.h
websocketWithTokenAuthentication
Websocket Token Authentication Configuration Parameter
@property (nonatomic) BOOL websocketWithTokenAuthentication
Availability
5.7.0
Discussion
Websocket Token Authentication Configuration Parameter
Declared In
SMConfiguration.h
ringingFeedbackOption
Ringing feedback configuration parameter. Default value is AUTO.
@property (nonatomic) SMRingingFeedbackOptions ringingFeedbackOption
Availability
5.15.0 @updated 2022-06-20
Discussion
Ringing feedback configuration parameter. Default value is AUTO.
Declared In
SMConfiguration.h
webSocketConnectionRetryLimit
Websocket reconnecting limit parameter
@property (nonatomic) NSInteger webSocketConnectionRetryLimit
Availability
6.8.0
Discussion
Websocket reconnecting limit parameter
Declared In
SMConfiguration.h
+ getInstance
This method returns (creates if necessary) singleton instance of Configuration class
+ (nonnull SMConfiguration *)getInstance
Return Value
shared Configuration instance
Availability
2.0.0
Discussion
This method returns (creates if necessary) singleton instance of Configuration class
Declared In
SMConfiguration.h


A Quote is Required...
An Author name is Required...
Your Name is Required kindly...
Date is required


- we are the champions mp3
- Afrobeat Fever mp3
- beyoncy mp3
- youandme mp3
- empire-sun mp3
- final-bout mp3
- red-hot-chili-pepers mp3
- Kiss-it-better mp3
- the naked truth austin cain mp3
- surat bakara mp3
- Subsonica - Dentro I Miei Vuoti mp3
- Kings Of Tomorrow Finally mp3
- 八大巨星 mp3
- Dean martin mp3
- Lulu--Independence mp3
- Army of Lovers mp3
- Joan Manuel Serrat mp3
- calippo nothing mp3
- hockey goal horn mp3
- 티아라 sugar free mp3
- Namito mp3
- cirez D backlash mp3
- everything misia mp3
- felipe-araujo mp3
- grupo-bryndis- mp3
- Nosso-santo-bateu mp3
- arcangel-x-bad-bunny mp3
- l arc en ciel mp3
- kolsch loreley mp3
- THE AWAKENING RYAN DUPREE mp3
we are the champions
Reviewed by we are the champions on
.
we are the champions mp3 Download mp3skull
we are the champions Free Mp3 Music Download. Play we are the champions Mp3 songs online and download them for free. we are the champions 4shared, kat.cr, ask.fm, zippyshare, mp3skull, soundcloud, last.fm, mp3lio, aiomp3, mp3goo, junglevibe
Rating: 4.7
Reviewed by we are the champions on
.
we are the champions mp3 Download mp3skull
we are the champions Free Mp3 Music Download. Play we are the champions Mp3 songs online and download them for free. we are the champions 4shared, kat.cr, ask.fm, zippyshare, mp3skull, soundcloud, last.fm, mp3lio, aiomp3, mp3goo, junglevibe
Rating: 4.7
download, descargar, 下载, downloaden, télécharger, डाउनलोड, ダウンロード, 다운로드, nedlasting, Ściągnij, baixar, indir, تحميل, yukle, Λήψη, הורדה, scaricare, ಡೌನ್ಲೋಡ್, скачать, ladda ner, tải về


Inputs
Form test
Text
Textarea
Muchos textos
Select
Yaaay?
Yaaay!
...yay?
Start the yay!
Go back to main page