Heroku Database Connections Not Closed After Query Finished

13 Views Asked by At

I am working on a python script that interacts with a Heroku database. Currently I am having issues with connections that are being established not get closed. After this code is run, the connections stay open with status 'idle'

def connect_to_database():
    try:
        # Use a new variable for the modified URL or directly modify it in the create_engine call
        corrected_database_url = DATABASE_URL.replace('postgres://', 'postgresql://', 1)
        engine = create_engine(corrected_database_url, echo=False)
        return engine
    except Exception as e:
        logger.error(f"Error connecting to database: {e}")
        return None

def read_database(car_auction_dict):
    print("___________PRINTING DICT INFO______________")
    year = car_auction_dict.get("year")
    make = car_auction_dict.get("make")
    model = car_auction_dict.get("model")

    print(year, make, model)
    
    engine = connect_to_database()
    if engine is None:
        return "Error connecting to database"
    
    table_name = 'vehicle_listings'
    metadata = MetaData()
    table = Table(table_name, metadata, autoload_with=engine)

    # Use a context manager to ensure the connection is closed
    with engine.connect() as connection:
        query = select(table.c.Price).where(
            (table.c.Make == make) & (table.c.Model == model)
        )
        result = connection.execute(query)
        prices = [row._mapping['Price'] for row in result]

    connection.close()

    price_average = round(sum(prices) / len(prices), 2) if prices else 0

    print("___________PRINTING RESULTS______________")
    print(prices)
    print(f"***Price Average: {price_average}")
    return price_average

I know the connection.close() line is redundant, but even with this here it seems my connections are not getting closed.

Using PGAdmin I can see the connections prior to executing this code. After it runs, I see a new connection. Running it again adds an additional connection. Waiting does not result in these connections being closed.

Any ideas how I can troubleshoot why these connections are not terminated? Thanks.

0

There are 0 best solutions below