简体   繁体   中英

SQLAlchemy transaction not persisted

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.

I managed to get it working myself. Turns out db.begin(subtransactions=True) was not really needed.

this is my crud func now and it does what i need:

# create item as transaction
def create_item_v2(db: Session, item: items_schemas.ItemCreateV2):
    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)

    try:
        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()
        db.refresh(db_item)
        return db_item
    except:
        db.rollback()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM