Conditional UNIQUE constraint in SQLAlchemy
I have two simple classes for SQLAlchemy:
papers2authors_table = Table('papers2authors', Base.metadata,
Column('paper_id', Integer, ForeignKey('papers.id')),
Column('author_id', Integer, ForeignKey('authors.id'))
)
class Paper(Base):
__tablename__ = "papers"
id = Column(Integer, primary_key=True)
title = Column(String)
handle = Column(String)
authors = relationship("Author",
secondary="papers2authors",
backref="papers")
class Author(Base):
__tablename__ = "authors"
id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
code = Column(String, unique=True)
Then I run init elsewhere:
engine = create_engine('sqlite:///' + REPECI_DB, echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
self.s = session
And try adding items to papers
and authors
:
paper = Paper()
for line in lines: # the data is a sequence of lines "key: value" with few papers per file
br = line.find(':')
k = line[:br]
v = line[br+1:].strip()
if k == "Title":
paper.title = v
elif k == "Year":
paper.year = v
elif k == "Author-Name":
try:
self.s.begin_nested()
author = Author(name=v)
except IntegrityError:
print("Duplicate author")
self.s.rollback()
author = self.s.query(Author).filter(Author.name==v).first()
else:
self.s.commit()
paper.authors.append(author)
elif k == "Handle": # this appears in the end of a paper record
paper.handle = v
self.s.add(paper)
self.s.commit()
paper = Paper()
But something is wrong with the authors. After some authors are added to the table, I have an error (<class 'sqlalchemy.exc.IntegrityError'>, IntegrityError('(IntegrityError) UNIQUE constraint failed: authors.name',), None)
. Meanwhile, the database has only about 50 authors and only one article, and the rows I process contain about twice as many authors as articles. This means the script doesn't add them at all.
I tried to rewrite the code as recommended here , but the error still appears.
source to share
I found a solution that I don't like, but it works. Replace this:
try:
self.s.begin_nested()
author = Author(name=v)
except IntegrityError:
print("Duplicate author")
self.s.rollback()
author = self.s.query(Author).filter(Author.name==v).first()
else:
self.s.commit()
paper.authors.append(author)
Wherein:
author = self.s.query(Author).filter(Author.name==v).first()
if author is None:
author = Author(name=v)
paper.authors.append(author)
source to share