Search code examples
pythonsnowflake-cloud-data-platformsnowflake-connector

How to find out all the cursors associated with a connection in python-Snowflake connector


Is there any function in python-snowflake connector API to get the list of all cursors that were derived using the connection object. Also can you please confirm if exiting a function call will close the cursors?

def function(self,qry):
    cur = conn.cursor()
    return cur.execute(qry)

def proc(self):
    sel_cur = self.function("select.....")
    ....
    ....
    ....
    upd_cur = self.function("update.....")
    ....
    sel_cur1 = self.function("select.....")
    ....
    del_cur = self.function("delete.....")
    sel_cur2 = self.function("select.....")

The above two functions are written inside a class. There are multiple cursors getting created in proc(). Once the proc() exits, will it close the cursors? I assume they are not yet closed, but they become inaccessible due to local scope. I think they are still occupying the memory. Please clarify. I want to find out if any cursors are still open for a given connection. Please help me how to achieve this in python-snowflake connector.


Solution

  • There does not appear to be a list of cursors for a connection. Exiting a function call will not close a cursor (it is possible to create a cursor in a function call, return it to the caller, and verify that the cursor is still open).

    Context managers and the with statement are an easy way to ensure a cursor and a connection are closed when no longer required.

    with snowflake.connector.connect(**connection_parameters) as connection:
    
        with connection.cursor() as cursor:
    
            sql = "select * from product"
    
            # Simple fetch and print
            cursor.execute(sql)
            for (productId, name, parentId) in cursor:
            # ...
    

    When exiting the with cursor block, the cursor will be closed. Similarly when exiting the with connection block, the connection will be closed.