/dogsled-core:add-database-destinationfrom dogsled-core
Guides adding a new database load destination (Snowflake, PostgreSQL, ClickHouse, etc.) to the @bobsled-inc/loader package, implementing the DatabaseDestination interface with append/merge/full_refresh support.
Ships in dogsled-core. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Use this skill to add a database or warehouse loader destination.
Load the full reference only when the task needs its schemas, command tables, examples, or troubleshooting detail:
Guides an agent through adding a new database destination to packages/loader/. The new destination must implement the DatabaseDestination interface and wire into the config schema, factory, CLI, and check command.
/add-database-destination <destination-name>
Example: /add-database-destination snowflake
Before starting, read these files to understand the patterns:
| File | Purpose |
|---|---|
packages/loader/src/runtime/destinations/database.ts | DatabaseDestination interface, SYSTEM_COLUMNS, sanitizers, buildClusterColumns() |
packages/loader/src/runtime/destinations/duckdb.ts | Simpler reference implementation (~300 lines) |
packages/loader/src/runtime/destinations/bigquery.ts | Complex reference implementation (~500 lines, GCS staging, Parquet conversion) |
packages/loader/src/schemas/config.ts | Zod config schema (discriminated union on dest) |
packages/loader/src/commands/run.ts | Factory wiring: isDatabaseDestConfig, createDefaultDatabaseDestination, runDatabaseLoader |
packages/loader/src/commands/check.ts | Connectivity check pattern |
packages/loader/tests/unit/destinations/duckdb.test.ts | Test patterns for all strategies |
ls packages/loader/src/runtime/destinations/
If a file for the destination already exists, ask the user whether to update or abort.
Read packages/loader/src/runtime/destinations/database.ts to understand the contract. Then read both duckdb.ts (simpler, good starting point) and bigquery.ts (shows DI interfaces, retry patterns, staging format conversion).
Key interface:
export interface DatabaseDestination {
initialize(): Promise<void>;
ensureTable(
schemaName: string,
tableName: string,
columns: SchemaColumn[],
options?: EnsureTableOptions
): Promise<void>;
loadAndFinalize(
schemaName: string,
tableName: string,
filePath: string,
columns: SchemaColumn[],
strategy: LoadStrategy,
keyColumns: string[]
): Promise<LoadResult>;
deleteRows(
schemaName: string,
tableName: string,
column: string,
values: string[]
): Promise<void>;
close(): Promise<void>;
getTruncatedTables(): Set<string>;
setTruncatedTables(tables: Set<string>): void;
}
Key shared utilities from database.ts:
SYSTEM_COLUMNS.TIME_EXTRACTED = "_time_extracted" — set by extractor, arrives in JSONLSYSTEM_COLUMNS.LOADED_AT = "_dogsled_loaded_at" — set by destination at load time (CURRENT_TIMESTAMP or equivalent)sanitizeTableName(name) — validates [A-Za-z_][A-Za-z0-9_]*, rejects _dogsled_stg_ prefixsanitizeSchemaName(name) — same validation for schema namesbuildClusterColumns(columns, options) — builds up to 4 cluster columns from cursor_field + key_propertiesCreate packages/loader/src/runtime/destinations/<name>.ts. Follow this structure:
Define lightweight interfaces that mirror the real SDK's API surface. This enables unit testing without real database connections. Follow the BigQuery pattern:
// DI interfaces for testing
export interface <Name>ClientLike {
// Methods needed: connect, query, close, etc.
}
export interface <Name>DestinationOptions {
// Connection params (host, port, database, warehouse, etc.)
// Optional injected client for testing
client?: <Name>ClientLike;
logger?: LoaderLogger;
}
Map ColumnType (string | integer | number | boolean | timestamp | array | object) to the database's native types. Include an exhaustive switch with never check:
function map<Name>Type(type: ColumnType): string {
switch (type) {
case 'integer': return '<DB_INT_TYPE>';
case 'number': return '<DB_FLOAT_TYPE>';
case 'boolean': return '<DB_BOOL_TYPE>';
case 'timestamp': return '<DB_TIMESTAMP_TYPE>';
case 'string':
case 'array':
case 'object': return '<DB_STRING_TYPE>';
default: {
const _exhaustive: never = type;
throw new Error(`Unsupported column type: ${_exhaustive}`);
}
}
}
Note: array and object always map to the string/text type (JSON stored as text).
Create a quoteIdentifier() function appropriate for the database. Different databases use different quoting:
"identifier" (double quotes)`identifier` (backticks)"identifier" (double quotes, case-sensitive when quoted)`identifier` (backticks)Validate that the identifier does not contain the quote character to prevent SQL injection.
export class <Name>Destination implements DatabaseDestination {
// Private fields:
private cachedClient?: <Name>ClientLike; // Lazy-initialized client
private truncatedTables = new Set<string>(); // full_refresh checkpoint
private columnCache = new Map<string, Map<string, string>>(); // Avoids repeated schema queries
constructor(options: <Name>DestinationOptions) { ... }
}
initialize() — Connect to the databaseconst module = await import('<sdk-package>');SELECT 1 or equivalent)async initialize(): Promise<void> {
if (!this.cachedClient) {
try {
const module = await import('<sdk-package>');
this.cachedClient = new module.<Client>({ ...connectionOptions });
} catch (error) {
throw new Error(`Failed to load <sdk-package>. Install it to use --dest <name>. ${message}`);
}
}
// Verify connectivity and ensure schema exists
}
ensureTable() — Create or evolve the table schemaThis method is called before every loadAndFinalize(). It must be idempotent.
Column cache fast path: Check this.columnCache first. If all requested columns exist with matching types, return immediately without querying the database.
Cold path (first call for a table):
information_schema.columns (or equivalent) for existing columnscolumns array using the type mapping function_time_extracted TIMESTAMP and _dogsled_loaded_at TIMESTAMPCREATE TABLE IF NOT EXISTSError(Schema change conflict on ${table}.${col}: existing type ${existing} does not match expected ${expected}) — do NOT auto-castALTER TABLE ADD COLUMN (batch if the database supports it, otherwise one at a time)Type normalization: Some databases return type aliases (e.g., BigQuery returns INTEGER vs INT64). If the target database has aliases, write a normalizeType() function and compare normalized forms. See normalizeBqType() in bigquery.ts.
Clustering/partitioning (optional): If the database supports clustering or partitioning, use buildClusterColumns(columns, options) to determine cluster keys. BigQuery partitions by DATE(_time_extracted) and clusters by cursor_field + key_properties. Adapt to the target database's capabilities.
loadAndFinalize() — Load data with strategy-specific logicThis method receives a filePath pointing to a JSONL file containing records with all data columns plus _time_extracted. The _dogsled_loaded_at column is NOT in the JSONL — it must be set by the destination at load time.
Three strategy branches:
strategy === 'append')Straightforward INSERT from the JSONL file into the target table. Set _dogsled_loaded_at to CURRENT_TIMESTAMP (or equivalent) during the INSERT.
INSERT INTO <target> (<col_list>, _dogsled_loaded_at)
SELECT <data_cols>, CURRENT_TIMESTAMP FROM <staged_data>
Return { rowsAffected: <count> }.
strategy === 'full_refresh')Truncate-on-first-flush pattern:
this.truncatedTables.has(qualifiedTable)TRUNCATE TABLE (or DELETE FROM), then add to truncatedTablesThis ensures that multi-flush full_refresh runs don't lose data from earlier flushes.
strategy === 'merge')The most complex path. Uses a staging table + MERGE statement with dedup and time guard.
Validate: keyColumns.length > 0 — throw if empty
Create staging table with a unique name: _dogsled_stg_<table>_<random_hex>
ROW_NUMBER() OVER (PARTITION BY <key_cols> ORDER BY _time_extracted DESC NULLS LAST) = 1_dogsled_loaded_at = CURRENT_TIMESTAMP in the staging SELECTExecute MERGE:
MERGE INTO <target> T
USING <staging> S
ON T.<key1> = S.<key1> AND T.<key2> = S.<key2> ...
WHEN MATCHED AND S._time_extracted >= T._time_extracted
THEN UPDATE SET <non-key-cols> = S.<non-key-cols>
WHEN NOT MATCHED
THEN INSERT (<all_cols>) VALUES (S.<all_cols>)
S._time_extracted >= T._time_extracted) prevents older data from overwriting newer data during out-of-order flushesupdateSet is empty (all columns are keys), omit the WHEN MATCHED clause entirelyCleanup in finally block: DROP TABLE IF EXISTS <staging> — must always run, even on error
Return { rowsAffected: <staging_row_count> } (exact insert/update split is usually unavailable)
NULL key behavior: SQL NULL = NULL evaluates to UNKNOWN, so MERGE ON never matches NULL keys. Records with NULL keys always INSERT. This is standard SQL semantics — do not try to work around it.
BigQuery-specific MERGE patterns (reference for cloud warehouses):
_time_extracted changes every load and cursor or partition_by values can move forward, so the key's existing row falls outside the range and is inserted again as a duplicate_dogsled_loaded_at as tiebreaker in QUALIFY dedup (for cross-batch ordering)close() — Release resourcesCHECKPOINT)deleteRows() — Replace slices for REPLACEThe loader calls this before the next load of a stream that received a protocol REPLACE
message. Delete every row whose column equals one of values:
column with the dialect helper.getTruncatedTables() / setTruncatedTables()Simple checkpoint support for full_refresh recovery:
getTruncatedTables(): Set<string> {
return new Set(this.truncatedTables);
}
setTruncatedTables(tables: Set<string>): void {
this.truncatedTables = new Set(tables);
}
If the destination needs any shared type helpers (like mapDuckDbType in duckdb-primitives.ts), co-locate them with the destination class. Do not create separate type files.
Edit packages/loader/src/schemas/config.ts:
const <Name>DestConfigSchema = z.object({
dest: z.literal('<name>'),
// Connection options (host, port, database, warehouse, role, etc.)
targetSchema: sqlIdentifier.default('<default_schema>'),
loadStrategy: z.enum(LOAD_STRATEGIES).optional(),
bufferSize,
logFormat,
maxConcurrentLoads: z.coerce.number().int().positive().default(1),
checkpointDir: z.string().trim().min(1).optional(),
maxBufferMemory: memorySizePattern,
tablePrefix,
});
LoaderConfigSchema discriminated union:export const LoaderConfigSchema = z.discriminatedUnion('dest', [
LocalDestConfigSchema,
GcsDestConfigSchema,
S3DestConfigSchema,
DuckDbDestConfigSchema,
BigQueryDestConfigSchema,
<Name>DestConfigSchema, // Add here
]);
export type <Name>DestConfig = z.infer<typeof <Name>DestConfigSchema>;
run.tsEdit packages/loader/src/commands/run.ts:
Import the new config type at the top:
import type { <Name>DestConfig } from '../schemas/config.js';
Update isDatabaseDestConfig to include the new destination:
function isDatabaseDestConfig(
config: LoaderConfig
): config is DuckDbDestConfig | BigQueryDestConfig | <Name>DestConfig {
return config.dest === 'duckdb' || config.dest === 'bigquery' || config.dest === '<name>';
}
Update createDefaultDatabaseDestination to handle the new destination:
async function createDefaultDatabaseDestination(
config: DuckDbDestConfig | BigQueryDestConfig | <Name>DestConfig,
options?: CreateDatabaseDestOptions
): Promise<DatabaseDestination> {
if (config.dest === 'duckdb') { ... }
if (config.dest === '<name>') {
const { <Name>Destination } = await import('../runtime/destinations/<name>.js');
return new <Name>Destination({
// Map config fields to constructor options
logger: options?.logger,
});
}
// BigQuery fallthrough...
}
Update runDatabaseLoader signature to accept the new config type:
export async function runDatabaseLoader(
rawConfig: DuckDbDestConfig | BigQueryDestConfig | <Name>DestConfig,
...
Update RunLoaderDependencies.createDatabaseDestination type to include the new config.
Update registerRunCommand to add CLI options for the new destination (e.g., --host, --port, --warehouse).
Update the --dest option description to include the new destination name.
Edit packages/loader/src/commands/check.ts:
check<Name> function following the existing patterns:async function check<Name>(
options: {/* connection params */},
dependencies: CheckDependencies = {}
): Promise<void> {
const stderr = dependencies.stderr ?? process.stderr;
const setExitCode =
dependencies.setExitCode ??
((code: number) => {
process.exitCode = code;
});
try {
const module = await import('<sdk-package>');
// Create client, run SELECT 1 or equivalent
stderr.write(chalk.green(`OK: <Name> connected successfully`) + '\n');
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
stderr.write(chalk.red(`FAIL: <Name>: ${message}`) + '\n');
setExitCode(1);
}
}
Add a case '<name>': to the switch in registerCheckCommand's action handler.
Add any new CLI options needed for the check (e.g., --host, --warehouse).
Update the --dest default error message to include the new destination.
Export the check function for testability.
In packages/loader/src/commands/run.ts inside registerRunCommand:
.option() calls for every connection parameter.action() handlerIn packages/loader/src/commands/check.ts inside registerCheckCommand:
.option() calls for connection parametersUpdate the help text for --dest in both commands to list the new destination.
Create packages/loader/tests/unit/destinations/<name>.test.ts following the DuckDB test patterns.
Required test cases (see duckdb.test.ts for the exact patterns):
initialize() connects successfullyensureTable() creates table with correct column types including system columnsensureTable() on existing table with new columns adds them via ALTER TABLEensureTable() on type change throws errorloadAndFinalize("append") inserts rows directlyloadAndFinalize("merge") deduplicates by PK and merges into targetloadAndFinalize("merge") deduplicates within a single flush (keeps latest by _time_extracted)loadAndFinalize("full_refresh") truncates and insertsloadAndFinalize("full_refresh") on second flush appends without re-deletingclose() is idempotent_dogsled_loaded_at is populated for append and merge_time_extracted is populated correctlydeleteRows() deletes matching rows with bound values, batches, and is a no-op for a missing tableTest setup pattern:
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
// Helper to write JSONL test files
async function writeJsonl(filePath: string, records: Record<string, unknown>[]): Promise<void> {
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, records.map((r) => JSON.stringify(r)).join('\n') + '\n');
}
For databases that require network connections, use the DI interfaces to inject mock clients. See the BigQuery test patterns where BigQueryClientLike is mocked.
Print a summary:
Added database destination: <name>
Files created:
- packages/loader/src/runtime/destinations/<name>.ts
- packages/loader/tests/unit/destinations/<name>.test.ts
Files modified:
- packages/loader/src/schemas/config.ts (added <Name>DestConfigSchema)
- packages/loader/src/commands/run.ts (factory + CLI wiring)
- packages/loader/src/commands/check.ts (connectivity check)
Config options: <list of config fields>
Strategies: append, merge, full_refresh
SDK package: <npm-package-name> (optional peer dep, dynamically imported)
Run all of these before considering the task complete:
pnpm --filter @bobsled-inc/loader typecheck
pnpm --filter @bobsled-inc/loader lint
pnpm --filter @bobsled-inc/loader test
All must pass. Fix any failures before proceeding.
Every table gets two system columns added by ensureTable():
| Column | Source | Value |
|---|---|---|
_time_extracted | Extractor | Timestamp when the record was extracted (in JSONL) |
_dogsled_loaded_at | Destination | CURRENT_TIMESTAMP at load time (NOT in JSONL) |
Merge strategy staging tables use the prefix _dogsled_stg_ followed by the table name and a random hex suffix:
_dogsled_stg_<table>_<16-hex-chars>
sanitizeTableName() rejects any user table name starting with _dogsled_stg_ to prevent collisions.
Always run schema and table names through sanitizeSchemaName() / sanitizeTableName() from database.ts before using them in SQL. These validate the [A-Za-z_][A-Za-z0-9_]* pattern.
Within a single merge batch, dedup using:
ROW_NUMBER() OVER (PARTITION BY <key_cols> ORDER BY _time_extracted DESC NULLS LAST) = 1
This keeps the latest record per key within the batch. Note: PARTITION BY groups NULLs together (unlike JOIN), so two records with NULL keys in the same batch will be deduped against each other.
The WHEN MATCHED AND S._time_extracted >= T._time_extracted clause prevents out-of-order flushes from overwriting newer data. This is critical for correctness when flushes arrive non-sequentially.
Cache known column names and types per qualified table name (Map<string, Map<string, string>>) to avoid repeated information_schema queries. Invalidate/update the cache after any ALTER TABLE or CREATE TABLE.
Database SDK packages are optional peer dependencies. Always use dynamic import() inside initialize() or getClient(), wrapped in try/catch:
try {
const module = await import('<package>');
this.client = new module.<Client>({ ... });
} catch (error) {
throw new Error(`Failed to load <package>. Install it to use --dest <name>. ${message}`);
}
Define minimal interfaces that mirror the real SDK. Inject via constructor options. This enables unit tests to mock all database interactions without real connections. See BigQueryClientLike, BigQueryDatasetLike, BigQueryTableLike in bigquery.ts and DuckDbDatabaseLike, DuckDbConnectionLike in duckdb-primitives.ts.
The truncatedTables set tracks which tables have been truncated in the current run. On restart recovery, setTruncatedTables() restores this state from a checkpoint so already-truncated tables are not re-truncated (which would lose data from earlier flushes in the same run).
process.exitCode = N; return; in commands — never process.exit()CommandError from @bobsled-inc/protocol for user-facing errorsfinally block — always clean up even on errorclose() and idempotentWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
npx claudepluginhub bobsled-inc/dogsled-core --plugin dogsled-core65 skills in this plugin
/add-custom-api-integrationAuthor a generic custom_api source for any REST/GraphQL API purely in YAML — inline transport (base_url + auth), one declarative resource per endpoint, then validate/verify/extract. Use when the API isn't in the bundled catalog./add-custom-mcp-integrationAuthor a custom_mcp source for any remote MCP server (Model Context Protocol over streamable HTTP) purely in YAML — inline mcp_http transport (url + auth + auth_env_vars), one resource_kind mcp resource per tool, then validate/verify/extract. Use when the MCP server isn't in the bundled catalog./add-file-destinationAdd a new file-based load destination (e.g., Azure Blob Storage, R2, MinIO) to the @bobsled-inc/loader package. Walks through class implementation, config schema, factory wiring, CLI options, check command, and tests./add-file-storage-sourceOnboard documents (PDF, DOCX, PPTX, HTML, Markdown, text, email) from an Amazon S3 or Google Cloud Storage bucket — author a file-storage integration (source_type s3|gcs, bucket + auth) plus a document resource that parses and token-chunks each file, and an optional pipeline that embeds the chunks. Use when the user wants to ingest files/documents from cloud object storage rather than from an API./add-integrationAdd a new API integration to the @bobsled-inc/integrations library. Automates OpenAPI spec discovery, YAML generation, curation, and validation./add-warehouse-sourceAdd a new warehouse or database extractor source to @bobsled-inc/extractor. Guides through schema definitions, client implementation, SQL dialect support, type mappings, factory wiring, and tests.