Z
Z
zlodiak2019-12-08 15:28:47
Python
zlodiak, 2019-12-08 15:28:47

Why does rollback() exist?

Please explain why there is a transaction rollback in the form of rollback()? It is desirable in the form of an example at least in words.
For example, there is the following transaction:

import psycopg2

class DB_connection:   
    def __enter__(self):
        self.connection = psycopg2.connect(
            dbname='vendor',  
            user='vendor', 
            password='vendor',
            host='localhost'
        )
        return self.connection
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if hasattr(self, 'connection'):
            self.connection.close()   


with DB_connection() as db_connect:
    db_cursor = db_connect.cursor()

    req = "insert into vendors(vendor_name) values('nvidia')"
    db_cursor.execute(req)

    req = "insert into parts(part_name) values(NULL)"   # throw exception
    db_cursor.execute(req)

    db_connect.commit()

Here the second query will not succeed because at the table level I forbid an empty value in the part_name field. In this case, both operations will be rolled back because they are within the transaction. As I see it, rollback() was not needed. And I can't imagine a situation in which it would be needed.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kalapanga, 2019-12-08
@zlodiak

In this case, both operations will be rolled back.
This rollback is what it is. Read the documentation for the libraries you use!
rollback()
Roll back to the start of any pending transaction. Closing a connection without committing the changes first will cause an implicit rollback to be performed.
Changed in version 2.5: if the connection is used in a with statement, the method is automatically called if an exception is raised in the with block.
( The connection class )

I
Ivan Shumov, 2019-12-08
@inoise

Rollback is always needed because, in fact, no one can guarantee that the operation will be completed. The fact that you did all this and are sure that it will work is a so-so argument

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question