### Litestar Quickstart Plugin Setup Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/quickstart.rst Register the SQLSpec plugin and configure session injection for Litestar handlers. This example shows the basic setup required to start using SQLSpec with Litestar. ```python from litestar import Litestar from litestar.di import Provide from litestar.params import Dependency from sqlspec.litestar import SQLSpecConfig, SQLSpecPlugin from sqlspec.typing import AsyncSession def get_user(session: AsyncSession = Dependency(Provide[SQLSpecConfig.session_dependency])) -> dict: return {"user_id": 1} app = Litestar([ SQLSpecPlugin(config=SQLSpecConfig(connection_string="sqlite:///db.sqlite")) ], route_list=[ { "path": "/users/me", "get": get_user, } ]) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/litestar-org/sqlspec/blob/main/CONTRIBUTING.rst Installs all project dependencies and pre-commit hooks. This command should be run after setting up the environment. ```console make install ``` -------------------------------- ### Basic Configuration Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/configuration.rst Demonstrates the fundamental setup for SQLSpec configuration using Python. This is a starting point for most SQLSpec integrations. ```python sqlspec = SQLSpec(config=PostgresConfig(user="user", password="password", database="database")) ``` -------------------------------- ### Install VHS for Demo Recording Source: https://github.com/litestar-org/sqlspec/blob/main/CONTRIBUTING.rst Installs the VHS tool, which is used for recording terminal demos. Ensure Go is installed and configured in your PATH. ```console go install github.com/charmbracelet/vhs@latest ``` -------------------------------- ### Litestar Session Store Setup Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/session_stores.rst Configure Litestar's SessionMiddleware with a SQLSpec session store. This example demonstrates using AsyncpgStore for PostgreSQL. Ensure the session table is created if it doesn't exist. ```python from litestar import Litestar from litestar.middleware import SessionMiddleware from sqlspec.litestar import AsyncpgStore app = Litestar( route_handlers=[], middleware=[ SessionMiddleware( secret_key="a-very-secure-secret-key", store=AsyncpgStore(dsn="postgresql://user:password@host:port/database") ) ] ) ``` -------------------------------- ### Install SQLSpec with CockroachDB (uv) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the CockroachDB adapter and Google ADK SDK using uv. ```bash uv add "sqlspec[cockroach-asyncpg,adk]" ``` -------------------------------- ### Install SQLSpec with multiple extras using uv Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Install SQLSpec with multiple extras like asyncpg, msgspec, and litestar using uv. ```bash uv add "sqlspec[asyncpg,msgspec,litestar]" ``` -------------------------------- ### Install SQLSpec with MySQL (uv) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the MySQL adapter (asyncmy) and Google ADK SDK using uv. ```bash uv add "sqlspec[asyncmy,adk]" ``` -------------------------------- ### Install SQLSpec with CockroachDB (Poetry) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the CockroachDB adapter and Google ADK SDK using Poetry. ```bash poetry add "sqlspec[cockroach-asyncpg,adk]" ``` -------------------------------- ### Install SQLSpec with PostgreSQL (uv) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the PostgreSQL adapter and Google ADK SDK using uv. ```bash uv add "sqlspec[asyncpg,adk]" ``` -------------------------------- ### Install SQLSpec performance bundle with uv Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Install the performance extra with uv for Rust-backed hot-path helpers and high-speed serialization. ```bash uv add "sqlspec[performance]" ``` -------------------------------- ### Cloud Log Formatters Example Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/observability.rst This example demonstrates how to use cloud-specific log formatters for structured logging in cloud environments like GCP or AWS. It shows the setup for structured logging. ```python import logging from sqlspec.utils.logging import POOL_LOGGER_NAME # start-example # Enable pool debug logs for connection troubleshooting logging.getLogger(POOL_LOGGER_NAME).setLevel(logging.DEBUG) # Enable cloud log formatters logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s", handlers=[ logging.StreamHandler(), # Add cloud-specific handlers here, e.g., for GCP Cloud Logging or AWS CloudWatch ], ) # end-example ``` -------------------------------- ### SQLite Connection Example Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/drivers_and_querying.rst Demonstrates establishing a connection and executing a simple query with the SQLite driver. ```python from sqlspec import Session async def main() -> None: async with Session("sqlite:///:memory:") as session: await session.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name VARCHAR(255))") await session.execute("INSERT INTO users (name) VALUES (:name)", {"name": "Alice"}) result = await session.execute("SELECT * FROM users") print(result.all()) if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Install SQLSpec with DuckDB (uv) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the DuckDB adapter and Google ADK SDK using uv. ```bash uv add "sqlspec[duckdb,adk]" ``` -------------------------------- ### Install SQLSpec with PostgreSQL (Poetry) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the PostgreSQL adapter and Google ADK SDK using Poetry. ```bash poetry add "sqlspec[asyncpg,adk]" ``` -------------------------------- ### Driver Usage Example Source: https://github.com/litestar-org/sqlspec/blob/main/docs/reference/driver.rst Demonstrates the basic usage of the driver module, including importing necessary components and setting up a driver adapter. ```python from sqlspec.driver import AsyncDriverAdapterBase, SyncDriverAdapterBase from sqlspec.protocols import AsyncDriverProtocol, SyncDriverProtocol class MyAsyncDriver(AsyncDriverAdapterBase): async def connect(self, url: str) -> AsyncDriverProtocol: pass async def disconnect(self, connection: AsyncDriverProtocol) -> None: pass class MySyncDriver(SyncDriverAdapterBase): def connect(self, url: str) -> SyncDriverProtocol: pass def disconnect(self, connection: SyncDriverProtocol) -> None: pass ``` -------------------------------- ### Install SQLSpec with CockroachDB (PDM) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the CockroachDB adapter and Google ADK SDK using PDM. ```bash pdm add "sqlspec[cockroach-asyncpg,adk]" ``` -------------------------------- ### Install SQLSpec with DuckDB (Poetry) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the DuckDB adapter and Google ADK SDK using Poetry. ```bash poetry add "sqlspec[duckdb,adk]" ``` -------------------------------- ### Install SQLSpec with DuckDB (PDM) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the DuckDB adapter and Google ADK SDK using PDM. ```bash pdm add "sqlspec[duckdb,adk]" ``` -------------------------------- ### Install SQLSpec with SQLite (uv) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the SQLite adapter and Google ADK SDK using uv. ```bash uv add "sqlspec[aiosqlite,adk]" ``` -------------------------------- ### Install SQLSpec with MySQL (Poetry) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the MySQL adapter (asyncmy) and Google ADK SDK using Poetry. ```bash poetry add "sqlspec[asyncmy,adk]" ``` -------------------------------- ### Install SQLSpec Source: https://github.com/litestar-org/sqlspec/blob/main/docs/PYPI_README.md Install the SQLSpec package using pip. ```bash pip install sqlspec ``` -------------------------------- ### Install SQLSpec performance bundle with PDM Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Install the performance extra with PDM for Rust-backed hot-path helpers and high-speed serialization. ```bash pdm add "sqlspec[performance]" ``` -------------------------------- ### ADK Backend Configuration Example Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/adapters.rst Example of configuring the ADK backend using a standard config class. This demonstrates how to set up the database connection details for ADK. ```python from litestar import Litestar from litestar.contrib.adk.stores.memory import ADKMemoryStore from litestar.contrib.adk.stores.session import ADKSessionStore from sqlspec.adapters.asyncpg.adk import AsyncpgADKStore, AsyncpgADKMemoryStore class MyConfig: async def get_session_store(self) -> ADKSessionStore: return AsyncpgADKStore(dsn="postgresql+asyncpg://user:password@host:port/database") async def get_memory_store(self) -> ADKMemoryStore: return AsyncpgADKMemoryStore(dsn="postgresql+asyncpg://user:password@host:port/database") app = Litestar(stores=MyConfig()) ``` -------------------------------- ### AsyncpgConfig Example Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/backends.rst Example of configuring AsyncpgConfig for ADK, specifying connection details and ADK-specific settings like table names and FTS usage. ```python from sqlspec.adapters.asyncpg import AsyncpgConfig config = AsyncpgConfig( connection_config={"dsn": "postgresql://localhost/mydb"}, extension_config={ "adk": { "session_table": "adk_sessions", "events_table": "adk_events", "memory_table": "adk_memory_entries", "memory_use_fts": True, "owner_id_column": "tenant_id INTEGER NOT NULL", } }, ) ``` -------------------------------- ### Install SQLSpec with SQLite (Poetry) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the SQLite adapter and Google ADK SDK using Poetry. ```bash poetry add "sqlspec[aiosqlite,adk]" ``` -------------------------------- ### Install SQLSpec performance bundle with Poetry Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Install the performance extra with Poetry for Rust-backed hot-path helpers and high-speed serialization. ```bash poetry add "sqlspec[performance]" ``` -------------------------------- ### FastAPI Basic Setup Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/fastapi.rst Configure SQLSpec with your database and attach the FastAPI plugin. Use the provide_session dependency to inject sessions into your route handlers. ```python from fastapi import FastAPI, Depends from sqlspec import SqlSpec from sqlspec.ext.fastapi import SqlspecFastAPIExtension app = FastAPI() db_ext = SqlspecFastAPIExtension( extension_config={ "fastapi": { "dependency_overrides": {}, "middleware": [], } } ) spec = SqlSpec(db_ext) spec.add_config( { "connections": { "default": { "url": "sqlite:///db.sqlite3", } }, "databases": { "default": { "tables": {}, "engine_options": {}, } }, } ) @app.get("/") def read_root(session=Depends(db_ext.provide_session())): return {"message": "Hello World"} ``` -------------------------------- ### Basic Starlette Setup with SQLSpec Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/starlette.rst Demonstrates the basic setup for integrating SQLSpec with a Starlette application. This includes creating a SQLSpec instance, registering a database configuration, and attaching the plugin to the Starlette app. ```python from starlette.applications import Starlette from sqlspec import SQLSpec from sqlspec.config import AiosqliteConfig app = Starlette() spec = SQLSpec( configs=[ AiosqliteConfig(name="default", database=":memory:") ] ) spec.add_plugin_to_app(app) @app.route("/") async def homepage(request): async with request.state.sqlspec.get_session("default") as session: # Use the session here pass return JSONResponse({"hello": "world"}) ``` -------------------------------- ### Install SQLSpec with Sanic extra Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/sanic.rst Install SQLSpec with the Sanic extra using your preferred package manager. ```bash uv add "sqlspec[sanic]" ``` ```bash pip install "sqlspec[sanic]" ``` ```bash poetry add "sqlspec[sanic]" ``` ```bash pdm add "sqlspec[sanic]" ``` -------------------------------- ### Install SQLSpec with MySQL (PDM) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the MySQL adapter (asyncmy) and Google ADK SDK using PDM. ```bash pdm add "sqlspec[asyncmy,adk]" ``` -------------------------------- ### Install SQLSpec with SQLite (PDM) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the SQLite adapter and Google ADK SDK using PDM. ```bash pdm add "sqlspec[aiosqlite,adk]" ``` -------------------------------- ### Install SQLSpec with CockroachDB (pip) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the CockroachDB adapter and Google ADK SDK using pip. ```bash pip install "sqlspec[cockroach-asyncpg,adk]" ``` -------------------------------- ### Install SQLSpec with PostgreSQL (PDM) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the PostgreSQL adapter and Google ADK SDK using PDM. ```bash pdm add "sqlspec[asyncpg,adk]" ``` -------------------------------- ### Install uv Source: https://github.com/litestar-org/sqlspec/blob/main/CONTRIBUTING.rst Installs the uv package manager if not already present. This is a prerequisite for installing other project dependencies. ```console make install-uv ``` -------------------------------- ### Basic Sanic Setup Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/sanic.rst Set up a SQLSpec instance, register database configurations, and attach the SQLSpecPlugin to your Sanic application. Configure Sanic-specific options within extension_config. ```python from sanic import Sanic from sqlspec import SQLSpec, SQLSpecPlugin app = Sanic(__name__) app.config.update( { "sqlspec": { "databases": { "default": { "connection_key": "db", "pool_key": "db_pool", "session_key": "db_session", "connection_opts": { "dsn": "postgres://user:password@host:port/database" } } }, "extension_config": { "sanic": { "request_ctx_key": "db", "pool_ctx_key": "db_pool", "session_ctx_key": "db_session" } } } } ) plugin = SQLSpecPlugin(app=app) @app.get("/") async def hello_world(request): return app.response.text("Hello, world!") if __name__ == "__main__": app.run(host="0.0.0.0", port=8000) ``` -------------------------------- ### SQLSpec Registry Example Source: https://github.com/litestar-org/sqlspec/blob/main/docs/reference/base.rst Demonstrates the basic usage of the SQLSpec registry for managing database configurations and sessions. ```python from sqlspec.base import SQLSpec registry = SQLSpec() @registry.register_connection("my_db") def get_my_db_config() -> dict[str, str]: return { "connection_url": "postgresql://user:password@host:port/database", "engine_kwargs": {"pool_size": 10}, } async def main() -> None: async with registry.session("my_db") as session: # Use the session here print(session) await registry.close_all_pools() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Basic Flask Setup with SQLSpec Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/flask.rst Initialize SQLSpec, register database configuration, and attach the plugin to your Flask application. Obtain a session using plugin.get_session() within request handlers. ```python sqlspec = SQLSpec() sqlspec.add_config(SqliteConfig(name="default", url="sqlite:///db.sqlite")) plugin = SQLSpecPlugin(sqlspec, app) @app.route("/") def index(session: Session) -> str: return "Hello, world!" ``` -------------------------------- ### Install SQLSpec with DuckDB (pip) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the DuckDB adapter and Google ADK SDK using pip. ```bash pip install "sqlspec[duckdb,adk]" ``` -------------------------------- ### Install SQLSpec with multiple extras using Poetry Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Install SQLSpec with multiple extras like asyncpg, msgspec, and litestar using Poetry. ```bash poetry add "sqlspec[asyncpg,msgspec,litestar]" ``` -------------------------------- ### Install SQLSpec performance bundle with pip Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Install the performance extra with pip for Rust-backed hot-path helpers and high-speed serialization. ```bash pip install "sqlspec[performance]" ``` -------------------------------- ### Install SQLSpec with multiple extras using PDM Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Install SQLSpec with multiple extras like asyncpg, msgspec, and litestar using PDM. ```bash pdm add "sqlspec[asyncpg,msgspec,litestar]" ``` -------------------------------- ### Install SQLSpec with uv Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Use this command to add SQLSpec to your project with uv. ```bash uv add sqlspec ``` -------------------------------- ### Install SQLSpec with PostgreSQL (pip) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the PostgreSQL adapter and Google ADK SDK using pip. ```bash pip install "sqlspec[asyncpg,adk]" ``` -------------------------------- ### Install SQLSpec with MySQL (pip) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the MySQL adapter (asyncmy) and Google ADK SDK using pip. ```bash pip install "sqlspec[asyncmy,adk]" ``` -------------------------------- ### Install SQLSpec with MySQL using pip Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to install SQLSpec with the asyncmy and litestar extras using pip. ```bash pip install "sqlspec[asyncmy,litestar]" ``` -------------------------------- ### Install SQLSpec with Flask Extra Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/flask.rst Install the SQLSpec library with the Flask extra dependencies using your preferred package manager. ```bash uv add "sqlspec[flask]" ``` ```bash pip install "sqlspec[flask]" ``` ```bash poetry add "sqlspec[flask]" ``` ```bash pdm add "sqlspec[flask]" ``` -------------------------------- ### Install SQLSpec with FastAPI Extra Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/fastapi.rst Install the necessary package for SQLSpec with FastAPI support using your preferred package manager. ```bash uv add "sqlspec[fastapi]" ``` ```bash pip install "sqlspec[fastapi]" ``` ```bash poetry add "sqlspec[fastapi]" ``` ```bash pdm add "sqlspec[fastapi]" ``` -------------------------------- ### Install SQLSpec with SQLite (pip) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/installation.rst Install SQLSpec with the SQLite adapter and Google ADK SDK using pip. ```bash pip install "sqlspec[aiosqlite,adk]" ``` -------------------------------- ### Install SQLSpec with multiple extras using pip Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Install SQLSpec with multiple extras like asyncpg, msgspec, and litestar using pip. ```bash pip install "sqlspec[asyncpg,msgspec,litestar]" ``` -------------------------------- ### Minimal SELECT Execution Example Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/data_flow.rst Demonstrates a basic SELECT query execution using SQLSpec. Ensure necessary imports are present. ```python from sqlspec.drivers import AsyncPostgresDriver from sqlspec.config import StatementConfig async def execute_select() -> None: # start-example async with AsyncPostgresDriver("postgresql://user:password@host:port/database") as driver: config = StatementConfig(sql="SELECT 1") result = await driver.execute(config) print(result.value) # end-example ``` -------------------------------- ### Install SQLSpec with PostgreSQL (asyncpg) using pip Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to install SQLSpec with the asyncpg and litestar extras using pip. ```bash pip install "sqlspec[asyncpg,litestar]" ``` -------------------------------- ### Asyncpg Driver Configuration Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/drivers_and_querying.rst Provides an example of configuring the asyncpg driver for PostgreSQL connections. ```python from sqlspec import Session async def main() -> None: # Example connection string for asyncpg # Replace with your actual connection details connection_string = "postgresql+asyncpg://user:password@host:port/database" async with Session(connection_string) as session: # Your database operations here pass if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Install SQLSpec with Poetry Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Use this command to add SQLSpec to your project with Poetry. ```bash poetry add sqlspec ``` -------------------------------- ### SQLite Setup and Data Insertion Source: https://github.com/litestar-org/sqlspec/blob/main/tools/sphinx_ext/playground_template.html This snippet demonstrates how to initialize SQLSpec with a SQLite adapter, configure an in-memory database, and execute SQL scripts for table creation and data insertion. ```python from sqlspec import SQLSpec from sqlspec.adapters.sqlite import SqliteConfig spec = SQLSpec() config = spec.add_config(SqliteConfig(connection_config={"database": ":memory:"})) with spec.provide_session(config) as session: session.execute_script(""" CREATE TABLE IF NOT EXISTS teams (id INTEGER PRIMARY KEY, name TEXT); INSERT INTO teams (name) VALUES ('Litestar'), ('SQLSpec'), ('Starlite'); """) results = session.select("SELECT * FROM teams") results ``` -------------------------------- ### Run All SQLSpec Examples Source: https://github.com/litestar-org/sqlspec/blob/main/docs/examples/README.md Execute the entire suite of SQLSpec examples using pytest. This command provides a quiet output, focusing on test results. ```bash uv run pytest docs/examples/ -q ``` -------------------------------- ### Install SQLSpec with Starlette Extra (uv) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/starlette.rst Install the SQLSpec package with the Starlette extra dependencies using the 'uv' package manager. ```bash uv add "sqlspec[starlette]" ``` -------------------------------- ### Install SQLSpec with SQLite (async) using pip Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to install SQLSpec with the aiosqlite and litestar extras using pip. ```bash pip install "sqlspec[aiosqlite,litestar]" ``` -------------------------------- ### SQLCommenter Example Output Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/observability.rst Example of how SQL statements appear with SQLCommenter enabled, including driver, framework, and route information. ```sql SELECT * FROM users /* db_driver='postgresql',framework='litestar',route='%2Fusers' */ ``` -------------------------------- ### Integration Test Fixtures Example Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/testing.rst Illustrates the pattern for integration testing against real databases using SQLSpec with adapter configuration and temporary databases. ```python from pathlib import Path from sqlspec import SQLSpec from sqlspec.adapters.sqlite import SqliteConfig def test_integration_users_table(tmp_path: Path): spec = SQLSpec() config = spec.add_config( SqliteConfig(connection_config={"database": str(tmp_path / "test.db")}) ) with spec.provide_session(config) as session: session.execute("create table users (id integer primary key, name text)") session.execute_many("insert into users (name) values (?)", [("Alice",), ("Bob",)]) users = session.execute("select name from users").fetchall() assert len(users) == 2 assert users == [("Alice",), ("Bob",)] ``` -------------------------------- ### Install SQLSpec with PDM Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/installation.rst Use this command to add SQLSpec to your project with PDM. ```bash pdm add sqlspec ``` -------------------------------- ### Install SQLSpec with PostgreSQL (psycopg) using pip Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to install SQLSpec with the psycopg and litestar extras using pip. ```bash pip install "sqlspec[psycopg,litestar]" ``` -------------------------------- ### Initialize SQLSpec Playground Source: https://github.com/litestar-org/sqlspec/blob/main/tools/sphinx_ext/playground_template.html Initializes the SQLSpec playground environment, setting up the CodeMirror editor, Pyodide, and event listeners for various UI elements. This is the main setup function for the interactive playground. ```javascript (function() { const root = document.getElementById("sqlspec-playground-{{ id }}"); const outputEl = root.querySelector("[data-output]"); const tableOutputEl = root.querySelector("[data-table-output]"); const rowCountEl = root.querySelector("[data-row-count]"); const errorOutputEl = root.querySelector("[data-error-output]"); const inlineStatusEl = root.querySelector("[data-inline-status]"); const pythonTextarea = root.querySelector("[data-python-editor]"); const runPythonButton = root.querySelector("[data-run-python]"); const resetPythonButton = root.querySelector("[data-reset-python]"); const clearOutputButton = root.querySelector("[data-clear-output]"); const tipsDialog = root.querySelector("[data-tips-dialog]"); const openTipsButton = root.querySelector("[data-open-tips]"); const closeTipsButton = root.querySelector("[data-close-tips]"); const pythonDefault = pythonTextarea.value.trim(); let currentData = null; let sortColumn = null; let sortDirection = 'asc'; const pythonEditor = CodeMirror.fromTextArea(pythonTextarea, { mode: "python", lineNumbers: true, indentUnit: 4, tabSize: 4, indentWithTabs: false, viewportMargin: Infinity, styleActiveLine: true, cursorBlinkRate: 530 }); let pyodide = null; const setInlineStatus = (text, type) => { if (!inlineStatusEl) return; inlineStatusEl.className = "sqlspec-playground__inline-status"; while (inlineStatusEl.firstChild) inlineStatusEl.removeChild(inlineStatusEl.firstChild); if (type === "running") { const spinner = document.createElement('span'); spinner.className = 'sqlspec-playground__spinner'; inlineStatusEl.appendChild(spinner); inlineStatusEl.appendChild(document.createTextNode(' ' + text)); inlineStatusEl.classList.add("sqlspec-playground__inline-status--running"); } else if (type === "success") { inlineStatusEl.textContent = '\u2713 ' + text; inlineStatusEl.classList.add("sqlspec-playground__inline-status--success"); } else if (type === "error") { inlineStatusEl.textContent = '\u2717 ' + text; inlineStatusEl.classList.add("sqlspec-playground__inline-status--error"); } else { inlineStatusEl.textContent = text; } }; const clearOutput = () => { outputEl.textContent = ""; outputEl.hidden = true; while (tableOutputEl.firstChild) tableOutputEl.removeChild(tableOutputEl.firstChild); tableOutputEl.hidden = true; if (rowCountEl) rowCountEl.hidden = true; errorOutputEl.textContent = ""; errorOutputEl.hidden = true; currentData = null; sortColumn = null; }; const sortData = (data, column, direction) => { return [...data].sort((a, b) => { const aVal = a[column], bVal = b[column]; if (aVal === bVal) return 0; if (aVal == null) return 1; if (bVal == null) return -1; return (aVal < bVal ? -1 : 1) * (direction === 'asc' ? 1 : -1); }); }; const renderTable = (data) => { if (!Array.isArray(data) || data.length === 0 || typeof data[0] !== 'object') { return false; } currentData = data; const displayData = sortColumn ? sortData(data, sortColumn, sortDirection) : data; const headers = Object.keys(data[0]); while (tableOutputEl.firstChild) tableOutputEl.removeChild(tableOutputEl.firstChild); const table = document.createElement('table'); table.className = 'sqlspec-playground__table'; // Header with sort const thead = document.createElement('thead'); const trHead = document.createElement('tr'); headers.forEach(header => { const th = document.createElement('th'); th.textContent = header; const indicator = document.createElement('span'); indicator.className = 'sort-indicator'; th.appendChild(indicator); if (header === sortColumn) { th.classList.add(sortDirection === 'asc' ? 'sorted-asc' : 'sorted-desc'); } th.addEventListener('click', () => { if (sortColumn === header) { sortDirection = sortDirection === 'asc' ? 'desc' : 'asc'; } else { sortColumn = header; sortDirection = 'asc'; } renderTable(currentData); }); trHead.appendChild(th); }); thead.appendChild(trHead); table.appendChild(thead); // Body const tbody = document.createElement('tbody'); displayData.forEach(row => { const tr = document.createElement('tr'); headers.forEach(header => { const td = document.createElement('td'); const val = row[header]; td.textContent = val === null ? 'null' : val; tr.appendChild(td); }); tbody.appendChild(tr); }); table.appendChild(tbody); tableOutputEl.appendChild(table); tableOutputEl.hidden = false; if (rowCountEl) { rowCountEl.textContent = data.length + ' row' + (data.length !== 1 ? 's' : ''); rowCountEl.hidden = false; } return true; }; const showError = (error) => { errorOutputEl.textContent = error; errorOutputEl.hidden = false; }; const initializePlayground = async () => { try { setInlineStatus("Loading...", "running"); pyodide = await load ``` -------------------------------- ### Configure Correlation Middleware Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/observability.rst This example demonstrates how to set up correlation middleware to track a correlation ID across your application, linking SQL logs with specific requests. ```python from sqlspec.observability import CorrelationMiddleware app.add_middleware(CorrelationMiddleware) ``` -------------------------------- ### Execute a Stack Source: https://github.com/litestar-org/sqlspec/blob/main/docs/reference/query-stack.rst This section demonstrates how to build and execute a StatementStack using the provided Python example. It shows the process of composing SQL operations and running them in a single driver call. ```APIDOC ## Execute a Stack ### Description This example demonstrates how to build and execute a `StatementStack`. A `StatementStack` allows you to compose multiple SQL operations into a single immutable object that can be executed in one driver call. ### Usage ```python from sqlspec.core.stack import StatementStack from sqlspec.driver import SyncDriverAdapterBase # Assume 'session' is an instance of SyncDriverAdapterBase or a compatible adapter # session: SyncDriverAdapterBase stack = StatementStack() stack = stack.execute("SELECT 1") stack = stack.execute_many("INSERT INTO my_table (col1) VALUES (:val)", [{"val": 1}, {"val": 2}]) stack = stack.execute_script("CREATE TABLE IF NOT EXISTS another_table (id INT)") # Execute the stack # continue_on_error=False (default) will stop on the first error # continue_on_error=True will run all operations and collect errors result = session.execute_stack(stack, continue_on_error=False) # Inspect the result print(result.result[0].rows_affected) # Rows affected by the first operation print(result.result[1].rows_affected) # Rows affected by the second operation print(result.result[2].rows_affected) # Rows affected by the third operation # You can also access individual results and call helpers like all(), one(), to_pandas(), to_arrow() print(result.result[0].all()) ``` ### Components - **StatementStack**: An immutable builder used to compose SQL operations. It provides `push` helpers like `execute`, `execute_many`, `execute_script`, and `execute_arrow`. - **StackOperation**: A tuple-like object representing a single operation within the stack, containing the method, statement, arguments, and keyword arguments. - **StackResult**: Wraps the driver's raw result and provides stack metadata such as `rows_affected`, `warning`, and `error`. ### Driver APIs - **AsyncDriverAdapterBase.execute_stack**: The asynchronous method to execute a `StatementStack`. - **SyncDriverAdapterBase.execute_stack**: The synchronous method to execute a `StatementStack`. ### Execution Options - **continue_on_error**: A boolean flag. If `False` (default), execution stops on the first error. If `True`, all operations are executed, and errors are collected in the `StackResult`. ``` -------------------------------- ### Install SQLSpec with MySQL using uv Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the asyncmy and litestar extras to your project using the uv package manager. ```bash uv add "sqlspec[asyncmy,litestar]" ``` -------------------------------- ### Install SQLSpec with MySQL using Poetry Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the asyncmy and litestar extras to your project using Poetry. ```bash poetry add "sqlspec[asyncmy,litestar]" ``` -------------------------------- ### Dependency Injection with Database Operations Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/dependency_injection.rst Example of injecting a database connection and performing an operation. ```python from litestar import Litestar, get, Depends from typing import Any def get_db_connection_pool() -> Any: # In a real app, this would return a connection pool return "mock_db_pool" def get_db_session(db_pool: Any = Depends(get_db_connection_pool)) -> Any: # In a real app, this would create a session from the pool return f"session_from_{db_pool}" @get("/sync-data") def sync_data(db_session: Any = Depends(get_db_session)) -> dict: # Example of using the session # In a real app, you might execute SQL here print(f"Using DB session: {db_session}") # Simulate a database operation result = {"synced": True} return result app = Litestar([sync_data]) ``` -------------------------------- ### Install SQLSpec with PostgreSQL (asyncpg) using uv Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the asyncpg and litestar extras to your project using the uv package manager. ```bash uv add "sqlspec[asyncpg,litestar]" ``` -------------------------------- ### Install SQLSpec with MySQL using PDM Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the asyncmy and litestar extras to your project using PDM. ```bash pdm add "sqlspec[asyncmy,litestar]" ``` -------------------------------- ### Generate Documentation Demos Source: https://github.com/litestar-org/sqlspec/blob/main/CONTRIBUTING.rst Runs the make target to process all .tape files and generate GIF demos. Output is saved to docs/_static/demos/. ```console make docs-demos ``` -------------------------------- ### Basic Query with Pydantic Mapping Source: https://github.com/litestar-org/sqlspec/blob/main/docs/PYPI_README.md Demonstrates executing a simple SQL query and mapping the result to a Pydantic model. Ensure Pydantic is installed. ```python from pydantic import BaseModel from sqlspec import SQLSpec from sqlspec.adapters.sqlite import SqliteConfig class Greeting(BaseModel): message: str spec = SQLSpec() db = spec.add_config(SqliteConfig(connection_config={"database": ":memory:"})) with spec.provide_session(db) as session: greeting = session.select_one( "SELECT 'Hello, SQLSpec!' AS message", schema_type=Greeting, ) print(greeting.message) # Output: Hello, SQLSpec! ``` -------------------------------- ### Install SQLSpec with PostgreSQL (asyncpg) using Poetry Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the asyncpg and litestar extras to your project using Poetry. ```bash poetry add "sqlspec[asyncpg,litestar]" ``` -------------------------------- ### Install SQLSpec with Starlette Extra (Poetry) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/starlette.rst Add the SQLSpec package with the Starlette extra dependencies to your project using Poetry. ```bash poetry add "sqlspec[starlette]" ``` -------------------------------- ### Install SQLSpec with PostgreSQL (asyncpg) using PDM Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the asyncpg and litestar extras to your project using PDM. ```bash pdm add "sqlspec[asyncpg,litestar]" ``` -------------------------------- ### Install SQLSpec with Starlette Extra (pip) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/starlette.rst Install the SQLSpec package with the Starlette extra dependencies using 'pip'. ```bash pip install "sqlspec[starlette]" ``` -------------------------------- ### Install SQLSpec with SQLite (async) using PDM Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the aiosqlite and litestar extras to your project using PDM. ```bash pdm add "sqlspec[aiosqlite,litestar]" ``` -------------------------------- ### Install SQLSpec with SQLite (async) using Poetry Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the aiosqlite and litestar extras to your project using Poetry. ```bash poetry add "sqlspec[aiosqlite,litestar]" ``` -------------------------------- ### Install SQLSpec with Starlette Extra (PDM) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/starlette.rst Add the SQLSpec package with the Starlette extra dependencies to your project using PDM. ```bash pdm add "sqlspec[starlette]" ``` -------------------------------- ### Install SQLSpec with SQLite (async) using uv Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the aiosqlite and litestar extras to your project using the uv package manager. ```bash uv add "sqlspec[aiosqlite,litestar]" ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/litestar-org/sqlspec/blob/main/CONTRIBUTING.rst Serves the project documentation locally for preview. This command is useful for verifying documentation changes. ```console make docs-serve ``` -------------------------------- ### Install SQLSpec with PostgreSQL (psycopg) using Poetry Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the psycopg and litestar extras to your project using Poetry. ```bash poetry add "sqlspec[psycopg,litestar]" ``` -------------------------------- ### Pagination with SQL Objects Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/filtering.rst Use SQL.paginate() to add LIMIT/OFFSET to queries and select_with_total to retrieve both page data and the total count. This example demonstrates basic pagination patterns. ```python from sql import SQL async def pagination_example(db_session: AsyncpgDriver) -> None: query = SQL.paginate(SQL.select("*").from_("users")) data, total = await db_session.select_with_total(query) # ... process data and total ``` -------------------------------- ### Flask Application Factory Pattern Setup Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/flask.rst When using the application factory pattern in Flask, initialize the SQLSpec plugin within your create_app function. ```python def create_app(): app = Flask(__name__) sqlspec = SQLSpec() sqlspec.add_config(SqliteConfig(...)) plugin = SQLSpecPlugin(sqlspec, app) return app ``` -------------------------------- ### Install SQLSpec with PostgreSQL (psycopg) using uv Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the psycopg and litestar extras to your project using the uv package manager. ```bash uv add "sqlspec[psycopg,litestar]" ``` -------------------------------- ### Execute a Statement Stack Source: https://github.com/litestar-org/sqlspec/blob/main/docs/reference/query-stack.rst Demonstrates how to build and execute a StatementStack using SQLspec. This example shows composing multiple SQL operations and executing them as a single unit. ```python from sqlspec.driver import AsyncDriverAdapterBase from sqlspec.core.stack import StatementStack async def example( session: AsyncDriverAdapterBase, ) -> None: stack = StatementStack() stack.execute("SELECT 1") stack.execute_many("INSERT INTO ""users"" (name) VALUES (:name)", [{"name": "Alice"}, {"name": "Bob"}]) stack.execute_script("CREATE TABLE IF NOT EXISTS ""items"" (id SERIAL PRIMARY KEY, name TEXT)") stack.execute_arrow("SELECT * FROM ""users""") result = await session.execute_stack(stack) print(result.rows_affected) print(result.result.all()) ``` -------------------------------- ### Advanced DuckDB Configuration with Extensions Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/dependency_injection.rst Configure DuckDB connections with extensions and initialization hooks. Use 'driver_features' for extensions like 'postgres' and 'on_connection_create' for custom setup, enabling querying external databases directly. ```python from typing import Any from sqlspec import SQLSpec from sqlspec.adapters.duckdb import DuckDBConfig, DuckDBExtensionConfig def on_connection_create(connection: Any) -> None: """Configure DuckDB connection with PostgreSQL attachment.""" # Load postgres extension and attach external database connection.execute("LOAD postgres") connection.execute( "ATTACH 'dbname=app user=app password=secret host=localhost' " "AS pg (TYPE POSTGRES, SCHEMA 'public')" ) sqlspec = SQLSpec() sqlspec.add_config( DuckDBConfig( connection_config={ "database": "/tmp/analytics.db", "temp_directory": "/tmp", }, driver_features={ "extensions": [ DuckDBExtensionConfig(name="postgres"), DuckDBExtensionConfig(name="encodings"), ], "on_connection_create": on_connection_create, }, extension_config={ "litestar": { "session_key": "etl_db", "connection_key": "etl_connection", } } ) ) ``` -------------------------------- ### Build All Documentation Source: https://github.com/litestar-org/sqlspec/blob/main/CONTRIBUTING.rst Builds the complete documentation, including any generated demo GIFs. This command ensures all documentation assets are processed. ```console make docs-all ``` -------------------------------- ### Configure SQL Logging Level using SQL_LOGGER_NAME Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/observability.rst This example shows how to configure the SQL logging level using the SQL_LOGGER_NAME constant for more explicit control over SQL-related logs. ```python from sqlspec.observability import SQL_LOGGER_NAME # Configure SQL logging level logging.getLogger(SQL_LOGGER_NAME).setLevel(logging.INFO) ``` -------------------------------- ### Basic Dependency Injection Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/dependency_injection.rst Demonstrates a simple dependency injection scenario using a function. ```python from litestar import Litestar, get def get_user_id() -> int: return 1 @get("/users/{user_id:int}") def get_user(user_id: int, dep: int = Depends(get_user_id)) -> dict: return {"user_id": user_id, "dep": dep} app = Litestar([get_user]) ``` -------------------------------- ### Initialize Pyodide and Load Packages Source: https://github.com/litestar-org/sqlspec/blob/main/tools/sphinx_ext/playground_template.html Initializes Pyodide, sets up stdout/stderr buffering, and loads necessary Python packages like 'sqlite3' and 'micropip'. This is required before running any Python code. ```javascript Pyodide({ indexURL: "https://cdn.jsdelivr.net/pyodide/v0.29.0/full/" }); const stdoutBuffer = []; pyodide.setStdout({ batched: (t) => stdoutBuffer.push(t) }); pyodide.setStderr({ batched: (t) => stdoutBuffer.push(t) }); await pyodide.loadPackage(["sqlite3", "micropip"]); const micropip = pyodide.pyimport("micropip"); await micropip.install("sqlspec"); setInlineStatus("Ready", "success"); runPythonButton.disabled = false; } catch (err) { setInlineStatus("Failed", "error"); showError('Failed to initialize: ' + err); console.error(err); } }; runPythonButton.disabled = true; ``` -------------------------------- ### Build Documentation Source: https://github.com/litestar-org/sqlspec/blob/main/CONTRIBUTING.rst Builds the project documentation. This command generates the static documentation files. ```console make docs ``` -------------------------------- ### Initialize Asyncpg ADK Memory Store Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/quickstart.rst Configure and initialize the AsyncpgADKMemoryStore for retaining agent context with optional full-text search. Ensure tables are created before use. ```python from sqlspec.adapters.asyncpg.adk import AsyncpgADKMemoryStore from sqlspec.extensions.adk import SQLSpecMemoryService memory_store = AsyncpgADKMemoryStore(config) await memory_store.ensure_tables() memory_service = SQLSpecMemoryService(memory_store) ``` -------------------------------- ### Async Dependencies Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/dependency_injection.rst Demonstrates how to use asynchronous functions as dependencies. ```python import asyncio from litestar import Litestar, get, Depends async def get_async_data() -> dict: await asyncio.sleep(0.1) return {"data": "some async data"} @get("/async-data") def read_async_data(data: dict = Depends(get_async_data)) -> dict: return data app = Litestar([read_async_data]) ``` -------------------------------- ### get_author Source: https://github.com/litestar-org/sqlspec/blob/main/docs/reference/migrations.rst Utility function to get the author of a migration. ```APIDOC ## get_author ### Description Utility function to get the author of a migration. ### Parameters (Parameters are not detailed in the source, so they cannot be listed.) ### Returns (Return type is not detailed in the source, so it cannot be listed.) ``` -------------------------------- ### get_migration_loader Source: https://github.com/litestar-org/sqlspec/blob/main/docs/reference/migrations.rst Factory function to get a migration loader instance. ```APIDOC ## get_migration_loader ### Description Factory function to get a migration loader instance. ### Parameters (Parameters are not detailed in the source, so they cannot be listed.) ### Returns (Return type is not detailed in the source, so it cannot be listed.) ``` -------------------------------- ### Configure Sampling for SQL Logging Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/observability.rst This configuration snippet shows how to set up detailed SQL logging and sampling to reduce noise in production environments. ```python from sqlspec.config import StatementConfig config = StatementConfig( enable_sqlcommenter=True, sqlcommenter_enable_traceparent=True, ) ``` -------------------------------- ### get_or_create_session Source: https://github.com/litestar-org/sqlspec/blob/main/docs/reference/extensions/sanic.rst Gets an existing session or creates a new one from the current Sanic request context. ```APIDOC ## Function: get_or_create_session ### Description Retrieves a request-scoped session if it already exists, otherwise creates and returns a new one. This ensures session consistency throughout a request. ### Parameters * **request** (SanicRequest) - The Sanic request object to associate the session with. ``` -------------------------------- ### Initialize Asyncpg ADK Session Store Source: https://github.com/litestar-org/sqlspec/blob/main/docs/extensions/adk/quickstart.rst Configure and initialize the AsyncpgADKStore for persisting agent sessions and events. Ensure tables are created before use. ```python from sqlspec.adapters.asyncpg import AsyncpgConfig from sqlspec.adapters.asyncpg.adk import AsyncpgADKStore from sqlspec.extensions.adk import SQLSpecSessionService config = AsyncpgConfig( connection_config={"dsn": "postgresql://localhost/mydb"}, extension_config={ "adk": { "session_table": "adk_sessions", "events_table": "adk_events", } }, ) store = AsyncpgADKStore(config) await store.ensure_tables() session_service = SQLSpecSessionService(store) # Create a session with scoped state session = await session_service.create_session( app_name="my_agent", user_id="user_123", state={ "app:model": "gemini-2.0", # shared across all sessions "user:name": "Alice", # shared across user's sessions "conversation_turn": 0, # session-local "temp:scratch": "...", # runtime-only, never persisted }, ) ``` -------------------------------- ### Load SQL Files Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/sql_files.rst Demonstrates how to load SQL files from a specified directory into the SQLSpec registry. Ensure the directory contains .sql files with named queries. ```python from sqlspec import SQLSpec spec = SQLSpec() spec.load_sql("sql") # Execute a query query = spec.get_sql("users.all") print(query) ``` -------------------------------- ### Class-Based Dependencies Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/dependency_injection.rst Illustrates using class instances as dependencies. ```python from litestar import Litestar, get, Depends class UserService: def __init__(self, user_repo: str) -> None: self.user_repo = user_repo def get_user_name(self, user_id: int) -> str: return f"User {user_id} from {self.user_repo}" def provide_user_repo() -> str: return "PostgresRepo" @get("/users/{user_id:int}") def get_user(user_service: UserService = Depends(UserService, use_cache=True, constructor_parameters={"user_repo": Depends(provide_user_repo)})) -> dict: return {"name": user_service.get_user_name(user_id)} app = Litestar([get_user]) ``` -------------------------------- ### Run First Query Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/quickstart.rst Executes a simple SQL query to fetch data. ```python from sqlspec import SQLSpec spec = SQLSpec("sqlite:///db.sqlite") spec.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)") spec.execute("INSERT INTO users (name) VALUES (?)", ["Alice"]) result = spec.fetch_one("SELECT * FROM users") print(result) ``` -------------------------------- ### Install SQLSpec with PostgreSQL (psycopg) using PDM Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/litestar/installation.rst Use this command to add SQLSpec with the psycopg and litestar extras to your project using PDM. ```bash pdm add "sqlspec[psycopg,litestar]" ``` -------------------------------- ### Tweak Statement Configuration Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/quickstart.rst Demonstrates how to configure statement execution, such as setting timeouts. ```python from sqlspec import SQLSpec spec = SQLSpec("sqlite:///db.sqlite") spec.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)") spec.execute("INSERT INTO users (name) VALUES (?)", ["Alice"]) result = spec.fetch_one("SELECT * FROM users", timeout=10) print(result) ``` -------------------------------- ### Connect to SQLite Source: https://github.com/litestar-org/sqlspec/blob/main/docs/getting_started/quickstart.rst Establishes a connection to an SQLite database. ```python from sqlspec import SQLSpec spec = SQLSpec("sqlite:///db.sqlite") ``` -------------------------------- ### Register Multiple Databases Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/frameworks/fastapi.rst Configure and inject sessions for multiple databases by assigning unique names to each configuration and dependency. ```python sqlspec.add_config(primary_config, name="primary") sqlspec.add_config(analytics_config, name="analytics") primary_dep = db_ext.provide_session("primary") analytics_dep = db_ext.provide_session("analytics") ``` -------------------------------- ### Python Migration with Schema Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/migrations.rst Example of a Python migration script that utilizes schema specification. This snippet demonstrates how to define and use schemas within migration operations. ```python from litestar.contrib.sqlalchemy.cli import MigrationConfig migration_config = MigrationConfig(schema="my_schema") ``` -------------------------------- ### sql (Convenience Instance) Source: https://github.com/litestar-org/sqlspec/blob/main/docs/reference/builder/factory.rst A pre-configured SQLFactory instance for simplified query building, callable directly with SQL strings. ```APIDOC ## sql (Convenience Instance) ### Description The ``sql`` object is a pre-configured instance of ``SQLFactory``, designed for convenient query building. It can be directly called with a SQL string and an optional dialect to create a builder. ### Usage `sql(statement, dialect=None)` - **statement** (str): The SQL string to build. - **dialect** (Optional[Dialect]): The SQL dialect to use. ``` -------------------------------- ### Build an Update Query Source: https://github.com/litestar-org/sqlspec/blob/main/docs/usage/query_builder.rst Generate an UPDATE statement to modify existing records in a table. This example shows how to set new values and specify which rows to update using a WHERE clause. ```python from sqlspec.builder import SQL query = SQL.update('users').set(values={'email': 'alice.updated@example.com'}).where(name='Alice') ```