Database Transaction in API method

Hello,

Just making sure, I am creating an API function with @frappe.whitelist() decorator and within that function there are several database related APIs called (ex: document.save, frappe.new_doc).

If between those API calls, I throw an error via frappe.throw, does previous calls become reverted back. If that so, on the last part of that function should I place a frappe.db.commit() ?

Thank you.

hi, do you find the solution to your problem?
I’m having the same problem

It does implicitly save your object in DB
But it depends on your previous calls if in previous calls you have created some objects that wont get reverted but current transaction will get rolled back

can you give an example? did you use frappe.db.rollback or something? I can’t get my head around on how to use frappe.db.rollback

try:
     create_item()
     so_doc = frappe.new_doc("Sales Order")
     so_doc.customer = 'Valen'
     # some more properties to this object
     so_doc.save()
except Exception,e:
    #here you can rollback
    frappe.db.rollback() #this will revert only SO current transaction not item object that 
    we have created

if I have 2 transaction in one go, for ex:

    so_doc = frappe.new_doc("Sales Order")
    # add some properties
    so_doc.save()

    si_doc = frappe.get_doc("Sales Invoice", "SI-0001")
    # add some properties
    si_doc.save()

turns out the si_doc have failed to execute, do you know how I can cancel the SO transaction that already success?

in exception block you can get the no of so_doc so just get it and cancel

doc_to_cancel = frappe.get_doc("Sales Order", so_doc.name)
doc_to_cancel.cancel()