090-database

090-database is a cursor rule for Cursor from juandoroteoflesiauni-lang/Market-options-stocks-Scanner. It costs 0 tokens per session (2,693 once invoked), scanned A, original, Apache-2.0.

A set of database, migration and cache rules for a trading terminal. It defines how the application stores data and communicates with its database using SQLAlchemy, an object-based Python database library.

In plain words
What is it for?
Use it when creating database models, sessions, migrations or cached data for the trading terminal, especially when handling money, UUID identifiers and UTC times.
Why use it?
It reduces inconsistent data access and helps avoid problems with blocking operations, inaccurate money calculations, unstable identifiers and incorrect timestamps.

Cursor rule for Cursor

Written for Cursor: installed under .cursor/.

Good fit Use it when creating database models, sessions, migrations or cached data for the trading terminal, especially when handling money, UUID identifiers and UTC times.

Compare 6 cursor rules from other repositories ↓
Install with agentmods
npx agentmods add rules/juandoroteoflesiauni-lang/market-options-stocks-scanner/090-database
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Clone the repo
git clone --depth 1 https://github.com/juandoroteoflesiauni-lang/Market-options-stocks-Scanner

Made for: Cursor.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for 090-database

README.md
[![agentmods](https://agentmods.dev/badge/rules/juandoroteoflesiauni-lang/market-options-stocks-scanner/090-database/github.svg)](https://agentmods.dev/rules/juandoroteoflesiauni-lang/market-options-stocks-scanner/090-database)
Your own site
<a href="https://agentmods.dev/rules/juandoroteoflesiauni-lang/market-options-stocks-scanner/090-database"><img src="https://agentmods.dev/badge/rules/juandoroteoflesiauni-lang/market-options-stocks-scanner/090-database/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for 090-database

Your own site · 80×15
<a href="https://agentmods.dev/rules/juandoroteoflesiauni-lang/market-options-stocks-scanner/090-database"><img src="https://agentmods.dev/badge/rules/juandoroteoflesiauni-lang/market-options-stocks-scanner/090-database.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 2,693 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00000 $0.02693
Opus 5 $0.00000 $0.01347
Sonnet 5 $0.00000 $0.00539
Haiku 4.5 $0.00000 $0.00269

Measured 12d ago against content hash 79667b548638, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-11, from the pricing page.

Security

Grade A, and why

090-database scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 12d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.cursor/rules/090-database.mdc · 375 lines

How it starts

The opening of the file, as written. The whole thing — 375 lines — stays where its author put it; the contents beside it link to each section on GitHub.

🗄️ BASE DE DATOS Y PERSISTENCIA — TRADING TERMINAL

PRINCIPIOS DE ACCESO A DATOS

  • Nunca SQL raw en services o endpoints → usar SQLAlchemy ORM
  • Siempre async para no bloquear el event loop
  • Decimal para todos los valores monetarios (nunca float)
  • UUID como primary key (no autoincrement entero)
  • Timestamps en UTC siempre

🔌 CONEXIÓN Y SESIÓN

# core/database.py

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
from core.config import settings

# Motor async — una sola instancia global
engine = create_async_engine(
    settings.DATABASE_URL,
    echo=settings.DEBUG,          # Solo SQL logs en modo debug
    pool_size=10,                 # Conexiones en el pool
    max_overflow=20,              # Conexiones extra bajo demanda
    pool_pre_ping=True,           # Verificar conexiones antes de usar
)

AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False        # Importante para async
)

class Base(DeclarativeBase):
    """Base para todos los modelos SQLAlchemy."""
    pass

# Dependency para FastAPI
async def get_db() -> AsyncSession:
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()

📋 PATRÓN REPOSITORY

# repositories/base_repo.py — Repository base genérico

from typing import Generic, TypeVar, Type, Optional, List
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, delete
from core.database import Base

ModelType = TypeVar("ModelType", bound=Base)

class BaseRepository(Generic[ModelType]):
    """Repository base con operaciones CRUD comunes."""

    def __init__(self, model: Type[ModelType]):
        self.model = model

    async def get_by_id(self, db: AsyncSession, id: UUID) -> Optional[ModelType]:
        result = await db.execute(select(self.model).where(self.model.id == id))
        return result.scalar_one_or_none()

    async def get_all(
        self,
        db: AsyncSession,
        skip: int = 0,
        limit: int = 100
    ) -> List[ModelType]:
        result = await db.execute(select(self.model).offset(skip).limit(limit))
        return list(result.scalars().all())

    async def create(self, db: AsyncSession, obj_data: dict) -> ModelType:
        db_obj = self.model(**obj_data)
        db.add(db_obj)
        await db.flush()   # flush, no commit (lo hace el middleware)
        await db.refresh(db_obj)
        return db_obj

    async def update(
        self,
        db: AsyncSession,
        id: UUID,
        update_data: dict
    ) -> Optional[ModelType]:
        await db.execute(
            update(self.model)
            .where(self.model.id == id)
            .values(**update_data)
        )
        return await self.get_by_id(db, id)

    async def delete(self, db: AsyncSession, id: UUID) -> bool:
        result = await db.execute(
            delete(self.model).where(self.model.id == id)
        )
        return result.rowcount > 0


# repositories/order_repo.py — Específico para órdenes

from sqlalchemy import select, and_, desc
from typing import Optional, List
from uuid import UUID
from datetime import datetime, date

from repositories.base_repo import BaseRepository
from models.order import Order, OrderStatus

class OrderRepository(BaseRepository[Order]):

    def __init__(self):
        super().__init__(Order)

    async def get_open_orders(
        self,
        db: AsyncSession,
        user_id: UUID
    ) -> List[Order]:
        """Obtener todas las órdenes abiertas de un usuario."""
        result = await db.execute(
            select(Order)
            .where(and_(
                Order.user_id == user_id,
                Order.status.in_([OrderStatus.PENDING, OrderStatus.OPEN])
            ))
            .order_by(desc(Order.created_at))
        )
        return list(result.scalars().all())

    async def get_by_symbol(
        self,
        db: AsyncSession,
        user_id: UUID,
        symbol: str,
        limit: int = 50
    ) -> List[Order]:
        """Historial de órdenes por símbolo."""
        result = await db.execute(
            select(Order)
            .where(and_(
                Order.user_id == user_id,
                Order.symbol == symbol
            ))
            .order_by(desc(Order.created_at))
            .limit(limit)
        )
        return list(result.scalars().all())

    async def get_daily_volume_usd(
        self,
        db: AsyncSession,
        user_id: UUID,
        date: date
    ) -> float:
        """
        Calcular volumen total operado en un día.
        Usado por RiskService para límites diarios.
        """
        from sqlalchemy import func, cast, Date

        result = await db.execute(
            select(func.sum(Order.quantity * Order.fill_price))
            .where(and_(
                Order.user_id == user_id,
                Order.status == OrderStatus.FILLED,
                cast(Order.filled_at, Date) == date
            ))
        )
        return float(result.scalar() or 0)

order_repo = OrderRepository()  # Singleton

Read the full file on GitHub · 375 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 12d ago First seen · 375 lines · 0 tokens per session scan A 79667b548638

Subscribe to this mod's changes

090-database is a cursor rule published in the GitHub repository juandoroteoflesiauni-lang/Market-options-stocks-Scanner (11 stars, last pushed 2mo ago), licensed Apache-2.0. It costs nothing until one of its globs matches a file; then it loads 2,693 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.