Raaid, softwarelog
Back

This week, my head-bashing was courtesy of SQL! Learned some good things though.

> alembic init alembic
# then I added my database's connection string to alembic.ini
> alembic revision -m "add unique constraint to article.url"
# filled out the upgrade and downgrade functions in the revision file
> alembic upgrade head

And thats it! The first comment is truly just a one line change, and filling out the upgrade/downgrade was really easy. The revision command creates a stub for the file, and you just need to fill out the body of the two functions. Here is all I wrote:

def upgrade():
    op.create_unique_constraint("unique_article_url", "article", ["url"])


def downgrade():
    op.drop_constraint("unique_article_url", "article")

Nice and easy.

# from this
db_client.add_all(db_articles)
# to this instead
insert_statement = insert(Article).on_conflict_do_nothing(index_elements=["url"])
db_client.exec(statement=insert_statement, params=db_articles)

And voila, any conflicts on my unique url column are handled as desired.

Cheers,

+raaid

© Raaid Arshad.RSS