# Attach Db > Adjunta un archivo de base de datos DuckDB para usarlo con /duckdb-skills:query. Explora el esquema (tablas, columnas, conteos) y escribe un state file SQL para restaurar la sesión con duckdb -init. Fuente: https://skillsagentes.com/skills/duckdb/duckdb-skills/attach-db Markdown: https://skillsagentes.com/skills/duckdb/duckdb-skills/attach-db.md Repositorio: https://github.com/duckdb/duckdb-skills Autor: duckdb Licencia: MIT Actualizado: hace 5 meses Coste de contexto: 55 tok instalada, 1.2k tok al activarse, 1.2k tok con todos los archivos del bundle Bundle: 1 archivo, 5 KB Permisos que pide: bash ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add duckdb/duckdb-skills --skill attach-db --agent claude-code # Cursor npx -y skills add duckdb/duckdb-skills --skill attach-db --agent cursor # Codex npx -y skills add duckdb/duckdb-skills --skill attach-db --agent codex # Gemini CLI npx -y skills add duckdb/duckdb-skills --skill attach-db --agent gemini # Windsurf npx -y skills add duckdb/duckdb-skills --skill attach-db --agent windsurf # Cline npx -y skills add duckdb/duckdb-skills --skill attach-db --agent cline ``` ## Qué hace - Resuelve y valida la ruta a un archivo .duckdb, creándolo si no existe y el usuario lo confirma - Explora el esquema: lista tablas, columnas y conteo de filas (hasta 20 tablas) - Escribe o actualiza un state.sql compartido con la instrucción ATTACH y USE para la base de datos - Verifica que el state.sql funcione ejecutando duckdb -init con SHOW TABLES - Reporta ruta resuelta, alias, ubicación del state file y resumen de tablas ## Cuándo usarla - El usuario quiere adjuntar un archivo de base de datos DuckDB para consultarlo interactivamente - Se necesita preparar el estado de sesión para usar después con /duckdb-skills:query ## Qué la activa - "Adjunta la base de datos ./data/ventas.duckdb para consultarla" - "Quiero explorar el esquema de mi_data.duckdb y dejarla lista para consultas" ## Antes de instalar - Requiere el binario duckdb instalado; si falta, delega a /duckdb-skills:install-duckdb. - Necesita en el PATH: git - Variables de entorno: PROJECT_ID, PROJECT_ROOT, RESOLVED_PATH, STATE_DIR - runs shell commands - reads environment config ## Archivos - SKILL.md — 5 KB ## SKILL.md Reproducido tal cual desde duckdb/duckdb-skills bajo MIT. Esta sección es el documento original y está en inglés. You are helping the user attach a DuckDB database file for interactive querying. Database path given: `$0` Follow these steps in order, stopping and reporting clearly if any step fails. **State file convention**: see the "Resolve state directory" section below. All skills share a single `state.sql` file per project. Once resolved, any skill can use it with `duckdb -init "$STATE_DIR/state.sql" -c ""`. ## Step 1 — Resolve the database path If `$0` is a relative path, resolve it against `$PWD` to get an absolute path (`RESOLVED_PATH`). ```bash RESOLVED_PATH="$(cd "$(dirname "$0")" 2>/dev/null && pwd)/$(basename "$0")" ``` Check the file exists: ```bash test -f "$RESOLVED_PATH" ``` - **File exists** -> continue to Step 2. - **File not found** -> ask the user if they want to create a new empty database (DuckDB creates the file on first write). If yes, continue. If no, stop. ## Step 2 — Check DuckDB is installed ```bash command -v duckdb ``` If not found, delegate to `/duckdb-skills:install-duckdb` and then continue. ## Step 3 — Validate the database ```bash duckdb "$RESOLVED_PATH" -c "PRAGMA version;" ``` - **Success** -> continue. - **Failure** -> report the error clearly (e.g. corrupt file, not a DuckDB database) and stop. ## Step 4 — Explore the schema First, list all tables: ```bash duckdb "$RESOLVED_PATH" -csv -c " SELECT table_name, estimated_size FROM duckdb_tables() ORDER BY table_name; " ``` If the database has **no tables**, note that it is empty and skip to Step 5. For each table discovered (up to 20), run: ```bash duckdb "$RESOLVED_PATH" -csv -c " DESCRIBE ; SELECT count() AS row_count FROM ; " ``` Collect the column definitions and row counts for the summary. ## Step 5 — Resolve the state directory Check if a state file already exists in either location: ```bash # Option 1: in the project directory test -f .duckdb-skills/state.sql && STATE_DIR=".duckdb-skills" # Option 2: in the home directory, scoped by project root path PROJECT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD")" PROJECT_ID="$(echo "$PROJECT_ROOT" | tr '/' '-')" test -f "$HOME/.duckdb-skills/$PROJECT_ID/state.sql" && STATE_DIR="$HOME/.duckdb-skills/$PROJECT_ID" ``` If **neither exists**, ask the user: > Where would you like to store the DuckDB session state for this project? > > 1. **In the project directory** (`.duckdb-skills/state.sql`) — colocated with the project, easy to find. You can choose to gitignore it. > 2. **In your home directory** (`~/.duckdb-skills//state.sql`) — keeps the project directory clean. Based on their choice: **Option 1:** ```bash STATE_DIR=".duckdb-skills" mkdir -p "$STATE_DIR" ``` Then ask: *"Would you like to gitignore `.duckdb-skills/`?"* If yes: ```bash echo '.duckdb-skills/' >> .gitignore ``` **Option 2:** ```bash PROJECT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD")" PROJECT_ID="$(echo "$PROJECT_ROOT" | tr '/' '-')" STATE_DIR="$HOME/.duckdb-skills/$PROJECT_ID" mkdir -p "$STATE_DIR" ``` ## Step 6 — Append to the state file `state.sql` is a shared, accumulative init file used by all duckdb-skills. It may already contain macros, LOAD statements, secrets, or other ATTACH statements written by other skills. **Never overwrite it** — always check for duplicates and append. Derive the database alias from the filename without extension (e.g. `my_data.duckdb` → `my_data`). Check if this ATTACH already exists: ```bash grep -q "ATTACH.*RESOLVED_PATH" "$STATE_DIR/state.sql" 2>/dev/null ``` If not already present, append: ```bash cat >> "$STATE_DIR/state.sql" <<'STATESQL' ATTACH IF NOT EXISTS 'RESOLVED_PATH' AS my_data; USE my_data; STATESQL ``` Replace `RESOLVED_PATH` and `my_data` with the actual values. If the alias would conflict with an existing one in the file, ask the user for a name. ## Step 7 — Verify the state file works ```bash duckdb -init "$STATE_DIR/state.sql" -c "SHOW TABLES;" ``` If this fails, fix the state file and retry. ## Step 8 — Report Summarize for the user: - **Database path**: the resolved absolute path - **Alias**: the database alias used in the state file - **State file**: the resolved `STATE_DIR/state.sql` path - **Tables**: name, column count, row count for each table (or note the DB is empty) - Confirm the database is now active for `/duckdb-skills:query` If the database is empty, suggest creating tables or importing data. ## Dónde encaja - Categoría: [Bases de datos](https://skillsagentes.com/categorias/bases-de-datos.md) — Diseño de esquemas, migraciones y optimización de consultas. - Creador: [duckdb](https://skillsagentes.com/creators/duckdb.md) — 0 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Spatial](https://skillsagentes.com/skills/duckdb/duckdb-skills/spatial.md): Responde preguntas sobre datos espaciales con DuckDB: ubicaciones, coordenadas, distancias, mapas, direcciones, formatos como GeoJSON, Shapefile, GeoPackage, GPX o GeoParquet, usando también Overture Maps. - [S3 Explore](https://skillsagentes.com/skills/duckdb/duckdb-skills/s3-explore.md): Explora y consulta datos en S3, Cloudflare R2, GCS, MinIO o cualquier almacenamiento compatible con S3, sin necesidad de descargarlos. - [Convert File](https://skillsagentes.com/skills/duckdb/duckdb-skills/convert-file.md): Convierte cualquier archivo de datos a otro formato: CSV, Parquet, JSON, Excel, GeoJSON y más, usando DuckDB. - [Duckdb Docs](https://skillsagentes.com/skills/duckdb/duckdb-skills/duckdb-docs.md): Busca en la documentación de DuckDB y DuckLake y en posts del blog, devolviendo fragmentos relevantes mediante búsqueda de texto completo contra un índice local cacheado. - [Read File](https://skillsagentes.com/skills/duckdb/duckdb-skills/read-file.md): Lee cualquier archivo de datos (CSV, JSON, Parquet, Avro, Excel, spatial, SQLite) o URL remota (S3, HTTPS) usando DuckDB. No sirve para código fuente. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)