Ending a SELECT transaction psycopg2 and postgres

Viewed 149

I am executing a number of SELECT queries on a postgres database using psycopg2, but I am getting ERROR: Out of shared memory. It suggests that I should increase max_locks_per_transaction., but this confuses me because each SELECT query is operating on only one table, and max_locks_per_transaction is already set to 512, 8 times the default.

I am using TimescaleDB, which could be the result of a larger than normal number of locks (one for each chunk rather than one for each table, maybe), but this still can't explain running out when so many are allowed. I'm assuming what is happening here is that all the queries are all being run as part of one transaction.

The code I am using looks something as follows.

db = DatabaseConnector(**connection_params)
tables = db.get_table_list()
for table in tables:
     result = db.query(f"""SELECT a, b, COUNT(c) FROM {table} GROUP BY a, b""")
     print(result)

Where db.query is defined as:

def query(self, sql):
    with self._connection.cursor() as cur:
        cur.execute(sql)
        return_value = cur.fetchall()
    return return_value

and self._connection is:

self._connection = psycopg2.connect(**connection_params)

Do I need to explicitly end the transaction in some way to free up locks? And how can I go about doing this in psycopg2? I would have assumed that there was an implicit end to the transaction when the cursor is closed on __exit__. I know if I was inserting or deleting rows I would use COMMIT at the end, but it seems strange to use as I am not changing the table.

UPDATE: When I explicitly open and close the connection in the loop, the error does not show. However, I assume there is a better way to end the transaction after each SELECT than this.

0 Answers
Related