Skip to content

sqlite_types

Class info

Classes

Name Children Inherits
ColumnInfo
toprompt.sqlite_types
Information about a SQLite column.
    FileDatabaseLike
    toprompt.sqlite_types
    Protocol for file-based database-like objects.
      ForeignKeyInfo
      toprompt.sqlite_types
      Information about a SQLite foreign key.
        InMemoryDatabaseLike
        toprompt.sqlite_types
        Protocol for in-memory database-like objects.
          IndexInfo
          toprompt.sqlite_types
          Information about a SQLite index.

            🛈 DocStrings

            ColumnInfo

            Bases: TypedDict

            Information about a SQLite column.

            Source code in src/toprompt/sqlite_types.py
            class ColumnInfo(TypedDict):
                """Information about a SQLite column."""
            
                name: str
                type: str
                notnull: bool
                default: str | None
                pk: bool
            

            FileDatabaseLike

            Bases: Protocol

            Protocol for file-based database-like objects.

            Source code in src/toprompt/sqlite_types.py
            @runtime_checkable
            class FileDatabaseLike(Protocol):
                """Protocol for file-based database-like objects."""
            
                @property
                def _filename(self) -> str | None: ...
            

            ForeignKeyInfo

            Bases: TypedDict

            Information about a SQLite foreign key.

            Source code in src/toprompt/sqlite_types.py
            class ForeignKeyInfo(TypedDict):
                """Information about a SQLite foreign key."""
            
                from_table: str
                from_col: str
                to_table: str
                to_col: str
            

            InMemoryDatabaseLike

            Bases: Protocol

            Protocol for in-memory database-like objects.

            Source code in src/toprompt/sqlite_types.py
            @runtime_checkable
            class InMemoryDatabaseLike(Protocol):
                """Protocol for in-memory database-like objects."""
            
                @property
                def in_memory(self) -> bool: ...
            

            IndexInfo

            Bases: TypedDict

            Information about a SQLite index.

            Source code in src/toprompt/sqlite_types.py
            class IndexInfo(TypedDict):
                """Information about a SQLite index."""
            
                name: str
                table: str
                unique: bool
                columns: list[str]
            

            get_db_path

            get_db_path(conn: Connection) -> str
            

            Get the path for a SQLite database connection.

            Source code in src/toprompt/sqlite_types.py
            def get_db_path(conn: sqlite3.Connection) -> str:
                """Get the path for a SQLite database connection."""
                import sqlite3
            
                try:
                    cursor = conn.cursor()
                    cursor.execute("PRAGMA database_list")
                    # This returns rows with (seq, name, file) for each database
                    for _, name, file_path in cursor.fetchall():
                        if name == "main":  # main database
                            return file_path or ":memory:"
                except sqlite3.Error:
                    pass
                return ":memory:"  # fallback to memory if we can't determine
            

            get_index_info

            get_index_info(cursor: Cursor, table: str) -> list[IndexInfo]
            

            Get information about the explicitly created indices on a table.

            Source code in src/toprompt/sqlite_types.py
            def get_index_info(cursor: sqlite3.Cursor, table: str) -> list[IndexInfo]:
                """Get information about the explicitly created indices on a table."""
                cursor.execute(
                    """
                    SELECT name FROM sqlite_master
                    WHERE type='index'
                    AND tbl_name=?
                    AND name NOT LIKE 'sqlite_%'
                    """,
                    (table,),
                )
                names = [row[0] for row in cursor.fetchall()]
                cursor.execute('SELECT name, "unique" FROM pragma_index_list(?)', (table,))
                unique = {name: bool(flag) for name, flag in cursor.fetchall()}
                indices: list[IndexInfo] = []
                for name in names:
                    # Original column names; None for expression columns.
                    cursor.execute("SELECT name FROM pragma_index_info(?) ORDER BY seqno", (name,))
                    columns = [col if col is not None else "<expression>" for (col,) in cursor.fetchall()]
                    indices.append({
                        "name": name,
                        "table": table,
                        "unique": unique.get(name, False),
                        "columns": columns,
                    })
                return indices
            

            get_sqlite_schema

            get_sqlite_schema(db: str | PathLike[str] | Connection) -> str
            

            Generate human-readable documentation from SQLite database.

            Parameters:

            Name Type Description Default
            db str | PathLike[str] | Connection

            Path to SQLite database file or Connection object

            required
            Source code in src/toprompt/sqlite_types.py
            def get_sqlite_schema(db: str | os.PathLike[str] | sqlite3.Connection) -> str:
                """Generate human-readable documentation from SQLite database.
            
                Args:
                    db: Path to SQLite database file or Connection object
                """
                import sqlite3
            
                if isinstance(db, sqlite3.Connection):
                    conn = db
                    should_close = False
                else:
                    path = pathlib.Path(db)
                    if not path.exists():
                        msg = f"Database file not found: {path}"
                        raise FileNotFoundError(msg)
                    # Read-only: documenting a schema must not create journal files or take locks.
                    conn = sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri=True)
                    should_close = True
            
                try:
                    cursor = conn.cursor()
                    # Get all tables
                    tables = get_tables(cursor)
                    if not tables:
                        return "Database contains no tables."
            
                    lines = ["SQLite Database Schema:"]
            
                    # Process each table
                    for table in tables:
                        lines.extend(get_table_info(cursor, table))
                        lines.append("")  # Empty line between tables
            
                    return "\n".join(lines)
            
                finally:
                    if should_close:
                        conn.close()
            

            get_table_info

            get_table_info(cursor: Cursor, table: str) -> list[str]
            

            Get detailed information about a specific table.

            Source code in src/toprompt/sqlite_types.py
            def get_table_info(cursor: sqlite3.Cursor, table: str) -> list[str]:
                """Get detailed information about a specific table."""
                # Get column information
                # Table-valued pragmas take the name as a parameter (quoted names, keywords).
                cursor.execute("SELECT * FROM pragma_table_info(?)", (table,))
                columns: list[ColumnInfo] = [
                    {
                        "name": row[1],
                        "type": row[2],
                        "notnull": bool(row[3]),
                        "default": row[4],
                        "pk": bool(row[5]),
                    }
                    for row in cursor.fetchall()
                ]
            
                # Get foreign keys
                cursor.execute("SELECT * FROM pragma_foreign_key_list(?)", (table,))
                foreign_keys: list[ForeignKeyInfo] = [
                    {
                        "from_table": table,
                        "from_col": row[3],
                        "to_table": row[2],
                        "to_col": row[4],
                    }
                    for row in cursor.fetchall()
                ]
            
                indices = get_index_info(cursor, table)
            
                # Format table documentation
                lines = [f"\nTable: {table}"]
            
                # Columns
                lines.append("\nColumns:")
                for col in columns:
                    parts = [f"- {col['name']}: {col['type']}"]
                    properties = []
            
                    if col["pk"]:
                        properties.append("primary key")
                    if col["notnull"]:
                        properties.append("not null")
                    if col["default"] is not None:
                        properties.append(f"default: {col['default']}")
            
                    if properties:
                        parts.append(f"({', '.join(properties)})")
                    lines.append(" ".join(parts))
            
                # Foreign Keys
                if foreign_keys:
                    lines.append("\nForeign Keys:")
                    lines.extend(
                        f"- {fk['from_col']} -> {fk['to_table']}.{fk['to_col']}" for fk in foreign_keys
                    )
            
                # Indices
                if indices:
                    lines.append("\nIndices:")
                    for idx in indices:
                        unique = "UNIQUE " if idx["unique"] else ""
                        cols = ", ".join(idx["columns"])
                        lines.append(f"- {idx['name']}: {unique}({cols})")
            
                return lines
            

            get_tables

            get_tables(cursor: Cursor) -> list[str]
            

            Get all table names from database.

            Source code in src/toprompt/sqlite_types.py
            def get_tables(cursor: sqlite3.Cursor) -> list[str]:
                """Get all table names from database."""
                cursor.execute(
                    """
                    SELECT name FROM sqlite_master
                    WHERE type='table'
                    AND name NOT LIKE 'sqlite_%'
                    ORDER BY name
                    """
                )
                return [row[0] for row in cursor.fetchall()]
            

            is_sqlite_db

            is_sqlite_db(obj: Any) -> bool
            

            Check if object is a SQLite database.

            Source code in src/toprompt/sqlite_types.py
            def is_sqlite_db(obj: Any) -> bool:
                """Check if object is a SQLite database."""
                import sqlite3
            
                return isinstance(obj, sqlite3.Connection)