[파이썬] SQLAlchemy Index 및 Unique 제약 조건 설정

Introduction

In a database schema, indexes and unique constraints are important tools for optimizing performance and ensuring data integrity. When working with SQLAlchemy in Python, you can easily define index and unique constraints on your database tables. In this blog post, we will explore how to set up index and unique constraints using SQLAlchemy.

SQLAlchemy Index

Indexes are used to improve the performance of database queries by allowing faster lookup of data based on specific columns. In SQLAlchemy, indexes can be defined using the Index class from the sqlalchemy.schema module.

Here’s an example of how to define an index on a database table:

from sqlalchemy import Index

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(50))
    email = Column(String(100))

# Define an index on the email column
EmailIndex = Index('email_index', User.email)

In the above code, we use the Index class to define an index named email_index on the email column of the users table.

SQLAlchemy Unique Constraint

Unique constraints ensure that the values in specified columns are unique across all rows in a table. In SQLAlchemy, unique constraints can be defined using the UniqueConstraint class from the sqlalchemy.schema module.

Here’s an example of how to define a unique constraint on a database table:

from sqlalchemy import UniqueConstraint

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(50))
    email = Column(String(100))

# Define a unique constraint on the username column
UsernameUniqueConstraint = UniqueConstraint('username', name='uq_username')

In the above code, we use the UniqueConstraint class to define a unique constraint named uq_username on the username column of the users table.

Applying Index and Unique Constraints

To actually apply the defined index and unique constraints to the database table, we need to create or update the table schema using SQLAlchemy’s create_all or metadata.create_all method.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('<database_connection_string>')
Session = sessionmaker(bind=engine)
session = Session()

# Create all tables including the defined indexes and unique constraints
Base.metadata.create_all(engine)

In the above code, we create an instance of the database engine and a session. Then, we use Base.metadata.create_all to create all the tables defined in our SQLAlchemy models, including the indexes and unique constraints.

Conclusion

In this blog post, we learned how to define and apply index and unique constraints using SQLAlchemy in Python. With index and unique constraints, you can optimize your database queries and enforce data integrity. SQLAlchemy provides a convenient and powerful way to work with indexes and constraints in your database schema.