migrate-postgres-tables-to-hypertables
Use this skill to migrate identified PostgreSQL tables to Timescale/TimescaleDB hypertables with optimal configuration and validation. **Trigger when user asks to:** - Migrate or convert PostgreSQL tables to hypertables - Execute hypertable migration with minimal downtime - Plan blue-green migration for large tables - Validate hypertable migration success - Configure compression after migration **Prerequisites:** Tables already identified as candidates (use find-hypertable-candidates first if needed) **Keywords:** migrate to hypertable, convert table, Timescale, TimescaleDB, blue-green migration, in-place conversion, create_hypertable, migration validation, compression setup Step-by-step migration planning including: partition column selection, chunk interval calculation, PK/constraint handling, migration execution (in-place vs blue-green), and performance validation queries.
What this skill does
# PostgreSQL to TimescaleDB Hypertable Migration
Migrate identified PostgreSQL tables to TimescaleDB hypertables with optimal configuration, migration planning and validation.
**Prerequisites**: Tables already identified as hypertable candidates (use companion "find-hypertable-candidates" skill if needed).
## Step 1: Optimal Configuration
### Partition Column Selection
```sql
-- Find potential partition columns
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'your_table_name'
AND data_type IN ('timestamp', 'timestamptz', 'bigint', 'integer', 'date')
ORDER BY ordinal_position;
```
**Requirements:** Time-based (TIMESTAMP/TIMESTAMPTZ/DATE) or sequential integer (INT/BIGINT)
Should represent when the event actually occurred or sequential ordering.
**Common choices:**
- `timestamp`, `created_at`, `event_time` - when event occurred
- `id`, `sequence_number` - auto-increment (for sequential data without timestamps)
- `ingested_at` - less ideal, only if primary query dimension
- `updated_at` - AVOID (records updated out of order, breaks chunk distribution) unless primary query dimension
#### Special Case: table with BOTH ID AND Timestamp
When table has sequential ID (PK) AND timestamp that correlate:
```sql
-- Partition by ID, enable minmax sparse indexes on timestamp
SELECT create_hypertable('orders', 'id', chunk_time_interval => 1000000);
ALTER TABLE orders SET (
timescaledb.sparse_index = 'minmax(created_at),...'
);
```
Sparse indexes on time column enable skipping compressed blocks outside queried time ranges.
Use when: ID correlates with time (newer records have higher IDs), need ID-based lookups, time queries also common
### Chunk Interval Selection
```sql
-- Ensure statistics are current
ANALYZE your_table_name;
-- Estimate index size per time unit
WITH time_range AS (
SELECT
MIN(timestamp_column) as min_time,
MAX(timestamp_column) as max_time,
EXTRACT(EPOCH FROM (MAX(timestamp_column) - MIN(timestamp_column)))/3600 as total_hours
FROM your_table_name
),
total_index_size AS (
SELECT SUM(pg_relation_size(indexname::regclass)) as total_index_bytes
FROM pg_stat_user_indexes
WHERE schemaname||'.'||tablename = 'your_schema.your_table_name'
)
SELECT
pg_size_pretty(tis.total_index_bytes / tr.total_hours) as index_size_per_hour
FROM time_range tr, total_index_size tis;
```
**Target:** Indexes of recent chunks < 25% of RAM
**Default:** IMPORTANT: Keep default of 7 days if unsure
**Range:** 1 hour minimum, 30 days maximum
**Example:** 32GB RAM → target 8GB for recent indexes. If index_size_per_hour = 200MB:
- 1 hour chunks: 200MB chunk index size × 40 recent = 8GB ✓
- 6 hour chunks: 1.2GB chunk index size × 7 recent = 8.4GB ✓
- 1 day chunks: 4.8GB chunk index size × 2 recent = 9.6GB ⚠️
Choose largest interval keeping 2+ recent chunk indexes under target.
### Primary Key/ Unique Constraints Compatibility
```sql
-- Check existing primary key/ unique constraints
SELECT conname, pg_get_constraintdef(oid) as definition
FROM pg_constraint
WHERE conrelid = 'your_table_name'::regclass AND contype = 'p' OR contype = 'u';
```
**Rules:** PK/UNIQUE must include partition column
**Actions:**
1. **No PK/UNIQUE:** No changes needed
2. **PK/UNIQUE includes partition column:** No changes needed
3. **PK/UNIQUE excludes partition column:** ⚠️ **ASK USER PERMISSION** to modify PK/UNIQUE
**Example: user prompt if needed:**
> "Primary key (id) doesn't include partition column (timestamp). Must modify to PRIMARY KEY (id, timestamp) to convert to hypertable. This may break application code. Is this acceptable?"
> "Unique constraint (id) doesn't include partition column (timestamp). Must modify to UNIQUE (id, timestamp) to convert to hypertable. This may break application code. Is this acceptable?"
If the user accepts, modify the constraint:
```sql
BEGIN;
ALTER TABLE your_table_name DROP CONSTRAINT existing_pk_name;
ALTER TABLE your_table_name ADD PRIMARY KEY (existing_columns, partition_column);
COMMIT;
```
If the user does not accept, you should NOT migrate the table.
IMPORTANT: DO NOT modify the primary key/unique constraint without user permission.
### Compression Configuration
For detailed segment_by and order_by selection, see "setup-timescaledb-hypertables" skill. Quick reference:
**segment_by:** Most common WHERE filter with >100 rows per value per chunk
- IoT: `device_id`
- Finance: `symbol`
- Analytics: `user_id` or `session_id`
```sql
-- Analyze cardinality for segment_by selection
SELECT column_name, COUNT(DISTINCT column_name) as unique_values,
ROUND(COUNT(*)::float / COUNT(DISTINCT column_name), 2) as avg_rows_per_value
FROM your_table_name GROUP BY column_name;
```
**order_by:** Usually `timestamp DESC`. The (segment_by, order_by) combination should form a natural time-series progression.
- If column has <100 rows/chunk (too low for segment_by), prepend to order_by: `order_by='low_density_col, timestamp DESC'`
**sparse indexes:** add minmax on the columns that are used in the WHERE clauses but are not in the segment_by or order_by. Use minmax for columns used in range queries.
```sql
ALTER TABLE your_table_name SET (
timescaledb.enable_columnstore,
timescaledb.segmentby = 'entity_id',
timescaledb.orderby = 'timestamp DESC'
timescaledb.sparse_index = 'minmax(value_1),...'
);
-- Compress after data unlikely to change (adjust `after` parameter based on update patterns)
CALL add_columnstore_policy('your_table_name', after => INTERVAL '7 days');
```
## Step 2: Migration Planning
### Pre-Migration Checklist
- [ ] Partition column selected
- [ ] Chunk interval calculated (or using default)
- [ ] PK includes partition column OR user approved modification
- [ ] No Hypertable→Hypertable foreign keys
- [ ] Unique constraints include partition column
- [ ] Created compression configuration (segment_by, order_by, sparse indexes, compression policy)
- [ ] Maintenance window scheduled / backup created.
### Migration Options
#### Option 1: In-Place (Tables < 1GB)
```sql
-- Enable extension
CREATE EXTENSION IF NOT EXISTS timescaledb;
-- Convert to hypertable (locks table)
SELECT create_hypertable(
'your_table_name',
'timestamp_column',
chunk_time_interval => INTERVAL '7 days',
if_not_exists => TRUE
);
-- Configure compression
ALTER TABLE your_table_name SET (
timescaledb.enable_columnstore,
timescaledb.segmentby = 'entity_id',
timescaledb.orderby = 'timestamp DESC',
timescaledb.sparse_index = 'minmax(value_1),...'
);
-- Adjust `after` parameter based on update patterns
CALL add_columnstore_policy('your_table_name', after => INTERVAL '7 days');
```
#### Option 2: Blue-Green (Tables > 1GB)
```sql
-- 1. Create new hypertable
CREATE TABLE your_table_name_new (LIKE your_table_name INCLUDING ALL);
-- 2. Convert to hypertable
SELECT create_hypertable('your_table_name_new', 'timestamp_column');
-- 3. Configure compression
ALTER TABLE your_table_name_new SET (
timescaledb.enable_columnstore,
timescaledb.segmentby = 'entity_id',
timescaledb.orderby = 'timestamp DESC'
);
-- 4. Migrate data in batches
INSERT INTO your_table_name_new
SELECT * FROM your_table_name
WHERE timestamp_column >= '2024-01-01' AND timestamp_column < '2024-02-01';
-- Repeat for each time range
-- 4. Enter maintenance window and do the following:
-- 5. Pause modification of the old table.
-- 6. Copy over the most recent data from the old table to the new table.
-- 7. Swap tables
BEGIN;
ALTER TABLE your_table_name RENAME TO your_table_name_old;
ALTER TABLE your_table_name_new RENAME TO your_table_name;
COMMIT;
-- 8. Exit maintenance window.
-- 9. (sometime much later) Drop old table after validation
-- DROP TABLE your_table_name_old;
```
### Common Issues
#### Foreign Keys
```sql
-- Check foreign keys
SELECT conname, confrelid::regclass as referenced_table
FROM pg_constraint
WHERE (conrelid = 'youRelated in Ads & Marketing
ads
IncludedMulti-platform paid advertising audit and optimization skill. Analyzes Google, Meta, YouTube, LinkedIn, TikTok, Microsoft, and Apple Ads. 250+ checks with scoring, parallel agents, industry templates, and AI creative generation.
banana
IncludedAI image generation Creative Director powered by Google Gemini Nano Banana models. Use this skill for ANY request involving image creation, editing, visual asset production, or creative direction. Triggers on: generate an image, create a photo, edit this picture, design a logo, make a banner, visual for my anything, and all /banana commands. Handles text-to-image, image editing, multi-turn creative sessions, batch workflows, and brand presets.
rpg-migration-analyzer
IncludedAnalyzes legacy RPG (Report Program Generator) programs from AS/400 and IBM i systems for migration to modern Java applications. Extracts business logic from RPG III/IV/ILE source code, identifies data structures (D-specs), file operations (F-specs), program dependencies (CALLB/CALLP), and converts RPG constructs to Java equivalents. Generates migration reports, complexity estimates, and Java implementation strategies with POJO classes, JPA entities, and service methods. Use when modernizing AS/400 or IBM i legacy systems, analyzing RPG source files (.rpg, .rpgle, .RPGLE), converting RPG to Java, mapping data specifications to Java classes, planning legacy system migration, or when user mentions RPG analysis, Report Program Generator, RPG III/IV/ILE, AS/400 modernization, IBM i migration, packed decimal conversion, or mainframe application rewrite.
brand-library-architect
IncludedBuild a complete brand library for a product — visual asset render pipeline, brand documentation set (BRAND, COPY, MANIFESTO, BIOS, FAQ, GLOSSARY, TONE, PRICING), open-source convention files (README, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT), and a self-contained press kit. This skill should be used when the user asks to "build a brand library / brand kit / press kit / brand assets" for a product, "set up a brand library workflow," "create a positioning manifesto plus visual identity," or any combination of brand documentation + visual asset pipeline. Apply phase-by-phase or run end-to-end. Templates are product-agnostic and use {{TOKEN}} placeholders the skill prompts the user to fill.
writing-tech-post
IncludedAuthors engineering blog posts end-to-end: launch deep-dives, incident postmortems, architecture migrations, performance case studies, tutorials, AI/agent system writeups, security disclosures, and research-to-product translations. Picks the correct archetype, plans the abstraction ladder, enforces an evidence cadence (diagrams, benchmarks, profiles, traces, code, ablations), tunes voice against publisher house styles (Datadog, Vercel, GitHub, AWS, Meta, Cloudflare, Jane Street), and runs a pre-publish gate for narrative momentum and disclosure ethics. Use when drafting a new engineering post, restructuring a draft that feels flat, deciding which evidence form belongs where, validating that depth and product context are balanced, or preparing a postmortem, migration, or performance narrative for external publication. Do not use for API reference documentation, README authoring, marketing copy, release notes, generic SEO content, ghost-written executive thought leadership, or non-engineering long-form essays.
blog-google
IncludedGoogle API integration for blog performance: PageSpeed Insights, CrUX Core Web Vitals with 25-week history, Search Console performance, URL Inspection, Indexing API, GA4 organic traffic, NLP entity analysis for E-E-A-T, YouTube video search for embedding, and Google Ads Keyword Planner. Progressive feature availability based on credential tier (API key, OAuth/service account, GA4, Ads). Shares config with claude-seo at ~/.config/claude-seo/google-api.json. Use when user says "google data", "page speed", "core web vitals", "search console", "indexation", "GA4", "keyword research", "nlp entities", "blog performance", "youtube search", "google api setup".