{"id":978,"hash":"abe9475d74ab08b15c476864e4747cd7f9f6169e09a9a45eff0642a27fa48385","pattern":"aiohttp+sqlalchemy: Can&#39;t reconnect until invalid transaction is rolled back","full_message":"I'm using aiohttp and sqlalchemy, and I've created a Singleton that helps me to connect when I'm needed a instance of SQLAlchemy (code follows).\nUnfortunately, every once in awhile I get the following error (which I \"solve\" by restarting the server):\n\n  Dec 11 09:35:29 ip-xxx-xxx-xxx-xxx gunicorn[16513]: sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) Can't reconnect until invalid transaction is rolled back [SQL: '... \\nFROM ...\\nWHERE ... = %(username_1)s \\n LIMIT %(param_1)s'] [parameters: [{}]]```\n\nIs there any way to fix the current code?\nThanks :)\n\nCONNECTION_DETAILS = {\n    'driver': 'pymysql',\n    'dialect': 'mysql',\n    'host': os.environ.get('HOST'),\n    'port': 3306,\n    'user': 'master',\n    'password': os.environ.get('PASSWORD'),\n    'database': 'ourdb',\n    'charset': 'utf8'\n}\n\n_instance = None\n\ndef __new__(cls, *args, **kwargs):\n    if not cls._instance:\n        con_str = '{dialect}+{driver}://{user}:{password}@' \\\n                  '{host}:{port}/{database}?charset={charset}'\\\n            .format(**cls.CONNECTION_DETAILS)\n        try:\n            engine = sqlalchemy.create_engine(con_str)\n\n            Session = scoped_session(sessionmaker(bind=engine))\n            session = Session()  # Create the ORM handle\n        except sqlalchemy.exc.OperationalError:\n            logger.exception('Establishing database connection error.')\n\n        cls._instance = super().__new__(cls)\n        logger.debug(\"Returning database's session.\")\n        cls._instance.session = session\n\n        # Initializing tables\n        cls._instance.Users = Users\n        cls._instance.Services = Services\n        cls._instance.APIKeys = APIKeys\n\n    return cls._instance","ecosystem":"pypi","package_name":"python-3.x","package_version":null,"solution":"This would be a fairly late answer. This is what happens: While using the session, a sqlalchemy Error is raised (anything which would also throw an error when be used as pure SQL: syntax errors, unique constraints, key collisions etc.). \n\nYou would have to find this error, wrap it into a try/except-block and perform a session.rollback(). \n\nAfter this you can reinstate your session.","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/41086632/aiohttpsqlalchemy-cant-reconnect-until-invalid-transaction-is-rolled-back","votes":22,"created_at":"2026-04-19T04:52:07.352769+00:00","updated_at":"2026-04-19T04:52:07.352769+00:00"}