Skip to content

Commit f745865

Browse files
committed
feat: added index to table, with agent migration skill
1 parent bbf05cc commit f745865

File tree

4 files changed

+59
-8
lines changed

4 files changed

+59
-8
lines changed

.agent/workflows/migrate.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
description: Detects changes in database schema/models, generates an Alembic migration with a descriptive name
3+
---
4+
5+
# Database Migration Skill
6+
7+
## Instructions
8+
9+
1. **Analyze Changes**: Review the recent changes made to the SQLAlchemy models or schema definitions in the codebase.
10+
2. **Generate Name**: Create a concise, snake_case migration message (slug) that summarizes the changes (e.g., `add_user_profile_table`, `add_index_to_orders`, `remove_legacy_columns`).
11+
3. **Create Revision**: Run the following command in the terminal, replacing `<message>` with the generated name:
12+
```bash
13+
uv run alembic revision --autogenerate -m "<message>"
14+
```
15+
4. **Apply Upgrade**: Once the revision is created successfully, run the following command to apply the changes:
16+
```bash
17+
uv run alembic upgrade head
18+
```
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""add_composite_index_silver_mbo
2+
3+
Revision ID: bdf5943aa4f5
4+
Revises: 5f9dbb4c8034
5+
Create Date: 2026-02-12 17:38:13.593991
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = 'bdf5943aa4f5'
14+
down_revision = '5f9dbb4c8034'
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade() -> None:
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.create_index('ix_silver_mbo_symbol_ts_action', 'silver_futures_mbo', ['symbol', 'ts_event', 'action'], unique=False)
22+
# ### end Alembic commands ###
23+
24+
25+
def downgrade() -> None:
26+
# ### commands auto generated by Alembic - please adjust! ###
27+
op.drop_index('ix_silver_mbo_symbol_ts_action', table_name='silver_futures_mbo')
28+
# ### end Alembic commands ###

curator/db_tools/queries.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
from collections.abc import Sequence
12
from datetime import datetime
23

34
import pandas as pd
4-
from sqlalchemy import case, delete, func, or_, select, update
5+
from sqlalchemy import Row, case, delete, func, or_, select, update
56
from sqlalchemy.dialects.postgresql import insert
67
from sqlalchemy.ext.asyncio import AsyncSession
78

@@ -70,7 +71,7 @@ async def query_options_tickers(
7071
months_hist: int = 24,
7172
all_=False,
7273
unexpired=False,
73-
) -> list[OptionsTickerModel]:
74+
) -> Sequence[Row]:
7475
"""
7576
This is to pull all options contracts for a given underlying ticker.
7677
The batch input is to only pull o_ticker_ids for given o_tickers
@@ -103,12 +104,12 @@ async def query_options_tickers(
103104

104105

105106
@Session
106-
async def query_stock_tickers(session: AsyncSession, all_: bool = True, tickers: list[str] = []) -> list[TickerModel]:
107+
async def query_stock_tickers(session: AsyncSession, tickers: list[str], all_: bool = True) -> list[TickerModel]:
107108
"""only returns tickers likely to have options contracts"""
108109
stmt = select(StockTickers.id, StockTickers.ticker).where(StockTickers.type.in_(["ADRC", "ETF", "CS"]))
109110
if not all_:
110111
stmt = stmt.where(StockTickers.ticker.in_(tickers))
111-
return (await session.execute(stmt)).all()
112+
return (await session.execute(stmt)).all() # type: ignore
112113

113114

114115
@Session
@@ -128,8 +129,8 @@ async def ticker_imported(session: AsyncSession, ticker_id: int):
128129
async def update_stock_metadata(session: AsyncSession, data: list[TickerModel]):
129130
df = pd.DataFrame(data)
130131
df = df.drop_duplicates(subset=["ticker"], keep="last")
131-
data = df.to_dict(orient="records")
132-
stmt = insert(StockTickers).values(data)
132+
clean_data = df.to_dict(orient="records")
133+
stmt = insert(StockTickers).values(clean_data)
133134
stmt = stmt.on_conflict_do_update(
134135
index_elements=["ticker"],
135136
set_=dict(
@@ -242,7 +243,7 @@ async def delete_stock_ticker(session: AsyncSession, ticker: str):
242243

243244

244245
@Session
245-
async def latest_date_per_ticker(session: AsyncSession, tickers: list[str] = [], options=False):
246+
async def latest_date_per_ticker(session: AsyncSession, tickers: list[str], options=False):
246247
"""query to retrieve the most recent date of record for ticker data (prices/quotes for stock/options).
247248
If tickers is [] empty, return all
248249
"""

curator/db_tools/schemas.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
Column,
1313
Enum,
1414
ForeignKey,
15+
Index,
1516
Integer,
1617
String,
1718
UniqueConstraint,
@@ -249,7 +250,10 @@ class SilverFuturesMBO(Base):
249250
"""
250251

251252
__tablename__ = "silver_futures_mbo"
252-
__table_args__ = (UniqueConstraint("ts_event", "order_id", "sequence", name="uq_silver_mbo_event"),)
253+
__table_args__ = (
254+
UniqueConstraint("ts_event", "order_id", "sequence", name="uq_silver_mbo_event"),
255+
Index("ix_silver_mbo_symbol_ts_action", "symbol", "ts_event", "action"),
256+
)
253257

254258
id = Column(BigInteger, primary_key=True, autoincrement=True)
255259
ts_recv = Column(DateTime, nullable=False)

0 commit comments

Comments
 (0)