### Configuration Example for Development Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt A sample configuration setup suitable for development environments. It includes common parameters like echo for debugging. ```python connection_params = { 'dsn': 'my_dev_db', 'user': 'dev_user', 'password': 'dev_password', 'echo': True # Enable query logging for debugging } ``` -------------------------------- ### Configuration Options Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Comprehensive guide to connection and pool parameters, connection string formats, and configuration examples. ```APIDOC ## Configuration Options ### Description Provides a detailed breakdown of all available configuration parameters for connections and connection pools, including examples for various database systems and environments. ### Connection Parameters - **dsn**: Data Source Name. - **autocommit**: Enable/disable autocommit. - **ansi**: Enable/disable ANSI settings. - **timeout**: Connection timeout. - **executor**: Custom executor for blocking operations. - **echo**: Enable/disable query echoing. - **after_created**: Callback function executed after connection creation. ### Pool Parameters - **minsize**: Minimum pool size. - **maxsize**: Maximum pool size. - **echo**: Enable/disable pool echo. - **pool_recycle**: Connection recycle interval. - **loop**: Event loop for the pool. - **\[kwargs]**: Additional keyword arguments passed to `connect()`. ### Parameter Descriptions - Detailed explanation of each connection and pool parameter. ### Connection String Examples - **SQLite**: Example connection strings. - **PostgreSQL**: Example connection strings. - **SQL Server**: Example connection strings. - **MySQL**: Example connection strings. ### Common Additional Parameters - **User, Password, Encrypt, TrustServerCertificate**, etc. ### Configuration Examples - **dev, production**: Environment-specific configurations. - **PostgreSQL, MySQL**: Database-specific configurations. ### Environment-Based Configuration - Patterns for configuring the library using environment variables. ### Validation Rules - Description of validation rules for parameters and associated error cases. ### Usage Examples - Includes 10+ configuration examples. ``` -------------------------------- ### Usage Patterns and Examples Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Practical guide to common usage patterns with numerous code examples for various operations. ```APIDOC ## Usage Patterns and Examples ### Description Illustrates common ways to use the aioodbc library through practical code examples, covering a wide range of operations from basic connections to advanced concurrency and metadata queries. ### Basic Operations - **Basic connection and query patterns**. ### Connection Pooling - **Connection pooling patterns** (with context manager, manual management). ### Data Fetching - **Data fetching patterns** (single row, all rows, batches, async iteration). ### Data Manipulation - **Insert/update/delete patterns**. ### Transaction Management - **Transaction management and savepoints**. ### Error Handling and Recovery - **Error handling and recovery strategies**. ### Query Echo and Debugging - **Using query echo for debugging**. ### Type Conversion - **Type conversion with custom converters**. ### Concurrent Operations - **Concurrent operations** (pool acquisitions, cursor operations). ### Metadata Queries - **Metadata queries** (tables, columns, primary keys). ### Database Initialization - **Database initialization** (schema creation, seeding). ### Framework Integration - **Integration with asyncio frameworks** (aiohttp, background tasks). ### Code Examples - Includes 20+ practical code examples demonstrating various patterns. ``` -------------------------------- ### Install development requirements Source: https://github.com/aio-libs/aioodbc/blob/master/CONTRIBUTING.rst Install all necessary libraries for development after activating your virtual environment. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### MySQL Connection String Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Example of a DSN string for connecting to a MySQL database. ```python dsn = "Driver=MySQL ODBC 8.0;Server=localhost;Database=mydb;User=root;Password=secret" ``` -------------------------------- ### Configuration Example for Production Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt A configuration example tailored for production environments. It typically focuses on performance and stability, potentially disabling verbose logging. ```python connection_params = { 'dsn': 'my_prod_db', 'user': 'prod_user', 'password': 'prod_password', 'autocommit': False, 'timeout': 30 } ``` -------------------------------- ### PostgreSQL Connection String Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Example of a DSN string for connecting to a PostgreSQL database. ```python dsn = "Driver=PostgreSQL;Server=localhost;Port=5432;Database=mydb" ``` -------------------------------- ### Development Database Setup Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Configure a development pool with low resource usage and query logging for local testing. ```python async def main(): async with aioodbc.create_pool( dsn="Driver=SQLite3;Database=dev.db", minsize=2, maxsize=5, echo=True # Log all queries ) as pool: async with pool.acquire() as conn: cur = await conn.cursor() await cur.execute("SELECT 1;") await cur.close() ``` -------------------------------- ### Cursor Description Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-cursor.md Example demonstrating how to access and interpret the cursor's description property after executing a query. ```python await cur.execute("SELECT id INT, name VARCHAR(50) FROM users;") # description is now: # [('id', int, None, 10, 10, 0, True), ('name', str, None, 50, 50, 0, True)] for col_info in cur.description: name, type_code = col_info[0], col_info[1] print(f"{name}: {type_code.__name__}") ``` -------------------------------- ### Production Database Setup Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Set up a production pool with higher concurrency and connection recycling for long-running applications. ```python async def main(): async with aioodbc.create_pool( dsn="Driver=ODBC Driver 17 for SQL Server;Server=prod.database.windows.net;Database=mydb", minsize=20, maxsize=50, pool_recycle=1800, # Recycle every 30 minutes User=os.getenv("DB_USER"), Password=os.getenv("DB_PASSWORD"), Encrypt="yes", TrustServerCertificate="no" ) as pool: # High-concurrency application pass ``` -------------------------------- ### Basic Pool Creation Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-pool.md Demonstrates basic pool creation and usage within an async context manager. Ensures connections are automatically managed. ```python import aioodbc import asyncio async def main(): dsn = "Driver=SQLite3;Database=example.db" async with aioodbc.create_pool(dsn=dsn) as pool: async with pool.acquire() as conn: cur = await conn.cursor() await cur.execute("SELECT 42;") print(await cur.fetchone()) await cur.close() asyncio.run(main()) ``` -------------------------------- ### SQLite Connection String Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Example of a DSN string for connecting to a SQLite database. ```python dsn = "Driver=SQLite3;Database=/path/to/db.sqlite" ``` -------------------------------- ### Connect to Database Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-connection.md Establishes a database connection using a DSN. This example demonstrates direct await usage for obtaining a connection. ```python import aioodbc import asyncio async def main(): dsn = "Driver=SQLite3;Database=example.db" conn = await aioodbc.connect(dsn=dsn) try: # Use connection cur = await conn.cursor() await cur.execute("SELECT 42;") result = await cur.fetchone() print(result) await cur.close() finally: await conn.close() asyncio.run(main()) ``` -------------------------------- ### Pool Creation with Custom Size Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-pool.md Example of creating a connection pool with specified minimum and maximum connection sizes. ```python async def main(): dsn = "Driver=SQLite3;Database=example.db" # Maintain 5-20 connections async with aioodbc.create_pool(dsn=dsn, minsize=5, maxsize=20) as pool: # Pool starts with 5 idle connections # Can grow to 20 connections under load pass ``` -------------------------------- ### SQL Server Connection String Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Example of a DSN string for connecting to a SQL Server database, including encryption settings. ```python dsn = "Driver=ODBC Driver 17 for SQL Server;Server=myserver.database.windows.net;Database=mydb;UID=user@server;PWD=password;Encrypt=yes" ``` -------------------------------- ### Install ipdb for debugging Source: https://github.com/aio-libs/aioodbc/blob/master/CONTRIBUTING.rst Optionally install the ipdb debugger for enhanced debugging capabilities. ```bash pip install ipdb ``` -------------------------------- ### Connection String Example for PostgreSQL Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Provides an example of a connection string for PostgreSQL databases. This format is used when specifying the DSN parameter. ```sql DRIVER={PostgreSQL Unicode};SERVER=localhost;PORT=5432;DATABASE=mydatabase;UID=myuser;PWD=mypassword; ``` -------------------------------- ### Connection String Example for SQL Server Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Illustrates a connection string format for SQL Server databases. This is used for connecting to SQL Server instances. ```sql DRIVER={ODBC Driver 17 for SQL Server};SERVER=myserver.database.windows.net;DATABASE=mydatabase;UID=myuser;PWD=mypassword;Encrypt=yes;TrustServerCertificate=no; ``` -------------------------------- ### Example of Pool Acquire Behavior Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-pool.md Demonstrates the behavior of acquiring connections from a pool, showing changes in pool size and free connections. ```python async with aioodbc.create_pool(dsn=dsn, minsize=5) as pool: # Acquire first connection async with pool.acquire() as conn1: print(f"Pool size: {pool.size}") # 5 (created) print(f"Free: {pool.freesize}") # 4 (1 in-use) async with pool.acquire() as conn2: print(f"Free: {pool.freesize}") # 3 (2 in-use) print(f"Free: {pool.freesize}") # 4 (conn2 released) print(f"Free: {pool.freesize}") # 5 (conn1 released) ``` -------------------------------- ### Create Pool with DSN Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Example of creating a connection pool using a Data Source Name (DSN) string. ```python pool = await aioodbc.create_pool(dsn="Driver=SQLite3;Database=db.sqlite") ``` -------------------------------- ### Basic aioodbc Query Execution Source: https://github.com/aio-libs/aioodbc/blob/master/docs/examples.rst Demonstrates a simple query execution using aioodbc. This example connects to a database and fetches a result. ```python import aioodbc import asyncio async def main(): conn = await aioodbc.connect(dsn='ExampleDSN', user='user', password='password') cursor = await conn.cursor() await cursor.execute('SELECT 42') row = await cursor.fetchone() print(row) await cursor.close() await conn.close() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Auto-Commit Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Demonstrates using aioodbc with autocommit=True, where statements are automatically committed. ```python # Auto-commit async with aioodbc.connect(dsn=dsn, autocommit=True) as conn: cur = await conn.cursor() await cur.execute("INSERT INTO users VALUES (1, 'Alice');") # Implicit auto-commit, no explicit commit needed ``` -------------------------------- ### Cursor Arraysize Usage Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-cursor.md Example showing how to set the arraysize property to control the batch size for fetchmany() calls. ```python cur.arraysize = 100 # Fetch 100 rows per fetchmany() call rows = await cur.fetchmany() # Fetches up to 100 rows ``` -------------------------------- ### Cursor Close Method Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-cursor.md Example demonstrating the usage of the close() method to close a cursor and verifying its closed state. ```python cur = await conn.cursor() await cur.execute("SELECT 42;") result = await cur.fetchone() await cur.close() assert cur.closed # True ``` -------------------------------- ### Connection String Example for MySQL Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Shows a typical connection string for MySQL databases. This format is used when the DSN parameter requires a full connection string. ```sql DRIVER={MySQL ODBC 8.0 Unicode Driver};Server=localhost;Database=mydatabase;Uid=myuser;Pwd=mypassword; ``` -------------------------------- ### Connect to a Database Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Establishes a connection to a database using the connect() factory function. This is the primary way to get a connection object for interacting with the database. ```python import aioodbc async def connect_to_db(): conn = await aioodbc.connect(dsn='my_dsn', user='my_user', password='my_password') # Use the connection object await conn.close() # Example usage: # asyncio.run(connect_to_db()) ``` -------------------------------- ### Seed Database with Initial Data Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/usage-patterns.md Populates the database with initial data using `executemany` for efficiency. This example demonstrates inserting multiple rows and requires manual commit. ```python async def seed_database(dsn): """Seed database with initial data.""" async with aioodbc.connect(dsn=dsn, autocommit=False) as conn: async with conn.cursor() as cur: # Insert initial users await cur.executemany( "INSERT INTO users (name, email) VALUES (?, ?);", ("Alice", "alice@example.com"), ("Bob", "bob@example.com"), ("Charlie", "charlie@example.com"), ) await conn.commit() asyncio.run(seed_database(dsn)) ``` -------------------------------- ### Default Unicode Connection Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Shows the default behavior of aioodbc.connect() which attempts to use Unicode (SQLDriverConnectW) first. ```python # Default: try Unicode first async with aioodbc.connect(dsn=dsn) as conn: pass ``` -------------------------------- ### Explicit Commit Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Demonstrates using aioodbc with autocommit=False, requiring an explicit commit after executing statements. ```python # Explicit commit required async with aioodbc.connect(dsn=dsn, autocommit=False) as conn: cur = await conn.cursor() await cur.execute("INSERT INTO users VALUES (1, 'Alice');") await conn.commit() # Explicit commit ``` -------------------------------- ### Login Timeout Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Configures a specific login timeout for establishing a connection. If the connection takes longer than the specified seconds, a pyodbc.OperationalError is raised. ```python # 30-second login timeout async with aioodbc.connect(dsn=dsn, timeout=30) as conn: # If connection takes > 30 seconds, raises pyodbc.OperationalError pass ``` -------------------------------- ### Force ANSI Connection Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Demonstrates forcing aioodbc.connect() to use ANSI mode (SQLDriverConnect) by setting ansi=True. ```python # Force ANSI async with aioodbc.connect(dsn=dsn, ansi=True) as conn: pass ``` -------------------------------- ### Custom Output Converter Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Demonstrates how to add a custom converter function to transform specific data types fetched from the database. This allows for flexible data handling. ```python import aioodbc import datetime def parse_custom_datetime(value): if isinstance(value, str): return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') return value async def use_custom_converter(conn): # Assuming a column 'event_time' stores datetime as string conn.add_output_converter("event_time", parse_custom_datetime) async with conn.cursor() as cursor: await cursor.execute("SELECT event_time FROM events LIMIT 1") row = await cursor.fetchone() if row: print(f"Parsed event time: {row.event_time}") print(f"Type: {type(row.event_time)}") # Example usage: # conn = await aioodbc.connect(dsn='my_dsn') # asyncio.run(use_custom_converter(conn)) # await conn.close() ``` -------------------------------- ### Pass-through Arguments to Connections Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Example of passing additional keyword arguments to `aioodbc.connect()` for all connections created by the pool. This allows configuring connection-specific settings like user, password, or autocommit. ```python # All pooled connections use these settings pool = await aioodbc.create_pool( dsn=dsn, minsize=5, maxsize=10, User="dbuser", Password=os.getenv("DB_PASSWORD"), autocommit=True, executor=my_executor ) ``` -------------------------------- ### Set Environment Variables for Database Connection Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Example bash commands to export environment variables required for establishing a database connection using aioodbc. Ensure these are set before running the application. ```bash export DB_DRIVER="ODBC Driver 17 for SQL Server" export DB_SERVER="prod.database.windows.net" export DB_DATABASE="mydb" export DB_USER="myuser@myserver" export DB_PASSWORD="mypassword" export DB_POOL_MIN="10" export DB_POOL_MAX="30" export DB_POOL_RECYCLE="1800" ``` -------------------------------- ### Custom Thread Pool Example Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Shows how to provide a custom ThreadPoolExecutor for aioodbc operations. If not provided, the event loop's default executor is used. ```python from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor(max_workers=10) async with aioodbc.connect(dsn=dsn, executor=executor) as conn: # Operations use the custom executor cur = await conn.cursor() await cur.execute("SELECT 1;") ``` -------------------------------- ### Custom Output Type Converters Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/usage-patterns.md Set up custom converters to modify how data types are returned from the database. This example shows converting strings to uppercase and decimals to strings. ```python import pyodbc from decimal import Decimal async def init_converters(conn): """Set up custom type converters.""" # Convert strings to uppercase def upper(s): return s.upper() if isinstance(s, str) else s await conn.add_output_converter(pyodbc.SQL_VARCHAR, upper) # Convert decimals to strings def decimal_to_string(s): return str(Decimal(s)) if s else None await conn.add_output_converter(pyodbc.SQL_DECIMAL, decimal_to_string) async with aioodbc.connect( dsn=dsn, after_created=init_converters ) as conn: async with conn.cursor() as cur: await cur.execute("SELECT name, price FROM products;") row = await cur.fetchone() print(row) # name is uppercase, price is string ``` -------------------------------- ### Configure Minimum Pool Size Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Demonstrates setting the minimum number of idle connections to maintain in the pool. The pool starts with this size and creates new connections if the free size drops below this value. ```python # Maintain at least 5 idle connections pool = await aioodbc.create_pool(dsn=dsn, minsize=5, maxsize=20) # Initially, pool has 5 connections print(pool.size) # 5 print(pool.freesize) # 5 ``` -------------------------------- ### Build project documentation Source: https://github.com/aio-libs/aioodbc/blob/master/CONTRIBUTING.rst Generate the project's documentation locally to preview changes before submitting a pull request. ```bash make doc ``` -------------------------------- ### Connect to a Database and Use Connection Pool Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-module.md Demonstrates how to establish a connection to a database using a DSN and how to utilize a connection pool for managing multiple connections. Imports the main aioodbc library. ```python import aioodbc # Connect to a single database async with aioodbc.connect(dsn="Driver=SQLite3;Database=db.sqlite") as conn: pass # Use connection pool async with aioodbc.create_pool(dsn="Driver=SQLite3;Database=db.sqlite") as pool: async with pool.acquire() as conn: pass # List available databases sources = await aioodbc.dataSources() ``` -------------------------------- ### Creating a Connection Pool Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/README.md Illustrates how to create and configure a connection pool with specified minimum and maximum sizes for efficient connection reuse. ```python pool = await aioodbc.create_pool(dsn=dsn, minsize=10, maxsize=20) # Maintains 10 idle connections, can grow to 20 under load ``` -------------------------------- ### Create aioodbc Pool with Minimum Connections Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-pool.md Demonstrates creating a pool and ensuring a minimum number of connections are established upon startup. The pool is ready for acquire calls once the minimum size is met. ```python async with aioodbc.create_pool(dsn=dsn, minsize=5) as pool: # At this point, pool has 5 idle connections assert pool.freesize == 5 assert pool.size == 5 ``` -------------------------------- ### Connection.rollback() Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-connection.md Rolls back (undoes) any pending transaction to the start. This discards all uncommitted changes. ```APIDOC ## rollback() ### Description Roll back (undo) any pending transaction to the start. Executes `pyodbc.Connection.rollback()` in the thread pool. Discards all uncommitted changes in the transaction. ### Method `rollback()` ### Return Type `None` ### Example ```python cur = await conn.cursor() await cur.execute("INSERT INTO users (name) VALUES (?);", "Bob") # Undo the insert before commit await conn.rollback() ``` ``` -------------------------------- ### Run the aioodbc test suite Source: https://github.com/aio-libs/aioodbc/blob/master/CONTRIBUTING.rst Execute the full test suite, including static and style checkers, after setting up the environment. ```bash make test ``` -------------------------------- ### Automatic Resource Cleanup with Context Managers Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/errors.md Demonstrates the preferred method of using context managers (async with) for both connections and cursors to ensure automatic and safe cleanup of resources, even in the presence of errors. ```python # Better: Use context managers (automatic cleanup) async with aioodbc.connect(dsn=dsn) as conn: async with conn.cursor() as cur: try: await cur.execute("SELECT * FROM large_table;") rows = await cur.fetchall() except pyodbc.DatabaseError as e: print(f"Error: {e}") # Cursor and connection auto-close on exit ``` -------------------------------- ### Rollback Database Transaction Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-connection.md Rolls back (undoes) any pending transaction to the start. Discards all uncommitted changes in the transaction. ```python async def rollback(self) -> None ``` ```python cur = await conn.cursor() await cur.execute("INSERT INTO users (name) VALUES (?);", "Bob") # Undo the insert before commit await conn.rollback() ``` -------------------------------- ### Using Async Context Managers for Connection and Cursor Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/README.md Demonstrates how to use async context managers for managing database connections and cursors, ensuring automatic resource cleanup. ```python async with aioodbc.connect(dsn=dsn) as conn: async with conn.cursor() as cur: await cur.execute("SELECT 1;") ``` -------------------------------- ### Connect using Context Manager Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-connection.md Establishes a database connection using a DSN and the `async with` statement for automatic resource management. This ensures the connection is properly closed. ```python async def main(): dsn = "Driver=SQLite3;Database=example.db" async with aioodbc.connect(dsn=dsn) as conn: async with conn.cursor() as cur: await cur.execute("SELECT 42;") print(await cur.fetchone()) ``` -------------------------------- ### Cursor Arraysize Property Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-cursor.md Get or set the number of rows to fetch at a time with fetchmany(). The default value is 1. ```python @property def arraysize(self) -> int @arraysize.setter def arraysize(self, size: int) -> None ``` -------------------------------- ### Get Type Information Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-cursor.md Retrieves information about supported SQL data types. Can be used for a specific type or all supported types. ```python def getTypeInfo(self, sql_type: int) -> Awaitable[None]: ``` -------------------------------- ### Get Table Metadata Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Retrieves metadata about tables in the database, such as table names. This is useful for introspection and dynamic query generation. ```python import aioodbc async def get_table_names(conn): async with conn.cursor() as cursor: tables = await cursor.tables() for table in tables: print(f"Table: {table.table_name}") # Example usage: # conn = await aioodbc.connect(dsn='my_dsn') # asyncio.run(get_table_names(conn)) # await conn.close() ``` -------------------------------- ### aioodbc.connect() Parameters Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Shows the signature for the aioodbc.connect() function, listing all available keyword arguments for establishing a database connection. ```python aioodbc.connect( dsn="...", autocommit=False, ansi=False, timeout=0, executor=None, echo=False, after_created=None, **kwargs ) ``` -------------------------------- ### Get Table Statistics Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Retrieves statistics about a table, such as its type and remarks. This can provide high-level information about the table's purpose or characteristics. ```python import aioodbc async def get_table_stats(conn, table_name): async with conn.cursor() as cursor: stats = await cursor.statistics(table=table_name, unique=False, approx=True) print(f"Statistics for table '{table_name}':") for stat in stats: print(f" - Column Name: {stat.column_name}, Index Name: {stat.index_name}, Type: {stat.type}") # Example usage: # conn = await aioodbc.connect(dsn='my_dsn') # asyncio.run(get_table_stats(conn, 'users')) # await conn.close() ``` -------------------------------- ### Get Connection Information Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Retrieves various attributes and information about the current database connection. This can be useful for diagnostics and understanding connection state. ```python import aioodbc async def get_connection_info(conn): info = await conn.getinfo() print(f"Database Product Name: {info.get('SQL_DBMS_NAME')}") print(f"Database Major Version: {info.get('SQL_DBMS_VER_MAJOR')}") print(f"Database Minor Version: {info.get('SQL_DBMS_VER_MINOR')}") # Example usage: # conn = await aioodbc.connect(dsn='my_dsn') # asyncio.run(get_connection_info(conn)) # await conn.close() ``` -------------------------------- ### Execute a Simple SELECT Query Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/usage-patterns.md Demonstrates how to connect to a database, create a cursor, execute a simple SELECT query, and fetch a single row. The connection and cursor are automatically closed upon exiting the context managers. ```python import asyncio import aioodbc async def main(): dsn = "Driver=SQLite3;Database=example.db" # Create connection (auto-closes on exit) async with aioodbc.connect(dsn=dsn) as conn: # Create cursor (auto-closes on exit) async with conn.cursor() as cur: # Execute query await cur.execute("SELECT * FROM users WHERE id = ?;", 42) # Fetch result row = await cur.fetchone() if row: print(f"User: {row}") asyncio.run(main()) ``` -------------------------------- ### Create and Use Connection Pool with Context Manager Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/usage-patterns.md Demonstrates creating a connection pool using a context manager, acquiring a connection from the pool, executing a query, and fetching results. The pool is automatically closed upon exiting the context manager. ```python async def main(): dsn = "Driver=SQLite3;Database=example.db" # Create pool (auto-closed on exit) async with aioodbc.create_pool(dsn=dsn, minsize=5, maxsize=10) as pool: # Acquire connection from pool async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute("SELECT COUNT(*) AS cnt FROM users;") result = await cur.fetchone() print(f"Total users: {result.cnt}") asyncio.run(main()) ``` -------------------------------- ### clear() Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-pool.md Closes all idle connections in the pool. This is useful for forcing the creation of new connections, for example, after database maintenance or if connection issues are suspected. ```APIDOC ## clear() ### Description Close all idle (free) connections in the pool. ### Method `clear()` ### Behavior Removes all connections from the free pool and closes them. In-use connections are not affected. ### Use case To force fresh connections after database maintenance or connection issues. ### Usage ```python async with aioodbc.create_pool(dsn=dsn) as pool: # ... use pool ... # Clear all idle connections await pool.clear() # Next acquire will create fresh connections async with pool.acquire() as conn: pass ``` ``` -------------------------------- ### Basic aioodbc Connection and Query Source: https://github.com/aio-libs/aioodbc/blob/master/README.rst Demonstrates establishing a connection to an ODBC data source, executing a simple query, fetching results, and closing the connection. Use this for straightforward, single operations. ```python import asyncio import aioodbc async def test_example(): dsn = "Driver=SQLite;Database=sqlite.db" conn = await aioodbc.connect(dsn=dsn) cur = await conn.cursor() await cur.execute("SELECT 42 AS age;") rows = await cur.fetchall() print(rows) print(rows[0]) print(rows[0].age) await cur.close() await conn.close() asyncio.run(test_example()) ``` -------------------------------- ### connect() Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-connection.md Factory function that returns a context manager for establishing database connections. It supports direct await or usage with `async with`. ```APIDOC ## connect() ### Description Factory function that returns a context manager for establishing database connections. It supports direct await or usage with `async with`. ### Method Factory function (coroutine) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **dsn** (str) - Required - ODBC connection string. Example: `"Driver=SQLite;Database=db.sqlite"` - **autocommit** (bool) - Optional - Default: `False` - If True, connection operates in ODBC autocommit mode and statements commit automatically. If False, explicit `commit()` or `rollback()` is required - **ansi** (bool) - Optional - Default: `False` - Use ANSI version of SQLDriverConnect. By default pyodbc attempts Unicode version first (SQLDriverConnectW), then falls back to ANSI if driver returns IM001 - **timeout** (int) - Optional - Default: `0` - Login timeout in seconds. Sets SQL_ATTR_LOGIN_TIMEOUT. Value 0 means database default timeout - **loop** (asyncio.AbstractEventLoop) - Optional - Default: `None` - **Deprecated**. Has no effect. Current event loop is used automatically - **executor** (concurrent.futures.ThreadPoolExecutor) - Optional - Default: `None` - Custom thread pool executor for operations. If None, default event loop executor is used - **echo** (bool) - Optional - Default: `False` - Enable query logging. When True, SQL statements are logged via `aioodbc.log.logger` - **after_created** (Callable[[pyodbc.Connection], Awaitable[None]]) - Optional - Default: `None` - Async callback function invoked after connection succeeds. Receives the raw pyodbc connection object. Useful for initialization (e.g., setting connection attributes) - **kwargs** (dict) - Optional - Additional keyword arguments passed to `pyodbc.connect()`. Common examples: `User`, `Password`, `TrustServerCertificate`, `Encrypt` ### Return Type `_ContextManager[Connection]` Returns a context manager that can be used with `async with` or awaited directly. ### Raises - `pyodbc.DatabaseError` (or subclass) – Connection fails (invalid DSN, authentication error, network timeout, etc.) ### Usage Examples #### Basic connection ```python import aioodbc import asyncio async def main(): dsn = "Driver=SQLite3;Database=example.db" conn = await aioodbc.connect(dsn=dsn) try: # Use connection cur = await conn.cursor() await cur.execute("SELECT 42;") result = await cur.fetchone() print(result) await cur.close() finally: await conn.close() asyncio.run(main()) ``` #### With context manager ```python async def main(): dsn = "Driver=SQLite3;Database=example.db" async with aioodbc.connect(dsn=dsn) as conn: async with conn.cursor() as cur: await cur.execute("SELECT 42;") print(await cur.fetchone()) ``` #### With initialization hook ```python async def init_connection(raw_conn): """Initialize the raw pyodbc connection.""" raw_conn.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8') raw_conn.setencoding(encoding='utf-8') async def main(): dsn = "Driver=PostgreSQL;Server=localhost;Database=mydb" async with aioodbc.connect( dsn=dsn, User="user", Password="pass", after_created=init_connection ) as conn: # Connection is initialized pass ``` #### With custom executor ```python from concurrent.futures import ThreadPoolExecutor async def main(): executor = ThreadPoolExecutor(max_workers=5) dsn = "Driver=SQLite3;Database=example.db" conn = await aioodbc.connect(dsn=dsn, executor=executor) # Use connection... await conn.close() ``` ``` -------------------------------- ### Create a virtual environment with virtualenvwrapper Source: https://github.com/aio-libs/aioodbc/blob/master/CONTRIBUTING.rst Use this command to create a Python 3.5 virtual environment named 'aioodbc' using virtualenvwrapper. ```bash cd aioodbc mkvirtualenv --python=`which python3.5` aioodbc ``` -------------------------------- ### Using Async Context Managers for Connection Pool Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/README.md Shows how to use async context managers for managing a connection pool, ensuring resources are properly acquired and released. ```python async with aioodbc.create_pool(dsn=dsn) as pool: async with pool.acquire() as conn: pass ``` -------------------------------- ### Connection Recycling Logic Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/types.md Example of how loop time is used to determine connection recycling. Connections idle longer than `pool_recycle` seconds are considered for recycling. ```python pool_recycle = 1800 # Recycle connections idle > 1800 seconds # Compared against: loop.time() - conn.last_usage ``` -------------------------------- ### Using Connection Pool with Context Manager Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Shows how to use the connection pool's `acquire` method as an asynchronous context manager. This ensures connections are automatically released back to the pool. ```python import aioodbc async def use_pool_context_manager(pool): async with pool.acquire() as conn: print("Connection acquired from pool.") async with conn.cursor() as cursor: await cursor.execute("SELECT 1") result = await cursor.fetchone() print(f"Query result: {result}") print("Connection released back to pool.") # Example usage: # pool = await aioodbc.create_pool(dsn='my_dsn') # asyncio.run(use_pool_context_manager(pool)) # await pool.close() ``` -------------------------------- ### Get Foreign Keys for a Table Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Retrieves the foreign key constraints for a given table. This helps in understanding how tables are related through foreign key relationships. ```python import aioodbc async def get_foreign_keys(conn, table_name): async with conn.cursor() as cursor: fk_info = await cursor.foreignKeys(table=table_name) print(f"Foreign keys for table '{table_name}':") for fk in fk_info: print(f" - FK Name: {fk.fk_name}, PK Table: {fk.pk_table_name}, PK Column: {fk.pk_column_name}") # Example usage: # conn = await aioodbc.connect(dsn='my_dsn') # asyncio.run(get_foreign_keys(conn, 'order_items')) # await conn.close() ``` -------------------------------- ### Get Column Metadata Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Retrieves metadata about columns for a specific table, including column names, types, and constraints. This aids in understanding table structures. ```python import aioodbc async def get_column_info(conn, table_name): async with conn.cursor() as cursor: columns = await cursor.columns(table=table_name) for column in columns: print(f"Column: {column.column_name}, Type: {column.type_name}") # Example usage: # conn = await aioodbc.connect(dsn='my_dsn') # asyncio.run(get_column_info(conn, 'users')) # await conn.close() ``` -------------------------------- ### Get Driver Information Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-connection.md Retrieve general information about the driver and data source using a pyodbc.SQL_* constant. This method calls SQLGetInfo() in the thread pool. ```python import pyodbc # Get driver capability for CREATE TABLE capability = await conn.getinfo(pyodbc.SQL_CREATE_TABLE) print(f"CREATE TABLE capability: {capability}") ``` -------------------------------- ### aioodbc Connection Pool Creation and Usage Source: https://github.com/aio-libs/aioodbc/blob/master/README.rst Shows how to create a connection pool for managing multiple database connections efficiently. Acquire connections from the pool using 'async with' for automatic release. ```python import asyncio import aioodbc async def test_pool(): dsn = "Driver=SQLite3;Database=sqlite.db" pool = await aioodbc.create_pool(dsn=dsn) async with pool.acquire() as conn: cur = await conn.cursor() await cur.execute("SELECT 42;") r = await cur.fetchall() print(r) await cur.close() await conn.close() pool.close() await pool.wait_closed() asyncio.run(test_pool()) ``` -------------------------------- ### Connection Autocommit Property Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-connection.md Get or set the autocommit mode. When True, SQL statements are committed immediately. When False, an explicit `commit()` call is required. ```python @property def autocommit(self) -> bool @autocommit.setter def autocommit(self, value: bool) -> None ``` -------------------------------- ### Connect with Initialization Hook Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-connection.md Establishes a database connection and executes an asynchronous initialization function (`after_created`) immediately after the connection is established. This is useful for setting connection-specific attributes or configurations. ```python async def init_connection(raw_conn): """Initialize the raw pyodbc connection.""" raw_conn.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8') raw_conn.setencoding(encoding='utf-8') async def main(): dsn = "Driver=PostgreSQL;Server=localhost;Database=mydb" async with aioodbc.connect( dsn=dsn, User="user", Password="pass", after_created=init_connection ) as conn: # Connection is initialized pass ``` -------------------------------- ### Concurrent Pool Acquisitions Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/usage-patterns.md Demonstrates how to acquire multiple connections from a pool concurrently and execute queries. Ensure the pool is created with appropriate minsize and maxsize. ```python import asyncio async def query_user(pool, user_id): """Fetch user data.""" async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute("SELECT * FROM users WHERE id = ?;", user_id) return await cur.fetchone() async def main(): async with aioodbc.create_pool(dsn=dsn, minsize=10, maxsize=20) as pool: # Execute multiple queries concurrently user_ids = [1, 2, 3, 4, 5] results = await asyncio.gather( *[query_user(pool, uid) for uid in user_ids] ) for user in results: print(user) asyncio.run(main()) ``` -------------------------------- ### Get Primary Keys for a Table Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/MANIFEST.txt Retrieves the primary key columns for a given table. This information is essential for understanding table relationships and performing updates or deletes. ```python import aioodbc async def get_primary_keys(conn, table_name): async with conn.cursor() as cursor: pk_info = await cursor.primaryKeys(table=table_name) print(f"Primary keys for table '{table_name}':") for pk in pk_info: print(f" - Column: {pk.column_name}, Key Sequence: {pk.key_seq}") # Example usage: # conn = await aioodbc.connect(dsn='my_dsn') # asyncio.run(get_primary_keys(conn, 'orders')) # await conn.close() ``` -------------------------------- ### aioodbc.create_pool() Parameters Overview Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md This snippet shows the signature of the `create_pool` function, listing its main parameters. ```python aioodbc.create_pool( dsn="...", minsize=10, maxsize=10, echo=False, pool_recycle=-1, **kwargs ) ``` -------------------------------- ### Configure Logging for aioodbc Queries Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-module.md Demonstrates how to set up Python's standard logging module to capture and display SQL queries executed by aioodbc when echo=True is enabled. This is useful for debugging. ```python import logging # Set up logging to see SQL queries logging.basicConfig(level=logging.INFO) logger = logging.getLogger("aioodbc") logger.setLevel(logging.DEBUG) # Now queries will be logged when echo=True is used async with aioodbc.connect(dsn=dsn, echo=True) as conn: # SQL statements will be logged pass ``` -------------------------------- ### Pool Creation with Connection Recycling Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-pool.md Demonstrates setting a connection lifetime to automatically recycle connections after a specified period. ```python async def main(): dsn = "Driver=PostgreSQL;Server=localhost" # Recycle connections every 30 minutes (1800 seconds) async with aioodbc.create_pool( dsn=dsn, pool_recycle=1800 ) as pool: pass ``` -------------------------------- ### Fetch Single Value with fetchval() Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-cursor.md Use fetchval() to retrieve the first column of the first row. It's a convenience method for getting a single scalar value from a query. ```python count = await cur.fetchval("SELECT COUNT(*) FROM users;") print(f"Total users: {count}") ``` ```python await cur.execute("SELECT MAX(age) FROM users;") max_age = await cur.fetchval() ``` -------------------------------- ### Create Database Tables Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/usage-patterns.md Initializes the database schema by creating tables and indexes if they do not already exist. This function uses autocommit for simplicity. ```python async def init_database(dsn): """Initialize database schema.""" async with aioodbc.connect(dsn=dsn, autocommit=True) as conn: async with conn.cursor() as cur: # Create users table await cur.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """) # Create indexes await cur.execute(""" CREATE INDEX IF NOT EXISTS idx_email ON users(email); """) asyncio.run(init_database(dsn)) ``` -------------------------------- ### Understanding Cursor Description Structure Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/types.md Iterate through cursor.description to get column metadata like name, type, size, and nullability. This is useful for dynamically inspecting query results. ```python await cur.execute("SELECT id INT, name VARCHAR(50), balance DECIMAL(10,2) FROM accounts;") for col_info in cur.description: name, type_code, _, internal_size, _, _, null_ok = col_info print(f"{name}: {type_code.__name__} (size={internal_size}, nullable={null_ok})") ``` -------------------------------- ### Acquire and Release Connection from Pool Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/api-reference-pool.md Shows how to acquire a connection from the pool for use within a context manager and how it is automatically released back to the pool upon exiting the context. Tracks the pool's free size during acquisition and release. ```python async with aioodbc.create_pool(dsn=dsn, minsize=3) as pool: print(f"Initial freesize: {pool.freesize}") # 3 async with pool.acquire() as conn: print(f"During use: {pool.freesize}") # 2 # Use connection print(f"After release: {pool.freesize}") # 3 ``` -------------------------------- ### Catching Constraint Violations with aioodbc Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/errors.md This example shows how to handle `pyodbc.IntegrityError`, which is raised when a database constraint (like unique, foreign key, or NOT NULL) is violated during an INSERT or UPDATE operation. ```python try: await cur.execute( "INSERT INTO users (id, email) VALUES (?, ?);", 1, "duplicate@example.com" ) except pyodbc.IntegrityError as e: print(f"Constraint violation: {e}") ``` -------------------------------- ### SQL Error Handling with Rollback Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/errors.md An example of handling specific SQL errors like IntegrityError and ProgrammingError during an insert operation, including rolling back the transaction and raising a more specific ValueError. ```python async def insert_user(conn, name, email): try: cur = await conn.cursor() await cur.execute( "INSERT INTO users (name, email) VALUES (?, ?);", name, email ) await conn.commit() await cur.close() except pyodbc.IntegrityError as e: await conn.rollback() raise ValueError(f"Duplicate email: {email}") from e except pyodbc.ProgrammingError as e: await conn.rollback() raise ValueError(f"Invalid SQL: {e}") from e ``` -------------------------------- ### Basic Try-Except for Database Operations Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/errors.md A fundamental example of using try-except blocks to catch common database-related errors like OperationalError, ProgrammingError, and generic DatabaseError during connection and query execution. ```python try: async with aioodbc.connect(dsn=dsn) as conn: cur = await conn.cursor() await cur.execute("SELECT * FROM users;") rows = await cur.fetchall() await cur.close() except pyodbc.OperationalError as e: print(f"Connection error: {e}") except pyodbc.ProgrammingError as e: print(f"SQL error: {e}") except pyodbc.DatabaseError as e: print(f"Database error: {e}") ``` -------------------------------- ### PostgreSQL Connection Initialization Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/configuration.md Configure a PostgreSQL pool with custom connection initialization, setting timezone and statement timeout. ```python async def init_postgres(conn): # Set UTC timezone conn.execute("SET timezone = 'UTC';") # Set statement timeout conn.execute("SET statement_timeout = '30s';") async def main(): async with aioodbc.create_pool( dsn="Driver=PostgreSQL;Server=localhost;Database=mydb", minsize=10, maxsize=20, User="dbuser", Password=os.getenv("DB_PASSWORD"), after_created=init_postgres ) as pool: pass ``` -------------------------------- ### Catching Data Conversion Errors with aioodbc Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/errors.md This example shows how to handle `pyodbc.DataError`, which occurs when there are issues with data conversion or values are out of range for a column, such as attempting to insert a string into a numeric column. ```python try: await cur.execute( "INSERT INTO products (price) VALUES (?);", "not_a_number" ) except pyodbc.DataError as e: print(f"Data error: {e}") ``` -------------------------------- ### aioodbc.connect() Source: https://github.com/aio-libs/aioodbc/blob/master/_autodocs/README.md Creates a database connection using the provided connection parameters. ```APIDOC ## aioodbc.connect() ### Description Creates a database connection. ### Method Not applicable (Python function) ### Parameters #### Connection Parameters - **dsn** (str) - Required - ODBC connection string - **autocommit** (bool) - Optional - Transaction mode (default: False) - **timeout** (int) - Optional - Login timeout in seconds (default: 0) - **executor** (ThreadPoolExecutor) - Optional - Custom thread pool (default: None) - **echo** (bool) - Optional - Enable query logging (default: False) - **after_created** (callable) - Optional - Init callback (default: None) ### Response #### Success Response - Returns a `aioodbc.Connection` object upon successful connection. ```