[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73S2YYMZDGSZ4YX0V7WKCE6":3,"skill-same:01M73S2YYMZDGSZ4YX0V7WKCE6":58},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73S2YYMZDGSZ4YX0V7WKCE6","database",null,"Universal database operations skill for modern applications. Expert in SQLModel\u002FSQLAlchemy patterns, async database operations, connection pooling, migrations, performance optimization, and multi-database support (PostgreSQL, MySQL, SQLite). Provides production-ready patterns for any database-driven application.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fdatabase\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: database\ndescription: Universal database operations skill for modern applications. Expert in SQLModel\u002FSQLAlchemy patterns, async database operations, connection pooling, migrations, performance optimization, and multi-database support (PostgreSQL, MySQL, SQLite). Provides production-ready patterns for any database-driven application.\nlicense: MIT\n---\n\n# Database Operations & Management\n\nThis skill provides comprehensive database patterns and best practices for 2025, focusing on async operations, performance optimization, and production-ready configurations that work across different database systems.\n\n## When to Use This Skill\n\nUse this skill when you need to:\n- Design database schemas with SQLModel\u002FSQLAlchemy\n- Implement async database operations\n- Optimize database performance\n- Set up connection pooling\n- Create and manage database migrations\n- Handle complex relationships and queries\n- Set up production database configurations\n- Monitor and troubleshoot database issues\n\n## Core Database Patterns\n\n### 1. Async Connection Management\n\n```python\n# Database connection setup with connection pooling\nimport asyncio\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker\nfrom sqlalchemy.pool import NullPool\nfrom contextlib import asynccontextmanager\nimport os\n\n# Environment-based configuration\nDATABASE_CONFIG = {\n    \"development\": {\n        \"url\": \"sqlite+aiosqlite:\u002F\u002F\u002F.\u002Fapp.db\",\n        \"poolclass\": NullPool,\n        \"echo\": True\n    },\n    \"production\": {\n        \"url\": os.getenv(\"DATABASE_URL\", \"postgresql+asyncpg:\u002F\u002Fuser:pass@localhost\u002Fdb\"),\n        \"pool_size\": 30,\n        \"max_overflow\": 40,\n        \"pool_pre_ping\": True,\n        \"pool_recycle\": 3600,\n        \"echo\": False\n    }\n}\n\nclass DatabaseManager:\n    \"\"\"Universal database manager for async operations\"\"\"\n\n    def __init__(self, env: str = \"development\"):\n        config = DATABASE_CONFIG[env]\n        self.engine = create_async_engine(**config)\n        self.async_session = async_sessionmaker(\n            self.engine,\n            class_=AsyncSession,\n            expire_on_commit=False\n        )\n\n    @asynccontextmanager\n    async def get_session(self):\n        \"\"\"Get async database session with proper cleanup\"\"\"\n        async with self.async_session() as session:\n            try:\n                yield session\n                await session.commit()\n            except Exception:\n                await session.rollback()\n                raise\n            finally:\n                await session.close()\n\n    async def create_tables(self, metadata):\n        \"\"\"Create all tables from metadata\"\"\"\n        async with self.engine.begin() as conn:\n            await conn.run_sync(metadata.create_all)\n\n    async def close(self):\n        \"\"\"Close database connections\"\"\"\n        await self.engine.dispose()\n\n# Singleton instance\ndb_manager = DatabaseManager(os.getenv(\"ENV\", \"development\"))\n```\n\n### 2. Base Model with Best Practices\n\n```python\n# models\u002Fbase.py\nfrom sqlmodel import SQLModel, Field, DateTime, func\nfrom typing import Optional\nfrom datetime import datetime\nfrom sqlalchemy import Column, DateTime as SQLDateTime, Index\n\nclass TimestampMixin(SQLModel):\n    \"\"\"Mixin for timestamp fields\"\"\"\n\n    created_at: datetime = Field(\n        default_factory=datetime.utcnow,\n        sa_column=Column(\n            SQLDateTime(timezone=True),\n            server_default=func.now(),\n            nullable=False\n        )\n    )\n\n    updated_at: Optional[datetime] = Field(\n        default=None,\n        sa_column=Column(\n            SQLDateTime(timezone=True),\n            onupdate=func.now(),\n            nullable=True\n        )\n    )\n\nclass SoftDeleteMixin(SQLModel):\n    \"\"\"Mixin for soft delete functionality\"\"\"\n\n    deleted_at: Optional[datetime] = None\n    is_deleted: bool = Field(default=False)\n\nclass BaseModel(SQLModel, TimestampMixin):\n    \"\"\"Base model with common fields and patterns\"\"\"\n\n    id: Optional[int] = Field(default=None, primary_key=True)\n\n    class Config:\n        # Enable Pydantic's strict mode\n        strict = True\n        # Validate defaults\n        validate_assignment = True\n        # Use enum values\n        use_enum_values = True\n\n# Indexes for common queries\nIndex(\"idx_base_created_at\", BaseModel.created_at)\n```\n\n### 3. Advanced Model Patterns\n\n```python\n# models\u002Fexamples.py\nfrom enum import Enum\nfrom typing import Optional, List\nfrom sqlalchemy import Column, String, Text, Boolean, Integer, Index, ForeignKey, UniqueConstraint\nfrom sqlalchemy.orm import relationship\nfrom sqlmodel import SQLModel, Field, Session, select, update, delete\n\n# Enums for type safety\nclass Status(str, Enum):\n    ACTIVE = \"active\"\n    INACTIVE = \"inactive\"\n    PENDING = \"pending\"\n\nclass Priority(str, Enum):\n    LOW = \"low\"\n    MEDIUM = \"medium\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\nclass User(BaseModel, table=True):\n    \"\"\"User model with optimized fields and indexes\"\"\"\n\n    __tablename__ = \"users\"\n\n    email: str = Field(\n        sa_column=Column(String(255), unique=True, nullable=False, index=True)\n    )\n    username: str = Field(\n        sa_column=Column(String(100), unique=True, nullable=False, index=True)\n    )\n    full_name: Optional[str] = Field(default=None, max_length=200)\n    is_active: bool = Field(default=True, sa_column=Column(Boolean, default=True))\n\n    # Optimized text fields\n    bio: Optional[str] = Field(\n        default=None,\n        sa_column=Column(Text)  # Use Text for longer content\n    )\n\n    # Relationships\n    tasks: List[\"Task\"] = Relationship(back_populates=\"owner\")\n\n    # Optimized queries\n    __table_args__ = (\n        Index(\"idx_user_active_email\", \"is_active\", \"email\"),\n        Index(\"idx_user_created_at\", \"created_at\"),\n    )\n\nclass Task(BaseModel, SoftDeleteMixin, table=True):\n    \"\"\"Task model with advanced patterns\"\"\"\n\n    __tablename__ = \"tasks\"\n\n    # Foreign key with index\n    owner_id: int = Field(\n        foreign_key=\"users.id\",\n        sa_column=Column(Integer, ForeignKey(\"users.id\"), nullable=False, index=True)\n    )\n\n    # Optimized fields\n    title: str = Field(\n        sa_column=Column(String(200), nullable=False)\n    )\n    description: Optional[str] = Field(\n        default=None,\n        sa_column=Column(Text)\n    )\n\n    # Enum fields\n    status: Status = Field(default=Status.PENDING)\n    priority: Priority = Field(default=Priority.MEDIUM)\n\n    # JSON field for flexible metadata\n    metadata: dict = Field(\n        default_factory=dict,\n        sa_column=Column(\"metadata\", JSON)\n    )\n\n    # Relationships\n    owner: User = Relationship(back_populates=\"tasks\")\n    tags: List[\"TaskTag\"] = Relationship(back_populates=\"task\")\n\n    # Optimized queries\n    __table_args__ = (\n        Index(\"idx_task_owner_status\", \"owner_id\", \"status\"),\n        Index(\"idx_task_priority_created\", \"priority\", \"created_at\"),\n        Index(\"idx_task_deleted\", \"is_deleted\"),\n    )\n\nclass Tag(BaseModel, table=True):\n    \"\"\"Tag model for many-to-many relationships\"\"\"\n\n    __tablename__ = \"tags\"\n\n    name: str = Field(\n        sa_column=Column(String(50), unique=True, nullable=False, index=True)\n    )\n    color: Optional[str] = Field(default=None, max_length=7)  # Hex color code\n\nclass TaskTag(BaseModel, table=True):\n    \"\"\"Many-to-many relationship table\"\"\"\n\n    __tablename__ = \"task_tags\"\n\n    task_id: int = Field(foreign_key=\"tasks.id\", primary_key=True)\n    tag_id: int = Field(foreign_key=\"tags.id\", primary_key=True)\n\n    task: Task = Relationship()\n    tag: Tag = Relationship()\n```\n\n### 4. Repository Pattern for Clean Code\n\n```python\n# repositories\u002Fbase.py\nfrom abc import ABC, abstractmethod\nfrom typing import TypeVar, Generic, List, Optional, Dict, Any\nfrom sqlmodel import SQLModel, Session, select, update, delete, func\n\nModelType = TypeVar(\"ModelType\", bound=SQLModel)\n\nclass BaseRepository(Generic[ModelType], ABC):\n    \"\"\"Base repository with common CRUD operations\"\"\"\n\n    def __init__(self, model: type[ModelType]):\n        self.model = model\n\n    async def create(self, db: Session, *, obj_in: Dict[str, Any]) -> ModelType:\n        \"\"\"Create a new record\"\"\"\n        db_obj = self.model(**obj_in)\n        db.add(db_obj)\n        db.commit()\n        db.refresh(db_obj)\n        return db_obj\n\n    async def get(self, db: Session, id: Any) -> Optional[ModelType]:\n        \"\"\"Get a record by ID\"\"\"\n        statement = select(self.model).where(self.model.id == id)\n        return db.exec(statement).first()\n\n    async def get_multi(\n        self,\n        db: Session,\n        *,\n        skip: int = 0,\n        limit: int = 100,\n        filters: Optional[Dict[str, Any]] = None\n    ) -> List[ModelType]:\n        \"\"\"Get multiple records with pagination\"\"\"\n        statement = select(self.model)\n\n        # Apply filters\n        if filters:\n            for key, value in filters.items():\n                if hasattr(self.model, key):\n                    statement = statement.where(getattr(self.model, key) == value)\n\n        statement = statement.offset(skip).limit(limit)\n        return db.exec(statement).all()\n\n    async def update(\n        self,\n        db: Session,\n        *,\n        db_obj: ModelType,\n        obj_in: Dict[str, Any]\n    ) -> ModelType:\n        \"\"\"Update a record\"\"\"\n        for field, value in obj_in.items():\n            if hasattr(db_obj, field):\n                setattr(db_obj, field, value)\n\n        db.add(db_obj)\n        db.commit()\n        db.refresh(db_obj)\n        return db_obj\n\n    async def remove(self, db: Session, *, id: int) -> ModelType:\n        \"\"\"Remove a record\"\"\"\n        obj = await self.get(db, id=id)\n        if obj:\n            db.delete(obj)\n            db.commit()\n        return obj\n\n    async def count(self, db: Session, filters: Optional[Dict[str, Any]] = None) -> int:\n        \"\"\"Count records with optional filters\"\"\"\n        statement = select(func.count(self.model.id))\n\n        if filters:\n            for key, value in filters.items():\n                if hasattr(self.model, key):\n                    statement = statement.where(getattr(self.model, key) == value)\n\n        return db.exec(statement).scalar()\n\n# repositories\u002Fuser.py\nclass UserRepository(BaseRepository[User]):\n    \"\"\"User repository with specific queries\"\"\"\n\n    async def get_by_email(self, db: Session, *, email: str) -> Optional[User]:\n        \"\"\"Get user by email\"\"\"\n        statement = select(User).where(User.email == email)\n        return db.exec(statement).first()\n\n    async def get_active_users(\n        self,\n        db: Session,\n        skip: int = 0,\n        limit: int = 100\n    ) -> List[User]:\n        \"\"\"Get active users\"\"\"\n        statement = select(User).where(User.is_active == True)\n        statement = statement.offset(skip).limit(limit)\n        return db.exec(statement).all()\n```\n\n### 5. Advanced Query Patterns\n\n```python\n# services\u002Fquery_builder.py\nfrom sqlalchemy import and_, or_, func, asc, desc, extract\nfrom typing import List, Optional, Dict, Any, Union\nfrom datetime import datetime, date\nfrom models.base import db_manager\n\nclass QueryBuilder:\n    \"\"\"Advanced query builder for complex database operations\"\"\"\n\n    def __init__(self, model):\n        self.model = model\n        self._filters = []\n        self._order_by = []\n        self._joins = []\n        self._group_by = []\n\n    def filter(self, *conditions) -> \"QueryBuilder\":\n        \"\"\"Add filter conditions\"\"\"\n        self._filters.extend(conditions)\n        return self\n\n    def where(self, condition) -> \"QueryBuilder\":\n        \"\"\"Add where condition\"\"\"\n        self._filters.append(condition)\n        return self\n\n    def order_by(self, *columns) -> \"QueryBuilder\":\n        \"\"\"Add order by clauses\"\"\"\n        self._order_by.extend(columns)\n        return self\n\n    def join(self, model, condition=None) -> \"QueryBuilder\":\n        \"\"\"Add join\"\"\"\n        self._joins.append((model, condition))\n        return self\n\n    def group_by(self, *columns) -> \"QueryBuilder\":\n        \"\"\"Add group by clauses\"\"\"\n        self._group_by.extend(columns)\n        return self\n\n    async def execute(self, db: Session):\n        \"\"\"Execute the built query\"\"\"\n        statement = select(self.model)\n\n        # Apply filters\n        if self._filters:\n            statement = statement.where(and_(*self._filters))\n\n        # Apply joins\n        for model, condition in self._joins:\n            if condition:\n                statement = statement.join(model, condition)\n            else:\n                statement = statement.join(model)\n\n        # Apply group by\n        if self._group_by:\n            statement = statement.group_by(*self._group_by)\n\n        # Apply order by\n        if self._order_by:\n            statement = statement.order_by(*self._order_by)\n\n        return db.exec(statement).all()\n\n# Usage examples\nasync def search_tasks_advanced(\n    owner_id: int,\n    keywords: Optional[str] = None,\n    status: Optional[Status] = None,\n    priority: Optional[Priority] = None,\n    date_range: Optional[tuple] = None\n) -> List[Task]:\n    \"\"\"Advanced task search with multiple filters\"\"\"\n\n    async with db_manager.get_session() as db:\n        query = QueryBuilder(Task)\n\n        # Base filters\n        query = query.filter(Task.owner_id == owner_id, Task.is_deleted == False)\n\n        # Text search\n        if keywords:\n            search_pattern = f\"%{keywords}%\"\n            query = query.where(\n                or_(\n                    Task.title.ilike(search_pattern),\n                    Task.description.ilike(search_pattern)\n                )\n            )\n\n        # Status filter\n        if status:\n            query = query.filter(Task.status == status)\n\n        # Priority filter\n        if priority:\n            query = query.filter(Task.priority == priority)\n\n        # Date range filter\n        if date_range:\n            start_date, end_date = date_range\n            query = query.filter(\n                and_(\n                    Task.created_at >= start_date,\n                    Task.created_at \u003C= end_date\n                )\n            )\n\n        # Order by priority and creation date\n        query = query.order_by(\n            desc(Task.priority),\n            desc(Task.created_at)\n        )\n\n        return await query.execute(db)\n```\n\n### 6. Database Migrations Best Practices\n\n```python\n# migrations\u002Fversions\u002F001_initial_tables.py\n\"\"\"Initial tables migration\n\nRevision ID: 001_initial\nRevises:\nCreate Date: 2025-01-01 00:00:00.000000\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers\nrevision = '001_initial'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\ndef upgrade():\n    \"\"\"Create initial tables with optimized schema\"\"\"\n\n    # Users table\n    op.create_table(\n        'users',\n        sa.Column('id', sa.Integer(), nullable=False),\n        sa.Column('email', sa.String(length=255), nullable=False),\n        sa.Column('username', sa.String(length=100), nullable=False),\n        sa.Column('full_name', sa.String(length=200), nullable=True),\n        sa.Column('is_active', sa.Boolean(), nullable=True, default=True),\n        sa.Column('bio', sa.Text(), nullable=True),\n        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),\n        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n        sa.PrimaryKeyConstraint('id'),\n        sa.UniqueConstraint('email'),\n        sa.UniqueConstraint('username')\n    )\n\n    # Create indexes\n    op.create_index('idx_user_email', 'users', ['email'])\n    op.create_index('idx_user_username', 'users', ['username'])\n    op.create_index('idx_user_active_email', 'users', ['is_active', 'email'])\n\n    # Tasks table\n    op.create_table(\n        'tasks',\n        sa.Column('id', sa.Integer(), nullable=False),\n        sa.Column('owner_id', sa.Integer(), nullable=False),\n        sa.Column('title', sa.String(length=200), nullable=False),\n        sa.Column('description', sa.Text(), nullable=True),\n        sa.Column('status', sa.Enum('ACTIVE', 'INACTIVE', 'PENDING', name='status'), nullable=True),\n        sa.Column('priority', sa.Enum('LOW', 'MEDIUM', 'HIGH', 'CRITICAL', name='priority'), nullable=True),\n        sa.Column('metadata', sa.JSON(), nullable=True),\n        sa.Column('is_deleted', sa.Boolean(), nullable=True, default=False),\n        sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True),\n        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),\n        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n        sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),\n        sa.PrimaryKeyConstraint('id')\n    )\n\n    # Create indexes\n    op.create_index('idx_task_owner', 'tasks', ['owner_id'])\n    op.create_index('idx_task_owner_status', 'tasks', ['owner_id', 'status'])\n    op.create_index('idx_task_priority_created', 'tasks', ['priority', 'created_at'])\n    op.create_index('idx_task_deleted', 'tasks', ['is_deleted'])\n\n    # Tags table\n    op.create_table(\n        'tags',\n        sa.Column('id', sa.Integer(), nullable=False),\n        sa.Column('name', sa.String(length=50), nullable=False),\n        sa.Column('color', sa.String(length=7), nullable=True),\n        sa.PrimaryKeyConstraint('id'),\n        sa.UniqueConstraint('name')\n    )\n\n    op.create_index('idx_tag_name', 'tags', ['name'])\n\n    # Task-Tag relationship table\n    op.create_table(\n        'task_tags',\n        sa.Column('task_id', sa.Integer(), nullable=False),\n        sa.Column('tag_id', sa.Integer(), nullable=False),\n        sa.ForeignKeyConstraint(['task_id'], ['tasks.id'], ),\n        sa.ForeignKeyConstraint(['tag_id'], ['tags.id'], ),\n        sa.PrimaryKeyConstraint('task_id', 'tag_id')\n    )\n\ndef downgrade():\n    \"\"\"Drop all tables\"\"\"\n    op.drop_table('task_tags')\n    op.drop_table('tags')\n    op.drop_table('tasks')\n    op.drop_table('users')\n```\n\n### 7. Performance Optimization\n\n```python\n# utils\u002Fperformance.py\nimport time\nfrom functools import wraps\nfrom typing import Callable, Any\nfrom sqlmodel import Session\n\ndef measure_query_time(func: Callable) -> Callable:\n    \"\"\"Decorator to measure query execution time\"\"\"\n    @wraps(func)\n    async def wrapper(*args, **kwargs):\n        start_time = time.time()\n        result = await func(*args, **kwargs)\n        execution_time = time.time() - start_time\n\n        # Log slow queries\n        if execution_time > 1.0:  # 1 second threshold\n            print(f\"Slow query detected: {func.__name__} took {execution_time:.2f}s\")\n\n        return result\n    return wrapper\n\nclass DatabaseOptimizer:\n    \"\"\"Database performance optimization utilities\"\"\"\n\n    @staticmethod\n    async def analyze_slow_queries(db: Session, threshold: float = 1.0) -> List[Dict]:\n        \"\"\"Analyze slow queries (PostgreSQL specific)\"\"\"\n        if db.bind.dialect.name != 'postgresql':\n            return []\n\n        query = \"\"\"\n        SELECT query, calls, total_time, mean_time, rows\n        FROM pg_stat_statements\n        WHERE mean_time > %s\n        ORDER BY total_time DESC\n        LIMIT 10\n        \"\"\"\n\n        result = db.execute(query, threshold)\n        return [dict(row) for row in result]\n\n    @staticmethod\n    async def get_table_statistics(db: Session) -> Dict[str, Any]:\n        \"\"\"Get table statistics\"\"\"\n        stats = {}\n\n        if db.bind.dialect.name == 'postgresql':\n            # PostgreSQL statistics\n            tables_query = \"\"\"\n            SELECT schemaname, tablename, n_tup_ins, n_tup_upd, n_tup_del, n_live_tup, n_dead_tup\n            FROM pg_stat_user_tables\n            \"\"\"\n\n            for row in db.execute(tables_query):\n                table_name = row.tablename\n                stats[table_name] = {\n                    'inserts': row.n_tup_ins,\n                    'updates': row.n_tup_upd,\n                    'deletes': row.n_tup_del,\n                    'live_rows': row.n_live_tup,\n                    'dead_rows': row.n_dead_tup\n                }\n\n        return stats\n```\n\n### 8. Testing Database Operations\n\n```python\n# tests\u002Fconftest.py\nimport pytest\nimport asyncio\nfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession\nfrom httpx import AsyncClient\nfrom sqlmodel import SQLModel\nfrom models.base import BaseModel\nfrom repositories.base import BaseRepository\n\n@pytest.fixture(scope=\"session\")\ndef event_loop():\n    \"\"\"Create an instance of the default event loop\"\"\"\n    loop = asyncio.get_event_loop_policy().new_event_loop()\n    yield loop\n    loop.close()\n\n@pytest.fixture(scope=\"function\")\nasync def test_db_session():\n    \"\"\"Create test database session\"\"\"\n    # In-memory SQLite for testing\n    engine = create_async_engine(\n        \"sqlite+aiosqlite:\u002F\u002F\u002F:memory:\",\n        echo=False\n    )\n\n    # Create tables\n    async with engine.begin() as conn:\n        await conn.run_sync(BaseModel.metadata.create_all)\n\n    # Create session\n    async_session = async_sessionmaker(\n        engine, class_=AsyncSession, expire_on_commit=False\n    )\n\n    async with async_session() as session:\n        yield session\n\n@pytest.fixture\ndef user_repository():\n    \"\"\"Create user repository instance\"\"\"\n    return UserRepository(User)\n\n# tests\u002Ftest_repositories.py\n@pytest.mark.asyncio\nasync def test_create_user(test_db_session: AsyncSession, user_repository):\n    \"\"\"Test user creation\"\"\"\n    user_data = {\n        \"email\": \"test@example.com\",\n        \"username\": \"testuser\",\n        \"full_name\": \"Test User\"\n    }\n\n    user = await user_repository.create(test_db_session, obj_in=user_data)\n\n    assert user.email == user_data[\"email\"]\n    assert user.username == user_data[\"username\"]\n    assert user.is_active == True\n```\n\n### 9. Production Configuration Checklist\n\n```yaml\n# config\u002Fproduction_checklist.yaml\ndatabase:\n  production_ready:\n    connection_pooling: true\n    ssl_enabled: true\n    max_connections: 100\n    min_connections: 10\n    connection_timeout: 30\n    idle_timeout: 300\n\n  monitoring:\n    slow_query_log: true\n    query_threshold: 1.0\n    connection_pool_metrics: true\n\n  backup:\n    automated_backups: true\n    backup_retention: 30_days\n    point_in_time_recovery: true\n\n  security:\n    encryption_at_rest: true\n    encryption_in_transit: true\n    least_privilege_access: true\n    regular_rotation: true\n```\n\nThis comprehensive database skill provides production-ready patterns optimized for 2025, including async operations, performance optimization, proper indexing, and comprehensive testing strategies that work across different database systems.","# Database Operations & Management\n\nThis skill provides comprehensive database patterns and best practices for 2025, focusing on async operations, performance optimization, and production-ready configurations that work across different database systems.\n\n## When to Use This Skill\n\nUse this skill when you need to:\n- Design database schemas with SQLModel\u002FSQLAlchemy\n- Implement async database operations\n- Optimize database performance\n- Set up connection pooling\n- Create and manage database migrations\n- Handle complex relationships and queries\n- Set up production database configurations\n- Monitor and troubleshoot database issues\n\n## Core Database Patterns\n\n### 1. Async Connection Management\n\n```python\n# Database connection setup with connection pooling\nimport asyncio\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker\nfrom sqlalchemy.pool import NullPool\nfrom contextlib import asynccontextmanager\nimport os\n\n# Environment-based configuration\nDATABASE_CONFIG = {\n    \"development\": {\n        \"url\": \"sqlite+aiosqlite:\u002F\u002F\u002F.\u002Fapp.db\",\n        \"poolclass\": NullPool,\n        \"echo\": True\n    },\n    \"production\": {\n        \"url\": os.getenv(\"DATABASE_URL\", \"postgresql+asyncpg:\u002F\u002Fuser:pass@localhost\u002Fdb\"),\n        \"pool_size\": 30,\n        \"max_overflow\": 40,\n        \"pool_pre_ping\": True,\n        \"pool_recycle\": 3600,\n        \"echo\": False\n    }\n}\n\nclass DatabaseManager:\n    \"\"\"Universal database manager for async operations\"\"\"\n\n    def __init__(self, env: str = \"development\"):\n        config = DATABASE_CONFIG[env]\n        self.engine = create_async_engine(**config)\n        self.async_session = async_sessionmaker(\n            self.engine,\n            class_=AsyncSession,\n            expire_on_commit=False\n        )\n\n    @asynccontextmanager\n    async def get_session(self):\n        \"\"\"Get async database session with proper cleanup\"\"\"\n        async with self.async_session() as session:\n            try:\n                yield session\n                await session.commit()\n            except Exception:\n                await session.rollback()\n                raise\n            finally:\n                await session.close()\n\n    async def create_tables(self, metadata):\n        \"\"\"Create all tables from metadata\"\"\"\n        async with self.engine.begin() as conn:\n            await conn.run_sync(metadata.create_all)\n\n    async def close(self):\n        \"\"\"Close database connections\"\"\"\n        await self.engine.dispose()\n\n# Singleton instance\ndb_manager = DatabaseManager(os.getenv(\"ENV\", \"development\"))\n```\n\n### 2. Base Model with Best Practices\n\n```python\n# models\u002Fbase.py\nfrom sqlmodel import SQLModel, Field, DateTime, func\nfrom typing import Optional\nfrom datetime import datetime\nfrom sqlalchemy import Column, DateTime as SQLDateTime, Index\n\nclass TimestampMixin(SQLModel):\n    \"\"\"Mixin for timestamp fields\"\"\"\n\n    created_at: datetime = Field(\n        default_factory=datetime.utcnow,\n        sa_column=Column(\n            SQLDateTime(timezone=True),\n            server_default=func.now(),\n            nullable=False\n        )\n    )\n\n    updated_at: Optional[datetime] = Field(\n        default=None,\n        sa_column=Column(\n            SQLDateTime(timezone=True),\n            onupdate=func.now(),\n            nullable=True\n        )\n    )\n\nclass SoftDeleteMixin(SQLModel):\n    \"\"\"Mixin for soft delete functionality\"\"\"\n\n    deleted_at: Optional[datetime] = None\n    is_deleted: bool = Field(default=False)\n\nclass BaseModel(SQLModel, TimestampMixin):\n    \"\"\"Base model with common fields and patterns\"\"\"\n\n    id: Optional[int] = Field(default=None, primary_key=True)\n\n    class Config:\n        # Enable Pydantic's strict mode\n        strict = True\n        # Validate defaults\n        validate_assignment = True\n        # Use enum values\n        use_enum_values = True\n\n# Indexes for common queries\nIndex(\"idx_base_created_at\", BaseModel.created_at)\n```\n\n### 3. Advanced Model Patterns\n\n```python\n# models\u002Fexamples.py\nfrom enum import Enum\nfrom typing import Optional, List\nfrom sqlalchemy import Column, String, Text, Boolean, Integer, Index, ForeignKey, UniqueConstraint\nfrom sqlalchemy.orm import relationship\nfrom sqlmodel import SQLModel, Field, Session, select, update, delete\n\n# Enums for type safety\nclass Status(str, Enum):\n    ACTIVE = \"active\"\n    INACTIVE = \"inactive\"\n    PENDING = \"pending\"\n\nclass Priority(str, Enum):\n    LOW = \"low\"\n    MEDIUM = \"medium\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\nclass User(BaseModel, table=True):\n    \"\"\"User model with optimized fields and indexes\"\"\"\n\n    __tablename__ = \"users\"\n\n    email: str = Field(\n        sa_column=Column(String(255), unique=True, nullable=False, index=True)\n    )\n    username: str = Field(\n        sa_column=Column(String(100), unique=True, nullable=False, index=True)\n    )\n    full_name: Optional[str] = Field(default=None, max_length=200)\n    is_active: bool = Field(default=True, sa_column=Column(Boolean, default=True))\n\n    # Optimized text fields\n    bio: Optional[str] = Field(\n        default=None,\n        sa_column=Column(Text)  # Use Text for longer content\n    )\n\n    # Relationships\n    tasks: List[\"Task\"] = Relationship(back_populates=\"owner\")\n\n    # Optimized queries\n    __table_args__ = (\n        Index(\"idx_user_active_email\", \"is_active\", \"email\"),\n        Index(\"idx_user_created_at\", \"created_at\"),\n    )\n\nclass Task(BaseModel, SoftDeleteMixin, table=True):\n    \"\"\"Task model with advanced patterns\"\"\"\n\n    __tablename__ = \"tasks\"\n\n    # Foreign key with index\n    owner_id: int = Field(\n        foreign_key=\"users.id\",\n        sa_column=Column(Integer, ForeignKey(\"users.id\"), nullable=False, index=True)\n    )\n\n    # Optimized fields\n    title: str = Field(\n        sa_column=Column(String(200), nullable=False)\n    )\n    description: Optional[str] = Field(\n        default=None,\n        sa_column=Column(Text)\n    )\n\n    # Enum fields\n    status: Status = Field(default=Status.PENDING)\n    priority: Priority = Field(default=Priority.MEDIUM)\n\n    # JSON field for flexible metadata\n    metadata: dict = Field(\n        default_factory=dict,\n        sa_column=Column(\"metadata\", JSON)\n    )\n\n    # Relationships\n    owner: User = Relationship(back_populates=\"tasks\")\n    tags: List[\"TaskTag\"] = Relationship(back_populates=\"task\")\n\n    # Optimized queries\n    __table_args__ = (\n        Index(\"idx_task_owner_status\", \"owner_id\", \"status\"),\n        Index(\"idx_task_priority_created\", \"priority\", \"created_at\"),\n        Index(\"idx_task_deleted\", \"is_deleted\"),\n    )\n\nclass Tag(BaseModel, table=True):\n    \"\"\"Tag model for many-to-many relationships\"\"\"\n\n    __tablename__ = \"tags\"\n\n    name: str = Field(\n        sa_column=Column(String(50), unique=True, nullable=False, index=True)\n    )\n    color: Optional[str] = Field(default=None, max_length=7)  # Hex color code\n\nclass TaskTag(BaseModel, table=True):\n    \"\"\"Many-to-many relationship table\"\"\"\n\n    __tablename__ = \"task_tags\"\n\n    task_id: int = Field(foreign_key=\"tasks.id\", primary_key=True)\n    tag_id: int = Field(foreign_key=\"tags.id\", primary_key=True)\n\n    task: Task = Relationship()\n    tag: Tag = Relationship()\n```\n\n### 4. Repository Pattern for Clean Code\n\n```python\n# repositories\u002Fbase.py\nfrom abc import ABC, abstractmethod\nfrom typing import TypeVar, Generic, List, Optional, Dict, Any\nfrom sqlmodel import SQLModel, Session, select, update, delete, func\n\nModelType = TypeVar(\"ModelType\", bound=SQLModel)\n\nclass BaseRepository(Generic[ModelType], ABC):\n    \"\"\"Base repository with common CRUD operations\"\"\"\n\n    def __init__(self, model: type[ModelType]):\n        self.model = model\n\n    async def create(self, db: Session, *, obj_in: Dict[str, Any]) -> ModelType:\n        \"\"\"Create a new record\"\"\"\n        db_obj = self.model(**obj_in)\n        db.add(db_obj)\n        db.commit()\n        db.refresh(db_obj)\n        return db_obj\n\n    async def get(self, db: Session, id: Any) -> Optional[ModelType]:\n        \"\"\"Get a record by ID\"\"\"\n        statement = select(self.model).where(self.model.id == id)\n        return db.exec(statement).first()\n\n    async def get_multi(\n        self,\n        db: Session,\n        *,\n        skip: int = 0,\n        limit: int = 100,\n        filters: Optional[Dict[str, Any]] = None\n    ) -> List[ModelType]:\n        \"\"\"Get multiple records with pagination\"\"\"\n        statement = select(self.model)\n\n        # Apply filters\n        if filters:\n            for key, value in filters.items():\n                if hasattr(self.model, key):\n                    statement = statement.where(getattr(self.model, key) == value)\n\n        statement = statement.offset(skip).limit(limit)\n        return db.exec(statement).all()\n\n    async def update(\n        self,\n        db: Session,\n        *,\n        db_obj: ModelType,\n        obj_in: Dict[str, Any]\n    ) -> ModelType:\n        \"\"\"Update a record\"\"\"\n        for field, value in obj_in.items():\n            if hasattr(db_obj, field):\n                setattr(db_obj, field, value)\n\n        db.add(db_obj)\n        db.commit()\n        db.refresh(db_obj)\n        return db_obj\n\n    async def remove(self, db: Session, *, id: int) -> ModelType:\n        \"\"\"Remove a record\"\"\"\n        obj = await self.get(db, id=id)\n        if obj:\n            db.delete(obj)\n            db.commit()\n        return obj\n\n    async def count(self, db: Session, filters: Optional[Dict[str, Any]] = None) -> int:\n        \"\"\"Count records with optional filters\"\"\"\n        statement = select(func.count(self.model.id))\n\n        if filters:\n            for key, value in filters.items():\n                if hasattr(self.model, key):\n                    statement = statement.where(getattr(self.model, key) == value)\n\n        return db.exec(statement).scalar()\n\n# repositories\u002Fuser.py\nclass UserRepository(BaseRepository[User]):\n    \"\"\"User repository with specific queries\"\"\"\n\n    async def get_by_email(self, db: Session, *, email: str) -> Optional[User]:\n        \"\"\"Get user by email\"\"\"\n        statement = select(User).where(User.email == email)\n        return db.exec(statement).first()\n\n    async def get_active_users(\n        self,\n        db: Session,\n        skip: int = 0,\n        limit: int = 100\n    ) -> List[User]:\n        \"\"\"Get active users\"\"\"\n        statement = select(User).where(User.is_active == True)\n        statement = statement.offset(skip).limit(limit)\n        return db.exec(statement).all()\n```\n\n### 5. Advanced Query Patterns\n\n```python\n# services\u002Fquery_builder.py\nfrom sqlalchemy import and_, or_, func, asc, desc, extract\nfrom typing import List, Optional, Dict, Any, Union\nfrom datetime import datetime, date\nfrom models.base import db_manager\n\nclass QueryBuilder:\n    \"\"\"Advanced query builder for complex database operations\"\"\"\n\n    def __init__(self, model):\n        self.model = model\n        self._filters = []\n        self._order_by = []\n        self._joins = []\n        self._group_by = []\n\n    def filter(self, *conditions) -> \"QueryBuilder\":\n        \"\"\"Add filter conditions\"\"\"\n        self._filters.extend(conditions)\n        return self\n\n    def where(self, condition) -> \"QueryBuilder\":\n        \"\"\"Add where condition\"\"\"\n        self._filters.append(condition)\n        return self\n\n    def order_by(self, *columns) -> \"QueryBuilder\":\n        \"\"\"Add order by clauses\"\"\"\n        self._order_by.extend(columns)\n        return self\n\n    def join(self, model, condition=None) -> \"QueryBuilder\":\n        \"\"\"Add join\"\"\"\n        self._joins.append((model, condition))\n        return self\n\n    def group_by(self, *columns) -> \"QueryBuilder\":\n        \"\"\"Add group by clauses\"\"\"\n        self._group_by.extend(columns)\n        return self\n\n    async def execute(self, db: Session):\n        \"\"\"Execute the built query\"\"\"\n        statement = select(self.model)\n\n        # Apply filters\n        if self._filters:\n            statement = statement.where(and_(*self._filters))\n\n        # Apply joins\n        for model, condition in self._joins:\n            if condition:\n                statement = statement.join(model, condition)\n            else:\n                statement = statement.join(model)\n\n        # Apply group by\n        if self._group_by:\n            statement = statement.group_by(*self._group_by)\n\n        # Apply order by\n        if self._order_by:\n            statement = statement.order_by(*self._order_by)\n\n        return db.exec(statement).all()\n\n# Usage examples\nasync def search_tasks_advanced(\n    owner_id: int,\n    keywords: Optional[str] = None,\n    status: Optional[Status] = None,\n    priority: Optional[Priority] = None,\n    date_range: Optional[tuple] = None\n) -> List[Task]:\n    \"\"\"Advanced task search with multiple filters\"\"\"\n\n    async with db_manager.get_session() as db:\n        query = QueryBuilder(Task)\n\n        # Base filters\n        query = query.filter(Task.owner_id == owner_id, Task.is_deleted == False)\n\n        # Text search\n        if keywords:\n            search_pattern = f\"%{keywords}%\"\n            query = query.where(\n                or_(\n                    Task.title.ilike(search_pattern),\n                    Task.description.ilike(search_pattern)\n                )\n            )\n\n        # Status filter\n        if status:\n            query = query.filter(Task.status == status)\n\n        # Priority filter\n        if priority:\n            query = query.filter(Task.priority == priority)\n\n        # Date range filter\n        if date_range:\n            start_date, end_date = date_range\n            query = query.filter(\n                and_(\n                    Task.created_at >= start_date,\n                    Task.created_at \u003C= end_date\n                )\n            )\n\n        # Order by priority and creation date\n        query = query.order_by(\n            desc(Task.priority),\n            desc(Task.created_at)\n        )\n\n        return await query.execute(db)\n```\n\n### 6. Database Migrations Best Practices\n\n```python\n# migrations\u002Fversions\u002F001_initial_tables.py\n\"\"\"Initial tables migration\n\nRevision ID: 001_initial\nRevises:\nCreate Date: 2025-01-01 00:00:00.000000\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers\nrevision = '001_initial'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\ndef upgrade():\n    \"\"\"Create initial tables with optimized schema\"\"\"\n\n    # Users table\n    op.create_table(\n        'users',\n        sa.Column('id', sa.Integer(), nullable=False),\n        sa.Column('email', sa.String(length=255), nullable=False),\n        sa.Column('username', sa.String(length=100), nullable=False),\n        sa.Column('full_name', sa.String(length=200), nullable=True),\n        sa.Column('is_active', sa.Boolean(), nullable=True, default=True),\n        sa.Column('bio', sa.Text(), nullable=True),\n        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),\n        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n        sa.PrimaryKeyConstraint('id'),\n        sa.UniqueConstraint('email'),\n        sa.UniqueConstraint('username')\n    )\n\n    # Create indexes\n    op.create_index('idx_user_email', 'users', ['email'])\n    op.create_index('idx_user_username', 'users', ['username'])\n    op.create_index('idx_user_active_email', 'users', ['is_active', 'email'])\n\n    # Tasks table\n    op.create_table(\n        'tasks',\n        sa.Column('id', sa.Integer(), nullable=False),\n        sa.Column('owner_id', sa.Integer(), nullable=False),\n        sa.Column('title', sa.String(length=200), nullable=False),\n        sa.Column('description', sa.Text(), nullable=True),\n        sa.Column('status', sa.Enum('ACTIVE', 'INACTIVE', 'PENDING', name='status'), nullable=True),\n        sa.Column('priority', sa.Enum('LOW', 'MEDIUM', 'HIGH', 'CRITICAL', name='priority'), nullable=True),\n        sa.Column('metadata', sa.JSON(), nullable=True),\n        sa.Column('is_deleted', sa.Boolean(), nullable=True, default=False),\n        sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True),\n        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),\n        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n        sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),\n        sa.PrimaryKeyConstraint('id')\n    )\n\n    # Create indexes\n    op.create_index('idx_task_owner', 'tasks', ['owner_id'])\n    op.create_index('idx_task_owner_status', 'tasks', ['owner_id', 'status'])\n    op.create_index('idx_task_priority_created', 'tasks', ['priority', 'created_at'])\n    op.create_index('idx_task_deleted', 'tasks', ['is_deleted'])\n\n    # Tags table\n    op.create_table(\n        'tags',\n        sa.Column('id', sa.Integer(), nullable=False),\n        sa.Column('name', sa.String(length=50), nullable=False),\n        sa.Column('color', sa.String(length=7), nullable=True),\n        sa.PrimaryKeyConstraint('id'),\n        sa.UniqueConstraint('name')\n    )\n\n    op.create_index('idx_tag_name', 'tags', ['name'])\n\n    # Task-Tag relationship table\n    op.create_table(\n        'task_tags',\n        sa.Column('task_id', sa.Integer(), nullable=False),\n        sa.Column('tag_id', sa.Integer(), nullable=False),\n        sa.ForeignKeyConstraint(['task_id'], ['tasks.id'], ),\n        sa.ForeignKeyConstraint(['tag_id'], ['tags.id'], ),\n        sa.PrimaryKeyConstraint('task_id', 'tag_id')\n    )\n\ndef downgrade():\n    \"\"\"Drop all tables\"\"\"\n    op.drop_table('task_tags')\n    op.drop_table('tags')\n    op.drop_table('tasks')\n    op.drop_table('users')\n```\n\n### 7. Performance Optimization\n\n```python\n# utils\u002Fperformance.py\nimport time\nfrom functools import wraps\nfrom typing import Callable, Any\nfrom sqlmodel import Session\n\ndef measure_query_time(func: Callable) -> Callable:\n    \"\"\"Decorator to measure query execution time\"\"\"\n    @wraps(func)\n    async def wrapper(*args, **kwargs):\n        start_time = time.time()\n        result = await func(*args, **kwargs)\n        execution_time = time.time() - start_time\n\n        # Log slow queries\n        if execution_time > 1.0:  # 1 second threshold\n            print(f\"Slow query detected: {func.__name__} took {execution_time:.2f}s\")\n\n        return result\n    return wrapper\n\nclass DatabaseOptimizer:\n    \"\"\"Database performance optimization utilities\"\"\"\n\n    @staticmethod\n    async def analyze_slow_queries(db: Session, threshold: float = 1.0) -> List[Dict]:\n        \"\"\"Analyze slow queries (PostgreSQL specific)\"\"\"\n        if db.bind.dialect.name != 'postgresql':\n            return []\n\n        query = \"\"\"\n        SELECT query, calls, total_time, mean_time, rows\n        FROM pg_stat_statements\n        WHERE mean_time > %s\n        ORDER BY total_time DESC\n        LIMIT 10\n        \"\"\"\n\n        result = db.execute(query, threshold)\n        return [dict(row) for row in result]\n\n    @staticmethod\n    async def get_table_statistics(db: Session) -> Dict[str, Any]:\n        \"\"\"Get table statistics\"\"\"\n        stats = {}\n\n        if db.bind.dialect.name == 'postgresql':\n            # PostgreSQL statistics\n            tables_query = \"\"\"\n            SELECT schemaname, tablename, n_tup_ins, n_tup_upd, n_tup_del, n_live_tup, n_dead_tup\n            FROM pg_stat_user_tables\n            \"\"\"\n\n            for row in db.execute(tables_query):\n                table_name = row.tablename\n                stats[table_name] = {\n                    'inserts': row.n_tup_ins,\n                    'updates': row.n_tup_upd,\n                    'deletes': row.n_tup_del,\n                    'live_rows': row.n_live_tup,\n                    'dead_rows': row.n_dead_tup\n                }\n\n        return stats\n```\n\n### 8. Testing Database Operations\n\n```python\n# tests\u002Fconftest.py\nimport pytest\nimport asyncio\nfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession\nfrom httpx import AsyncClient\nfrom sqlmodel import SQLModel\nfrom models.base import BaseModel\nfrom repositories.base import BaseRepository\n\n@pytest.fixture(scope=\"session\")\ndef event_loop():\n    \"\"\"Create an instance of the default event loop\"\"\"\n    loop = asyncio.get_event_loop_policy().new_event_loop()\n    yield loop\n    loop.close()\n\n@pytest.fixture(scope=\"function\")\nasync def test_db_session():\n    \"\"\"Create test database session\"\"\"\n    # In-memory SQLite for testing\n    engine = create_async_engine(\n        \"sqlite+aiosqlite:\u002F\u002F\u002F:memory:\",\n        echo=False\n    )\n\n    # Create tables\n    async with engine.begin() as conn:\n        await conn.run_sync(BaseModel.metadata.create_all)\n\n    # Create session\n    async_session = async_sessionmaker(\n        engine, class_=AsyncSession, expire_on_commit=False\n    )\n\n    async with async_session() as session:\n        yield session\n\n@pytest.fixture\ndef user_repository():\n    \"\"\"Create user repository instance\"\"\"\n    return UserRepository(User)\n\n# tests\u002Ftest_repositories.py\n@pytest.mark.asyncio\nasync def test_create_user(test_db_session: AsyncSession, user_repository):\n    \"\"\"Test user creation\"\"\"\n    user_data = {\n        \"email\": \"test@example.com\",\n        \"username\": \"testuser\",\n        \"full_name\": \"Test User\"\n    }\n\n    user = await user_repository.create(test_db_session, obj_in=user_data)\n\n    assert user.email == user_data[\"email\"]\n    assert user.username == user_data[\"username\"]\n    assert user.is_active == True\n```\n\n### 9. Production Configuration Checklist\n\n```yaml\n# config\u002Fproduction_checklist.yaml\ndatabase:\n  production_ready:\n    connection_pooling: true\n    ssl_enabled: true\n    max_connections: 100\n    min_connections: 10\n    connection_timeout: 30\n    idle_timeout: 300\n\n  monitoring:\n    slow_query_log: true\n    query_threshold: 1.0\n    connection_pool_metrics: true\n\n  backup:\n    automated_backups: true\n    backup_retention: 30_days\n    point_in_time_recovery: true\n\n  security:\n    encryption_at_rest: true\n    encryption_in_transit: true\n    least_privilege_access: true\n    regular_rotation: true\n```\n\nThis comprehensive database skill provides production-ready patterns optimized for 2025, including async operations, performance optimization, proper indexing, and comprehensive testing strategies that work across different database systems.",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fmarketplace\u002Fdatabase",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill database",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill database",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill database","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fdatabase\u002FSKILL.md",true,[48,54],{"path":49,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":52,"sourceHtmlUrl":53},"audit_output.json","REFERENCE","参考文档",6910,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fdatabase\u002Faudit_output.json",{"path":55,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":56,"sourceHtmlUrl":57},"skill-report.json",40033,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fdatabase\u002Fskill-report.json",[59,67,74,81,88,95],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":66},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":66},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":66},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":66},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":66},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":66},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]