Python Friday #89: Constraints, Indexes and Default Values in SQLAlchemy ORM

The right index can boost the performance of your SQL query enormously while constrains help you to enforce the integrity of your data in the database. Let us look how SQLAlchemy can help us with both. I made my examples for SQLAlchemy ORM, but they work in Core as well.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Attention: SQLite needs batch mode

If you try to add constraints to existing tables in SQLite you may get this error in Alembic:

INFO [alembic.runtime.migration] Context impl SQLiteImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
INFO [alembic.runtime.migration] Running upgrade 347126fc065d -> 6af8c1fdf679, make ISBN unique
..
NotImplementedError: No support for ALTER of constraints in SQLite dialect Please refer to the batch mode feature which allows for SQLite migrations using a copy-and-move strategy.

You can fix this by activating the batch mode as I explained in the last post.

 

Primary key constraint

In our models we can use primary_key=True in the table mapping to make a field a primary key:

If you need to create a composite primary key with multiple columns you can add primary_key=True to each of them:

 

Foreign key constraint

Foreign keys help us to enforce the relation between two tables. You can do that with ForeignKey(‘Table.Id’) as we did with books that need a publishers:

 

Indexes

We can create an index for a single column with the index=True option:

To create a multi-column index, we can add an index to the __table_args__ property and list all columns it should contain:

 

Unique constraint

Unique constraints are indexes with the option unique=True:

At least for SQLite you must set the index=True field as well.

 

Default values

We can specify a default value for a column with the default= argument. It accepts a fixed value or a function. If we use a function like the current date, we must use the function name without the () as we did with Decorators:

 

Next

With these constraints we can enforce the integrity of our data at the database level. Not everything that SQLAlchemy offers works in SQLite. Next week we look how we can connect to Microsoft SQL Server and what we need to do to get it working.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.