I recently had to implement a transaction on my app which goes as follows:
I have a:
- "items" table
- "tags" table which has "items.id" as ForeignKey
- "descriptions" table which has "items.id" as ForeignKey
I now want to perform this transaction or rollback if it fails:
- insert item into "items"
- flush and get item.id (primary key)
- insert tag into "tags" (using the item.id), this is a list of tags
- insert description into "descriptions" (using the item.id), this is a list of descriptions
My database is sqlite.
my code:
db_item = models.Items(title=item.title, description=item.description,
quantity=item.quantity, images=item.images,
category_name=item.category_name, status=item.status,
organization_id=item.organization_id, price=item.price)
db.begin(subtransactions=True)
db.add(db_item)
db.flush()
db_tags_to_items = [models.ItemsAndTags(tag_name=tag, item_id=db_item.id) for tag in item.tags]
db_short_descriptions = [models.ItemsShortDescription(line=line, item_id=db_item.id) for line in item.descriptions]
db.add_all(db_tags_to_items)
db.add_all(db_short_descriptions)
db.commit()
If i return db_item it returns it with the id, however if i check the db that item was not persisted nor the tags or descriptions. What am i doing wrong as i get no error.
If more of my code is needed pleaste let me know, i use the FastAPI framework with SQLAlchemy.