SQLAlchemy 0.5.7 Documentation

Version: 0.5.7 Last Updated: 12/26/2009 18:22:23
API Reference | Index

MySQL

Support for the MySQL database.

Overview

For normal SQLAlchemy usage, importing this module is unnecessary. It will be loaded on-demand when a MySQL connection is needed. The generic column types like String and Integer will automatically be adapted to the optimal matching MySQL column type.

But if you would like to use one of the MySQL-specific or enhanced column types when creating tables with your Table definitions, then you will need to import them from this module:

from sqlalchemy.databases import mysql

Table('mytable', metadata,
      Column('id', Integer, primary_key=True),
      Column('ittybittyblob', mysql.MSTinyBlob),
      Column('biggy', mysql.MSBigInteger(unsigned=True)))

All standard MySQL column types are supported. The OpenGIS types are available for use via table reflection but have no special support or mapping to Python classes. If you’re using these types and have opinions about how OpenGIS can be smartly integrated into SQLAlchemy please join the mailing list!

Supported Versions and Features

SQLAlchemy supports 6 major MySQL versions: 3.23, 4.0, 4.1, 5.0, 5.1 and 6.0, with capabilities increasing with more modern servers.

Versions 4.1 and higher support the basic SQL functionality that SQLAlchemy uses in the ORM and SQL expressions. These versions pass the applicable tests in the suite 100%. No heroic measures are taken to work around major missing SQL features- if your server version does not support sub-selects, for example, they won’t work in SQLAlchemy either.

Currently, the only DB-API driver supported is MySQL-Python (also referred to as MySQLdb). Either 1.2.1 or 1.2.2 are recommended. The alpha, beta and gamma releases of 1.2.1 and 1.2.2 should be avoided. Support for Jython and IronPython is planned.

Feature Minimum Version
sqlalchemy.orm 4.1.1
Table Reflection 3.23.x
DDL Generation 4.1.1
utf8/Full Unicode Connections 4.1.1
Transactions 3.23.15
Two-Phase Transactions 5.0.3
Nested Transactions 5.0.3

See the official MySQL documentation for detailed information about features supported in any given server release.

Character Sets

Many MySQL server installations default to a latin1 encoding for client connections. All data sent through the connection will be converted into latin1, even if you have utf8 or another character set on your tables and columns. With versions 4.1 and higher, you can change the connection character set either through server configuration or by including the charset parameter in the URL used for create_engine. The charset option is passed through to MySQL-Python and has the side-effect of also enabling use_unicode in the driver by default. For regular encoded strings, also pass use_unicode=0 in the connection arguments:

# set client encoding to utf8; all strings come back as unicode
create_engine('mysql:///mydb?charset=utf8')

# set client encoding to utf8; all strings come back as utf8 str
create_engine('mysql:///mydb?charset=utf8&use_unicode=0')

Storage Engines

Most MySQL server installations have a default table type of MyISAM, a non-transactional table type. During a transaction, non-transactional storage engines do not participate and continue to store table changes in autocommit mode. For fully atomic transactions, all participating tables must use a transactional engine such as InnoDB, Falcon, SolidDB, PBXT, etc.

Storage engines can be elected when creating tables in SQLAlchemy by supplying a mysql_engine='whatever' to the Table constructor. Any MySQL table creation option can be specified in this syntax:

Table('mytable', metadata,
      Column('data', String(32)),
      mysql_engine='InnoDB',
      mysql_charset='utf8'
     )

Keys

Not all MySQL storage engines support foreign keys. For MyISAM and similar engines, the information loaded by table reflection will not include foreign keys. For these tables, you may supply a ForeignKeyConstraint at reflection time:

Table('mytable', metadata,
      ForeignKeyConstraint(['other_id'], ['othertable.other_id']),
      autoload=True
     )

