PluginWorks in Claude CodeCurrent
Duckdb skills
DuckDB-powered skills for Claude Code: read any data file, attach and query DuckDB databases, search DuckDB/DuckLake docs, search past session logs, and install/update DuckDB extensions.
0
Try it
See what this would do for you. No sign-up needed.
Install in Claude Code
Run these in Claude Code, in order. The first adds the marketplace, the second installs the plugin.
Step 1
/plugin marketplace add anthropics/claude-plugins-official
Step 2
/plugin install duckdb-skills@claude-plugins-official
Review commands before running them. Promptu never runs code on your machine or pushes changes to your repo.
What's inside
9 skills
- attach-db
- convert-file
- duckdb-docs
- install-duckdb
- query
- read-file
- read-memories
- s3-explore
- spatial
Security scan
Flagged
Promptu's text scan flagged something in this plugin. Read its files before you install it.
pipe-to-shell in skills/install-duckdb/SKILL.md:27
Details
# duckdb-skills
A [Claude Code](https://claude.ai/code) plugin that adds DuckDB-powered skills for data exploration and session memory.
## Installation
### From the Discover tab (coming soon)
We are working on submitting this plugin to the official Anthropic marketplace. Once listed, it will appear in the **Discover** tab when you run `/plugin` inside Claude Code.
### From GitHub (available now)
Add the repository as a plugin source and install:
```
/plugin marketplace add duckdb/duckdb-skills
```
```
/plugin install duckdb-skills@duckdb-skills
```
This registers the GitHub repo as a marketplace and installs the plugin. Skills will be available as `/duckdb-skills:<skill-name>` in all future sessions.
### Updating
To pull the latest version, update the marketplace first and then the plugin:
```
/plugin marketplace update duckdb-skills
/plugin update duckdb-skills@duckdb-skills
```
## Skills
### `attach-db`
Attach a DuckDB database file for interactive querying. Explores the schema (tables, columns, row counts) and writes a SQL state file so all other skills can restore the session automatically. You can choose to store state in the project directory (`.duckdb-skills/state.sql`) or in your home directory (`~/.duckdb-skills/<project>/state.sql`).
```
/duckdb-skills:attach-db my_analytics.duckdb
```
Supports multiple databases — running `attach-db` again can append to the existing state file.
### `query`
Run SQL queries against attached databases or ad-hoc against files. Accepts raw SQL or natural language questions. Uses DuckDB's Friendly SQL dialect. Automatically picks up session state from `attach-db`.
```
/duckdb-skills:query FROM sales LIMIT 10
/duckdb-skills:query "what are the top 5 customers by revenue?"
/duckdb-skills:query FROM 'exports.csv' WHERE amount > 100
```
### `read-file`
Read and explore any data file — CSV, JSON, Parquet, Avro, Excel, spatial, SQLite, Jupyter notebooks, and more — locally or from remote storage (S3, GCS, Azure, HTTPS). Auto-detects the format by file extension using a built-in `read_any` table macro. Suggests `query` for further exploration.
```
/duckdb-skills:read-file variants.parquet what columns does it have?
/duckdb-skills:read-file s3://my-bucket/data.parquet describe the schema
/duckdb-skills:read-file https://example.com/data.csv how many rows?
```
### `duckdb-docs`
Search DuckDB and DuckLake documentation and blog posts using full-text search against the hosted search indexes. No local setup required — queries run over HTTPS by default, with an option to cache the index locally for faster offline searches.
```
/duckdb-skills:duckdb-docs window functions
/duckdb-skills:duckdb-docs "how do I read a CSV with custom delimiters?"
```
### `read-memories`
Search past Claude Code session logs to recover context from previous conversations — decisions made, patterns established, open TODOs. Offloads large result sets to a temporary DuckDB file for interactive drill-down.
```
/duckdb-skills:read-memories duckdb --here
```
### `install-duckdb`
Install or update DuckDB extensions. Supports `name@repo` syntax for community extensions and a `--update` flag that also checks whether your DuckDB CLI is on the latest stable version.
```
/duckdb-skills:install-duckdb spatial httpfs
/duckdb-skills:install-duckdb gcs@community
/duckdb-skills:install-duckdb --update
```
## Session state
All skills share a single `state.sql` file per project — a plain SQL file containing ATTACH/USE/LOAD statements, secrets, and macros. When state is first needed, you'll be asked where to store it:
1. **In the project directory** (`.duckdb-skills/state.sql`) — colocated with the project, optionally gitignored
2. **In your home directory** (`~/.duckdb-skills/<project>/state.sql`) — keeps the repo clean
The file is append-only and idempotent. Any skill restores the session via `duckdb -init state.sql`.
## Local development
To test skills locally from a clone of this repo:
```bash
# 1. Clone the repo
git clone https://github.com/duckdb/duckdb-skills.git
cd duckdb-skills
# 2. Launch Claude Code with the local plugin directory
claude --plugin-dir .
```
This loads the plugin from disk instead of the marketplace, so any edits to `skills/*/SKILL.md` take effect immediately — just start a new conversation (or re-run the slash command) to pick up changes.
You can test individual skills directly:
```
/duckdb-skills:read-file some_local_file.parquet
/duckdb-skills:duckdb-docs pivot unpivot
/duckdb-skills:query SELECT 42
```
**Prerequisites:** DuckDB CLI must be installed. If it isn't, the skills will offer to install it via `/duckdb-skills:install-duckdb`.
## How the skills work together
Skills reference each other where it makes sense:
- `read-file` suggests `query` for follow-up exploration and `attach-db` for persisting large files
- `query`, `read-file`, and `read-memories` all use `duckdb-docs` to troubleshoot DuckDB errors automatically
- All skills share the same `state.sql` — secrets and macros set up by `read-file` are reused by `query`, and databases attached by `attach-db` are available everywhere
## Platform support
These skills have been tested on **macOS** and **Linux**. Windows is not yet fully supported — some shell commands and path handling may not work as expected. We plan to improve Windows compatibility in a future release.
## Reporting issues & suggestions
Found a bug or have an idea for improvement? Open an issue at:
**https://github.com/duckdb/duckdb-skills/issues**
For DuckDB-specific bugs (extension loading, SQL errors), please include the DuckDB version (`duckdb --version`) and the full error message.
## skills/attach-db/SKILL.md
---
name: attach-db
description: >
Attach a DuckDB database file for use with /duckdb-skills:query.
Explores the schema (tables, columns, row counts) and writes a SQL state file
so subsequent queries can restore this session automatically via duckdb -init.
argument-hint: <path-to-database.duckdb>
allowed-tools: Bash
---
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 "<QUERY>"`.
## 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 <table_name>;
SELECT count() AS row_count FROM <table_name>;
"
```
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/<project-id>/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.
## skills/convert-file/SKILL.md
---
name: convert-file
description: >
Convert any data file to another format: CSV, Parquet, JSON, Excel, GeoJSON, and more.
Use when the user says "convert to parquet", "save as xlsx", "export as JSON", "make this a CSV",
"turn into parquet", or any variation of format-to-format conversion for data files.
Also triggers when the user wants to write Parquet, Excel, or other binary formats that Claude cannot produce natively.
argument-hint: <input-file> [output-file]
allowed-tools: Bash
---
You are helping the user convert a data file from one format to another using DuckDB.
Input file: `$0`
Output file: `${1:-}`
## Step 1 — Resolve input and output
**Input**: `$0`. If it's a bare filename (no `/`), resolve to a full path with `find "$PWD" -name "$0" -not -path '*/.git/*' 2>/dev/null | head -1`.
**Output**: If `$1` is provided, use it as the output path. If not, default to the same stem as the input with a `.parquet` extension (e.g., `data.csv` → `data.parquet`).
Infer the output format from the output file extension:
| Extension | Format clause |
|---|---|
| `.parquet`, `.pq` | *(default, no clause needed)* |
| `.csv` | `(FORMAT csv, HEADER)` |
| `.tsv` | `(FORMAT csv, HEADER, DELIMITER '\t')` |
| `.json` | `(FORMAT json, ARRAY true)` |
| `.jsonl`, `.ndjson` | `(FORMAT json, ARRAY false)` |
| `.xlsx` | `(FORMAT xlsx)` — requires `INSTALL excel; LOAD excel;` |
| `.geojson` | `(FORMAT GDAL, DRIVER 'GeoJSON')` — requires `LOAD spatial;` |
| `.gpkg` | `(FORMAT GDAL, DRIVER 'GPKG')` — requires `LOAD spatial;` |
| `.shp` | `(FORMAT GDAL, DRIVER 'ESRI Shapefile')` — requires `LOAD spatial;` |
## Step 2 — Convert
Run a single DuckDB command. Prepend extension loads as needed based on both the input and output formats.
```bash
duckdb -c "
<EXTENSION_LOADS>
COPY (FROM '<INPUT_PATH>') TO '<OUTPUT_PATH>' <FORMAT_CLAUSE>;
"
```
For remote inputs (`s3://`, `https://`, etc.), prepend the same protocol setup as `read-file`:
| Protocol | Prepend |
|---|---|
| `s3://` | `LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER credential_chain);` |
| `gs://` / `gcs://` | `LOAD httpfs; CREATE SECRET (TYPE GCS, PROVIDER credential_chain);` |
| `https://` / `http://` | `LOAD httpfs;` |
**If the user mentions partitioning** (e.g., "partition by year"), add `PARTITION_BY (col)` to the format clause. This only works with Parquet and CSV output.
**If the user mentions compression** (e.g., "use zstd"), add `CODEC 'zstd'` for Parquet output.
## Step 3 — Report
On success, report:
- Input file and detected format
- Output file, format, and size (`ls -lh`)
- Row count if quick to compute
On failure:
- **`duckdb: command not found`** → delegate to `/duckdb-skills:install-duckdb`
- **Missing extension** → install it and retry
- **Input parse error** → suggest the user check the input format or try `/duckdb-skills:read-file` first to inspect it
## skills/duckdb-docs/SKILL.md
---
name: duckdb-docs
description: >
Search DuckDB and DuckLake documentation and blog posts. Returns relevant
doc chunks for a question or keyword using full-text search against a
locally cached index.
argument-hint: <question or keyword>
allowed-tools: Bash
---
You are helping the user find relevant DuckDB or DuckLake documentation.
Query: `$@`
Follow these steps in order.
## Step 1 — Check DuckDB is installed
```bash
command -v duckdb
```
If not found, delegate to `/duckdb-skills:install-duckdb` and then continue.
## Step 2 — Ensure required extensions are installed
```bash
duckdb :memory: -c "INSTALL httpfs; INSTALL fts;"
```
If this fails, report the error and stop.
## Step 3 — Choose the data source and extract search terms
The query is: `$@`
### Data source selection
There are two search indexes available:
| Index | Remote URL | Local cache filename | Versions | Use when |
|-------|-----------|---------------------|----------|----------|
| **DuckDB docs + blog** | `https://duckdb.org/data/docs-search.duckdb` | `duckdb-docs.duckdb` | `lts`, `current`, `blog` | Default — any DuckDB question |
| **DuckLake docs** | `https://ducklake.select/data/docs-search.duckdb` | `ducklake-docs.duckdb` | `stable`, `preview` | Query mentions DuckLake, catalogs, or DuckLake-specific features |
Both indexes share the same schema:
| Column | Type | Description |
|--------|------|-------------|
| `chunk_id` | `VARCHAR` (PK) | e.g. `stable/sql/functions/numeric#absx` |
| `page_title` | `VARCHAR` | Page title from front matter |
| `section` | `VARCHAR` | Section heading (null for page intros) |
| `breadcrumb` | `VARCHAR` | e.g. `SQL > Functions > Numeric` |
| `url` | `VARCHAR` | URL path with anchor |
| `version` | `VARCHAR` | See table above |
| `text` | `TEXT` | Full markdown of the chunk |
By default, search **DuckDB docs** and filter to `version = 'lts'`. Use different versions when:
- The user explicitly asks about `current`/nightly features → `version = 'current'`
- The user asks about a blog post or wants background/motivation → `version = 'blog'`
- The user asks about DuckLake → search the DuckLake index with `version = 'stable'`
- When unsure, omit the version filter to search across all versions.
### Search terms
If the input is a **natural language question** (e.g. "how do I find the most frequent value"), extract the key technical terms (nouns, function names, SQL keywords) to form a compact BM25 query string. Drop stop words like "how", "do", "I", "the".
If the input is already a **function name or technical term** (e.g. `arg_max`, `GROUP BY ALL`), use it as-is.
Use the extracted terms as `SEARCH_QUERY` in the next step.
## Step 4 — Ensure local cache is fresh
The cache lives at `$HOME/.duckdb/docs/CACHE_FILENAME` (where `CACHE_FILENAME` is `duckdb-docs.duckdb` or `ducklake-docs.duckdb` per Step 3).
First, ensure the directory exists:
```bash
mkdir -p "$HOME/.duckdb/docs"
```
Then check whether the cache file exists and is fresh (≤2 days old):
```bash
CACHE_FILE="$HOME/.duckdb/docs/CACHE_FILENAME"
if [ -f "$CACHE_FILE" ]; then
MTIME=$(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE")
CACHE_AGE_DAYS=$(( ( $(date +%s) - MTIME ) / 86400 ))
else
CACHE_AGE_DAYS=999
fi
echo "Cache age: $CACHE_AGE_DAYS days"
```
**If `CACHE_AGE_DAYS` ≤ 2** → skip to Step 5.
**Otherwise** (stale or missing) → fetch the index:
```bash
duckdb -c "
LOAD httpfs;
LOAD fts;
ATTACH 'REMOTE_URL' AS remote (READ_ONLY);
ATTACH '$HOME/.duckdb/docs/CACHE_FILENAME.tmp' AS tmp;
COPY FROM DATABASE remote TO tmp;
" && mv "$HOME/.duckdb/docs/CACHE_FILENAME.tmp" "$HOME/.duckdb/docs/CACHE_FILENAME"
```
Replace `REMOTE_URL` and `CACHE_FILENAME` per Step 3. If the fetch fails (network error), report the error and stop.
## Step 5 — Search the docs
```bash
duckdb "$HOME/.duckdb/docs/CACHE_FILENAME" -readonly -json -c "
LOAD fts;
SELECT
chunk_id, page_title, section, breadcrumb, url, version, text,
fts_main_docs_chunks.match_bm25(chunk_id, 'SEARCH_QUERY') AS score
FROM docs_chunks
WHERE score IS NOT NULL
AND version = 'VERSION'
ORDER BY score DESC
LIMIT 8;
"
```
Replace `CACHE_FILENAME`, `SEARCH_QUERY`, and `VERSION` per Step 3. Remove the `AND version = 'VERSION'` line if searching across all versions.
If the user's question could benefit from both DuckDB docs and blog results, run two queries (one with `version = 'stable'`, one with `version = 'blog'`) or omit the version filter entirely.
## Step 6 — Handle errors
- **Extension not installed** (`httpfs` or `fts` not found): run `duckdb :memory: -c "INSTALL httpfs; INSTALL fts;"` and retry.
- **ATTACH fails / network unreachable**: inform the user that the docs index is unavailable and suggest checking their internet connection. The DuckDB index is hosted at `https://duckdb.org/data/docs-search.duckdb` and the DuckLake index at `https://ducklake.select/data/docs-search.duckdb`.
- **No results** (all scores NULL or empty result set): try broadening the query — drop the least specific term, or try a single-word version of the query — then retry Step 5. If still no results, tell the user no matching documentation was found and suggest visiting https://duckdb.org/docs or https://ducklake.select/docs directly.
## Step 7 — Present results
For each result chunk returned (ordered by score descending), format as:
```
### {section} — {page_title}
{url}
{text}
---
```
After presenting all chunks, synthesize a concise answer to the user's original question (`$@`) based on the retrieved documentation. If the chunks directly answer the question, lead with the answer before showing the sources.
## skills/install-duckdb/SKILL.md
---
name: install-duckdb
description: >
Install or update DuckDB extensions. Each argument is either a plain
extension name (installs from core) or name@repo (e.g. magic@community).
Pass --update to update extensions instead of installing.
argument-hint: "[--update] [ext1 ext2@repo ext3 ...]"
allowed-tools: Bash
---
Arguments: `$@`
Each extension argument has the form `name` or `name@repo`.
- `name` → `INSTALL name;`
- `name@repo` → `INSTALL name FROM repo;`
## Step 1 — Locate DuckDB
```bash
DUCKDB=$(command -v duckdb)
```
If not found, tell the user:
> **DuckDB is not installed.** Install it first with one of:
> - macOS: `brew install duckdb`
> - Linux: `curl -fsSL https://install.duckdb.org | sh`
> - Windows: `winget install DuckDB.cli`
>
> Then re-run `/duckdb-skills:install-duckdb`.
Stop if DuckDB is not found.
## Step 2 — Check for --update flag
If `--update` is present in `$@`, remove it from the argument list and set mode to **update**.
Otherwise mode is **install**.
## Step 3 — Build and run statements
**Install mode:**
Parse each remaining argument:
- If it contains `@`, split on `@` → `INSTALL <name> FROM <repo>;`
- Otherwise → `INSTALL <name>;`
Run all in a single DuckDB call:
```bash
"$DUCKDB" :memory: -c "INSTALL <ext1>; INSTALL <ext2> FROM <repo2>; ..."
```
**Update mode:**
First, check if the DuckDB CLI itself is up to date:
```bash
CURRENT=$(duckdb --version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
LATEST=$(curl -fsSL https://duckdb.org/data/latest_stable_version.txt)
```
- If `CURRENT` == `LATEST` → report DuckDB CLI is up to date.
- If `CURRENT` != `LATEST` → ask the user:
> **DuckDB CLI is outdated** (installed: `CURRENT`, latest: `LATEST`). Upgrade now?
If the user agrees, detect the platform and run the appropriate upgrade command:
- macOS (`brew` available): `brew upgrade duckdb`
- Linux: `curl -fsSL https://install.duckdb.org | sh`
- Windows: `winget upgrade DuckDB.cli`
Then update extensions:
- No extension names → update all: `UPDATE EXTENSIONS;`
- With extension names → update in a single call (ignore `@repo`):
`UPDATE EXTENSIONS (<name1>, <name2>, ...);`
```bash
"$DUCKDB" :memory: -c "UPDATE EXTENSIONS;"
# or
"$DUCKDB" :memory: -c "UPDATE EXTENSIONS (<ext1>, <ext2>, ...);"
```
Report success or failure after the call completes.
## skills/query/SKILL.md
---
name: query
description: >
Run SQL queries against the attached DuckDB database or ad-hoc against files.
Accepts raw SQL or natural language questions. Uses DuckDB Friendly SQL idioms.
argument-hint: <SQL or question> [--file path]
allowed-tools: Bash
---
You are helping the user query data using DuckDB.
Input: `$@`
Follow these steps in order.
## Step 1 — Resolve state and determine the mode
Look for an existing state file in either location:
```bash
STATE_DIR=""
test -f .duckdb-skills/state.sql && STATE_DIR=".duckdb-skills"
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 found, verify the databases it references are still accessible:
```bash
duckdb -init "$STATE_DIR/state.sql" -c "SHOW DATABASES;"
```
Now determine the mode:
- **Ad-hoc mode** if: the `--file` flag is present, or the SQL references file paths/literals (e.g. `FROM 'data.csv'`), or `STATE_DIR` is empty.
- **Session mode** if: `STATE_DIR` is set and the input references table names, is natural language, or is SQL without file references.
If no state file exists and no file is referenced, fall back to ad-hoc mode against `:memory:` — the user must reference files directly in their SQL.
If the state file exists but any ATTACH in it fails, warn the user and fall back to ad-hoc mode.
## Step 2 — Check DuckDB is installed
```bash
command -v duckdb
```
If not found, delegate to `/duckdb-skills:install-duckdb` and then continue.
## Step 3 — Generate SQL if needed
If the input is natural language (not valid SQL), generate SQL using the Friendly SQL reference below.
In **session mode**, first retrieve the schema to inform query generation:
```bash
duckdb -init "$STATE_DIR/state.sql" -csv -c "
SELECT table_name FROM duckdb_tables() ORDER BY table_name;
"
```
Then for relevant tables:
```bash
duckdb -init "$STATE_DIR/state.sql" -csv -c "DESCRIBE <table_name>;"
```
Use the schema context and the Friendly SQL reference to generate the most appropriate query.
## Step 4 — Estimate result size
Before executing, estimate whether the query could produce a very large result that would
consume excessive tokens when returned to this conversation.
**Session mode** — check row counts for the tables involved:
```bash
duckdb -init "$STATE_DIR/state.sql" -csv -c "
SELECT table_name, estimated_size, column_count
FROM duckdb_tables()
WHERE table_name IN ('<table1>', '<table2>');
"
```
**Ad-hoc mode** — probe the source:
```bash
duckdb :memory: -csv -c "
SET allowed_paths=['FILE_PATH'];
SET enable_external_access=false;
SET allow_persistent_secrets=false;
SET lock_configuration=true;
SELECT count() AS row_count FROM 'FILE_PATH';
"
```
**Evaluate**:
- If the query already has a `LIMIT`, `count()`, or other aggregation that bounds the output -> safe, proceed.
- If the source has **>1M rows** and the query has no LIMIT or aggregation -> tell the user:
*"This query would return a very large result set. Displaying it here would consume a lot of tokens and increase cost. I'd recommend adding `LIMIT 1000` or an aggregation to keep the output manageable."*
Ask for confirmation before running as-is.
- If the data size is **>10 GB** -> additionally warn:
*"This table is over 10 GB — the query may take a while to complete."*
Proceed if the user confirms.
Skip this step for queries that are intrinsically bounded (e.g. `DESCRIBE`, `SUMMARIZE`, aggregations, `count()`).
## Step 5 — Execute the query
**Ad-hoc mode** (sandboxed — only the referenced file is accessible):
```bash
duckdb :memory: -csv <<'SQL'
SET allowed_paths=['FILE_PATH'];
SET enable_external_access=false;
SET allow_persistent_secrets=false;
SET lock_configuration=true;
<QUERY>;
SQL
```
Replace `FILE_PATH` with the actual file path extracted from the query or `--file` argument.
If multiple files are referenced, include all paths in the `allowed_paths` list.
**Session mode** (user-trusted database):
```bash
duckdb -init "$STATE_DIR/state.sql" -csv -c "<QUERY>"
```
For multi-line queries, use a heredoc with `-init`:
```bash
duckdb -init "$STATE_DIR/state.sql" -csv <<'SQL'
<QUERY>;
SQL
```
Always use heredocs (`<<'SQL'`) for multi-line queries to avoid shell quoting issues.
## Step 6 — Handle errors
- **Syntax error**: show the error, suggest a corrected query, and re-run.
- **Missing extension** (e.g. `Extension "X" not loaded`): delegate to `/duckdb-skills:install-duckdb <ext>`, then retry.
- **Table not found** (session mode): list available tables with `FROM duckdb_tables()` and suggest corrections.
- **File not found** (ad-hoc mode): use `find "$PWD" -name "<filename>" 2>/dev/null` to locate the file and suggest the corrected path.
- **Persistent or unclear DuckDB error**: use `/duckdb-skills:duckdb-docs <error message or relevant keywords>` to search the documentation for guidance, then apply the fix and retry.
## Step 7 — Present results
Show the query output to the user. If the result has more than 100 rows, note the truncation and suggest adding `LIMIT` to the query.
For natural language questions, also provide a brief interpretation of the results.
---
## DuckDB Friendly SQL Reference
When generating SQL, prefer these idiomatic DuckDB constructs:
### Compact clauses
- **FROM-first**: `FROM table WHERE x > 10` (implicit `SELECT *`)
- **GROUP BY ALL**: auto-groups by all non-aggregate columns
- **ORDER BY ALL**: orders by all columns for deterministic results
- **SELECT * EXCLUDE (col1, col2)**: drop columns from wildcard
- **SELECT * REPLACE (expr AS col)**: transform a column in-place
- **UNION ALL BY NAME**: combine tables with different column orders
- **Percentage LIMIT**: `LIMIT 10%` returns a percentage of rows
- **Prefix aliases**: `SELECT x: 42` instead of `SELECT 42 AS x`
- **Trailing commas** allowed in SELECT lists
### Query features
- **count()**: no need for `count(*)`
- **Reusable aliases**: use column aliases in WHERE / GROUP BY / HAVING
- **Lateral column aliases**: `SELECT i+1 AS j, j+2 AS k`
- **COLUMNS(*)**: apply expressions across columns; supports regex, EXCLUDE, REPLACE, lambdas
- **FILTER clause**: `count() FILTER (WHERE x > 10)` for conditional aggregation
- **GROUPING SETS / CUBE / ROLLUP**: advanced multi-level aggregation
- **Top-N per group**: `max(col, 3)` returns top 3 as a list; also `arg_max(arg, val, n)`, `min_by(arg, val, n)`
- **DESCRIBE table_name**: schema summary (column names and types)
- **SUMMARIZE table_name**: instant statistical profile
- **PIVOT / UNPIVOT**: reshape between wide and long formats
- **SET VARIABLE x = expr**: define SQL-level variables, reference with `getvariable('x')`
### Data import
- **Direct file queries**: `FROM 'file.csv'`, `FROM 'data.parquet'`
- **Globbing**: `FROM 'data/part-*.parquet'` reads multiple files
- **Auto-detection**: CSV headers and schemas are inferred automatically
### Expressions and types
- **Dot operator chaining**: `'hello'.upper()` or `col.trim().lower()`
- **List comprehensions**: `[x*2 FOR x IN list_col]`
- **List/string slicing**: `col[1:3]`, negative indexing `col[-1]`
- **STRUCT.* notation**: `SELECT s.* FROM (SELECT {'a': 1, 'b': 2} AS s)`
- **Square bracket lists**: `[1, 2, 3]`
- **format()**: `format('{}->{}', a, b)` for string formatting
### Joins
- **ASOF joins**: approximate matching on ordered data (e.g. timestamps)
- **POSITIONAL joins**: match rows by position, not keys
- **LATERAL joins**: reference prior table expressions in subqueries
### Data modification
- **CREATE OR REPLACE TABLE**: no need for `DROP TABLE IF EXISTS` first
- **CREATE TABLE ... AS SELECT (CTAS)**: create tables from query results
- **INSERT INTO ... BY NAME**: match columns by name, not position
- **INSERT OR IGNORE INTO / INSERT OR REPLACE INTO**: upsert patterns
## skills/read-file/SKILL.md
---
name: read-file
description: >
Read any data file (CSV, JSON, Parquet, Avro, Excel, spatial, SQLite) or remote URL (S3, HTTPS).
Use when user references a data file, asks "what's in this file", or wants to preview/profile a dataset.
Not for source code.
argument-hint: <filename or URL> [question about the data]
allowed-tools: Bash
---
You are helping the user read and analyze a data file using DuckDB.
Filename given: `$0`
Question: `${1:-describe the data}`
## Step 1 — Read it
`RESOLVED_PATH` is `$0`. If the user gave a bare filename (no `/`), resolve it to a full path with `find` first.
Run a single DuckDB command that defines the `read_any` macro inline and reads the file.
For **remote files**, prepend the necessary LOAD/SECRET before the macro:
| Protocol | Prepend |
|---|---|
| `https://` / `http://` | `LOAD httpfs;` |
| `s3://` | `LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER credential_chain);` |
| `gs://` / `gcs://` | `LOAD httpfs; CREATE SECRET (TYPE GCS, PROVIDER credential_chain);` |
| `az://` / `azure://` / `abfss://` | `LOAD httpfs; LOAD azure; CREATE SECRET (TYPE AZURE, PROVIDER credential_chain);` |
For **local files**, no prefix needed.
```bash
duckdb -csv -c "
CREATE OR REPLACE MACRO read_any(file_name) AS TABLE
WITH json_case AS (FROM read_json_auto(file_name))
, csv_case AS (FROM read_csv(file_name))
, parquet_case AS (FROM read_parquet(file_name))
, avro_case AS (FROM read_avro(file_name))
, blob_case AS (FROM read_blob(file_name))
, spatial_case AS (FROM st_read(file_name))
, excel_case AS (FROM read_xlsx(file_name))
, sqlite_case AS (FROM sqlite_scan(file_name, (SELECT name FROM sqlite_master(file_name) LIMIT 1)))
, ipynb_case AS (
WITH nb AS (FROM read_json_auto(file_name))
SELECT cell_idx, cell.cell_type,
array_to_string(cell.source, '') AS source,
cell.execution_count
FROM nb, UNNEST(cells) WITH ORDINALITY AS t(cell, cell_idx)
ORDER BY cell_idx
)
FROM query_table(
CASE
WHEN file_name ILIKE '%.json' OR file_name ILIKE '%.jsonl' OR file_name ILIKE '%.ndjson' OR file_name ILIKE '%.geojson' OR file_name ILIKE '%.geojsonl' OR file_name ILIKE '%.har' THEN 'json_case'
WHEN file_name ILIKE '%.csv' OR file_name ILIKE '%.tsv' OR file_name ILIKE '%.tab' OR file_name ILIKE '%.txt' THEN 'csv_case'
WHEN file_name ILIKE '%.parquet' OR file_name ILIKE '%.pq' THEN 'parquet_case'
WHEN file_name ILIKE '%.avro' THEN 'avro_case'
WHEN file_name ILIKE '%.xlsx' OR file_name ILIKE '%.xls' THEN 'excel_case'
WHEN file_name ILIKE '%.shp' OR file_name ILIKE '%.gpkg' OR file_name ILIKE '%.fgb' OR file_name ILIKE '%.kml' THEN 'spatial_case'
WHEN file_name ILIKE '%.ipynb' THEN 'ipynb_case'
WHEN file_name ILIKE '%.db' OR file_name ILIKE '%.sqlite' OR file_name ILIKE '%.sqlite3' THEN 'sqlite_case'
ELSE 'blob_case'
END
);
DESCRIBE FROM read_any('RESOLVED_PATH');
SELECT count(*) AS row_count FROM read_any('RESOLVED_PATH');
FROM read_any('RESOLVED_PATH') LIMIT 20;
"
```
**If this fails:**
- **`duckdb: command not found`** → invoke `/duckdb-skills:install-duckdb` and retry.
- **Missing extension** (e.g. spatial files, xlsx, sqlite) → retry with `INSTALL spatial; LOAD spatial;` or `INSTALL sqlite_scanner; LOAD sqlite_scanner;` prepended before the macro.
- **Wrong reader / parse error** → use the correct `read_*` function directly instead of `read_any`.
## Step 2 — Answer
Using the schema, row count, and sample rows, answer:
`${1:-describe the data: summarize column types, row count, and any notable patterns.}`
## skills/read-memories/SKILL.md
---
name: read-memories
description: >
Search past Claude Code session logs to recall prior decisions, patterns, or unresolved work.
Use when user says "do you remember", "what did we do", references past conversations, or you need context from prior sessions.
argument-hint: <keyword> [--here]
allowed-tools: Bash
---
Search past session logs silently — do NOT narrate the process. Absorb the results and continue with enriched context.
`$0` is the keyword. Pass `--here` as `$1` to scope to the current project only.
## Step 1 — Query
```bash
duckdb :memory: -c "
SELECT
regexp_extract(filename, 'projects/([^/]+)/', 1) AS project,
strftime(timestamp::TIMESTAMPTZ, '%Y-%m-%d %H:%M') AS ts,
message.role AS role,
left(message.content::VARCHAR, 500) AS content
FROM read_ndjson('<SEARCH_PATH>', auto_detect=true, ignore_errors=true, filename=true)
WHERE message::VARCHAR ILIKE '%<KEYWORD>%'
AND message.role IS NOT NULL
ORDER BY timestamp
LIMIT 40;
"
```
Search paths:
- All projects: `$HOME/.claude/projects/*/*.jsonl`
- Current only (`--here`): `$HOME/.claude/projects/$(echo "$PWD" | sed 's|[/_]|-|g')/*.jsonl`
Replace `<SEARCH_PATH>` and `<KEYWORD>` before running.
## Step 2 — Internalize
From the results, extract decisions, patterns, unresolved TODOs, and user corrections. Use this to inform your current response — do not repeat raw logs to the user.
## skills/s3-explore/SKILL.md
---
name: s3-explore
description: >
Explore and query data on S3, Cloudflare R2, GCS, MinIO, or any S3-compatible storage.
Use when the user mentions an s3://, r2://, gs://, or gcs:// URL, asks "what's in this bucket",
wants to list remote files, preview remote Parquet/CSV/JSON, or query data on object storage
without downloading it. Also triggers when the user wants to know the size, schema, or row count
of remote datasets.
argument-hint: <s3-url> [question about the data]
allowed-tools: Bash
---
You are helping the user explore data on remote object storage using DuckDB.
URL: `$0`
Question: `${1:-list and describe what's there}`
## Step 1 — Detect provider and set up credentials
Based on the URL or user context, prepend the appropriate secret configuration:
| Provider | URL patterns | Secret setup |
|---|---|---|
| **AWS S3** | `s3://` | `CREATE SECRET (TYPE S3, PROVIDER credential_chain);` |
| **Cloudflare R2** | `r2://`, `s3://` with R2 endpoint | `CREATE SECRET (TYPE R2, PROVIDER credential_chain);` |
| **GCS** | `gs://`, `gcs://` | `CREATE SECRET (TYPE GCS, PROVIDER credential_chain);` |
| **MinIO / custom** | `s3://` with custom endpoint | `CREATE SECRET (TYPE S3, KEY_ID '...', SECRET '...', ENDPOINT '...', USE_SSL true);` |
For R2, if the user provides an account ID, the endpoint is `<account_id>.r2.cloudflarestorage.com`. R2 URLs like `r2://bucket/path` should be rewritten to `s3://bucket/path` with the R2 secret.
For public buckets (e.g., Overture Maps, AWS open data), no secret is needed — skip this step.
Always prepend:
```sql
LOAD httpfs;
```
## Step 2 — Determine what the URL points to
If the URL looks like a **directory or bucket** (no file extension, or ends with `/`), list its contents with sizes:
```bash
duckdb -c "
LOAD httpfs;
<SECRET_SETUP>
SELECT filename, (size / 1024 / 1024)::DECIMAL(10,1) AS size_mb, last_modified
FROM read_blob('<URL>/*')
ORDER BY filename
LIMIT 50;
"
```
Note: only select `filename`, `size`, `last_modified` — never select `content`, which would download the actual files.
If the URL points to a **specific file or glob pattern** (has a file extension or contains `*`), preview it:
```bash
duckdb -c "
LOAD httpfs;
<SECRET_SETUP>
DESCRIBE FROM '<URL>';
SELECT count(*) AS row_count FROM '<URL>';
FROM '<URL>' LIMIT 20;
"
```
For **Parquet files**, get row counts and sizes from metadata (no data download):
```bash
duckdb -c "
LOAD httpfs;
<SECRET_SETUP>
SELECT file_name,
sum(row_group_num_rows) AS total_rows,
(sum(row_group_compressed_bytes) / 1024 / 1024)::DECIMAL(10,1) AS compressed_mb
FROM parquet_metadata('<URL>')
GROUP BY file_name;
"
```
## Step 3 — Answer the question
Using the listing, schema, or sample data, answer:
`${1:-list and describe what's there}`
If the user asks an analytical question (e.g., "how many rows match X"), write and run the appropriate SQL query. DuckDB pushes predicates down into Parquet on S3, so filtering is efficient even on large remote datasets.
## Error handling
- **`duckdb: command not found`** → delegate to `/duckdb-skills:install-duckdb`
- **Access denied / 403** → suggest the user check credentials: `aws configure`, environment variables, or provide explicit key/secret
- **Bucket not found / 404** → check the URL and region
- **Timeout on large listing** → suggest narrowing the glob pattern or adding a prefix
## skills/spatial/SKILL.md
---
name: spatial
description: >
Answer questions about spatial data using DuckDB. Use when the user mentions locations,
coordinates, lat/lng, distances, maps, addresses, "near", "within", "closest", geographic
names, or spatial file formats (GeoJSON, Shapefile, GeoPackage, GPX, GeoParquet). Also
triggers when the user wants to find places, buildings, or roads — Overture Maps provides
free global data on S3 with zero API keys. Handles spatial joins, distance calculations,
containment checks, density analysis, and format conversions for geographic data.
argument-hint: <question or file> [additional context]
allowed-tools: Bash
---
You are answering spatial questions using DuckDB's spatial extension and, when needed, Overture Maps as a free global data source.
Question or file: `$0`
Additional context: `${1:-}`
## Step 1 — Understand what the user needs
Classify the question:
| Pattern | Data source | Key functions |
|---------|-------------|---------------|
| "Find X near Y" (no user file) | Overture Maps on S3 | `ST_Distance_Spheroid`, bbox filtering |
| "How far between A and B" | Geocode or user data | `ST_Distance_Spheroid` |
| "Which points fall inside polygons" | User files | `ST_Contains` |
| "Analyze this GeoJSON/Shapefile/GPX" | User file | `ST_Read`, measurement functions |
| "Show density/hotspots" | User or Overture data | H3 hex binning |
| "Convert to GeoJSON/GeoPackage" | User file | `COPY TO (FORMAT GDAL)` |
| "Count buildings/roads in area" | Overture Maps | bbox filtering + aggregation |
If the question involves real-world places, POIs, buildings, roads, or boundaries and the user hasn't provided a file, use **Overture Maps** — read `references/overture.md` for S3 paths and schema.
For spatial function syntax, read `references/functions.md`.
## Step 2 — Write and run the query
Always start with:
```sql
LOAD spatial;
SET geometry_always_xy = true;
```
Add extensions as needed:
- Overture/remote data: `LOAD httpfs; CREATE SECRET (TYPE S

