{"id":5105,"library":"aiopg","title":"Aiopg","description":"aiopg is a library for accessing a PostgreSQL database from the asyncio (PEP-3156/tulip) framework. It wraps asynchronous features of the Psycopg database driver. The current version is 1.4.0, and it is actively maintained by the aio-libs organization, though the last release was in October 2022.","status":"active","version":"1.4.0","language":"en","source_language":"en","source_url":"https://github.com/aio-libs/aiopg","tags":["asyncio","postgresql","database","orm"],"install":[{"cmd":"pip install aiopg","lang":"bash","label":"Core library"},{"cmd":"pip install aiopg[sa]","lang":"bash","label":"With SQLAlchemy support"}],"dependencies":[{"reason":"Required for PostgreSQL database connectivity.","package":"psycopg2-binary","optional":false},{"reason":"Optional, for using the aiopg.sa module for SQLAlchemy functional SQL layer support.","package":"SQLAlchemy","optional":true}],"imports":[{"symbol":"aiopg","correct":"import aiopg"},{"symbol":"create_pool","correct":"import aiopg\nawait aiopg.create_pool(...)"},{"note":"For SQLAlchemy integration, create_engine is typically imported directly from aiopg.sa.","wrong":"import aiopg.sa","symbol":"create_engine","correct":"from aiopg.sa import create_engine"}],"quickstart":{"code":"import asyncio\nimport aiopg\nimport os\n\ndsn = os.environ.get('AIOPG_DSN', 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1')\n\nasync def main():\n    # Establish a connection pool\n    async with aiopg.create_pool(dsn) as pool:\n        # Acquire a connection from the pool\n        async with pool.acquire() as conn:\n            # Open a cursor to perform database operations\n            async with conn.cursor() as cur:\n                # Execute a simple query\n                await cur.execute(\"SELECT 1\")\n                ret = []\n                # Iterate over the results\n                async for row in cur:\n                    ret.append(row)\n                assert ret == [(1,)]\n                print(f\"Query result: {ret}\")\n\nif __name__ == '__main__':\n    # For Python 3.10+\n    try:\n        asyncio.run(main())\n    except RuntimeError as e:\n        if \"cannot run an event loop while another loop is running\" in str(e):\n            # Handle cases where an event loop might already be running (e.g., in notebooks)\n            loop = asyncio.get_event_loop()\n            if loop.is_running():\n                loop.create_task(main())\n            else:\n                loop.run_until_complete(main())\n        else:\n            raise\n","lang":"python","description":"This quickstart demonstrates how to establish an asynchronous connection pool, acquire a connection, execute a simple query, and fetch results using aiopg. It includes error handling for already running event loops common in interactive environments. Ensure your PostgreSQL instance is running and accessible with the provided DSN, or set the AIOPG_DSN environment variable."},"warnings":[{"fix":"Do not call `conn.commit()` or `conn.rollback()`. Instead, explicitly execute SQL: `await cur.execute('BEGIN')`, then `await cur.execute('COMMIT')` or `await cur.execute('ROLLBACK')`.","message":"aiopg internally uses `psycopg2-binary` connections in `autocommit=True` mode for asynchronous operations. This means `conn.commit()` and `conn.rollback()` methods are disabled and will raise `psycopg2.ProgrammingError`. Transactions must be explicitly managed by executing `BEGIN` and `COMMIT`/`ROLLBACK` SQL statements manually.","severity":"breaking","affected_versions":"<1.0.0 (behavior established early)"},{"fix":"Ensure all `aiopg` connection and cursor methods are `await`ed, e.g., `await conn.execute(...)`, `await cur.fetchone()`. For `cur.mogrify()`, do not use `await`.","message":"Almost all connection and cursor methods in aiopg are coroutines and *must* be `await`ed. However, `Cursor.mogrify()` specifically had its `await` requirement removed in a later version and should now be called synchronously.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Prefer explicit iteration using `async for row in cur:` for cursors, and `await result.fetchall()` or `async for row in result:` for `ResultProxy` objects, rather than synchronous iteration.","message":"Iteration protocol support in `cursor` and `ResultProxy` was deprecated in version 0.7.0. While still functional for older codebases, relying on direct iteration for results might lead to unexpected behavior or future breakage.","severity":"deprecated","affected_versions":">=0.7.0"},{"fix":"Ensure your project uses Python 3.7 or newer and exclusively uses `async def` and `await` for asynchronous code.","message":"aiopg requires Python 3.7+ and only supports the `async/await` syntax. Older `asyncio` patterns (e.g., `@asyncio.coroutine` decorators) are not supported.","severity":"gotcha","affected_versions":"<1.0.0 (modern asyncio syntax enforced)"},{"fix":"Avoid passing `name`, `scrollable`, or `withhold` to `conn.cursor()`. If custom cursor behavior is needed, use `cursor_factory`.","message":"When creating a cursor via `conn.cursor()`, some parameters like `name`, `scrollable`, and `withhold` are not supported by `psycopg2-binary` in asynchronous mode and will be ignored or raise errors if specified. Only `cursor_factory` and `timeout` are reliably supported.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-13T00:00:00.000Z","next_check":"2026-07-12T00:00:00.000Z"}