0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQLAlchemy Migrateで複合ユニークキーを作成する方法

Posted at

失敗例

SQLAlchemy Migrateで、複合ユニークキーを作成しようとしたがうまくいかなかった。
以下はカラムa,b,cに対して複合ユニークキーを作成しようとした例。

from sqlalchemy import *
from migrate import *
from sqlalchemy.dialects.mysql import BIGINT, INTEGER, VARCHAR

meta = MetaData()
mytable = Table(
    'ng_images', meta,
    Column('id', BIGINT(unsigned=True), primary_key=True, nullable=False, autoincrement=True),
    Column('a', INTEGER(unsigned=True), unique=True),
    Column('b', INTEGER(unsigned=True), unique=True),
    Column('c', VARCHAR(60), unique=True)
)

解決策

UniqueConstraintを使うことで解決できた。

from sqlalchemy import *
from migrate import *
from sqlalchemy.dialects.mysql import BIGINT, INTEGER, VARCHAR
from migrate.changeset.constraint  import  UniqueConstraint

meta = MetaData()
mytable = Table(
    'ng_images', meta,
    Column('id', BIGINT(unsigned=True), primary_key=True, nullable=False, autoincrement=True),
    Column('a', INTEGER(unsigned=True), unique=True),
    Column('b', INTEGER(unsigned=True), unique=True),
    Column('c', VARCHAR(60), unique=True)
)
UniqueConstraint('a', 'b', 'c', name="unique_idx_mytable", table=mytable)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?