archiving-databases
БесплатноЗапускает вложенные скриптыНе проверенProcess use when you need to archive historical database records to reduce primary database size. This skill automates moving old data to archive tables or…
от jeremylongshore★ 2 961 звезда на GitHubОб этом скилле
Database Archival System
Overview
Implement automated data archival pipelines that move historical records from primary database tables to archive storage (archive tables, S3, Azure Blob, or GCS) based on age, status, or access frequency criteria.
Prerequisites
- Database credentials with SELECT, INSERT, and DELETE permissions on source and archive tables
- Cloud storage credentials (AWS S3, Azure Blob, or GCS) if archiving to cold storage
psqlormysqlCLI for executing archival queriesaws s3,az storage, orgsutilCLI for cloud storage uploads- Understanding of data retention requirements and compliance policies (GDPR, HIPAA, SOX)
- Current table sizes:
SELECT pg_size_pretty(pg_total_relation_size('table_name'))to identify archival candidates
Instructions
Identify archival candidates by finding large tables with time-based data:
SELECT relname, n_live_tup, pg_size_pretty(pg_total_relation_size(relid)) FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT 10- Focus on tables where historical data is rarely queried: logs, audit trails, events, old orders, expired sessions
Define archival criteria for each table:
- Age-based: Records older than N days/months (
WHERE created_at < NOW() - INTERVAL '1 year') - Status-based: Records in terminal state (
WHERE status IN ('completed', 'cancelled', 'expired')) - Combined: Old AND terminal (
WHERE created_at < NOW() - INTERVAL '6 months' AND status = 'completed') - Calculate the expected volume:
SELECT COUNT(*), pg_size_pretty(pg_column_size(t.*)) FROM table_name t WHERE <criteria>
- Age-based: Records older than N days/months (
Handle referential integrity by archiving in dependency order:
- Archive child records first (order_items before orders)
- For tables with active foreign key references, verify no active records reference the candidates:
SELECT COUNT(*) FROM active_child WHERE parent_id IN (SELECT id FROM parent WHERE <archive_criteria>) - Option: cascade archive by archiving parent and all descendants together
Create archive destination tables matching the source schema plus metadata columns:
CREATE TABLE orders_archive (LIKE orders INCLUDING ALL)ALTER TABLE orders_archive ADD COLUMN archived_at TIMESTAMPTZ DEFAULT NOW()ALTER TABLE orders_archive ADD COLUMN archive_batch_id UUID- Remove foreign key constraints on archive tables (archived data is self-contained)
Implement the archival operation as an atomic batch:
- Generate a batch ID:
SELECT gen_random_uuid() AS batch_id - Insert into archive:
INSERT INTO orders_archive SELECT *, NOW(), batch_id FROM orders WHERE <criteria> - Verify row counts match:
SELECT COUNT(*) FROM orders_archive WHERE archive_batch_id = batch_id - Delete from source only after verification:
DELETE FROM orders WHERE id IN (SELECT id FROM orders_archive WHERE archive_batch_id = batch_id) - Wrap in a transaction for atomicity
- Generate a batch ID:
For cloud storage archival, export data to files before upload:
- PostgreSQL:
COPY (SELECT * FROM orders WHERE <criteria>) TO '/tmp/archive_orders_2023.csv' WITH CSV HEADER - Compress:
gzip /tmp/archive_orders_2023.csv - Upload:
aws s3 cp /tmp/archive_orders_2023.csv.gz s3://archive-bucket/orders/2023/ --sse aws:kms - Store manifest: record file path, row count, checksum, and date range in an archive_manifest table
- PostgreSQL:
Process archival in batches to avoid long-running transactions and excessive lock time:
- Archive 10,000-50,000 rows per batch
- Add a short delay between batches (100-500ms) to allow other transactions to proceed
- Log progress after each batch for monitoring and restart capability
Run
VACUUM ANALYZEon source tables after archival to reclaim disk space and update statistics. For large archival operations (>30% of table), considerVACUUM FULLduring a maintenance window (requires exclusive lock).Implement data retrieval procedures for archived data:
- For archive tables: direct SQL queries with
UNION ALLbetween active and archive tables - For cloud storage: import script that restores specific date ranges from S3/GCS to temporary tables
- Document retrieval procedures for support and compliance teams
- For archive tables: direct SQL queries with
Schedule recurring archival with a cron job or database scheduler. Run weekly or monthly. Include monitoring that alerts on: archival job failure, unexpected archive volume (too many or too few records), and source table size not decreasing after archival.
Output
- Archive table DDL with matching schema plus metadata columns
- Archival scripts (SQL and shell) for batch extraction, verification, and deletion
- Cloud storage upload scripts with compression and encryption
- Archive manifest table tracking all archival batches with metadata
- Retrieval scripts for restoring archived data when needed
- Cron job configuration for scheduled recurring archival
Error Handling
| Error | Cause
Установить archiving-databases в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditGrepGlobBash(psql:*)Bash(mysql:*)Bash(aws:s3:*)Bash(az:storage:*)Вложенные файлы
FAQ
Что делает скилл archiving-databases?
Process use when you need to archive historical database records to reduce primary database size. This skill automates moving old data to archive tables or cold storage (S3, Azure Blob, GCS). Trigger with phrases like "archive old database records", "implement data retention policy", "move historical data to cold storage", or "reduce database size with archival".
Как установить скилл archiving-databases?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл archiving-databases запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic