How can I create a table using sqlalchemy and set it to ignore duplicates on a unique index?

Viewed 33

I'm creating a table using SQLAclhemy. The table includes a unique index, and I would like the table to be setup to ignore attempts to insert a row that is a duplicate of an existing index value. This is what my code looks like:

import os

import sqlalchemy
from sqlalchemy import (Column, String, Integer, Float, DateTime, Index)

from sqlalchemy.ext.declarative import declarative_base

db_user = 'USERNAME'
db_password = 'PASSWORD'
address = '000.000.0.0' 
port = '1111'
database = 'my_db'


engine = sqlalchemy.create_engine(
        f"mariadb+mariadbconnector://{db_user}:{db_password}@{address}:{port}/{database}")

Base = declarative_base()

class Pet(Base):
    __tablename__ = 'pets'
    id = Column(Integer, primary_key=True)
    name = Column(String(8))
    weight = Column(Float)
    breed = Column(Float)
    birthday = Column(DateTime)
    __table_args__ = (Index('breed_bd', "breed", "birthday", unique=True), )

Base.metadata.create_all(engine)
Session = sqlalchemy.orm.sessionmaker()
Session.configure(bind=engine)
session = Session()

I've seen that in straight sql, you can do things like

CREATE TABLE dbo.foo (bar int PRIMARY KEY WITH (IGNORE_DUP_KEY = ON))

or

CREATE UNIQUE INDEX UNQ_CustomerMemo ON CustomerMemo (MemoID, CustomerID)
    WITH (IGNORE_DUP_KEY = ON);

I'm wondering what I should change/add in my code to accomplish something similar.

0 Answers
Related