source

여러 열에 걸쳐 고유한 sqlalchemy

nicesource 2022. 12. 4. 22:29
반응형

여러 열에 걸쳐 고유한 sqlalchemy

예를 들어 장소를 나타내는 클래스가 있다고 합시다.고객의 「아래」에 있는 곳위치는 유니코드 10 문자 코드로 식별됩니다.「로케이션 코드」는, 특정의 고객의 로케이션 마다 일의로 할 필요가 있습니다.

The two below fields in combination should be unique
customer_id = Column(Integer,ForeignKey('customers.customer_id')
location_code = Column(Unicode(10))

고객 '123'과 '456' 두 명의 고객이 있는 경우둘 다 "main"이라고 불리는 위치를 가질 수 있지만 둘 다 main이라고 불리는 두 개의 위치를 가질 수 없습니다.

비즈니스 로직으로 처리할 수는 있지만 sqlalchemy에서 쉽게 요건을 추가할 수 있는 방법은 없는지 확인하고 싶습니다.독자적인 =True 옵션은 특정 필드에 적용되었을 때만 작동하며 테이블 전체가 모든 위치에 대해 고유한 코드만 갖게 됩니다.

매뉴얼에서 발췌합니다.Column:

unique : True일 경우 이 컬럼에 고유한 제약조건이 포함되어 있음을 나타냅니다.인덱스가 True일 경우 인덱스를 고유 플래그로 작성해야 함을 나타냅니다.제약 조건/인덱스에서 여러 열을 지정하거나 명시적 이름을 지정하려면 UniqueConstraint 또는 Index 구성을 명시적으로 사용합니다.

이들은 매핑된 클래스가 아닌 테이블에 속하므로 테이블 정의 또는 에서와 같이 선언문을 사용하는 경우 선언합니다.__table_args__:

# version1: table definition
mytable = Table('mytable', meta,
    # ...
    Column('customer_id', Integer, ForeignKey('customers.customer_id')),
    Column('location_code', Unicode(10)),

    UniqueConstraint('customer_id', 'location_code', name='uix_1')
    )
# or the index, which will ensure uniqueness as well
Index('myindex', mytable.c.customer_id, mytable.c.location_code, unique=True)


# version2: declarative
class Location(Base):
    __tablename__ = 'locations'
    id = Column(Integer, primary_key = True)
    customer_id = Column(Integer, ForeignKey('customers.customer_id'), nullable=False)
    location_code = Column(Unicode(10), nullable=False)
    __table_args__ = (UniqueConstraint('customer_id', 'location_code', name='_customer_location_uc'),
                     )
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Location(Base):
      __table_args__ = (
        # this can be db.PrimaryKeyConstraint if you want it to be a primary key
        db.UniqueConstraint('customer_id', 'location_code'),
      )
      customer_id = Column(Integer,ForeignKey('customers.customer_id')
      location_code = Column(Unicode(10))

이 Python3의 답변은 완전히 파생적인 것으로, MySQL을 위한 작은 자기 완결형 작업 예제에 모든 것을 포함시킬 뿐입니다.다대다 관계를 구현하는 테이블에 대한 고유한 제약이 필요했습니다.로컬 환경 문제를 디버깅하기 위해 이 작업을 수행할 수 있습니다.내 경우는 키보드와 의자 사이에 문제가 있었습니다.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, ForeignKey, Integer, String, UniqueConstraint
from sqlalchemy.orm import relationship
import logging

logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://user:pass@localhost/mydb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

user_role = db.Table(
    'user_role',
    Column('uid', String(6), ForeignKey('user.uid')),
    Column('role', String(32), ForeignKey('role.name')),
    UniqueConstraint('uid', 'role', name='idx_uid_role'))

class UserModel(db.Model):
    __tablename__ = 'user'
    uid = Column(String(6), primary_key=True)
    create_time = Column(Integer, nullable=False)
    login_time = Column(Integer, nullable=True)
    roles = relationship('RoleModel', secondary='user_role',
                         backref='user', lazy='joined')

class RoleModel(db.Model):
    __tablename__ = 'role'
    name = Column(String(32), primary_key=True)
    description = Column(String(256), nullable=False)

db.create_all()

실행 후 테이블에 정의된 인덱스를 다음과 같이 확인합니다.

mysql> show index from user_role;

다음 사항을 확인해 주십시오.

+-----------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table     | Non_unique | Key_name     | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+-----------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| user_role |          0 | idx_uid_role |            1 | uid         | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
| user_role |          0 | idx_uid_role |            2 | role        | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
| user_role |          1 | role         |            1 | role        | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
+-----------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
3 rows in set (0.00 sec)

테스트 데이터 생성:

mysql> insert into user values ('abc123', 1, 2);
mysql> insert into role values ('role1', 'Description');
mysql> insert into user_role (uid, role) values ('abc123', 'role1');

마지막으로 마지막 삽입을 다시 실행하여 고유성 제약 조건을 테스트합니다.다음 메시지가 나타납니다.

mysql> insert into user_role (uid, role) values ('abc123', 'role1');
ERROR 1062 (23000): Duplicate entry 'abc123-role1' for key 'user_role.idx_uid_role'

언급URL : https://stackoverflow.com/questions/10059345/sqlalchemy-unique-across-multiple-columns

반응형