db-migration
Use when setting up Alembic migrations or making database schema changes. Triggers for: initializing Alembic, generating migrations, applying upgrades, rolling back changes, or creating data migrations. NOT for: raw SQL execution outside migration context or non-database schema updates.
What this skill does
# Database Migration Skill
Expert Alembic migration management for SQLModel/FastAPI projects with safe schema evolution and rollback capabilities.
## Quick Reference
| Command | Purpose |
|---------|---------|
| `alembic init alembic` | Initialize Alembic in project |
| `alembic revision --autogenerate -m "message"` | Generate migration from model changes |
| `alembic revision -m "message"` | Create empty migration manually |
| `alembic upgrade head` | Apply all pending migrations |
| `alembic upgrade +1` | Apply one migration at a time |
| `alembic downgrade -1` | Rollback last migration |
| `alembic downgrade base` | Rollback all migrations |
| `alembic current` | Show current revision |
| `alembic history` | Show migration history |
## Initial Setup
### 1. Initialize Alembic
```bash
alembic init alembic
```
### 2. Configure alembic.ini
```ini
# alembic.ini
sqlalchemy.url = driver://user:pass@localhost/dbname
file_template = %%(year)s_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d_%%(rev)s_%%(slug)s
timezone = UTC
```
### 3. Configure env.py for SQLModel
```python
# alembic/env.py
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from alembic.runtime.migration import MigrationContext
from sqlmodel import SQLModel, create_engine
from myapp.models import * # Import all SQLModel classes
config = context.config
config.set_main_option("sqlalchemy.url", "postgresql://user:pass@localhost/dbname")
target_metadata = SQLModel.metadata
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode."""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
connectable = create_engine(
config.get_main_option("sqlalchemy.url"),
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
```
## Generating Migrations
### Auto-Generate from Model Changes
```bash
# Generate migration automatically based on model diffs
alembic revision --autogenerate -m "add_fees_table"
# With specific revision range
alembic revision --autogenerate -m "add_user_email" --rev-id=abc123
```
### Manual Migration
```bash
# Create empty migration for manual changes
alembic revision -m "add_status_column"
```
### Example: Adding a New Table
```python
# alembic/versions/2024_01_15_1200_add_fees_table.py
"""add_fees_table
Revision ID: abc123
Revises: def456
Create Date: 2024-01-15 12:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
from sqlmodel import SQLModel
# revision identifiers
revision = 'abc123'
down_revision = 'def456'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'fees',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('student_id', sa.Integer(), nullable=False),
sa.Column('amount', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('status', sa.String(length=20), nullable=False, default='pending'),
sa.Column('due_date', sa.DateTime(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['student_id'], ['students.id']),
)
op.create_index('ix_fees_student_id', 'fees', ['student_id'])
op.create_index('ix_fees_status', 'fees', ['status'])
def downgrade() -> None:
op.drop_index('ix_fees_status', table_name='fees')
op.drop_index('ix_fees_student_id', table_name='fees')
op.drop_table('fees')
```
### Example: Adding a Column
```python
# alembic/versions/2024_01_16_0900_add_fees_description.py
"""add_fees_description
Revision ID: ghi789
Revises: abc123
Create Date: 2024-01-16 09:00:00.000000
"""
from alembic import op
def upgrade() -> None:
op.add_column('fees', sa.Column('description', sa.Text(), nullable=True))
def downgrade() -> None:
op.drop_column('fees', 'description')
```
## Applying Migrations
### Standard Upgrade
```bash
# Upgrade to latest revision
alembic upgrade head
# Upgrade one step at a time
alembic upgrade +1
# Upgrade to specific revision
alembic upgrade abc123
```
### Dry Run (Check What Would Happen)
```bash
# Show pending migrations without applying
alembic show heads
alembic history --verbose
```
## Rollback (Downgrade)
```bash
# Rollback one migration
alembic downgrade -1
# Rollback to specific revision
alembic downgrade abc123
# Rollback all migrations (empty database)
alembic downgrade base
```
### Safe Downgrade Pattern
```python
def downgrade() -> None:
# Always drop indexes before table
op.drop_index('ix_fees_status', table_name='fees')
op.drop_index('ix_fees_student_id', table_name='fees')
# Drop foreign keys before table
op.drop_constraint('fees_student_id_fkey', 'fees', type_='foreignkey')
op.drop_table('fees')
```
## Data Migrations
### Example: Data Migration with Batch Update
```python
# alembic/versions/2024_01_17_1400_update_fees_status.py
"""update_fees_status_values
Revision ID: jkl012
Revises: ghi789
Create Date: 2024-01-17 14:00:00.000000
"""
from alembic import op
from sqlalchemy import text
def upgrade() -> None:
# Update existing records
op.execute(
text("UPDATE fees SET status = 'pending' WHERE status = 'unpaid'")
)
def downgrade() -> None:
# Revert status values
op.execute(
text("UPDATE fees SET status = 'unpaid' WHERE status = 'pending'")
)
```
### Example: Enum Migration
```python
def upgrade() -> None:
# Add new enum type
op.execute("CREATE TYPE fee_status_new AS ENUM ('pending', 'paid', 'overdue', 'waived')")
# Copy data to new type
op.execute("ALTER TABLE fees ALTER COLUMN status TYPE fee_status_new USING status::text::fee_status_new")
# Drop old type
op.execute("DROP TYPE fee_status_old")
def downgrade() -> None:
# Reverse the process
op.execute("ALTER TABLE fees ALTER COLUMN status TYPE VARCHAR(20)")
op.execute("DROP TYPE fee_status_new")
```
## Quality Checklist
- [ ] **Data migrations**: Handle existing data when modifying columns/tables
- [ ] **Test migrations**: Run `alembic upgrade` then `alembic downgrade` in test
- [ ] **Idempotent operations**: up() and down() can run multiple times safely
- [ ] **No data loss**: Use `DROP TABLE IF EXISTS`, `DROP COLUMN IF EXISTS`
- [ ] **Indexes created**: Include index creation in upgrade, drop in downgrade
- [ ] **Foreign keys**: Handle constraint ordering (create before, drop after)
- [ ] **Backwards compatible**: Don't break existing application during migration
## Integration with Other Skills
| Skill | Integration Point |
|-------|-------------------|
| `@sqlmodel-crud` | Model changes trigger migrations |
| `@fastapi-app` | Migrations run at startup or via CLI |
| `@jwt-auth` | May need to handle auth during migrations |
## Migration Best Practices
### 1. Always Generate Before Manual Edit
```bash
alembic revision --autogenerate -m "describe_change"
# Then review and edit the generated file
```
### 2. Review Generated Migrations
```python
# Check that:
# - Column types match SQLModel definitions
# - Foreign key constraints are correct
# - Indexes are appropriate
# - Default values are set
```
### 3. Test Migration Cycle
```bash
# In test environment
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.