### Quickstart: SQLite Example Source: https://github.com/encode/databases/blob/master/docs/index.md Demonstrates a basic usage of the 'databases' library with an SQLite database. It covers connecting, creating a table, inserting data, and fetching records asynchronously. ```python # Create a database instance, and connect to it. from databases import Database database = Database('sqlite+aiosqlite:///example.db') await database.connect() # Create a table. query = """CREATE TABLE HighScores (id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)""" await database.execute(query=query) # Insert some data. query = "INSERT INTO HighScores(name, score) VALUES (:name, :score)" values = [ {"name": "Daisy", "score": 92}, {"name": "Neil", "score": 87}, {"name": "Carol", "score": 43}, ] await database.execute_many(query=query, values=values) # Run a database query. query = "SELECT * FROM HighScores" rows = await database.fetch_all(query=query) print('High Scores:', rows) ``` -------------------------------- ### Quickstart: SQLite Example Source: https://github.com/encode/databases/blob/master/README.md Demonstrates a basic usage of the 'databases' library with an SQLite database. It covers connecting to the database, creating a table, inserting data, and fetching records using asyncio. ```python # Create a database instance, and connect to it. from databases import Database database = Database('sqlite+aiosqlite:///example.db') await database.connect() # Create a table. query = """CREATE TABLE HighScores (id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)""" await database.execute(query=query) # Insert some data. query = "INSERT INTO HighScores(name, score) VALUES (:name, :score)" values = [ {"name": "Daisy", "score": 92}, {"name": "Neil", "score": 87}, {"name": "Carol", "score": 43}, ] await database.execute_many(query=query, values=values) # Run a database query. query = "SELECT * FROM HighScores" rows = await database.fetch_all(query=query) print('High Scores:', rows) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/encode/databases/blob/master/docs/contributing.md Installs the project dependencies, including the databases package itself, from the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Databases Package Source: https://github.com/encode/databases/blob/master/docs/index.md Installs the 'databases' Python package using pip. This is the primary command for setting up the library. ```shell pip install databases ``` -------------------------------- ### Install Databases Source: https://github.com/encode/databases/blob/master/README.md Installs the 'databases' Python package. This command is used to add the library to your project's dependencies. ```shell pip install databases ``` -------------------------------- ### Alembic Installation Source: https://github.com/encode/databases/blob/master/docs/tests_and_migrations.md Provides the command to install Alembic, a database migration tool for SQLAlchemy. ```shell pip install alembic alembic init migrations ``` -------------------------------- ### Install Databases with Database Drivers Source: https://github.com/encode/databases/blob/master/README.md Installs the 'databases' package along with specific asynchronous database drivers. Choose the driver that matches your database system. ```shell pip install databases[asyncpg] pip install databases[aiopg] pip install databases[aiomysql] pip install databases[asyncmy] pip install databases[aiosqlite] ``` -------------------------------- ### Install Databases with Database Drivers Source: https://github.com/encode/databases/blob/master/docs/index.md Installs the 'databases' package along with specific asynchronous database drivers. Choose the driver corresponding to your database. ```shell pip install databases[asyncpg] pip install databases[aiopg] pip install databases[aiomysql] pip install databases[asyncmy] pip install databases[aiosqlite] ``` -------------------------------- ### Test Database URLs Source: https://github.com/encode/databases/blob/master/docs/contributing.md Example of TEST_DATABASE_URLS environment variable configuration for testing with multiple database backends and drivers. ```text sqlite:///test.db, sqlite+aiosqlite:///test.db, mysql+aiomysql://username:password@localhost:3306/testsuite, mysql+asyncmy://username:password@localhost:3306/testsuite, postgresql+aiopg://username:password@127.0.0.1:5432/testsuite, postgresql+asyncpg://username:password@localhost:5432/testsuite ``` -------------------------------- ### Sync Database Drivers Source: https://github.com/encode/databases/blob/master/requirements.txt Synchronous database drivers for standard tooling, often used for setup, teardown, and migrations. ```python psycopg==3.1.18 pymysql==1.1.0 ``` -------------------------------- ### Execute Raw SQL Queries Source: https://github.com/encode/databases/blob/master/docs/database_queries.md Demonstrates how to execute raw SQL queries for inserting single and multiple rows, fetching multiple rows, and fetching a single row using the 'databases' library. It highlights the use of named parameters (e.g., :text) and provides examples for execute, execute_many, fetch_all, and fetch_one. ```python # Execute query = "INSERT INTO notes(text, completed) VALUES (:text, :completed)" values = {"text": "example1", "completed": True} await database.execute(query=query, values=values) # Execute many query = "INSERT INTO notes(text, completed) VALUES (:text, :completed)" values = [ {"text": "example2", "completed": False}, {"text": "example3", "completed": True}, ] await database.execute_many(query=query, values=values) # Fetch multiple rows query = "SELECT * FROM notes WHERE completed = :completed" rows = await database.fetch_all(query=query, values={"completed": True}) # Fetch single row query = "SELECT * FROM notes WHERE id = :id" result = await database.fetch_one(query=query, values={"id": 1}) ``` -------------------------------- ### Build and Preview Documentation Source: https://github.com/encode/databases/blob/master/docs/contributing.md Builds the project's documentation and provides a command to preview it locally. ```bash ./scripts/docs ``` -------------------------------- ### Set Up and Activate Virtual Environment Source: https://github.com/encode/databases/blob/master/docs/contributing.md Creates a virtual environment named 'env' and activates it. ```bash virtualenv env source env/bin/activate ``` -------------------------------- ### Docker Configuration for Testing Source: https://github.com/encode/databases/blob/master/docs/contributing.md A sample docker-compose configuration for setting up PostgreSQL and MySQL services for testing. ```dockerfile version: '2.1' services: postgres: image: postgres:10.8 environment: POSTGRES_USER: username POSTGRES_PASSWORD: password POSTGRES_DB: testsuite ports: - 5432:5432 mysql: image: mysql:5.7 environment: MYSQL_USER: username MYSQL_PASSWORD: password MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: testsuite ports: - 3306:3306 ``` -------------------------------- ### Documentation Dependencies Source: https://github.com/encode/databases/blob/master/requirements.txt Packages required for generating project documentation, including a static site generator and themes. ```python mkdocs==1.3.1 mkdocs-material==8.3.9 mkautodoc==0.1.0 ``` -------------------------------- ### Run Linting and Formatting Source: https://github.com/encode/databases/blob/master/docs/contributing.md Executes the project's linting and formatting scripts, which use tools like black, autoflake, and mypy. ```bash ./scripts/lint ``` -------------------------------- ### Run Tests Source: https://github.com/encode/databases/blob/master/docs/contributing.md Executes the project's test suite. ```bash ./scripts/test ``` -------------------------------- ### Packaging Dependencies Source: https://github.com/encode/databases/blob/master/requirements.txt Tools necessary for packaging and distributing Python projects. ```python twine==4.0.1 wheel==0.38.1 setuptools==69.0.3 ``` -------------------------------- ### Alembic Configuration for Databases Project Source: https://github.com/encode/databases/blob/master/docs/tests_and_migrations.md Shows how to configure Alembic by setting the sqlalchemy.url and target_metadata in the migrations/env.py file. This integrates Alembic with the project's database URL and table definitions. ```python # The Alembic Config object. config = context.config # Configure Alembic to use our DATABASE_URL and our table definitions. # These are just examples - the exact setup will depend on whatever # framework you're integrating against. from myapp.settings import DATABASE_URL from myapp.tables import metadata config.set_main_option('sqlalchemy.url', str(DATABASE_URL)) target_metadata = metadata ... ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/encode/databases/blob/master/docs/contributing.md Clones your fork of the databases repository and changes the directory to the repository root. ```bash git clone git@github.com:/databases.git cd databases ``` -------------------------------- ### Create Tables using SQLAlchemy Core Source: https://github.com/encode/databases/blob/master/docs/database_queries.md Demonstrates how to create database tables using SQLAlchemy Core by compiling table definitions to SQL and executing them with the 'databases' library. It includes connecting, defining a table, compiling the CREATE TABLE statement, executing it, and disconnecting. ```python from databases import Database import sqlalchemy database = Database("postgresql+asyncpg://localhost/example") # Establish the connection pool await database.connect() metadata = sqlalchemy.MetaData() dialect = sqlalchemy.dialects.postgresql.dialect() # Define your table(s) notes = sqlalchemy.Table( "notes", metadata, sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), sqlalchemy.Column("text", sqlalchemy.String(length=100)), sqlalchemy.Column("completed", sqlalchemy.Boolean), ) # Create tables for table in metadata.tables.values(): # Set `if_not_exists=False` if you want the query to throw an # exception when the table already exists schema = sqlalchemy.schema.CreateTable(table, if_not_exists=True) query = str(schema.compile(dialect=dialect)) await database.execute(query=query) # Close all connections in the connection pool await database.disconnect() ``` -------------------------------- ### Conditional Database Initialization Source: https://github.com/encode/databases/blob/master/docs/tests_and_migrations.md Shows a common pattern for initializing the Database class based on an environment variable (TESTING). It uses a different database URL for testing with force_rollback enabled. ```python if TESTING: database = Database(TEST_DATABASE_URL, force_rollback=True) else: database = Database(DATABASE_URL) ``` -------------------------------- ### Explicit Force-Rollback Transactions Source: https://github.com/encode/databases/blob/master/docs/tests_and_migrations.md Illustrates how to manually create force-rollback transactions using an async context manager for lower-level control over database operations. ```python async with database.transaction(force_rollback=True): ... ``` -------------------------------- ### Database Initialization for Test Isolation Source: https://github.com/encode/databases/blob/master/docs/tests_and_migrations.md Demonstrates how to initialize the Database class with force_rollback=True for strict test isolation between test cases. This ensures all database operations are transactional and rolled back. ```python database = Database(DATABASE_URL, force_rollback=True) ``` -------------------------------- ### Database Connection with Keyword Arguments Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Establishes a database connection using keyword arguments for configuration options like SSL and connection pool sizing. This method allows for flexible configuration. ```python database = Database('postgresql+asyncpg://localhost/example', ssl=True, min_size=5, max_size=20) ``` -------------------------------- ### Testing Dependencies Source: https://github.com/encode/databases/blob/master/requirements.txt A collection of Python packages used for testing, including linters, formatters, HTTP clients, and test runners. ```python autoflake==1.4 black==22.6.0 httpx==0.24.1 isort==5.10.1 mypy==0.971 pytest==7.1.2 pytest-cov==3.0.0 starlette==0.36.2 requests==2.31.0 ``` -------------------------------- ### Database Connection using Async Context Manager Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Establishes a database connection using an asynchronous context manager. The connection is automatically acquired and released. ```python async with Database(DATABASE_URL) as database: ... ``` -------------------------------- ### MySQL Dialect Replacement for Alembic Source: https://github.com/encode/databases/blob/master/docs/tests_and_migrations.md Demonstrates how to specify the 'pymysql' dialect for MySQL when using Alembic, as the default MySQL dialect may not support Python 3. ```python DATABASE_URL.replace(dialect="pymysql") ``` -------------------------------- ### Async Database Drivers Source: https://github.com/encode/databases/blob/master/requirements.txt Asynchronous database drivers for various SQL databases, enabling non-blocking I/O operations. ```python asyncmy==0.2.9 aiomysql==0.2.0 aiopg==1.4.0 aiosqlite==0.20.0 asyncpg==0.29.0 ``` -------------------------------- ### Execute SQLAlchemy Core Queries Source: https://github.com/encode/databases/blob/master/docs/database_queries.md Shows how to perform various database operations using SQLAlchemy Core queries with the 'databases' library, including inserting single and multiple rows, fetching all rows, fetching a single row, fetching a single value, and iterating over results. It covers connecting, executing queries, and disconnecting. ```python from databases import Database database = Database('postgresql+asyncpg://localhost/example') # Establish the connection pool await database.connect() # Execute query = notes.insert() values = {"text": "example1", "completed": True} await database.execute(query=query, values=values) # Execute many query = notes.insert() values = [ {"text": "example2", "completed": False}, {"text": "example3", "completed": True}, ] await database.execute_many(query=query, values=values) # Fetch multiple rows query = notes.select() rows = await database.fetch_all(query=query) # Fetch single row query = notes.select() row = await database.fetch_one(query=query) # Fetch single value, defaults to `column=0`. query = notes.select() value = await database.fetch_val(query=query) # Fetch multiple rows without loading them all into memory at once query = notes.select() async for row in database.iterate(query=query): ... # Close all connections in the connection pool await database.disconnect() ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/encode/databases/blob/master/docs/contributing.md Checks out a new branch for developing a new feature. ```bash git checkout -b my-new-feature-branch ``` -------------------------------- ### Transaction Management using Async Context Manager Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Manages a database transaction using an asynchronous context manager. Operations within the block are executed within a single transaction. ```python async with database.transaction(): ... ``` -------------------------------- ### Starlette Web Framework Integration Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Integrates database connection management with Starlette web framework's startup and shutdown events. Ensures the database is connected on startup and disconnected on shutdown. ```python @app.on_event("startup") async def startup(): await database.connect() @app.on_event("shutdown") async def shutdown(): await database.disconnect() ``` -------------------------------- ### Declare SQLAlchemy Table Source: https://github.com/encode/databases/blob/master/docs/database_queries.md Defines a SQLAlchemy table named 'notes' with 'id', 'text', and 'completed' columns. This is a prerequisite for using SQLAlchemy Core for database operations. ```python import sqlalchemy metadata = sqlalchemy.MetaData() notes = sqlalchemy.Table( "notes", metadata, sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), sqlalchemy.Column("text", sqlalchemy.String(length=100)), sqlalchemy.Column("completed", sqlalchemy.Boolean), ) ``` -------------------------------- ### Child Task Transaction Inheritance Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Demonstrates how child tasks can inherit and use the connection from a parent task's transaction. Changes made in the parent transaction are visible to child tasks. ```python async def add_excitement(connnection: databases.core.Connection, id: int): await connection.execute( "UPDATE notes SET text = CONCAT(text, '!!!') WHERE id = :id", {"id": id} ) async with Database(database_url) as database: async with database.transaction(): # This note won't exist until the transaction closes... await database.execute( "INSERT INTO notes(id, text) values (1, 'databases is cool')" ) # ...but child tasks can use this connection now! await asyncio.create_task(add_excitement(database.connection(), id=1)) await database.fetch_val("SELECT text FROM notes WHERE id=1") # ^ returns: "databases is cool!!!" ``` -------------------------------- ### Database Connection with Connection Pool Sizing Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Configures a MySQL database connection pool with a minimum size of 5 and a maximum size of 20 connections. These parameters control the pool's behavior. ```python database = Database('mysql+aiomysql://localhost/example?min_size=5&max_size=20') ``` -------------------------------- ### Transaction Management from a Specific Connection Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Acquires and manages a transaction from a specific database connection. This allows for finer control over transaction scope. ```python async with database.connection() as connection: async with connection.transaction(): ... ``` -------------------------------- ### Accessing Query Results with `_mapping` Source: https://github.com/encode/databases/blob/master/docs/database_queries.md Demonstrates how to access data from a query result object using both attribute access and the `_mapping` property. This is useful for processing results from raw queries and SQLAlchemy Rows consistently. ```python query = "SELECT * FROM notes WHERE id = :id" result = await database.fetch_one(query=query, values={"id": 1}) result.id # Access field via attribute result._mapping['id'] # Access field via mapping ``` -------------------------------- ### Database Connection with SSL Option Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Connects to a PostgreSQL database using SSL encryption. The SSL option is appended to the database URL. ```python database = Database('postgresql+asyncpg://localhost/example?ssl=true') ``` -------------------------------- ### Nested Transactions with Savepoints Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Illustrates nested transaction management using savepoints. Inner transactions can be rolled back without affecting the outer transaction. ```python async with databases.Database(database_url) as db: async with db.transaction() as outer: # Do something in the outer transaction ... # Suppress to prevent influence on the outer transaction with contextlib.suppress(ValueError): async with db.transaction(): # Do something in the inner transaction ... raise ValueError('Abort the inner transaction') # Observe the results of the outer transaction, # without effects from the inner transaction. await db.fetch_all('SELECT * FROM ...') ``` -------------------------------- ### Transaction Management using Function Decorator Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Applies transaction management to an asynchronous function using a decorator. The function's execution is wrapped in a transaction. ```python @database.transaction() async def create_users(request): ... ``` -------------------------------- ### Database Connection using Explicit Connect/Disconnect Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Manages a database connection by explicitly calling connect and disconnect methods. This provides more control over the connection lifecycle. ```python database = Database(DATABASE_URL) await database.connect() ... await database.disconnect() ``` -------------------------------- ### Low-Level Transaction API Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Utilizes a lower-level API for transaction management, allowing explicit commit and rollback operations. This is useful for complex transaction logic. ```python transaction = await database.transaction() try: ... except: await transaction.rollback() else: await transaction.commit() ``` -------------------------------- ### Transaction Isolation Level Source: https://github.com/encode/databases/blob/master/docs/connections_and_transactions.md Specifies the transaction isolation level, such as 'serializable', if supported by the database driver. This controls how transactions are isolated from each other. ```python async with database.transaction(isolation="serializable"): ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.