When creating tables, SQLAlchemy will automatically set AUTO_INCREMENT` on an integer primary key column:

>>> t = Table('mytable', metadata,
...   Column('mytable_id', Integer, primary_key=True)
... )
>>> t.create()
CREATE TABLE mytable (
        id INTEGER NOT NULL AUTO_INCREMENT,
        PRIMARY KEY (id)
)

You can disable this behavior by supplying autoincrement=False to the Column. This flag can also be used to enable auto-increment on a secondary column in a multi-column key for some storage engines:

Table('mytable', metadata,
      Column('gid', Integer, primary_key=True, autoincrement=False),
      Column('id', Integer, primary_key=True)
     )

SQL Mode

MySQL SQL modes are supported. Modes that enable ANSI_QUOTES (such as ANSI) require an engine option to modify SQLAlchemy’s quoting style. When using an ANSI-quoting mode, supply use_ansiquotes=True when creating your Engine:

create_engine('mysql://localhost/test', use_ansiquotes=True)

This is an engine-wide option and is not toggleable on a per-connection basis. SQLAlchemy does not presume to SET sql_mode for you with this option. For the best performance, set the quoting style server-wide in my.cnf or by supplying --sql-mode to mysqld. You can also use a sqlalchemy.pool.Pool listener hook to issue a SET SESSION sql_mode='...' on connect to configure each connection.

If you do not specify use_ansiquotes, the regular MySQL quoting style is used by default.

If you do issue a SET sql_mode through SQLAlchemy, the dialect must be updated if the quoting style is changed. Again, this change will affect all connections:

connection.execute('SET sql_mode="ansi"')
connection.dialect.use_ansiquotes = True

MySQL SQL Extensions

Many of the MySQL SQL extensions are handled through SQLAlchemy’s generic function and operator support:

table.select(table.c.password==func.md5('plaintext'))
table.select(table.c.username.op('regexp')('^[a-d]'))

And of course any valid MySQL statement can be executed as a string as well.

Some limited direct support for MySQL extensions to SQL is currently available.

  • SELECT pragma:

    select(..., prefixes=['HIGH_PRIORITY', 'SQL_SMALL_RESULT'])
  • UPDATE with LIMIT:

    update(..., mysql_limit=10)

Troubleshooting

If you have problems that seem server related, first check that you are using the most recent stable MySQL-Python package available. The Database Notes page on the wiki at http://www.sqlalchemy.org is a good resource for timely information affecting MySQL in SQLAlchemy.

MySQL Column Types

class sqlalchemy.databases.mysql.MSNumeric(precision=10, scale=2, asdecimal=True, **kw)

Bases: sqlalchemy.types.Numeric, sqlalchemy.databases.mysql._NumericType

MySQL NUMERIC type.

__init__(precision=10, scale=2, asdecimal=True, **kw)

Construct a NUMERIC.

Parameters:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.
  • scale – The number of digits after the decimal point.
  • unsigned – a boolean, optional.
  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.
class sqlalchemy.databases.mysql.MSDecimal(precision=10, scale=2, asdecimal=True, **kw)

Bases: sqlalchemy.databases.mysql.MSNumeric

MySQL DECIMAL type.

__init__(precision=10, scale=2, asdecimal=True, **kw)

Construct a DECIMAL.

Parameters:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.
  • scale – The number of digits after the decimal point.
  • unsigned – a boolean, optional.
  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.
class sqlalchemy.databases.mysql.MSDouble(precision=None, scale=None, asdecimal=True, **kw)

Bases: sqlalchemy.types.Float, sqlalchemy.databases.mysql._NumericType

MySQL DOUBLE type.

__init__(precision=None, scale=None, asdecimal=True, **kw)

Construct a DOUBLE.

Parameters:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.
  • scale – The number of digits after the decimal point.
  • unsigned – a boolean, optional.
  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.
class sqlalchemy.databases.mysql.MSReal(precision=None, scale=None, asdecimal=True, **kw)

Bases: sqlalchemy.databases.mysql.MSDouble

MySQL REAL type.

__init__(precision=None, scale=None, asdecimal=True, **kw)

Construct a REAL.

Parameters:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.
  • scale – The number of digits after the decimal point.
  • unsigned – a boolean, optional.
  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.
class sqlalchemy.databases.mysql.MSFloat(precision=None, scale=None, asdecimal=False, **kw)

Bases: sqlalchemy.types.Float, sqlalchemy.databases.mysql._NumericType

MySQL FLOAT type.

__init__(precision=None, scale=None, asdecimal=False, **kw)

Construct a FLOAT.

Parameters:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.
  • scale – The number of digits after the decimal point.
  • unsigned – a boolean, optional.
  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.
class sqlalchemy.databases.mysql.MSInteger(display_width=None, **kw)

Bases: sqlalchemy.types.Integer, sqlalchemy.databases.mysql._NumericType

MySQL INTEGER type.

__init__(display_width=None, **kw)

Construct an INTEGER.

Parameters:
  • display_width – Optional, maximum display width for this number.
  • unsigned – a boolean, optional.
  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.
class sqlalchemy.databases.mysql.MSBigInteger(display_width=None, **kw)

Bases: sqlalchemy.databases.mysql.MSInteger

MySQL BIGINTEGER type.

__init__(display_width=None, **kw)

Construct a BIGINTEGER.

Parameters:
  • display_width – Optional, maximum display width for this number.
  • unsigned – a boolean, optional.
  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.
class sqlalchemy.databases.mysql.MSMediumInteger(display_width=None, **kw)

Bases: sqlalchemy.databases.mysql.MSInteger

MySQL MEDIUMINTEGER type.

__init__(display_width=None, **kw)

Construct a MEDIUMINTEGER

Parameters:
  • display_width – Optional, maximum display width for this number.
  • unsigned – a boolean, optional.
  • zerofill